chore: checkpoint web Blender migration source, tools and docs
Accumulated uncommitted work: GHOST Web backend, WebGL/GPU web layer, web workflow engine and protocol, tooling, docs and task records. Large generated evidence, user-testing archives, build snapshots and imported test assets remain untracked. Co-Authored-By: Claude Code <noreply@anthropic.com>
@@ -6,8 +6,13 @@
|
||||
<meta name="theme-color" content="#181818" />
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||
<title>Blender 5.2.0 LTS - Web</title>
|
||||
<link rel="preload" as="fetch" type="application/wasm" crossorigin href="/vendor/blender/single/web_engine.wasm" />
|
||||
<link rel="stylesheet" href="/src/app/app-shell.css" />
|
||||
<link rel="stylesheet" href="/src/app/operator-properties.css" />
|
||||
<link rel="stylesheet" href="/src/app/native-workflows.css" />
|
||||
<link rel="stylesheet" href="/src/robot/robot-tool.css" />
|
||||
<link rel="stylesheet" href="/src/app/desktop-menus.css" />
|
||||
<link rel="stylesheet" href="/src/app/desktop-workspace.css" />
|
||||
<link rel="stylesheet" href="/src/app/wasm-editors.css" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -16,12 +16,12 @@
|
||||
"js": {
|
||||
"fileName": "web_engine.js",
|
||||
"url": "/vendor/blender/single/web_engine.js",
|
||||
"sha256": "25aa51361aa8c95479873240c776d6213c1092dd480ee2a0036d2cbbd561dcad"
|
||||
"sha256": "79647f65c0097db15bde505ec79917c558d42ed53271250ba816235b64c6f175"
|
||||
},
|
||||
"wasm": {
|
||||
"fileName": "web_engine.wasm",
|
||||
"url": "/vendor/blender/single/web_engine.wasm",
|
||||
"sha256": "7f3a50f1d41b2ac0e6366e84caaabefc3cdfc47c055d5ea459abec654da6fcc0"
|
||||
"sha256": "9df8b0197186b6eab005a1bee5a50cb9d41c511040504f18c8e2d57f1c05745a"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
BIN
web/app/public/manuals/WEB_Blender_Desktop_Menus.pdf
Normal file
BIN
web/app/public/manuals/WEB_Blender_Function_User_Guide.pdf
Normal file
BIN
web/app/public/manuals/WEB_Blender_Robot_Tool_User_Manual.pdf
Normal file
BIN
web/app/public/manuals/WEB_Blender_Viewport_Navigation.pdf
Normal file
73
web/app/public/robot-assets/abb-irb120/LICENSE
Normal file
@@ -0,0 +1,73 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
8
web/app/public/robot-assets/abb-irb120/NOTICE.txt
Normal file
@@ -0,0 +1,8 @@
|
||||
ABB IRB 120-3/0.58 example assets
|
||||
|
||||
Source: https://github.com/ros-industrial/abb/tree/1.5.0/abb_irb120_support
|
||||
Commit: eefdf01c956a6f2129aacb88d598201feff3cf19
|
||||
License: Apache-2.0 (see LICENSE and package.xml)
|
||||
URDF expanded from upstream Xacro without changing joint semantics.
|
||||
Visual STL assets are unmodified. No collision geometry is imported by this tool.
|
||||
provenance.json records the original downloaded and expanded file hashes.
|
||||
250
web/app/public/robot-assets/abb-irb120/abb_irb120.urdf
Normal file
@@ -0,0 +1,250 @@
|
||||
<?xml version="1.0" ?>
|
||||
<!-- =================================================================================== -->
|
||||
<!-- | This document was autogenerated by xacro from /home/mes123456/workinf_Blender_Wasm/user-testing/WEB_Blender_ABB_IRB120_20260916/expanded-source/irb120_3_58.xacro | -->
|
||||
<!-- | EDITING THIS FILE BY HAND IS NOT RECOMMENDED | -->
|
||||
<!-- =================================================================================== -->
|
||||
<robot name="abb_irb120_3_58">
|
||||
<!-- Conversion were obtained from http://www.e-paint.co.uk/Lab_values.asp
|
||||
unless otherwise stated. -->
|
||||
<link name="base_link">
|
||||
<inertial>
|
||||
<mass value="6.215"/>
|
||||
<origin rpy="0 0 0" xyz="-0.04204 8.01E-05 0.07964"/>
|
||||
<inertia ixx="0.0247272" ixy="-8.0784E-05" ixz="0.00130902" iyy="0.0491285" iyz="-8.0419E-06" izz="0.0472376"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/base_link.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="0.7372549 0.3490196 0.1607843 1"/>
|
||||
</material>
|
||||
</visual>
|
||||
<collision>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/base_link.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="1 1 0 1"/>
|
||||
</material>
|
||||
</collision>
|
||||
</link>
|
||||
<link name="link_1">
|
||||
<inertial>
|
||||
<mass value="3.067"/>
|
||||
<origin rpy="0 0 0" xyz="9.77E-05 -0.00012 0.23841"/>
|
||||
<inertia ixx="0.0142175" ixy="-1.28579E-05" ixz="-2.31364E-05" iyy="0.0144041" iyz="1.93404E-05" izz="0.0104533"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/link_1.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="0.7372549 0.3490196 0.1607843 1"/>
|
||||
</material>
|
||||
</visual>
|
||||
<collision>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/link_1.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="1 1 0 1"/>
|
||||
</material>
|
||||
</collision>
|
||||
</link>
|
||||
<link name="link_2">
|
||||
<inertial>
|
||||
<mass value="3.909"/>
|
||||
<origin rpy="0 0 0" xyz="0.00078 -0.00212 0.10124"/>
|
||||
<inertia ixx="0.0603111" ixy="9.83431E-06" ixz="5.72407E-05" iyy="0.041569" iyz="-0.00050497" izz="0.0259548"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/link_2.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="0.7372549 0.3490196 0.1607843 1"/>
|
||||
</material>
|
||||
</visual>
|
||||
<collision>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/link_2.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="1 1 0 1"/>
|
||||
</material>
|
||||
</collision>
|
||||
</link>
|
||||
<link name="link_3">
|
||||
<inertial>
|
||||
<mass value="2.944"/>
|
||||
<origin rpy="0 0 0" xyz="0.02281 0.00106 0.05791"/>
|
||||
<inertia ixx="0.00835606" ixy="-8.01545E-05" ixz="0.00142884" iyy="0.016713" iyz="-0.000182227" izz="0.0126984"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/link_3.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="0.7372549 0.3490196 0.1607843 1"/>
|
||||
</material>
|
||||
</visual>
|
||||
<collision>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/link_3.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="1 1 0 1"/>
|
||||
</material>
|
||||
</collision>
|
||||
</link>
|
||||
<link name="link_4">
|
||||
<inertial>
|
||||
<mass value="1.328"/>
|
||||
<origin rpy="0 0 0" xyz="0.2247 0.00015 0.00041"/>
|
||||
<inertia ixx="0.00284661" ixy="-2.12765E-05" ixz="-1.6435E-05" iyy="0.00401346" iyz="1.31336E-05" izz="0.0052535"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/link_4.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="0.7372549 0.3490196 0.1607843 1"/>
|
||||
</material>
|
||||
</visual>
|
||||
<collision>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/link_4.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="1 1 0 1"/>
|
||||
</material>
|
||||
</collision>
|
||||
</link>
|
||||
<link name="link_5">
|
||||
<inertial>
|
||||
<mass value="0.546"/>
|
||||
<origin rpy="0 0 0" xyz="-0.00109 3.68E-05 6.22E-05"/>
|
||||
<inertia ixx="0.000404891" ixy="1.61943E-06" ixz="8.46805E-07" iyy="0.000892825" iyz="-1.51792E-08" izz="0.000815468"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/link_5.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="0.7372549 0.3490196 0.1607843 1"/>
|
||||
</material>
|
||||
</visual>
|
||||
<collision>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/link_5.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="1 1 0 1"/>
|
||||
</material>
|
||||
</collision>
|
||||
</link>
|
||||
<link name="link_6">
|
||||
<inertial>
|
||||
<mass value="0.137"/>
|
||||
<origin rpy="0 0 0" xyz="-0.00706 -0.00017 -1.32E-06"/>
|
||||
<inertia ixx="0.001" ixy="0" ixz="0" iyy="0.001" iyz="0" izz="0.001"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/link_6.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="0.1882353 0.1960784 0.2039216 1"/>
|
||||
</material>
|
||||
</visual>
|
||||
<collision>
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/link_6.stl"/>
|
||||
</geometry>
|
||||
<material name="">
|
||||
<color rgba="1 1 0 1"/>
|
||||
</material>
|
||||
</collision>
|
||||
</link>
|
||||
<joint name="joint_1" type="revolute">
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<parent link="base_link"/>
|
||||
<child link="link_1"/>
|
||||
<limit effort="0" lower="-2.87979" upper="2.87979" velocity="4.36332"/>
|
||||
<axis xyz="0 0 1"/>
|
||||
<dynamics damping="0.0" friction="0.0"/>
|
||||
</joint>
|
||||
<joint name="joint_2" type="revolute">
|
||||
<origin rpy="0 0 0" xyz="0 0 0.29"/>
|
||||
<parent link="link_1"/>
|
||||
<child link="link_2"/>
|
||||
<limit effort="0" lower="-1.91986" upper="1.91986" velocity="4.36332"/>
|
||||
<axis xyz="0 1 0"/>
|
||||
<dynamics damping="0.0" friction="0.0"/>
|
||||
</joint>
|
||||
<joint name="joint_3" type="revolute">
|
||||
<origin rpy="0 0 0" xyz="0 0 0.27"/>
|
||||
<parent link="link_2"/>
|
||||
<child link="link_3"/>
|
||||
<limit effort="0" lower="-1.91986" upper="1.22173" velocity="4.36332"/>
|
||||
<axis xyz="0 1 0"/>
|
||||
<dynamics damping="0.0" friction="0.0"/>
|
||||
</joint>
|
||||
<joint name="joint_4" type="revolute">
|
||||
<origin rpy="0 0 0" xyz="0 0 0.07"/>
|
||||
<parent link="link_3"/>
|
||||
<child link="link_4"/>
|
||||
<limit effort="0" lower="-2.79253" upper="2.79253" velocity="5.58505"/>
|
||||
<axis xyz="1 0 0"/>
|
||||
<dynamics damping="0.0" friction="0.0"/>
|
||||
</joint>
|
||||
<joint name="joint_5" type="revolute">
|
||||
<origin rpy="0 0 0" xyz="0.302 0 0"/>
|
||||
<parent link="link_4"/>
|
||||
<child link="link_5"/>
|
||||
<limit effort="0" lower="-2.094395" upper="2.094395" velocity="5.58505"/>
|
||||
<axis xyz="0 1 0"/>
|
||||
<dynamics damping="0.0" friction="0.0"/>
|
||||
</joint>
|
||||
<joint name="joint_6" type="revolute">
|
||||
<origin rpy="0 0 0" xyz="0.072 0 0"/>
|
||||
<parent link="link_5"/>
|
||||
<child link="link_6"/>
|
||||
<limit effort="0" lower="-6.98132" upper="6.98132" velocity="7.33038"/>
|
||||
<axis xyz="1 0 0"/>
|
||||
<dynamics damping="0.0" friction="0.0"/>
|
||||
</joint>
|
||||
<link name="base"/>
|
||||
<joint name="base_link-base" type="fixed">
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<parent link="base_link"/>
|
||||
<child link="base"/>
|
||||
</joint>
|
||||
<link name="flange"/>
|
||||
<joint name="joint_6-flange" type="fixed">
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<parent link="link_6"/>
|
||||
<child link="flange"/>
|
||||
</joint>
|
||||
<link name="tool0"/>
|
||||
<joint name="link_6-tool0" type="fixed">
|
||||
<origin rpy="0 1.5707963267948966 0" xyz="0 0 0"/>
|
||||
<parent link="flange"/>
|
||||
<child link="tool0"/>
|
||||
</joint>
|
||||
</robot>
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0"?>
|
||||
<?xml-model href="http://download.ros.org/schema/package_format2.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
|
||||
<package format="2">
|
||||
<name>abb_irb120_support</name>
|
||||
<version>1.5.0</version>
|
||||
<description>
|
||||
<p>
|
||||
ROS-Industrial support for the ABB IRB 120 (and variants).
|
||||
</p>
|
||||
<p>
|
||||
This package contains configuration data, 3D models and launch files
|
||||
for ABB IRB 120 manipulators. This includes the base model (120) and
|
||||
the 120T.
|
||||
</p>
|
||||
<p>
|
||||
Joint limits and max joint velocities are based on the information in the
|
||||
<a href="http://new.abb.com/products/robotics/industrial-robots/irb-120/irb-120-data">
|
||||
ABB IRB 120 technical data sheet</a> (Version: ROB0149EN_D, May 2012).
|
||||
All urdfs / xacros are based on the default motion and joint velocity
|
||||
limits, unless noted otherwise (ie: no support for high speed joints,
|
||||
extended / limited motion ranges or other options).
|
||||
</p>
|
||||
<p>
|
||||
Inertial and mass properties were calculated using 3D modelling software, based on the
|
||||
supplied <a href="http://new.abb.com/products/robotics/industrial-robots/irb-120/irb-120-cad">
|
||||
ABB IRB 120 CAD model</a>.
|
||||
</p>
|
||||
<p>
|
||||
Before using any of the configuration files and / or meshes included
|
||||
in this package, be sure to check they are correct for the particular
|
||||
robot model and configuration you intend to use them with.
|
||||
</p>
|
||||
</description>
|
||||
<author>Mark Culleton (Trinity College Dublin)</author>
|
||||
<author>Kevin Kelly (Trinity College Dublin)</author>
|
||||
<author>Levi Armstrong (SwRI)</author>
|
||||
<maintainer email="noreply@rosindustrial.org">ROS-Industrial community</maintainer>
|
||||
<license>Apache-2.0</license>
|
||||
|
||||
<url type="website">http://wiki.ros.org/abb_irb120_support</url>
|
||||
<url type="bugtracker">https://github.com/ros-industrial/abb/issues</url>
|
||||
<url type="repository">https://github.com/ros-industrial/abb</url>
|
||||
|
||||
<buildtool_depend>catkin</buildtool_depend>
|
||||
|
||||
<test_depend>roslaunch</test_depend>
|
||||
|
||||
<exec_depend>abb_driver</exec_depend>
|
||||
<exec_depend>abb_resources</exec_depend>
|
||||
<exec_depend>industrial_robot_client</exec_depend>
|
||||
<exec_depend>joint_state_publisher_gui</exec_depend>
|
||||
<exec_depend>robot_state_publisher</exec_depend>
|
||||
<exec_depend>rviz</exec_depend>
|
||||
<exec_depend>xacro</exec_depend>
|
||||
|
||||
<export>
|
||||
<architecture_independent/>
|
||||
</export>
|
||||
</package>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" ?>
|
||||
|
||||
<robot name="abb_irb120_3_58" xmlns:xacro="http://ros.org/wiki/xacro">
|
||||
<xacro:include filename="$(find abb_irb120_support)/urdf/irb120_3_58_macro.xacro"/>
|
||||
<xacro:abb_irb120_3_58 prefix=""/>
|
||||
</robot>
|
||||
@@ -0,0 +1,231 @@
|
||||
<?xml version="1.0"?>
|
||||
<robot xmlns:xacro="http://ros.org/wiki/xacro">
|
||||
<xacro:include filename="$(find abb_resources)/urdf/common_materials.xacro"/>
|
||||
|
||||
<xacro:macro name="abb_irb120_3_58" params="prefix">
|
||||
<!-- link list -->
|
||||
<link name="${prefix}base_link">
|
||||
<inertial>
|
||||
<mass value="6.215"/>
|
||||
<origin xyz="-0.04204 8.01E-05 0.07964" rpy="0 0 0"/>
|
||||
<inertia ixx="0.0247272" ixy="-8.0784E-05" ixz="0.00130902" iyy="0.0491285" iyz="-8.0419E-06" izz="0.0472376"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/base_link.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_orange />
|
||||
</visual>
|
||||
<collision>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/base_link.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_yellow />
|
||||
</collision>
|
||||
</link>
|
||||
<link name="${prefix}link_1">
|
||||
<inertial>
|
||||
<mass value="3.067" />
|
||||
<origin xyz="9.77E-05 -0.00012 0.23841" rpy="0 0 0"/>
|
||||
<inertia ixx="0.0142175" ixy="-1.28579E-05" ixz="-2.31364E-05" iyy="0.0144041" iyz="1.93404E-05" izz="0.0104533"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/link_1.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_orange />
|
||||
</visual>
|
||||
<collision>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/link_1.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_yellow />
|
||||
</collision>
|
||||
</link>
|
||||
<link name="${prefix}link_2">
|
||||
<inertial>
|
||||
<mass value="3.909"/>
|
||||
<origin xyz="0.00078 -0.00212 0.10124" rpy="0 0 0"/>
|
||||
<inertia ixx="0.0603111" ixy="9.83431E-06" ixz="5.72407E-05" iyy="0.041569" iyz="-0.00050497" izz="0.0259548"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/link_2.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_orange />
|
||||
</visual>
|
||||
<collision>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/link_2.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_yellow />
|
||||
</collision>
|
||||
</link>
|
||||
<link name="${prefix}link_3">
|
||||
<inertial>
|
||||
<mass value="2.944"/>
|
||||
<origin xyz="0.02281 0.00106 0.05791" rpy="0 0 0"/>
|
||||
<inertia ixx="0.00835606" ixy="-8.01545E-05" ixz="0.00142884" iyy="0.016713" iyz="-0.000182227" izz="0.0126984"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/link_3.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_orange />
|
||||
</visual>
|
||||
<collision>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/link_3.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_yellow />
|
||||
</collision>
|
||||
</link>
|
||||
<link name="${prefix}link_4">
|
||||
<inertial>
|
||||
<mass value="1.328"/>
|
||||
<origin xyz="0.2247 0.00015 0.00041" rpy="0 0 0"/>
|
||||
<inertia ixx="0.00284661" ixy="-2.12765E-05" ixz="-1.6435E-05" iyy="0.00401346" iyz="1.31336E-05" izz="0.0052535"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/link_4.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_orange />
|
||||
</visual>
|
||||
<collision>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/link_4.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_yellow />
|
||||
</collision>
|
||||
</link>
|
||||
<link name="${prefix}link_5">
|
||||
<inertial>
|
||||
<mass value="0.546"/>
|
||||
<origin xyz="-0.00109 3.68E-05 6.22E-05" rpy="0 0 0"/>
|
||||
<inertia ixx="0.000404891" ixy="1.61943E-06" ixz="8.46805E-07" iyy="0.000892825" iyz="-1.51792E-08" izz="0.000815468"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/link_5.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_orange />
|
||||
</visual>
|
||||
<collision>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/link_5.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_yellow />
|
||||
</collision>
|
||||
</link>
|
||||
<link name="${prefix}link_6">
|
||||
<inertial>
|
||||
<mass value="0.137"/>
|
||||
<origin xyz="-0.00706 -0.00017 -1.32E-06" rpy="0 0 0"/>
|
||||
<inertia ixx="0.001" ixy="0" ixz="0" iyy="0.001" iyz="0" izz="0.001"/>
|
||||
</inertial>
|
||||
<visual>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/visual/link_6.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_black />
|
||||
</visual>
|
||||
<collision>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="package://abb_irb120_support/meshes/irb120_3_58/collision/link_6.stl"/>
|
||||
</geometry>
|
||||
<xacro:material_abb_yellow />
|
||||
</collision>
|
||||
</link>
|
||||
<!-- end of link list -->
|
||||
|
||||
<!-- joint list -->
|
||||
<joint name="${prefix}joint_1" type="revolute">
|
||||
<origin rpy="0 0 0" xyz="0 0 0"/>
|
||||
<parent link="${prefix}base_link"/>
|
||||
<child link="${prefix}link_1"/>
|
||||
<limit effort="0" lower="-2.87979" upper="2.87979" velocity="4.36332"/>
|
||||
<axis xyz="0 0 1"/>
|
||||
<dynamics damping="0.0" friction="0.0"/>
|
||||
</joint>
|
||||
<joint name="${prefix}joint_2" type="revolute">
|
||||
<origin rpy="0 0 0" xyz="0 0 0.29"/>
|
||||
<parent link="${prefix}link_1"/>
|
||||
<child link="${prefix}link_2"/>
|
||||
<limit effort="0" lower="-1.91986" upper="1.91986" velocity="4.36332"/>
|
||||
<axis xyz="0 1 0"/>
|
||||
<dynamics damping="0.0" friction="0.0"/>
|
||||
</joint>
|
||||
<joint name="${prefix}joint_3" type="revolute">
|
||||
<origin rpy="0 0 0" xyz="0 0 0.27"/>
|
||||
<parent link="${prefix}link_2"/>
|
||||
<child link="${prefix}link_3"/>
|
||||
<limit effort="0" lower="-1.91986" upper="1.22173" velocity="4.36332"/>
|
||||
<axis xyz="0 1 0"/>
|
||||
<dynamics damping="0.0" friction="0.0"/>
|
||||
</joint>
|
||||
<joint name="${prefix}joint_4" type="revolute">
|
||||
<origin rpy="0 0 0" xyz="0 0 0.07"/>
|
||||
<parent link="${prefix}link_3"/>
|
||||
<child link="${prefix}link_4"/>
|
||||
<limit effort="0" lower="-2.79253" upper="2.79253" velocity="5.58505"/>
|
||||
<axis xyz="1 0 0"/>
|
||||
<dynamics damping="0.0" friction="0.0"/>
|
||||
</joint>
|
||||
<joint name="${prefix}joint_5" type="revolute">
|
||||
<origin rpy="0 0 0" xyz="0.302 0 0"/>
|
||||
<parent link="${prefix}link_4"/>
|
||||
<child link="${prefix}link_5"/>
|
||||
<limit effort="0" lower="-2.094395" upper="2.094395" velocity="5.58505"/>
|
||||
<axis xyz="0 1 0"/>
|
||||
<dynamics damping="0.0" friction="0.0"/>
|
||||
</joint>
|
||||
<joint name="${prefix}joint_6" type="revolute">
|
||||
<origin rpy="0 0 0" xyz="0.072 0 0"/>
|
||||
<parent link="${prefix}link_5"/>
|
||||
<child link="${prefix}link_6"/>
|
||||
<limit effort="0" lower="-6.98132" upper="6.98132" velocity="7.33038"/>
|
||||
<axis xyz="1 0 0"/>
|
||||
<dynamics damping="0.0" friction="0.0"/>
|
||||
</joint>
|
||||
<!-- end of joint list -->
|
||||
|
||||
<!-- ROS-Industrial 'base' frame: base_link to ABB World Coordinates transform -->
|
||||
<link name="${prefix}base" />
|
||||
<joint name="${prefix}base_link-base" type="fixed">
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<parent link="${prefix}base_link"/>
|
||||
<child link="${prefix}base"/>
|
||||
</joint>
|
||||
|
||||
<!-- ROS-Industrial 'flange' frame: attachment point for EEF models -->
|
||||
<link name="${prefix}flange"/>
|
||||
<joint type="fixed" name="${prefix}joint_6-flange">
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<parent link="${prefix}link_6"/>
|
||||
<child link="${prefix}flange"/>
|
||||
</joint>
|
||||
|
||||
<!-- ROS-Industrial 'tool0' frame: all-zeros tool frame -->
|
||||
<link name="${prefix}tool0" />
|
||||
<joint name="${prefix}link_6-tool0" type="fixed">
|
||||
<origin xyz="0 0 0" rpy="0 ${radians(90)} 0" />
|
||||
<parent link="${prefix}flange" />
|
||||
<child link="${prefix}tool0" />
|
||||
</joint>
|
||||
</xacro:macro>
|
||||
</robot>
|
||||
97
web/app/public/robot-assets/abb-irb120/provenance.json
Normal file
@@ -0,0 +1,97 @@
|
||||
{
|
||||
"repository": "https://github.com/ros-industrial/abb",
|
||||
"tag": "1.5.0",
|
||||
"commit": "eefdf01c956a6f2129aacb88d598201feff3cf19",
|
||||
"files": [
|
||||
{
|
||||
"path": "LICENSE",
|
||||
"bytes": 10280,
|
||||
"sha256": "074e6e32c86a4c0ef8b3ed25b721ca23aca83df277cd88106ef7177c354615ff"
|
||||
},
|
||||
{
|
||||
"path": "abb_irb120.urdf",
|
||||
"bytes": 8809,
|
||||
"sha256": "297ef0159f4e1e6606b0617fc010fafd2f702f510629b73d21e67aa0cb0dfca8"
|
||||
},
|
||||
{
|
||||
"path": "abb_irb120_support/meshes/irb120_3_58/visual/base_link.stl",
|
||||
"bytes": 685684,
|
||||
"sha256": "49a02590535dbfad67698375ee47f000ed078b8bb8594f9d4b1b083ee61a5223"
|
||||
},
|
||||
{
|
||||
"path": "abb_irb120_support/meshes/irb120_3_58/visual/link_1.stl",
|
||||
"bytes": 144484,
|
||||
"sha256": "402c5fc5107fbea74a23d519267c79b1e4800683065468d7f27e2933f7720a9a"
|
||||
},
|
||||
{
|
||||
"path": "abb_irb120_support/meshes/irb120_3_58/visual/link_2.stl",
|
||||
"bytes": 287084,
|
||||
"sha256": "e90166c9e96ccfbab5dd4d0e9d93a8826a5666b86fd91948412be52b4affecaa"
|
||||
},
|
||||
{
|
||||
"path": "abb_irb120_support/meshes/irb120_3_58/visual/link_3.stl",
|
||||
"bytes": 246684,
|
||||
"sha256": "e110970dba3b4f437afb08a908cebfb56e4d4ca4475f4a44050198d42bf22d03"
|
||||
},
|
||||
{
|
||||
"path": "abb_irb120_support/meshes/irb120_3_58/visual/link_4.stl",
|
||||
"bytes": 315084,
|
||||
"sha256": "09665ea995035a5e68d203d343cac7b78e5437d2ac7aa8c528dd6662700839b2"
|
||||
},
|
||||
{
|
||||
"path": "abb_irb120_support/meshes/irb120_3_58/visual/link_5.stl",
|
||||
"bytes": 277584,
|
||||
"sha256": "693fd935384f0cbbd0acfd52a8a54f7311a8461ba523d889d793d2a2e0525ee1"
|
||||
},
|
||||
{
|
||||
"path": "abb_irb120_support/meshes/irb120_3_58/visual/link_6.stl",
|
||||
"bytes": 44984,
|
||||
"sha256": "c38e09e1e787164fbeacb52105d0d3016a34eaa495063a474a64718647a6ffbc"
|
||||
},
|
||||
{
|
||||
"path": "abb_irb120_support/package.xml",
|
||||
"bytes": 2430,
|
||||
"sha256": "1d15e0dc351c46c8cb5e2b8d0cec7377fd7589b7a57ef52643c0e9426d7781bb"
|
||||
},
|
||||
{
|
||||
"path": "abb_irb120_support/urdf/irb120_3_58.xacro",
|
||||
"bytes": 227,
|
||||
"sha256": "bf1b16b2eadb2db4812893f553a9ab40549fca5aed86a9625bf7c601f4c048a5"
|
||||
},
|
||||
{
|
||||
"path": "abb_irb120_support/urdf/irb120_3_58_macro.xacro",
|
||||
"bytes": 8793,
|
||||
"sha256": "25f1b00a7388d02c35422b4a34b865a5f0ec1c76630edf6a613e56224bc74522"
|
||||
},
|
||||
{
|
||||
"path": "abb_resources/urdf/common_colours.xacro",
|
||||
"bytes": 2341,
|
||||
"sha256": "da5e23b29d6ee6a38ee85969f59310fad0dd6b5387e1d23516b2817882f0243a"
|
||||
},
|
||||
{
|
||||
"path": "abb_resources/urdf/common_materials.xacro",
|
||||
"bytes": 2407,
|
||||
"sha256": "4be8a1ba6cb0407d31c32143be106036777c74a869c2dc237f42704bc690d314"
|
||||
},
|
||||
{
|
||||
"path": "joints.json",
|
||||
"bytes": 3075,
|
||||
"sha256": "ffa2ff88780a9f68895ebc27c35267950d7d39c090d3b7a0a5ecb9a1652c909c"
|
||||
},
|
||||
{
|
||||
"path": "start-scene.blend",
|
||||
"bytes": 90044,
|
||||
"sha256": "35c36777a9546a88de5ecb237808fb0519d7ddb2550608123ed629fb9a949416"
|
||||
},
|
||||
{
|
||||
"path": "upstream-tag.json",
|
||||
"bytes": 378,
|
||||
"sha256": "7cd9f02d6d5faaff01dd1627a92a1a879c50f6b90794dddbfb0f4dd16fb3e51c"
|
||||
},
|
||||
{
|
||||
"path": "xacro-2.1.1-py3-none-any.whl",
|
||||
"bytes": 27087,
|
||||
"sha256": "c3b330ebd984a3bce6d6482e0047eae5c5333fedd49b30b9b6df863a086b35f7"
|
||||
}
|
||||
]
|
||||
}
|
||||
BIN
web/app/public/robot-assets/abb-irb120/start-scene.blend
Normal file
5
web/app/public/templates/NOTICE.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
General startup template copied without modification from:
|
||||
blender-5.2.0/release/datafiles/startup.blend
|
||||
|
||||
Distributed as part of the local Blender source and corresponding source offer.
|
||||
Used by File > New > General in Web Blender.
|
||||
BIN
web/app/public/templates/general.blend
Normal file
277
web/app/public/vendor/blender/CPYTHON-LICENSE.txt
vendored
Normal file
@@ -0,0 +1,277 @@
|
||||
A. HISTORY OF THE SOFTWARE
|
||||
==========================
|
||||
|
||||
Python was created in the early 1990s by Guido van Rossum at Stichting
|
||||
Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
|
||||
as a successor of a language called ABC. Guido remains Python's
|
||||
principal author, although it includes many contributions from others.
|
||||
|
||||
In 1995, Guido continued his work on Python at the Corporation for
|
||||
National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
|
||||
in Reston, Virginia where he released several versions of the
|
||||
software.
|
||||
|
||||
In May 2000, Guido and the Python core development team moved to
|
||||
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
|
||||
year, the PythonLabs team moved to Digital Creations, which became
|
||||
Zope Corporation. In 2001, the Python Software Foundation (PSF, see
|
||||
https://www.python.org/psf/) was formed, a non-profit organization
|
||||
created specifically to own Python-related Intellectual Property.
|
||||
Zope Corporation was a sponsoring member of the PSF.
|
||||
|
||||
All Python releases are Open Source (see https://opensource.org for
|
||||
the Open Source Definition). Historically, most, but not all, Python
|
||||
releases have also been GPL-compatible; the table below summarizes
|
||||
the various releases.
|
||||
|
||||
Release Derived Year Owner GPL-
|
||||
from compatible? (1)
|
||||
|
||||
0.9.0 thru 1.2 1991-1995 CWI yes
|
||||
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
|
||||
1.6 1.5.2 2000 CNRI no
|
||||
2.0 1.6 2000 BeOpen.com no
|
||||
1.6.1 1.6 2001 CNRI yes (2)
|
||||
2.1 2.0+1.6.1 2001 PSF no
|
||||
2.0.1 2.0+1.6.1 2001 PSF yes
|
||||
2.1.1 2.1+2.0.1 2001 PSF yes
|
||||
2.1.2 2.1.1 2002 PSF yes
|
||||
2.1.3 2.1.2 2002 PSF yes
|
||||
2.2 and above 2.1.1 2001-now PSF yes
|
||||
|
||||
Footnotes:
|
||||
|
||||
(1) GPL-compatible doesn't mean that we're distributing Python under
|
||||
the GPL. All Python licenses, unlike the GPL, let you distribute
|
||||
a modified version without making your changes open source. The
|
||||
GPL-compatible licenses make it possible to combine Python with
|
||||
other software that is released under the GPL; the others don't.
|
||||
|
||||
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
|
||||
because its license has a choice of law clause. According to
|
||||
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
|
||||
is "not incompatible" with the GPL.
|
||||
|
||||
Thanks to the many outside volunteers who have worked under Guido's
|
||||
direction to make these releases possible.
|
||||
|
||||
|
||||
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
|
||||
===============================================================
|
||||
|
||||
Python software and documentation are licensed under the
|
||||
Python Software Foundation License Version 2.
|
||||
|
||||
Starting with Python 3.8.6, examples, recipes, and other code in
|
||||
the documentation are dual licensed under the PSF License Version 2
|
||||
and the Zero-Clause BSD license.
|
||||
|
||||
Some software incorporated into Python is under different licenses.
|
||||
The licenses are listed with code falling under that license.
|
||||
|
||||
|
||||
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
|
||||
--------------------------------------------
|
||||
|
||||
1. This LICENSE AGREEMENT is between the Python Software Foundation
|
||||
("PSF"), and the Individual or Organization ("Licensee") accessing and
|
||||
otherwise using this software ("Python") in source or binary form and
|
||||
its associated documentation.
|
||||
|
||||
2. Subject to the terms and conditions of this License Agreement, PSF hereby
|
||||
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
|
||||
analyze, test, perform and/or display publicly, prepare derivative works,
|
||||
distribute, and otherwise use Python alone or in any derivative version,
|
||||
provided, however, that PSF's License Agreement and PSF's notice of copyright,
|
||||
i.e., "Copyright (c) 2001-2024 Python Software Foundation; All Rights Reserved"
|
||||
are retained in Python alone or in any derivative version prepared by Licensee.
|
||||
|
||||
3. In the event Licensee prepares a derivative work that is based on
|
||||
or incorporates Python or any part thereof, and wants to make
|
||||
the derivative work available to others as provided herein, then
|
||||
Licensee hereby agrees to include in any such work a brief summary of
|
||||
the changes made to Python.
|
||||
|
||||
4. PSF is making Python available to Licensee on an "AS IS"
|
||||
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
|
||||
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
6. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
7. Nothing in this License Agreement shall be deemed to create any
|
||||
relationship of agency, partnership, or joint venture between PSF and
|
||||
Licensee. This License Agreement does not grant permission to use PSF
|
||||
trademarks or trade name in a trademark sense to endorse or promote
|
||||
products or services of Licensee, or any third party.
|
||||
|
||||
8. By copying, installing or otherwise using Python, Licensee
|
||||
agrees to be bound by the terms and conditions of this License
|
||||
Agreement.
|
||||
|
||||
|
||||
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
|
||||
-------------------------------------------
|
||||
|
||||
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
|
||||
|
||||
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
|
||||
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
|
||||
Individual or Organization ("Licensee") accessing and otherwise using
|
||||
this software in source or binary form and its associated
|
||||
documentation ("the Software").
|
||||
|
||||
2. Subject to the terms and conditions of this BeOpen Python License
|
||||
Agreement, BeOpen hereby grants Licensee a non-exclusive,
|
||||
royalty-free, world-wide license to reproduce, analyze, test, perform
|
||||
and/or display publicly, prepare derivative works, distribute, and
|
||||
otherwise use the Software alone or in any derivative version,
|
||||
provided, however, that the BeOpen Python License is retained in the
|
||||
Software, alone or in any derivative version prepared by Licensee.
|
||||
|
||||
3. BeOpen is making the Software available to Licensee on an "AS IS"
|
||||
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
|
||||
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
|
||||
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
|
||||
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
5. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
6. This License Agreement shall be governed by and interpreted in all
|
||||
respects by the law of the State of California, excluding conflict of
|
||||
law provisions. Nothing in this License Agreement shall be deemed to
|
||||
create any relationship of agency, partnership, or joint venture
|
||||
between BeOpen and Licensee. This License Agreement does not grant
|
||||
permission to use BeOpen trademarks or trade names in a trademark
|
||||
sense to endorse or promote products or services of Licensee, or any
|
||||
third party. As an exception, the "BeOpen Python" logos available at
|
||||
http://www.pythonlabs.com/logos.html may be used according to the
|
||||
permissions granted on that web page.
|
||||
|
||||
7. By copying, installing or otherwise using the software, Licensee
|
||||
agrees to be bound by the terms and conditions of this License
|
||||
Agreement.
|
||||
|
||||
|
||||
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
|
||||
---------------------------------------
|
||||
|
||||
1. This LICENSE AGREEMENT is between the Corporation for National
|
||||
Research Initiatives, having an office at 1895 Preston White Drive,
|
||||
Reston, VA 20191 ("CNRI"), and the Individual or Organization
|
||||
("Licensee") accessing and otherwise using Python 1.6.1 software in
|
||||
source or binary form and its associated documentation.
|
||||
|
||||
2. Subject to the terms and conditions of this License Agreement, CNRI
|
||||
hereby grants Licensee a nonexclusive, royalty-free, world-wide
|
||||
license to reproduce, analyze, test, perform and/or display publicly,
|
||||
prepare derivative works, distribute, and otherwise use Python 1.6.1
|
||||
alone or in any derivative version, provided, however, that CNRI's
|
||||
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
|
||||
1995-2001 Corporation for National Research Initiatives; All Rights
|
||||
Reserved" are retained in Python 1.6.1 alone or in any derivative
|
||||
version prepared by Licensee. Alternately, in lieu of CNRI's License
|
||||
Agreement, Licensee may substitute the following text (omitting the
|
||||
quotes): "Python 1.6.1 is made available subject to the terms and
|
||||
conditions in CNRI's License Agreement. This Agreement together with
|
||||
Python 1.6.1 may be located on the internet using the following
|
||||
unique, persistent identifier (known as a handle): 1895.22/1013. This
|
||||
Agreement may also be obtained from a proxy server on the internet
|
||||
using the following URL: http://hdl.handle.net/1895.22/1013".
|
||||
|
||||
3. In the event Licensee prepares a derivative work that is based on
|
||||
or incorporates Python 1.6.1 or any part thereof, and wants to make
|
||||
the derivative work available to others as provided herein, then
|
||||
Licensee hereby agrees to include in any such work a brief summary of
|
||||
the changes made to Python 1.6.1.
|
||||
|
||||
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
|
||||
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
|
||||
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
|
||||
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||
|
||||
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
|
||||
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||
|
||||
6. This License Agreement will automatically terminate upon a material
|
||||
breach of its terms and conditions.
|
||||
|
||||
7. This License Agreement shall be governed by the federal
|
||||
intellectual property law of the United States, including without
|
||||
limitation the federal copyright law, and, to the extent such
|
||||
U.S. federal law does not apply, by the law of the Commonwealth of
|
||||
Virginia, excluding Virginia's conflict of law provisions.
|
||||
Notwithstanding the foregoing, with regard to derivative works based
|
||||
on Python 1.6.1 that incorporate non-separable material that was
|
||||
previously distributed under the GNU General Public License (GPL), the
|
||||
law of the Commonwealth of Virginia shall govern this License
|
||||
Agreement only as to issues arising under or with respect to
|
||||
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
|
||||
License Agreement shall be deemed to create any relationship of
|
||||
agency, partnership, or joint venture between CNRI and Licensee. This
|
||||
License Agreement does not grant permission to use CNRI trademarks or
|
||||
trade name in a trademark sense to endorse or promote products or
|
||||
services of Licensee, or any third party.
|
||||
|
||||
8. By clicking on the "ACCEPT" button where indicated, or by copying,
|
||||
installing or otherwise using Python 1.6.1, Licensee agrees to be
|
||||
bound by the terms and conditions of this License Agreement.
|
||||
|
||||
ACCEPT
|
||||
|
||||
|
||||
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
|
||||
--------------------------------------------------
|
||||
|
||||
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
|
||||
The Netherlands. All rights reserved.
|
||||
|
||||
Permission to use, copy, modify, and distribute this software and its
|
||||
documentation for any purpose and without fee is hereby granted,
|
||||
provided that the above copyright notice appear in all copies and that
|
||||
both that copyright notice and this permission notice appear in
|
||||
supporting documentation, and that the name of Stichting Mathematisch
|
||||
Centrum or CWI not be used in advertising or publicity pertaining to
|
||||
distribution of the software without specific, written prior
|
||||
permission.
|
||||
|
||||
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
|
||||
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
|
||||
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
||||
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
|
||||
----------------------------------------------------------------------
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
BIN
web/app/public/vendor/blender/modules/pthread/web_engine.primary.wasm
vendored
Normal file
BIN
web/app/public/vendor/blender/modules/single/web_engine.primary.wasm
vendored
Normal file
2
web/app/public/vendor/blender/web_engine.js
vendored
BIN
web/app/public/vendor/blender/web_engine.wasm
vendored
373
web/app/public/vendor/pyodide/LICENSE-MPL-2.0
vendored
Normal file
@@ -0,0 +1,373 @@
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under this License. Except to the extent prohibited by statute
|
||||
or regulation, such description must be sufficiently detailed for a
|
||||
recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
125
web/app/public/vendor/pyodide/package.json
vendored
Normal file
@@ -0,0 +1,125 @@
|
||||
{
|
||||
"name": "pyodide",
|
||||
"version": "314.0.4",
|
||||
"description": "The Pyodide JavaScript package",
|
||||
"keywords": [
|
||||
"python",
|
||||
"webassembly"
|
||||
],
|
||||
"homepage": "https://github.com/pyodide/pyodide",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/pyodide/pyodide.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/pyodide/pyodide/issues"
|
||||
},
|
||||
"license": "MPL-2.0",
|
||||
"dependencies": {
|
||||
"@types/emscripten": "^1.41.4",
|
||||
"ws": "^8.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "2.1.1",
|
||||
"@playwright/test": "^1.55.1",
|
||||
"@types/assert": "^1.5.6",
|
||||
"@types/expect": "^24.3.0",
|
||||
"@types/node": "^20.8.4",
|
||||
"@types/ws": "^8.5.3",
|
||||
"cross-env": "^7.0.3",
|
||||
"dts-bundle-generator": "^8.1.1",
|
||||
"esbuild": "^0.25.0",
|
||||
"express": "^4.17.3",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"nyc": "^15.1.0",
|
||||
"playwright": "^1.55.1",
|
||||
"prettier": "^2.2.1",
|
||||
"tsd": "^0.24.1",
|
||||
"tsx": "^4.20.5",
|
||||
"typedoc": "^0.27.9",
|
||||
"typescript": "5.8",
|
||||
"wabt": "^1.0.32"
|
||||
},
|
||||
"main": "pyodide.js",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./pyodide.d.ts",
|
||||
"require": "./pyodide.js",
|
||||
"import": "./pyodide.mjs"
|
||||
},
|
||||
"./ffi": {
|
||||
"types": "./ffi.d.ts"
|
||||
},
|
||||
"./pyodide.asm.wasm": "./pyodide.asm.wasm",
|
||||
"./pyodide.asm.mjs": "./pyodide.asm.mjs",
|
||||
"./python_stdlib.zip": "./python_stdlib.zip",
|
||||
"./pyodide.mjs": "./pyodide.mjs",
|
||||
"./pyodide.js": "./pyodide.js",
|
||||
"./package.json": "./package.json",
|
||||
"./pyodide-lock.json": "./pyodide-lock.json"
|
||||
},
|
||||
"files": [
|
||||
"pyodide.asm.mjs",
|
||||
"pyodide.asm.wasm",
|
||||
"python_stdlib.zip",
|
||||
"pyodide.mjs",
|
||||
"pyodide.js.map",
|
||||
"pyodide.mjs.map",
|
||||
"pyodide.d.ts",
|
||||
"ffi.d.ts",
|
||||
"pyodide-lock.json",
|
||||
"console.html",
|
||||
"console-v2.html"
|
||||
],
|
||||
"browser": {
|
||||
"child_process": false,
|
||||
"crypto": false,
|
||||
"fs": false,
|
||||
"fs/promises": false,
|
||||
"path": false,
|
||||
"url": false,
|
||||
"vm": false,
|
||||
"ws": false
|
||||
},
|
||||
"scripts": {
|
||||
"build-inner": "node esbuild.config.inner.mjs",
|
||||
"build": "tsc --noEmit && node esbuild.config.outer.mjs",
|
||||
"test": "npm-run-all test:*",
|
||||
"test:unit": "cross-env TEST_NODE=1 node --import tsx --experimental-wasm-stack-switching --test 'test/unit/**/*.test.*'",
|
||||
"test:node": "cross-env TEST_NODE=1 npx playwright test",
|
||||
"test:browser": "npx playwright test",
|
||||
"tsc": "tsc --noEmit",
|
||||
"coverage": "cross-env TEST_NODE=1 npm-run-all coverage:*",
|
||||
"coverage:build": "nyc npm run test:node"
|
||||
},
|
||||
"nyc": {
|
||||
"reporter": [
|
||||
"html",
|
||||
"text-summary"
|
||||
],
|
||||
"include": [
|
||||
"*.ts"
|
||||
],
|
||||
"all": true,
|
||||
"clean": true,
|
||||
"cache": false,
|
||||
"instrument": false,
|
||||
"checkCoverage": true,
|
||||
"statements": 95,
|
||||
"functions": 95,
|
||||
"branches": 80,
|
||||
"lines": 95
|
||||
},
|
||||
"tsd": {
|
||||
"compilerOptions": {
|
||||
"lib": [
|
||||
"ES2017",
|
||||
"DOM"
|
||||
]
|
||||
}
|
||||
},
|
||||
"types": "./pyodide.d.ts",
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
}
|
||||
1
web/app/public/vendor/pyodide/pyodide-lock.json
vendored
Normal file
2
web/app/public/vendor/pyodide/pyodide.asm.mjs
vendored
Normal file
BIN
web/app/public/vendor/pyodide/pyodide.asm.wasm
vendored
Executable file
4
web/app/public/vendor/pyodide/pyodide.mjs
vendored
Normal file
BIN
web/app/public/vendor/pyodide/python_stdlib.zip
vendored
Normal file
46
web/app/public/vendor/pyodide/runtime-manifest.json
vendored
Normal file
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"status": "COPIED_UNVERIFIED",
|
||||
"validation": "NOT_RUN",
|
||||
"source": "/home/mes123456/workingRobotDKToWeb/public/wasm/pyodide",
|
||||
"package": "314.0.4",
|
||||
"python": "3.14.0",
|
||||
"abi": "2026_0",
|
||||
"files": [
|
||||
{
|
||||
"path": "pyodide.mjs",
|
||||
"sha256": "c75dd73bb0c70674135f9f4ab746c9b5316e9fe027cafacb2be445e658f04c92",
|
||||
"bytes": 17931
|
||||
},
|
||||
{
|
||||
"path": "pyodide.asm.mjs",
|
||||
"sha256": "fd7a3cefa122ff6463dcf2997961eb341250e4cc4ed60281448390f0a767cca2",
|
||||
"bytes": 1249500
|
||||
},
|
||||
{
|
||||
"path": "pyodide.asm.wasm",
|
||||
"sha256": "6c8986a8ee583401069aa403e76ee79d4633a1478ab11cea76030bc299aded9f",
|
||||
"bytes": 9596386
|
||||
},
|
||||
{
|
||||
"path": "python_stdlib.zip",
|
||||
"sha256": "b5ca2308e9fa72eda319889a1ddf086389e9f1234ced279cc71267fe9ba56e54",
|
||||
"bytes": 2545198
|
||||
},
|
||||
{
|
||||
"path": "pyodide-lock.json",
|
||||
"sha256": "c963d22858f6bcb8f41586a2142f03905ab370c88ea22a86a2736e95fac2a8f3",
|
||||
"bytes": 113804
|
||||
},
|
||||
{
|
||||
"path": "package.json",
|
||||
"sha256": "cd351ec0150e7b3dc65a64a72cc72686dac357b6f8c8183b6f3a41f9a5f959f9",
|
||||
"bytes": 2999
|
||||
},
|
||||
{
|
||||
"path": "LICENSE-MPL-2.0",
|
||||
"sha256": "fab3dd6bdab226f1c08630b1dd917e11fcb4ec5e1e020e2c16f83a0a13863e85",
|
||||
"bytes": 16726
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -9,8 +9,8 @@
|
||||
"resources": {
|
||||
"single": {
|
||||
"fileName": "web_engine.wasm",
|
||||
"url": "/vendor/blender/single/web_engine.wasm",
|
||||
"sha256": "7f3a50f1d41b2ac0e6366e84caaabefc3cdfc47c055d5ea459abec654da6fcc0"
|
||||
"url": "/vendor/blender/web_engine.wasm",
|
||||
"sha256": "37cc42b1c169289d063a4473165c3f8ab1c9ea1d8c9b68c71c1cd933963e32b5"
|
||||
},
|
||||
"pthread": {
|
||||
"fileName": "web_engine.wasm",
|
||||
@@ -26,8 +26,8 @@
|
||||
"resources": {
|
||||
"single": {
|
||||
"fileName": "web_engine.wasm",
|
||||
"url": "/vendor/blender/single/web_engine.wasm",
|
||||
"sha256": "7f3a50f1d41b2ac0e6366e84caaabefc3cdfc47c055d5ea459abec654da6fcc0"
|
||||
"url": "/vendor/blender/web_engine.wasm",
|
||||
"sha256": "37cc42b1c169289d063a4473165c3f8ab1c9ea1d8c9b68c71c1cd933963e32b5"
|
||||
},
|
||||
"pthread": {
|
||||
"fileName": "web_engine.wasm",
|
||||
@@ -43,8 +43,8 @@
|
||||
"resources": {
|
||||
"single": {
|
||||
"fileName": "web_engine.wasm",
|
||||
"url": "/vendor/blender/single/web_engine.wasm",
|
||||
"sha256": "7f3a50f1d41b2ac0e6366e84caaabefc3cdfc47c055d5ea459abec654da6fcc0"
|
||||
"url": "/vendor/blender/web_engine.wasm",
|
||||
"sha256": "37cc42b1c169289d063a4473165c3f8ab1c9ea1d8c9b68c71c1cd933963e32b5"
|
||||
},
|
||||
"pthread": {
|
||||
"fileName": "web_engine.wasm",
|
||||
@@ -55,13 +55,13 @@
|
||||
},
|
||||
{
|
||||
"id": "debug-incremental",
|
||||
"lifecycle": "debug",
|
||||
"lifecycle": "complete",
|
||||
"preload": false,
|
||||
"resources": {
|
||||
"single": {
|
||||
"fileName": "web_engine.wasm",
|
||||
"url": "/vendor/blender/web_engine.wasm",
|
||||
"sha256": "1c89a1fd0e00e30330d151cb9a42d9d54aabd5ed2c9ae45dd3b1961d9a0c75d5"
|
||||
"sha256": "37cc42b1c169289d063a4473165c3f8ab1c9ea1d8c9b68c71c1cd933963e32b5"
|
||||
},
|
||||
"pthread": {
|
||||
"fileName": "web_engine.wasm",
|
||||
@@ -72,7 +72,7 @@
|
||||
},
|
||||
{
|
||||
"id": "debug-incremental-secondary",
|
||||
"lifecycle": "debug",
|
||||
"lifecycle": "complete",
|
||||
"preload": false,
|
||||
"resources": {
|
||||
"single": {
|
||||
|
||||
24
web/app/src/app/AutosaveRecoveryDialog.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { StorageClient } from '../storage/StorageClient';
|
||||
import type { StorageSnapshotRecord } from '../../../protocol/storage';
|
||||
import { DesktopDialog } from './DesktopMenus';
|
||||
export interface RecoveryPointSelection { projectId: string; displayName: string; revision: number; sha256: string; }
|
||||
type ProjectChoice = { projectId: string; displayName: string };
|
||||
export function AutosaveRecoveryDialog({ projects, initialProjectId, storage, onClose, onRecover }: { projects: ProjectChoice[]; initialProjectId: string; storage: Pick<StorageClient, 'listSnapshots'>; onClose: () => void; onRecover: (selection: RecoveryPointSelection) => void }) {
|
||||
const [projectId, setProjectId] = useState(initialProjectId), [snapshots, setSnapshots] = useState<StorageSnapshotRecord[]>([]);
|
||||
const [selectedRevision, setSelectedRevision] = useState('');
|
||||
const [loading, setLoading] = useState(true), [error, setError] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
let active = true; setLoading(true); setError(null); setSnapshots([]); setSelectedRevision('');
|
||||
void storage.listSnapshots(projectId).then(result => { if (!active) return; if (result.projectId !== projectId || result.snapshots.some(item => item.projectId !== projectId)) throw new Error('恢复点所属项目已改变,请重新选择。'); const items = [...result.snapshots].sort((a, b) => b.revision - a.revision); setSnapshots(items); setSelectedRevision(items[0] ? String(items[0].revision) : ''); })
|
||||
.catch(reason => { if (active) setError(reason instanceof Error ? reason.message : String(reason)); }).finally(() => { if (active) setLoading(false); });
|
||||
return () => { active = false; };
|
||||
}, [projectId, storage]);
|
||||
const selected = snapshots.find(item => item.projectId === projectId && String(item.revision) === selectedRevision);
|
||||
return <DesktopDialog title="恢复自动保存" onClose={onClose}>
|
||||
<p>选择项目与自动恢复点。执行位置:浏览器存储 / 原生 WASM。</p>
|
||||
<label>恢复项目<select aria-label="恢复项目" value={projectId} onChange={event => setProjectId(event.target.value)}>{projects.map(project => <option key={project.projectId} value={project.projectId}>{project.displayName}</option>)}</select></label>
|
||||
<label>自动恢复点<select aria-label="自动恢复点" value={selectedRevision} disabled={loading || !snapshots.length} onChange={event => setSelectedRevision(event.target.value)}><option value="">选择自动恢复点</option>{snapshots.map(item => <option key={item.revision} value={String(item.revision)}>r{item.revision} · {item.createdAt} · {(item.bytes / 1024).toFixed(1)} KiB</option>)}</select></label>
|
||||
{loading ? <p role="status">正在读取自动恢复点…</p> : error ? <p role="alert">{error}</p> : !snapshots.length ? <p role="status">此项目暂无可用自动恢复点。</p> : null}
|
||||
<div><button type="button" onClick={onClose}>取消</button><button type="button" disabled={loading || !selected} onClick={() => { if (selected) onRecover({ projectId, displayName: projects.find(project => project.projectId === projectId)?.displayName ?? projectId, revision: selected.revision, sha256: selected.sha256 }); }}>恢复选中版本</button></div>
|
||||
</DesktopDialog>; }
|
||||
34
web/app/src/app/CameraPresetControls.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
type PresetEdit = { method: 'ADD'; name: string; useFocalLength: boolean } | { method: 'REMOVE'; path: string };
|
||||
export function CameraPresetControls({ disabled, canCreate, removable, onManage }: {
|
||||
disabled: boolean; canCreate: boolean; removable: Array<{ id: string; label: string }>;
|
||||
onManage: (edit: PresetEdit) => Promise<boolean>;
|
||||
}) {
|
||||
const [name, setName] = useState(''), [includeFocalLength, setIncludeFocalLength] = useState(false);
|
||||
const [selected, setSelected] = useState(''), [confirmRemove, setConfirmRemove] = useState(false);
|
||||
const [saving, setSaving] = useState(false), [message, setMessage] = useState(''); const pending = useRef(false);
|
||||
useEffect(() => { if (selected && !removable.some(item => item.id === selected)) { setSelected(''); setConfirmRemove(false); } }, [removable, selected]);
|
||||
const submit = async (edit: PresetEdit) => {
|
||||
if (disabled || pending.current) return;
|
||||
pending.current = true; setSaving(true); setMessage('');
|
||||
try { if (await onManage(edit)) { if (edit.method === 'ADD') setName(''); else { setSelected(''); setConfirmRemove(false); } } else setMessage('Preset change failed. Review the error and retry.'); }
|
||||
catch (error) { setMessage(error instanceof Error ? error.message : String(error)); }
|
||||
finally { pending.current = false; setSaving(false); }
|
||||
};
|
||||
const nameValid = !!name.trim() && new TextEncoder().encode(name).byteLength <= 63 && !/[/\\\u0000-\u001f]/.test(name); // eslint-disable-line no-control-regex -- Reject control characters in file and resource paths.
|
||||
return <fieldset disabled={disabled || saving} onKeyUp={event => event.stopPropagation()} onKeyDown={event => {
|
||||
event.stopPropagation(); if (event.key === 'Enter' && event.nativeEvent.isComposing) event.preventDefault();
|
||||
if (event.key === 'Escape' && !event.nativeEvent.isComposing && !pending.current) { event.preventDefault(); setConfirmRemove(false); setName(''); setMessage(''); }
|
||||
}}><legend>Manage Camera Presets</legend>
|
||||
<form onSubmit={event => { event.preventDefault(); if (canCreate && nameValid) void submit({ method: 'ADD', name: name.trim(), useFocalLength: includeFocalLength }); }}>
|
||||
<label>Preset Name<input value={name} maxLength={63} disabled={!canCreate} onChange={event => setName(event.target.value)} /></label>
|
||||
<label><input type="checkbox" checked={includeFocalLength} disabled={!canCreate} onChange={event => setIncludeFocalLength(event.target.checked)} />Include Focal Length</label>
|
||||
<button type="submit" disabled={!canCreate || !nameValid}>Create Preset</button><button type="button" onClick={() => { setName(''); setMessage(''); }}>Cancel</button>
|
||||
</form>
|
||||
<label>User Preset<select value={selected} onChange={event => { setSelected(event.target.value); setConfirmRemove(false); setMessage(''); }}>
|
||||
<option value="">Select a user preset</option>{removable.map(item => <option key={item.id} value={item.id}>{item.label}</option>)}
|
||||
</select></label><button type="button" disabled={!selected || !removable.some(item => item.id === selected)} onClick={() => setConfirmRemove(true)}>Remove Preset</button>
|
||||
{confirmRemove && <span role="group" aria-label="Confirm preset removal">Remove {removable.find(item => item.id === selected)?.label}? <button type="button" disabled={!removable.some(item => item.id === selected)} onClick={() => void submit({ method: 'REMOVE', path: selected })}>Confirm Remove</button><button type="button" onClick={() => setConfirmRemove(false)}>Cancel</button></span>}
|
||||
{message && <small role="alert">{message}</small>}
|
||||
</fieldset>;
|
||||
}
|
||||
80
web/app/src/app/CameraShaderBundle.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { EDITOR_RESOURCE_MAX_BYTES, SHADER_BUNDLE_MAX_FILES, shaderResourcePath } from '../../../protocol/editor-resource-path';
|
||||
import { absoluteShaderPath, prepareShaderIncludes, type ShaderSourceFile } from './shader-include-paths';
|
||||
export type ShaderBundleFile = ShaderSourceFile;
|
||||
export type ShaderBundleTransfer = { signal: AbortSignal; progress: (completed: number) => void; committing: () => void };
|
||||
export function CameraShaderBundle({ disabled, onApply }: {
|
||||
disabled: boolean; onApply: (files: ShaderBundleFile[], entry: string, batchId: string, transfer: ShaderBundleTransfer) => Promise<boolean>;
|
||||
}) {
|
||||
const [files, setFiles] = useState<ShaderBundleFile[]>([]), [entry, setEntry] = useState('');
|
||||
const [pathEdits, setPathEdits] = useState<Record<number, string>>({});
|
||||
const [sourceEdits, setSourceEdits] = useState<Record<number, string>>({});
|
||||
const hasDrafts = Object.keys(pathEdits).length > 0 || Object.keys(sourceEdits).length > 0;
|
||||
const [batchId, setBatchId] = useState(''), [message, setMessage] = useState(''), [busy, setBusy] = useState(false); const pending = useRef(false);
|
||||
const controller = useRef<AbortController | null>(null), [committing, setCommitting] = useState(false);
|
||||
useEffect(() => () => controller.current?.abort(), []);
|
||||
const select = (selected: FileList | null, append = false) => {
|
||||
if (!selected?.length || pending.current) return;
|
||||
if (selected.length > SHADER_BUNDLE_MAX_FILES) { setMessage('Choose a shader folder with at most 256 files'); return; }
|
||||
const next = [...(append ? files : []), ...Array.from(selected).map(file => ({ file, path: file.webkitRelativePath || file.name }))], id = crypto.randomUUID();
|
||||
try {
|
||||
if (next.length > SHADER_BUNDLE_MAX_FILES || next.reduce((bytes, item) => bytes + item.file.size, 0) > EDITOR_RESOURCE_MAX_BYTES) throw new Error('Choose up to 256 shader files totaling at most 256 MiB');
|
||||
const names = new Set<string>();
|
||||
for (const item of next) { shaderResourcePath({ batchId: id, relativePath: item.path }); if (names.has(item.path)) throw new Error('Duplicate shader path: ' + item.path + '. Map the existing file to its relative folder first, or choose their shared parent folder.'); names.add(item.path); }
|
||||
const entries = next.filter(item => item.file.size > 0 && /\.(osl|oso)$/.test(item.path));
|
||||
if (!entries.length) throw new Error('Choose a folder or files containing a nonempty .osl or .oso entry');
|
||||
setFiles(next); setPathEdits({}); setSourceEdits({}); setEntry(append && entries.some(item => item.path === entry) ? entry : entries.length === 1 ? entries[0].path : ''); setBatchId(id); setMessage('');
|
||||
} catch (error) { setMessage(error instanceof Error ? error.message : String(error)); }
|
||||
};
|
||||
const remap = (previous: string, next: string) => {
|
||||
if (disabled || pending.current) return false;
|
||||
try {
|
||||
shaderResourcePath({ batchId, relativePath: next });
|
||||
if (files.some(item => item.path !== previous && item.path === next)) throw new Error('Shader paths must be unique');
|
||||
setFiles(files.map(item => item.path === previous ? { ...item, path: next } : item)); if (entry === previous) setEntry(/\.(osl|oso)$/.test(next) ? next : ''); setBatchId(crypto.randomUUID()); setMessage(''); return true;
|
||||
} catch (error) { setMessage(error instanceof Error ? error.message : String(error)); return false; }
|
||||
};
|
||||
const mapSource = (index: number, value: string) => {
|
||||
if (disabled || pending.current) return;
|
||||
try {
|
||||
const sourcePath = value ? absoluteShaderPath(value) : undefined;
|
||||
if (sourcePath && files.some((item, position) => position !== index && item.sourcePath === sourcePath)) throw new Error('Original include path is already mapped to another file');
|
||||
setFiles(files.map((item, position) => position === index ? { ...item, sourcePath } : item)); setBatchId(crypto.randomUUID()); setMessage(''); setSourceEdits(current => { const next = { ...current }; delete next[index]; return next; });
|
||||
} catch (error) { setMessage(error instanceof Error ? error.message : String(error)); }
|
||||
};
|
||||
const submit = async () => {
|
||||
if (hasDrafts) { setMessage('Apply or discard the edited paths before uploading.'); return; }
|
||||
if (disabled || pending.current || !files.some(item => item.path === entry && item.file.size > 0 && /\.(osl|oso)$/.test(item.path))) return;
|
||||
const request = new AbortController(); controller.current = request; pending.current = true; setBusy(true); setCommitting(false); setMessage('Preparing shader files…');
|
||||
try {
|
||||
const prepared = await prepareShaderIncludes(files, request.signal, entry);
|
||||
const applied = await onApply(prepared, entry, batchId, { signal: request.signal, progress: count => setMessage(`Uploaded ${count} of ${prepared.length} files`), committing: () => { setCommitting(true); setMessage('Applying camera shader…'); } });
|
||||
setMessage(applied ? 'Shader folder applied.' : request.signal.aborted ? 'Upload cancelled. Selection retained.' : 'Shader folder was not fully applied. Review the Properties error; retry or choose files again.');
|
||||
} catch (error) { setMessage(error instanceof Error ? error.message : String(error)); }
|
||||
finally { controller.current = null; pending.current = false; setBusy(false); setCommitting(false); }
|
||||
};
|
||||
return <fieldset aria-label="Camera shader folder" onKeyDown={event => { event.stopPropagation(); if (event.key === 'Escape' && !committing) controller.current?.abort(); }} onKeyUp={event => event.stopPropagation()}>
|
||||
<legend>Shader Folder and Dependencies</legend>
|
||||
<p>Choose a folder and its main .osl or .oso file. Add dependencies and set paths relative to a shared root, such as shaders/camera.osl and include/common.h. For a quoted absolute #include, enter its Original Include Path on the matching file. Only uploaded text copies are adjusted; macros, texture paths and compiled .oso paths are not mapped.</p>
|
||||
<label>Choose Folder<input type="file" multiple ref={input => { input?.setAttribute('webkitdirectory', ''); }} disabled={disabled || busy} onChange={event => { select(event.currentTarget.files); event.currentTarget.value = ''; }} /></label>
|
||||
<label>Choose Files<input type="file" multiple disabled={disabled || busy} onChange={event => { select(event.currentTarget.files); event.currentTarget.value = ''; }} /></label>
|
||||
<label>Add Dependency Files<input type="file" multiple disabled={disabled || busy || !files.length || hasDrafts} onChange={event => { select(event.currentTarget.files, true); event.currentTarget.value = ''; }} /></label>
|
||||
<label>Add Dependency Folder<input type="file" multiple ref={input => { input?.setAttribute('webkitdirectory', ''); }} disabled={disabled || busy || !files.length || hasDrafts} onChange={event => { select(event.currentTarget.files, true); event.currentTarget.value = ''; }} /></label>
|
||||
<label>Shader Entry<select value={entry} disabled={disabled || busy} onChange={event => setEntry(event.target.value)}><option value="">Select .osl or .oso entry</option>
|
||||
{files.filter(item => item.file.size > 0 && /\.(osl|oso)$/.test(item.path)).map(item => <option key={item.path} value={item.path}>{item.path}</option>)}
|
||||
</select></label>
|
||||
<details><summary>Dependency Paths ({files.length})</summary>
|
||||
{files.map((item, index) => <div key={index}><label>{item.file.name} — Relative Path<input value={pathEdits[index] ?? item.path} disabled={disabled || busy} onChange={event => setPathEdits(current => ({ ...current, [index]: event.target.value }))} /></label>
|
||||
<button type="button" disabled={disabled || busy || pathEdits[index] === undefined} onClick={() => { if (remap(item.path, pathEdits[index] ?? item.path)) setPathEdits(current => { const next = { ...current }; delete next[index]; return next; }); }}>Apply Path</button>
|
||||
<label>Original Include Path (optional)<input value={sourceEdits[index] ?? item.sourcePath ?? ''} disabled={disabled || busy} onChange={event => setSourceEdits(current => ({ ...current, [index]: event.target.value }))} /></label>
|
||||
<button type="button" disabled={disabled || busy || sourceEdits[index] === undefined} onClick={() => mapSource(index, sourceEdits[index] ?? '')}>Apply Include Mapping</button>
|
||||
<button type="button" disabled={disabled || busy || hasDrafts} onClick={() => { setFiles(current => current.filter((_, position) => position !== index)); if (entry === item.path) setEntry(''); setBatchId(crypto.randomUUID()); setPathEdits({}); setSourceEdits({}); setMessage(''); }}>Remove File</button></div>)}
|
||||
<button type="button" disabled={disabled || busy || !hasDrafts} onClick={() => { setPathEdits({}); setSourceEdits({}); }}>Discard Path Edits</button>
|
||||
</details>
|
||||
<output>{files.length} files selected</output>
|
||||
<button type="button" disabled={disabled || busy || !entry} onClick={() => void submit()}>Apply Shader Folder</button>
|
||||
<button type="button" disabled={!busy || committing} onClick={() => controller.current?.abort()}>Cancel Upload</button>
|
||||
<button type="button" disabled={busy} onClick={() => { setFiles([]); setPathEdits({}); setSourceEdits({}); setEntry(''); setBatchId(''); setMessage(''); }}>Clear Selection</button>
|
||||
{message && <p role="status">{message}</p>}
|
||||
</fieldset>;
|
||||
}
|
||||
146
web/app/src/app/DesktopFileTransfer.tsx
Normal file
@@ -0,0 +1,146 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { WebEngineClient } from '../engine-client/WebEngineClient';
|
||||
import { readFileBytes } from '../../../protocol/file-byte-reader';
|
||||
import { desktopRelativeParts, DESKTOP_TRANSFER_MAX_BYTES, DESKTOP_TRANSFER_MAX_FILES, saveDesktopFolder } from './desktop-folder-transfer';
|
||||
|
||||
/** Preserve companion names; a drop can isolate its batch without overwriting live media. */
|
||||
export async function stageDesktopFiles(client: WebEngineClient, session: string,
|
||||
files: File[], prefix = '', cancelled: () => boolean = () => false,
|
||||
options: { restoreRoot?: boolean; progress?: (message: string) => void; signal?: AbortSignal } = {}): Promise<string[]> {
|
||||
if (!files.length || files.length > DESKTOP_TRANSFER_MAX_FILES) throw new Error(`请选择 1–${DESKTOP_TRANSFER_MAX_FILES} 个文件`);
|
||||
const relative = files.map(file => file.webkitRelativePath || file.name);
|
||||
const root = relative[0].split('/')[0];
|
||||
if (options.restoreRoot && relative.some(path => !path.startsWith(`${root}/`))) throw new Error('请选择完整的桌面保存文件夹');
|
||||
const paths = relative.map(path => prefix + (options.restoreRoot ? path.slice(root.length + 1) : path));
|
||||
for (const path of paths) desktopRelativeParts(path);
|
||||
if (new Set(paths).size !== paths.length) throw new Error('同一批文件中存在重复路径');
|
||||
for (const file of files) {
|
||||
if (file.size > DESKTOP_TRANSFER_MAX_BYTES) throw new Error(`${file.name}: 文件超过 256 MiB`);
|
||||
}
|
||||
let completed = 0;
|
||||
try { for (let index = 0; index < files.length; index++) {
|
||||
if (cancelled()) throw new Error('桌面文件传输已取消');
|
||||
const buffer = options.signal
|
||||
? await readFileBytes(files[index], { signal: options.signal, yieldControl: () => new Promise(resolve => setTimeout(resolve, 0)) })
|
||||
: await files[index].arrayBuffer();
|
||||
if (cancelled()) throw new Error('桌面文件传输已取消');
|
||||
await client.desktopFiles(session, 'upload', paths[index], buffer);
|
||||
completed++;
|
||||
options.progress?.(`已上传 ${completed}/${files.length} 个文件`);
|
||||
}
|
||||
if (cancelled()) throw new Error('桌面文件传输已取消');
|
||||
} catch (reason) {
|
||||
const detail = typeof reason === 'object' && reason && 'message' in reason ? String(reason.message) : String(reason);
|
||||
throw new Error(`已上传 ${completed}/${files.length} 个文件;${detail}`, { cause: reason });
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
/** Browser file access only; format parsing and export stay in Blender's WM. */
|
||||
export function DesktopFileTransfer({ client, session, attached, initiallyOpen = false }: {
|
||||
client: WebEngineClient; session: string; attached: boolean; initiallyOpen?: boolean;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(initiallyOpen);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [entries, setEntries] = useState<Array<{ path: string; size: number }>>([]);
|
||||
const [selected, setSelected] = useState('');
|
||||
const transfer = useRef<AbortController | null>(null);
|
||||
const owner = useRef({ client, session, attached, mounted: true });
|
||||
Object.assign(owner.current, { client, session, attached });
|
||||
useEffect(() => {
|
||||
owner.current.mounted = true;
|
||||
return () => { owner.current.mounted = false; transfer.current?.abort(); };
|
||||
}, [client, session, attached]);
|
||||
const run = async (action: (cancelled: () => boolean, signal: AbortSignal) => Promise<void>) => {
|
||||
if (transfer.current || !attached) return;
|
||||
const task = new AbortController();
|
||||
transfer.current = task;
|
||||
const current = () => owner.current.mounted && owner.current.client === client && owner.current.session === session && owner.current.attached === attached;
|
||||
const cancelled = () => task.signal.aborted || !current();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setMessage('');
|
||||
try { await action(cancelled, task.signal); if (current() && task.signal.aborted) setMessage('传输已取消,已完成的文件会保留。'); }
|
||||
catch (reason) { if (current()) {
|
||||
const detail = reason instanceof Error ? reason.message : typeof reason === 'object' && reason && 'message' in reason ? String(reason.message) : String(reason);
|
||||
if (task.signal.aborted) setMessage(`传输已取消。${detail};已完成的文件会保留。`); else setError(detail);
|
||||
} }
|
||||
finally {
|
||||
if (transfer.current === task) { transfer.current = null; if (owner.current.mounted) setBusy(false); }
|
||||
}
|
||||
};
|
||||
const refresh = async (cancelled: () => boolean) => {
|
||||
const result = await client.desktopFiles(session, 'list');
|
||||
if (cancelled()) return;
|
||||
setEntries(result.entries);
|
||||
setSelected(previous => result.entries.some(item => item.path === previous) ? previous : result.entries[0]?.path ?? '');
|
||||
};
|
||||
const upload = async (files: File[], cancelled: () => boolean, signal: AbortSignal, restoreRoot = false) => {
|
||||
try {
|
||||
const paths = await stageDesktopFiles(client, session, files, '', cancelled, { restoreRoot, signal, progress: value => { if (!cancelled()) setMessage(value); } });
|
||||
if (cancelled()) return;
|
||||
if (restoreRoot) setMessage(`已恢复 ${paths.length} 个文件及相对目录。请从 Blender 的 File → Open 打开 /browser/ 下对应的 .blend 文件。`);
|
||||
else setMessage(`已上传 ${paths.length} 个文件,可在 Blender 文件浏览器的 /browser/ 中打开。模型从 File → Import 导入;WAV、MP3、AAC、AC3、MP2、Matroska、FLAC 或 Ogg 音频从视频序列编辑器的 Add → Sound 添加。`);
|
||||
} finally {
|
||||
// A later companion can fail after earlier uploads succeeded. Keep the
|
||||
// actual directory visible instead of pretending the batch was atomic.
|
||||
if (!cancelled()) await refresh(cancelled).catch(() => { if (!cancelled()) setError('文件列表刷新失败,请稍后手动刷新查看已传输文件。'); });
|
||||
}
|
||||
};
|
||||
const download = async (cancelled: () => boolean) => {
|
||||
const result = await client.desktopFiles(session, 'download', selected);
|
||||
if (cancelled()) return;
|
||||
if (!result.buffer) throw new Error('文件下载未返回数据');
|
||||
const url = URL.createObjectURL(new Blob([result.buffer]));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = selected.split('/').at(-1) || 'download';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
};
|
||||
const saveFolder = async (cancelled: () => boolean) => {
|
||||
const result = await saveDesktopFolder(client, session, cancelled, value => { if (!cancelled()) setMessage(value); });
|
||||
if (!cancelled()) setMessage(result);
|
||||
};
|
||||
return <details open={expanded} onToggle={event => setExpanded(event.currentTarget.open)} style={{ flexShrink: 0, padding: '4px 8px' }} onKeyDown={event => event.stopPropagation()} onKeyUp={event => event.stopPropagation()}>
|
||||
<summary>桌面文件传输</summary>
|
||||
<p>保存桌面文件夹前,请在 Blender 中将当前 .blend 保存到 /browser/,并等待保存、导出或烘焙完成。保存文件夹会将 /browser/ 内的文件和相对目录写入所选位置下的新文件夹;传输期间请勿修改这些文件。未保存的编辑和 /browser/ 外的资源不包含在内。</p>
|
||||
<p>恢复时选择此前生成的 blender-… 文件夹,其内容会放回 /browser/,然后通过 File → Open 打开其中的 .blend。已有同名文件不会被覆盖;请先通过原生文件浏览器重命名或删除冲突文件。每批最多 2048 个文件,单个文件最多 256 MiB。</p>
|
||||
<p>恢复外部自动保存文件时,先上传 .blend 和所需依赖,再从原生 File → Recover → Auto Save 进入恢复窗口;按 Ctrl+L 可定位到 /browser/ 中对应目录。该流程调用 Blender 的原生文件恢复,区别于浏览器检查点。</p>
|
||||
<p>恢复默认关闭自动执行脚本。确需恢复可信工程的注册脚本或脚本驱动时,在原生文件选择器的操作选项中勾选 Trusted Source,再确认恢复;取消选择器不会执行该文件的脚本。此选项交由 Blender 原生恢复流程处理。</p>
|
||||
<p>“恢复上一次会话”读取原生临时目录中的 quit.blend,默认路径为 /browser/.autosave/quit.blend。请使用“退出并保存会话”或原生 File → Quit,并等到“会话已保存并退出”提示后再关闭页面;直接关闭标签页或浏览器进程可能中断异步写入。退出保存失败时可保留当前会话、备份文件或重试;文件缺失时恢复入口显示 Blender 的原生错误。</p>
|
||||
<p>/browser/ 文件在上传或原生操作完成后同步到本浏览器存储,重新打开页面时恢复;默认原生自动保存目录为 /browser/.autosave/。同一站点只允许一个原生编辑窗口写入。若同步失败,请先下载备份再关闭页面;清除浏览器数据会删除这些文件,建议定期保存桌面文件夹。</p>
|
||||
<p>上传 OBJ、PLY、STL 或 FBX 文件后,在 Blender 的 File → Import 中选择对应格式,在文件浏览器中打开 /browser/。OBJ 的 MTL、OBJ/FBX 的贴图可一并上传;上传文件夹可保留贴图的相对路径。OBJ、PLY 和 STL 可在 File → Export 中导出到 /browser/,然后刷新并下载生成的文件。</p>
|
||||
<p>WAV、MP3、AAC、AC3、MP2、Matroska、FLAC 或 Ogg 音频上传后,在视频序列编辑器中选择 Add → Sound,打开 /browser/ 下的文件。通过顶部 Render → Render Audio 将场景音频保存为 /browser/ 下的 WAV、MP3、AAC、AC3、MP2、Matroska、FLAC 或 Ogg 文件(Vorbis / Opus / FLAC),再刷新并下载;分离声道时可逐个下载生成的文件。MP3 支持单声道、立体声或分离声道输出;常用的 32000、44100、48000 Hz 可使用 32–320 kbit/s 的标准固定码率,较低采样率需降低码率。Opus 支持 8000、12000、16000、24000、48000 Hz;Vorbis 的 Bitrate 设置目标平均码率,实际文件大小随内容而变。Matroska 可选择音频编码器;AAC、AC3 和 MP2 使用各自对应的编码器。码率按每个输出文件计算;如果编码器不接受所选组合,请调整码率、采样率或声道数。</p>
|
||||
<fieldset disabled={busy || !attached} style={{ border: 0, padding: 0, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
|
||||
<label>上传文件 <input type="file" multiple onChange={event => {
|
||||
const files = Array.from(event.target.files ?? []);
|
||||
event.target.value = '';
|
||||
if (files.length) void run((cancelled, signal) => upload(files, cancelled, signal));
|
||||
}}/></label>
|
||||
<label>上传文件夹 <input type="file" multiple ref={input => { input?.setAttribute('webkitdirectory', ''); }} onChange={event => {
|
||||
const files = Array.from(event.target.files ?? []);
|
||||
event.target.value = '';
|
||||
if (files.length) void run((cancelled, signal) => upload(files, cancelled, signal));
|
||||
}}/></label>
|
||||
<button type="button" onClick={() => void run(refresh)}>刷新文件</button>
|
||||
<button type="button" onClick={() => void run(saveFolder)}>保存桌面文件夹</button>
|
||||
<label>恢复桌面文件夹 <input type="file" multiple ref={input => { input?.setAttribute('webkitdirectory', ''); }} onChange={event => {
|
||||
const files = Array.from(event.target.files ?? []); event.target.value = '';
|
||||
if (files.length) void run((cancelled, signal) => upload(files, cancelled, signal, true));
|
||||
}}/></label>
|
||||
<select aria-label="下载桌面文件" value={selected} onChange={event => setSelected(event.target.value)}>
|
||||
{!entries.length && <option value="">无文件</option>}
|
||||
{entries.map(item => <option key={item.path} value={item.path}>{item.path} ({item.size} bytes)</option>)}
|
||||
</select>
|
||||
<button type="button" disabled={!selected} onClick={() => void run(download)}>下载文件</button>
|
||||
</fieldset>
|
||||
{busy && <button type="button" onClick={() => { transfer.current?.abort(); setMessage('已请求取消,已完成的文件会保留。'); }}>取消传输</button>}
|
||||
{message && <output role="status">{message}</output>}
|
||||
{error && <output role="alert">{error}</output>}
|
||||
</details>;
|
||||
}
|
||||
83
web/app/src/app/DesktopMenus.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
import {useEffect,useLayoutEffect,useRef,useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {createIMECompositionState, reduceIMEComposition, shouldBlockOperatorShortcuts} from '../../../protocol/ime-composition';
|
||||
|
||||
export interface DesktopMenuItem {label:string;action?:()=>void;children?:DesktopMenuItem[];disabled?:boolean;reason?:string;shortcut?:string;separator?:boolean;checked?:boolean}
|
||||
export function DesktopMenu({label,items,open,onToggle,onClose,className=''}:{label:string;items:DesktopMenuItem[];open?:boolean;onToggle?:()=>void;onClose?:()=>void;className?:string}){
|
||||
const [local,setLocal]=useState(false),[path,setPath]=useState<number[]>([]),[position,setPosition]=useState({left:0,top:0});
|
||||
const trigger=useRef<HTMLButtonElement>(null),panel=useRef<HTMLDivElement>(null),active=open??local;
|
||||
const close=()=>{setLocal(false);setPath([]);onClose?.();trigger.current?.focus();};
|
||||
let entries=items;let title=label;for(const index of path){title=entries[index]?.label??label;entries=entries[index]?.children??[];}
|
||||
useLayoutEffect(()=>{if(active){const bounds=trigger.current?.getBoundingClientRect();if(bounds)setPosition({left:Math.max(4,Math.min(bounds.left,window.innerWidth-284)),top:bounds.bottom+2});panel.current?.querySelector<HTMLElement>('[role^="menuitem"]:not(:disabled)')?.focus();}},[active,path.length]);
|
||||
useEffect(()=>{if(!active)return;const click=(event:PointerEvent)=>{const target=event.target as Node;if(!panel.current?.contains(target)&&!trigger.current?.contains(target))close();};document.addEventListener('pointerdown',click);return()=>document.removeEventListener('pointerdown',click);},[active]);
|
||||
return <span className={'desktop-menu-trigger '+className}><button ref={trigger} type="button" aria-label={label} aria-haspopup="menu" aria-expanded={active} onClick={()=>{setPath([]);if(onToggle)onToggle();else setLocal(!active);}}>{label}</button>{active?createPortal(
|
||||
<div ref={panel} role="menu" aria-label={title} className="desktop-menu-panel" style={{left:position.left,top:position.top,maxHeight:`calc(100vh - ${position.top+8}px)`}} onKeyDown={event=>{
|
||||
event.stopPropagation();const controls=Array.from(panel.current?.querySelectorAll<HTMLButtonElement>('[role^="menuitem"]:not(:disabled)')??[]),index=controls.indexOf(document.activeElement as HTMLButtonElement);
|
||||
if(event.key==='Escape'){event.preventDefault();close();}
|
||||
else if(event.key==='ArrowLeft'&&path.length){event.preventDefault();setPath(path.slice(0,-1));}
|
||||
else if(['ArrowDown','ArrowUp','Home','End'].includes(event.key)){event.preventDefault();controls[event.key==='Home'?0:event.key==='End'?controls.length-1:(index+(event.key==='ArrowDown'?1:-1)+controls.length)%controls.length]?.focus();}
|
||||
else if(event.key==='ArrowRight'){const target=document.activeElement as HTMLButtonElement;if(target?.getAttribute('aria-haspopup')==='menu'){event.preventDefault();target.click();}}
|
||||
else if(event.key==='Tab'){event.preventDefault();close();}
|
||||
}}>
|
||||
{path.length?<button type="button" role="menuitem" className="desktop-menu-back" onClick={()=>setPath(path.slice(0,-1))}>‹ {title}</button>:null}
|
||||
{entries.map((item,index)=>item.separator?<div key={index} role="separator"/>:<button key={index} type="button" role={item.checked===undefined?'menuitem':'menuitemcheckbox'} aria-label={item.label} aria-checked={item.checked} disabled={item.disabled} title={item.reason} aria-haspopup={item.children?'menu':undefined} onClick={()=>{if(item.children)setPath([...path,index]);else{close();item.action?.();}}}><span>{item.checked===true?'✓ ':''}{item.label}</span><span className="desktop-menu-shortcut">{item.children?'›':item.shortcut??''}</span>{item.disabled&&item.reason?<small>{item.reason}</small>:null}</button>)}
|
||||
</div>,document.body):null}</span>;
|
||||
}
|
||||
|
||||
// Disabled fieldsets and hidden panels must not become modal Tab destinations.
|
||||
function dialogControls(dialog: HTMLDivElement): HTMLElement[] {
|
||||
return Array.from(dialog.querySelectorAll<HTMLElement>(
|
||||
'button,input,textarea,select,a[href],[tabindex],[contenteditable]'
|
||||
)).filter(item => item.tabIndex >= 0 && !item.matches(':disabled,[aria-disabled="true"]') &&
|
||||
!item.closest('[hidden],[inert]') && item.getClientRects().length > 0 &&
|
||||
getComputedStyle(item).visibility !== 'hidden');
|
||||
}
|
||||
|
||||
export function DesktopDialog({title,onClose,children}:{title:string;onClose:()=>void;children:React.ReactNode}){
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const composition = useRef(createIMECompositionState());
|
||||
useEffect(() => {
|
||||
const before = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
const dialog = ref.current;
|
||||
if (!dialog) return;
|
||||
const controls = dialogControls(dialog);
|
||||
// Rename/save-as should put the cursor in the editable field, not Close.
|
||||
(controls.find(item => item.matches('input,textarea,select,[contenteditable="true"]')) ??
|
||||
controls[0] ?? dialog).focus();
|
||||
return () => {
|
||||
if (before?.isConnected) before.focus();
|
||||
};
|
||||
}, []);
|
||||
return <div className="desktop-dialog-backdrop"
|
||||
onCompositionStart={event => {
|
||||
composition.current = reduceIMEComposition(composition.current, {type:'compositionstart',data:event.data});
|
||||
}}
|
||||
onCompositionEnd={event => {
|
||||
composition.current = reduceIMEComposition(composition.current, {type:'compositionend',data:event.data});
|
||||
}}
|
||||
onBlur={event => {
|
||||
if (event.target !== event.relatedTarget) composition.current = createIMECompositionState();
|
||||
}}
|
||||
onKeyDown={event => {
|
||||
event.stopPropagation();
|
||||
// Escape can dismiss the IME candidate list without cancelling this form.
|
||||
if (shouldBlockOperatorShortcuts(composition.current, event.nativeEvent.isComposing) ||
|
||||
event.keyCode === 229) return;
|
||||
if (event.defaultPrevented) return;
|
||||
if (event.key === 'Escape') { event.preventDefault(); onClose(); return; }
|
||||
if (event.key !== 'Tab' || !ref.current) return;
|
||||
const controls = dialogControls(ref.current);
|
||||
const index = controls.indexOf(document.activeElement as HTMLElement);
|
||||
if (!controls.length) { event.preventDefault(); ref.current.focus(); }
|
||||
else if (index < 0 || (!event.shiftKey && index === controls.length - 1) ||
|
||||
(event.shiftKey && index === 0)) {
|
||||
event.preventDefault();
|
||||
controls[event.shiftKey ? controls.length - 1 : 0].focus();
|
||||
}
|
||||
}}>
|
||||
<div ref={ref} role="dialog" aria-modal="true" aria-label={title} tabIndex={-1} className="desktop-dialog">
|
||||
<header><h2>{title}</h2><button type="button" aria-label={`关闭${title}`} title="关闭" onClick={onClose}>×</button></header>
|
||||
{children}
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
158
web/app/src/app/DesktopWorkspace.tsx
Normal file
@@ -0,0 +1,158 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {NativeSessionClient} from '../engine-client/NativeSessionClient';
|
||||
import {NativeResourceClient} from '../engine-client/NativeResourceClient';
|
||||
import type {NativeDesktopEvent,NativeSessionCommand} from '../../../protocol/native-workflow';
|
||||
import {recoverDesktop,saveDesktop} from './desktop-workspace-storage';
|
||||
|
||||
type SessionFiles=Awaited<ReturnType<NativeSessionClient['files']>>;
|
||||
function download(blob:Blob,name:string){const url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download=name;link.click();setTimeout(()=>URL.revokeObjectURL(url),30000);}
|
||||
|
||||
export function DesktopWorkspace(){
|
||||
const [phase,setPhase]=useState('STARTING'),[error,setError]=useState(''),[busy,setBusy]=useState(false),[picture,setPicture]=useState('');
|
||||
const [persisting,setPersisting]=useState(false);
|
||||
const [files,setFiles]=useState<SessionFiles>({files:[]}),[drawer,setDrawer]=useState(false),[fit,setFit]=useState(true),[savedAt,setSavedAt]=useState<number|null>(null);
|
||||
const [size,setSize]=useState({width:1280,height:900}),[cursor,setCursor]=useState(false),[restart,setRestart]=useState(0);
|
||||
const client=useRef<NativeSessionClient|null>(null),resources=useRef<NativeResourceClient|null>(null),active=useRef(false),locked=useRef(false),unsaved=useRef(false),pending=useRef<NativeDesktopEvent[]>([]);
|
||||
const keyboard=useRef<HTMLTextAreaElement>(null),surface=useRef<HTMLDivElement>(null),upload=useRef<HTMLInputElement>(null),folder=useRef<HTMLInputElement>(null),image=useRef<HTMLImageElement>(null);
|
||||
const slot=useRef(''),composition=useRef(false),held=useRef(new Set<string>()),pointer=useRef(false),urlRef=useRef(''),inputGeneration=useRef(0),saving=useRef(false),savedSequence=useRef(0),lastComposition=useRef({text:'',at:0});
|
||||
const wheel=useRef({x:0,y:0});
|
||||
const flush=async()=>{const session=client.current;if(!session)return;while(pending.current.length)await session.events(pending.current.splice(0,64));};
|
||||
const push=(event:NativeDesktopEvent)=>{
|
||||
if(phase!=='READY')return;
|
||||
if(locked.current&&event.type!=='release')return;
|
||||
if(event.type!=='move'&&event.type!=='release'){unsaved.current=true;inputGeneration.current++;}
|
||||
if(event.type==='move'&&pending.current.at(-1)?.type==='move')pending.current[pending.current.length-1]=event;
|
||||
else if(pending.current.length<256)pending.current.push(event);
|
||||
else pending.current=[{type:'release'}];
|
||||
};
|
||||
const execute=async(command:NativeSessionCommand)=>{
|
||||
const session=client.current;if(!session||locked.current)throw new Error('SESSION_BUSY');
|
||||
locked.current=true;setBusy(true);
|
||||
try{await flush();return await session.execute(command);}finally{locked.current=false;if(active.current)setBusy(false);}
|
||||
};
|
||||
const checkpoint=async(deliver:boolean)=>{
|
||||
if(locked.current||saving.current||pointer.current||held.current.size)return;
|
||||
const session=client.current;if(!session)return;
|
||||
saving.current=true;setPersisting(true);const generation=inputGeneration.current;
|
||||
try{
|
||||
const result=await execute({kind:deliver?'download-project':'commit'});
|
||||
const blend=result.files.find(file=>file.artifact.mime==='application/x-blender');
|
||||
if(!blend)throw new Error('DESKTOP_CHECKPOINT_MISSING');
|
||||
const id=crypto.randomUUID(),resourceProject=`desktop-${slot.current}-${id}`,saved=Date.now();
|
||||
const resourceClient=resources.current!;resourceClient.setProject(resourceProject);await resourceClient.adopt(result.resources);
|
||||
const removed=await saveDesktop({id,slot:slot.current,savedAt:saved,blend:new Blob([blend.bytes],{type:'application/x-blender'}),resourceProject});
|
||||
for(const project of removed)await NativeResourceClient.removeStoredProject(project);
|
||||
if(!active.current)return;setSavedAt(saved);if(inputGeneration.current===generation)unsaved.current=false;
|
||||
if(deliver){const artifact=result.files.find(file=>file.artifact.id.startsWith('project-'));if(artifact)download(new Blob([artifact.bytes],{type:artifact.artifact.mime}),artifact.artifact.name);}
|
||||
return true;
|
||||
}catch(reason){if(!String(reason).includes('SESSION_MODAL_ACTIVE_')||deliver)setError(String(reason));}
|
||||
finally{saving.current=false;if(active.current)setPersisting(false);}
|
||||
};
|
||||
useEffect(()=>{
|
||||
active.current=true;let stopped=false,disconnected=false,screenFailures=0,timer:ReturnType<typeof setTimeout>,fileTimer:ReturnType<typeof setTimeout>,eventTimer:ReturnType<typeof setInterval>,backupTimer:ReturnType<typeof setInterval>;
|
||||
const controller=new AbortController(),session=new NativeSessionClient(),resourceClient=new NativeResourceClient();client.current=session;resources.current=resourceClient;
|
||||
const start=async()=>{
|
||||
try{
|
||||
setPhase('STARTING');setError('');
|
||||
const requested=new URLSearchParams(location.search).get('desktopSlot');
|
||||
let key=requested&&/^[a-f0-9-]{36}$/.test(requested)?requested:sessionStorage.getItem('blender-desktop-slot');
|
||||
if(!key)key=crypto.randomUUID();sessionStorage.setItem('blender-desktop-slot',key);slot.current=key;
|
||||
const recovery=await recoverDesktop(key);if(stopped)return;
|
||||
let source:ArrayBuffer;
|
||||
if(recovery){resourceClient.setProject(recovery.resourceProject);source=await recovery.blend.arrayBuffer();setSavedAt(recovery.savedAt);}
|
||||
else{const response=await fetch('/templates/general.blend',{signal:controller.signal});if(!response.ok)throw new Error('DESKTOP_STARTUP_TEMPLATE_MISSING');source=await response.arrayBuffer();}
|
||||
const width=Math.max(640,Math.min(2560,Math.floor(window.innerWidth))),height=Math.max(360,Math.min(1600,Math.floor(window.innerHeight-30)));
|
||||
if(stopped)return;setSize({width,height});
|
||||
const binding=await resourceClient.resolve();if(stopped)return;
|
||||
await session.start({},binding,{source,desktop:{width,height,preserveLayout:true,useSavedStartup:!recovery,recoveryKey:key,recoverySavedAt:recovery?.savedAt??0}});
|
||||
if(stopped){await session.close();return;}setPhase('READY');
|
||||
const screen=async()=>{try{
|
||||
const blob=await session.screen(controller.signal);
|
||||
screenFailures=0;
|
||||
if(blob&&!stopped){const next=URL.createObjectURL(blob),previous=urlRef.current;urlRef.current=next;setPicture(next);setCursor(session.cursorEmbedded);if(previous)setTimeout(()=>URL.revokeObjectURL(previous),250);}
|
||||
}catch(reason){if(!stopped&&++screenFailures>=3){disconnected=true;setError(String(reason));setPhase('DISCONNECTED');}}finally{if(!stopped&&!disconnected)timer=setTimeout(()=>void screen(),screenFailures?1000*screenFailures:document.hidden?1000:65);}};
|
||||
const fileList=async()=>{try{const next=await session.files();if(!stopped){setFiles(next);if(next.preferenceError)setError(next.preferenceError);if(next.status?.error)setError(next.status.error);if(next.network?.lastError)setError(next.network.lastError);
|
||||
if(next.status&&next.status.savedSequence>savedSequence.current&&!locked.current&&!saving.current){if(await checkpoint(false))savedSequence.current=next.status.savedSequence;}
|
||||
}}catch(reason){if(!stopped)setError(String(reason));}finally{if(!stopped&&!disconnected)fileTimer=setTimeout(()=>void fileList(),2500);}};
|
||||
let sending=false;
|
||||
eventTimer=setInterval(()=>{if(stopped||disconnected||sending||session.busy||locked.current||!pending.current.length)return;sending=true;void flush().catch(reason=>{if(!stopped)setError(String(reason));}).finally(()=>{sending=false;});},20);
|
||||
backupTimer=setInterval(()=>{if(!disconnected&&unsaved.current&&!locked.current)void checkpoint(false);},60000);
|
||||
void screen();void fileList();keyboard.current?.focus();
|
||||
}catch(reason){if(!stopped){setError(String(reason));setPhase('FAILED');}}
|
||||
};
|
||||
void start();
|
||||
const unload=(event:BeforeUnloadEvent)=>{if(unsaved.current){event.preventDefault();event.returnValue='';}};
|
||||
const release=()=>{held.current.clear();pointer.current=false;pending.current.push({type:'release'});if(!session.busy)void flush().catch(()=>undefined);};
|
||||
window.addEventListener('beforeunload',unload);window.addEventListener('blur',release);
|
||||
return()=>{stopped=true;active.current=false;controller.abort();clearTimeout(timer);clearTimeout(fileTimer);clearInterval(eventTimer);clearInterval(backupTimer);window.removeEventListener('beforeunload',unload);window.removeEventListener('blur',release);session.dispose();pending.current=[];if(urlRef.current)URL.revokeObjectURL(urlRef.current);urlRef.current='';};
|
||||
},[restart]);
|
||||
const paste=async(text:string)=>{
|
||||
if(!text||locked.current)return;
|
||||
try{await execute({kind:'clipboard',text});await client.current?.events([{type:'release'},{type:'key',code:'ControlLeft',down:true},{type:'key',code:'KeyV',down:true},{type:'key',code:'KeyV',down:false},{type:'key',code:'ControlLeft',down:false}]);unsaved.current=true;inputGeneration.current++;}
|
||||
catch(reason){setError(String(reason));}
|
||||
};
|
||||
const point=(event:React.PointerEvent<HTMLImageElement>|React.WheelEvent<HTMLImageElement>,position:{clientX:number;clientY:number}=event)=>{
|
||||
const bounds=event.currentTarget.getBoundingClientRect(),scale=fit?Math.min(bounds.width/size.width,bounds.height/size.height):1;
|
||||
return {x:Math.max(0,Math.min(size.width-1,Math.floor((position.clientX-bounds.left-(bounds.width-size.width*scale)/2)/scale))),y:Math.max(0,Math.min(size.height-1,Math.floor((position.clientY-bounds.top-(bounds.height-size.height*scale)/2)/scale)))};
|
||||
};
|
||||
const pen=(event:React.PointerEvent<HTMLImageElement>,action:'move'|'press'|'release')=>{
|
||||
if(event.pointerType!=='pen')return false;
|
||||
if(!client.current?.inputCapabilities.pen){if(action==='press')setError('压感接口未载入,当前使用鼠标输入');return false;}
|
||||
const coalesced=action==='move'?event.nativeEvent.getCoalescedEvents?.():undefined;
|
||||
const samples=coalesced?.length?coalesced.slice(-64):[event.nativeEvent];
|
||||
for(const sample of samples)push({type:'pen',...point(event,sample),action,button:sample.button===2?3:sample.button===1?2:1,
|
||||
pressure:action==='release'?0:sample.pressure,tiltX:Math.max(-1,Math.min(1,sample.tiltX/90)),tiltY:Math.max(-1,Math.min(1,sample.tiltY/90)),eraser:sample.button===5||(sample.buttons&32)!==0});
|
||||
return true;
|
||||
};
|
||||
const uploadFiles=async(selected:FileList|null)=>{
|
||||
const session=client.current;if(!selected?.length||!session||locked.current)return;
|
||||
const chosen=Array.from(selected);
|
||||
locked.current=true;setBusy(true);setError('');
|
||||
const batch=`uploads/${Date.now()}-${crypto.randomUUID().slice(0,8)}`;
|
||||
try{await flush();for(const file of chosen){await session.upload(file,`${batch}/${file.webkitRelativePath||file.name}`);}setDrawer(true);setFiles(await session.files());
|
||||
const first=chosen[0],relative=chosen.length===1?(first.webkitRelativePath||first.name):'';
|
||||
const lastSlash=relative.lastIndexOf('/');
|
||||
try{await session.execute({kind:'file-browser',path:lastSlash>=0?`${batch}/${relative.slice(0,lastSlash)}`:batch,...(relative?{filename:relative.slice(lastSlash+1)}:{})});}catch(reason){if(!String(reason).includes('SESSION_OPEN_FILE_MENU_FIRST'))throw reason;}
|
||||
}catch(reason){setError(String(reason));}finally{locked.current=false;setBusy(false);}
|
||||
};
|
||||
return <main className="desktop-workspace" data-session-status={phase}>
|
||||
<div ref={surface} className={`desktop-workspace-surface ${fit?'fit':'pixels'}`}>
|
||||
{picture?<img ref={image} src={picture} alt="Blender 工作区" width={size.width} height={size.height} draggable={false} className={cursor?'native-cursor':''}
|
||||
onPointerMove={event=>{if(!pen(event,'move'))push({type:'move',...point(event)});}} onPointerDown={event=>{event.preventDefault();keyboard.current?.focus({preventScroll:true});event.currentTarget.setPointerCapture(event.pointerId);pointer.current=true;if(!pen(event,'press'))push({type:'button',...point(event),button:event.button===1?2:event.button===2?3:1,down:true});}}
|
||||
onPointerUp={event=>{pointer.current=false;if(!pen(event,'release'))push({type:'button',...point(event),button:event.button===1?2:event.button===2?3:1,down:false});if(event.currentTarget.hasPointerCapture(event.pointerId))event.currentTarget.releasePointerCapture(event.pointerId);}}
|
||||
onPointerCancel={()=>{pointer.current=false;push({type:'release'});}} onContextMenu={event=>event.preventDefault()} onWheel={event=>{event.preventDefault();push({type:'move',...point(event)});const factor=event.deltaMode===1?40:event.deltaMode===2?size.height:1;wheel.current.x+=event.deltaX*factor;wheel.current.y+=event.deltaY*factor;for(const axis of ['x','y'] as const){const delta=Math.max(-5,Math.min(5,Math.trunc(wheel.current[axis]/100)));if(delta){wheel.current[axis]-=delta*100;push({type:'wheel',delta,horizontal:axis==='x'});}}}}/>:
|
||||
<div className="desktop-workspace-start"><h1>Blender</h1><output>{phase==='STARTING'?'正在打开工作区…':phase}</output></div>}
|
||||
<textarea ref={keyboard} className="desktop-keyboard-input" aria-label="Blender 键盘输入" autoComplete="off" autoCapitalize="off" spellCheck={false}
|
||||
onBlur={()=>{held.current.clear();pointer.current=false;push({type:'release'});}}
|
||||
onKeyDown={event=>{if(composition.current||event.nativeEvent.isComposing)return;if((event.ctrlKey||event.metaKey)&&event.code==='KeyV')return;event.preventDefault();event.stopPropagation();if(event.key.length===1&&event.key.charCodeAt(0)>127&&!event.ctrlKey&&!event.metaKey){void paste(event.key);return;}held.current.add(event.code);push({type:'key',code:event.code,key:event.key,locks:{caps:event.getModifierState('CapsLock'),num:event.getModifierState('NumLock')},down:true});}}
|
||||
onKeyUp={event=>{if(composition.current||event.nativeEvent.isComposing)return;event.preventDefault();event.stopPropagation();held.current.delete(event.code);push({type:'key',code:event.code,key:event.key,locks:{caps:event.getModifierState('CapsLock'),num:event.getModifierState('NumLock')},down:false});}}
|
||||
onPaste={event=>{event.preventDefault();void paste(event.clipboardData.getData('text/plain'));}}
|
||||
onCompositionStart={()=>{composition.current=true;push({type:'release'});held.current.clear();}}
|
||||
onCompositionEnd={event=>{composition.current=false;event.currentTarget.value='';lastComposition.current={text:event.data,at:Date.now()};void paste(event.data);}}
|
||||
onInput={event=>{if(!composition.current){const value=event.currentTarget.value;event.currentTarget.value='';if(value&&!(value===lastComposition.current.text&&Date.now()-lastComposition.current.at<100))void paste(value);}}}/>
|
||||
</div>
|
||||
<footer className="desktop-browser-tools" aria-label="浏览器文件与会话"><strong>Web Blender</strong><span>{busy||persisting?'BUSY':phase}</span>
|
||||
<button title="切换原生窗口" aria-label="切换原生窗口" disabled={phase!=='READY'||busy} onClick={()=>void flush().then(()=>client.current?.events([{type:'release'},{type:'key',code:'AltLeft',down:true},{type:'key',code:'Tab',down:true},{type:'key',code:'Tab',down:false},{type:'key',code:'AltLeft',down:false}])).catch(reason=>setError(String(reason)))}>▢</button>
|
||||
<button title="上传文件" aria-label="上传文件" disabled={phase!=='READY'||busy} onClick={()=>upload.current?.click()}>↑</button>
|
||||
<button title="上传文件夹" aria-label="上传文件夹" disabled={phase!=='READY'||busy} onClick={()=>folder.current?.click()}>▱</button>
|
||||
<button title="下载工程及资源" aria-label="下载工程及资源" disabled={phase!=='READY'||busy||persisting} onClick={()=>void checkpoint(true)}>↓</button>
|
||||
<button title="会话文件" aria-label="会话文件" aria-pressed={drawer} onClick={()=>setDrawer(!drawer)}>▤</button>
|
||||
<button title="保存偏好设置" aria-label="保存偏好设置" disabled={phase!=='READY'||busy} onClick={()=>void execute({kind:'preferences-save'}).then(result=>{const file=result.files[0];if(file)download(new Blob([file.bytes]),file.artifact.name);}).catch(reason=>setError(String(reason)))}>⚙</button>
|
||||
<button title="粘贴剪贴板文字" aria-label="粘贴剪贴板文字" disabled={phase!=='READY'||busy} onClick={()=>void navigator.clipboard.readText().then(paste).catch(reason=>setError(String(reason)))}>▣</button>
|
||||
<button title="复制原生剪贴板文字" aria-label="复制原生剪贴板文字" disabled={phase!=='READY'||busy} onClick={()=>void execute({kind:'clipboard-read'}).then(result=>navigator.clipboard.writeText(result.output)).catch(reason=>setError(String(reason)))}>⧉</button>
|
||||
<button title={fit?'原始大小':'适应窗口'} aria-label="切换画面缩放" aria-pressed={!fit} onClick={()=>setFit(!fit)}>1:1</button>
|
||||
<button title="全屏" aria-label="全屏" onClick={()=>void (document.fullscreenElement?document.exitFullscreen():document.documentElement.requestFullscreen()).then(()=>{const api=(navigator as Navigator&{keyboard?:{lock:()=>Promise<void>}}).keyboard;if(document.fullscreenElement)void api?.lock().catch(()=>undefined);}).catch(reason=>setError(String(reason)))}>⛶</button>
|
||||
<a href="?ui=web" target="_blank" rel="noopener" title="Web 扩展工具" aria-disabled={busy||persisting} onClick={event=>{if(phase!=='READY'){if(savedAt&&slot.current)event.currentTarget.href=`?ui=web&desktopHandoff=${encodeURIComponent(slot.current)}`;return;}event.preventDefault();if(busy||persisting)return;const target=window.open('about:blank','_blank');if(!target){setError('浏览器阻止了新窗口');return;}target.opener=null;void checkpoint(false).then(saved=>{if(saved)target.location.replace(`?ui=web&desktopHandoff=${encodeURIComponent(slot.current)}`);else target.close();}).catch(reason=>{target.close();setError(String(reason));});}}>Web 扩展</a>
|
||||
<span className="desktop-recovery-time">{savedAt?`恢复点 ${new Date(savedAt).toLocaleTimeString()}`:''}</span>
|
||||
<a href="?ui=wasm" target="_blank" rel="noopener" title="浏览器工作区(WASM)">WASM</a>
|
||||
{phase==='FAILED'||phase==='DISCONNECTED'?<button onClick={()=>{if(unsaved.current&&!window.confirm('重新连接将恢复最近保存点。是否继续?'))return;setPicture('');savedSequence.current=0;setRestart(value=>value+1);}}>重新连接</button>:null}
|
||||
<input ref={upload} type="file" multiple hidden onChange={event=>{void uploadFiles(event.target.files);event.target.value='';}}/>
|
||||
<input ref={folder} type="file" multiple hidden {...{webkitdirectory:''}} onChange={event=>{void uploadFiles(event.target.files);event.target.value='';}}/>
|
||||
</footer>
|
||||
{drawer?<aside className="desktop-file-drawer" aria-label="会话文件"><header><strong>会话文件</strong><button aria-label="关闭会话文件" onClick={()=>setDrawer(false)}>×</button></header>
|
||||
<output>{files.status?.workspace??''}</output>{files.files.map(file=><div key={file.path}><span title={file.path}>{file.path}</span><small>{(file.bytes/1024).toFixed(1)} KiB</small><span className="desktop-file-actions">{file.path.toLowerCase().endsWith('.blend')?<button title="打开工程" aria-label={`打开 ${file.path}`} disabled={busy||persisting} onClick={()=>{void (async()=>{if(unsaved.current&&!window.confirm('打开将替换当前工程。是否继续?'))return;const saved=await checkpoint(false);if(!saved)return;await execute({kind:'open-blend',path:file.path});unsaved.current=true;inputGeneration.current++;setDrawer(false);await checkpoint(false);})().catch(reason=>setError(String(reason)));}}>▱</button>:null}<button title="下载" aria-label={`下载 ${file.path}`} onClick={()=>void client.current?.download(file.path).then(blob=>download(blob,file.path.split('/').at(-1)!)).catch(reason=>setError(String(reason)))}>↓</button></span></div>)}
|
||||
</aside>:null}
|
||||
{files.links?.length?<div className="desktop-browser-links">{files.links.map(link=><a key={link.id} href={link.url} target="_blank" rel="noopener noreferrer" onClick={()=>void client.current?.acknowledgeLink(link.id)}>{new URL(link.url).hostname} ↗</a>)}</div>:null}
|
||||
{error?<div className="desktop-workspace-error" role="alert"><span>{error}</span><button aria-label="关闭错误提示" onClick={()=>setError('')}>×</button></div>:null}
|
||||
</main>;
|
||||
}
|
||||
164
web/app/src/app/ModifierCurveProfileField.tsx
Normal file
@@ -0,0 +1,164 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { isModifierCurveProfile } from '../../../protocol/modifier';
|
||||
import { finishModifierInput } from './modifier-input-keyboard';
|
||||
|
||||
/** Displays Blender's sampled curve; all path and handle edits run in WASM. */
|
||||
export function ModifierCurveProfileField({ value, disabled, onCommit }: {
|
||||
value: unknown; disabled: boolean; onCommit: (value: unknown) => Promise<boolean> | void;
|
||||
}) {
|
||||
const [selected, setSelected] = useState(0);
|
||||
const [status, setStatus] = useState<string | null>(null);
|
||||
const graph = useRef<SVGSVGElement>(null);
|
||||
const drag = useRef<{ pointer: number; index: number; action: string; x: number; y: number } | null>(null);
|
||||
const snapshot = JSON.stringify(value);
|
||||
const cancelDrag = () => {
|
||||
const pending = drag.current;
|
||||
drag.current = null;
|
||||
if (pending && graph.current?.hasPointerCapture(pending.pointer)) {
|
||||
graph.current.releasePointerCapture(pending.pointer);
|
||||
}
|
||||
};
|
||||
// A new native profile or owner state retires the pending point/handle edit.
|
||||
// Do not apply a release to indices from a replaced curve snapshot.
|
||||
useEffect(() => { cancelDrag(); }, [snapshot, disabled]);
|
||||
useEffect(() => {
|
||||
const hidden = () => { if (document.hidden) cancelDrag(); };
|
||||
window.addEventListener('blur', cancelDrag);
|
||||
document.addEventListener('visibilitychange', hidden);
|
||||
return () => {
|
||||
window.removeEventListener('blur', cancelDrag);
|
||||
document.removeEventListener('visibilitychange', hidden);
|
||||
drag.current = null;
|
||||
};
|
||||
}, []);
|
||||
if (!isModifierCurveProfile(value)) return <p role="status">Custom profile is unavailable.</p>;
|
||||
const index = Math.min(selected, value.points.length - 1);
|
||||
const point = value.points[index];
|
||||
const endpoint = index === 0 || index === value.points.length - 1;
|
||||
const [left, bottom, right, top] = value.view;
|
||||
const markerSize = Math.min(right - left, top - bottom);
|
||||
const commit = async (operation: Record<string, unknown>) => {
|
||||
if (disabled) return;
|
||||
try {
|
||||
const applied = await onCommit(operation);
|
||||
setStatus(applied === false ? 'Curve value was not applied; value retained for retry.' : null);
|
||||
} catch { setStatus('Curve value was not applied; value retained for retry.'); }
|
||||
};
|
||||
const coordinates = (label: string, location: [number, number], action: string, locked: boolean) =>
|
||||
<div className="property-grid">{location.map((number, axis) => <label key={`${index}:${action}:${axis}:${number}`}>
|
||||
{label} {axis === 0 ? 'X' : 'Y'}
|
||||
<input type="number" step="any" min={-100000} max={100000} disabled={locked} defaultValue={Number(number.toPrecision(7))}
|
||||
onKeyDown={event => finishModifierInput(event, String(number))}
|
||||
onBlur={event => {
|
||||
const input = event.currentTarget;
|
||||
if (!locked && input.value !== '' && input.checkValidity() && Number.isFinite(input.valueAsNumber) && Math.fround(input.valueAsNumber) !== Math.fround(number)) {
|
||||
commit({ action, index, location: location.map((current, slot) => slot === axis ? input.valueAsNumber : current) });
|
||||
}
|
||||
input.value = String(number);
|
||||
}} />
|
||||
</label>)}</div>;
|
||||
return <fieldset disabled={disabled}>
|
||||
<legend>Custom Profile</legend>
|
||||
<svg ref={graph} tabIndex={disabled ? -1 : 0} viewBox={`${left} ${-top} ${right - left} ${top - bottom}`} aria-label="Custom profile path" style={{ width: '100%', maxHeight: 220, touchAction: 'none', background: 'var(--panel-bg, #252525)' }}
|
||||
onPointerDown={event => {
|
||||
if (disabled || drag.current || event.button !== 0 || !(event.target instanceof Element)) return;
|
||||
const target = event.target.closest('[data-profile-action]');
|
||||
if (!target) return;
|
||||
const slot = Number(target.getAttribute('data-profile-index'));
|
||||
const action = target.getAttribute('data-profile-action')!;
|
||||
setSelected(slot);
|
||||
if (action === 'MOVE' && (slot === 0 || slot === value.points.length - 1)) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
event.currentTarget.focus();
|
||||
drag.current = { pointer: event.pointerId, index: slot, action, x: event.clientX, y: event.clientY };
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
}}
|
||||
onPointerUp={event => {
|
||||
const pending = drag.current;
|
||||
if (!pending || pending.pointer !== event.pointerId) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
drag.current = null;
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
if (pending.x === event.clientX && pending.y === event.clientY) return;
|
||||
const matrix = event.currentTarget.querySelector('g')?.getScreenCTM();
|
||||
if (!matrix) return;
|
||||
const position = new DOMPoint(event.clientX, event.clientY).matrixTransform(matrix.inverse());
|
||||
commit({ action: pending.action, index: pending.index, location: [position.x, position.y] });
|
||||
}}
|
||||
onPointerCancel={cancelDrag}
|
||||
onLostPointerCapture={cancelDrag}
|
||||
onBlur={event => {
|
||||
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) cancelDrag();
|
||||
}}
|
||||
onKeyDown={event => {
|
||||
if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) {
|
||||
event.stopPropagation();
|
||||
return;
|
||||
}
|
||||
if (event.key === 'Escape' && drag.current) {
|
||||
cancelDrag();
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
}}>
|
||||
<g transform="scale(1 -1)">
|
||||
<rect x={value.clip[0]} y={value.clip[1]} width={value.clip[2] - value.clip[0]} height={value.clip[3] - value.clip[1]} fill="none" stroke="currentColor" strokeWidth={markerSize * 0.004} />
|
||||
<polyline points={value.samples.map(pair => pair.join(',')).join(' ')} fill="none" stroke="currentColor" strokeWidth={markerSize * 0.008} />
|
||||
{(point.handleType === 'FREE' || point.handleType === 'ALIGN') && <>
|
||||
<polyline points={[point.handle1, point.location, point.handle2].map(pair => pair.join(',')).join(' ')} fill="none" stroke="#ed9b40" strokeWidth={markerSize * 0.004} />
|
||||
{[point.handle1, point.handle2].map((handle, slot) => <circle key={slot} cx={handle[0]} cy={handle[1]} r={markerSize * 0.013}
|
||||
fill="#ed9b40" data-profile-action={slot === 0 ? 'HANDLE1' : 'HANDLE2'} data-profile-index={index} />)}
|
||||
</>}
|
||||
{value.points.map((candidate, slot) => <circle key={slot} cx={candidate.location[0]} cy={candidate.location[1]} r={markerSize * 0.018}
|
||||
data-profile-action="MOVE" data-profile-index={slot}
|
||||
fill={index === slot ? '#ed9b40' : 'currentColor'} role="button" tabIndex={disabled ? -1 : 0}
|
||||
aria-label={`Select profile point ${slot + 1}`} aria-pressed={index === slot} aria-disabled={disabled}
|
||||
onClick={() => { if (!disabled) setSelected(slot); }}
|
||||
onKeyDown={event => { if (!disabled && (event.key === 'Enter' || event.key === ' ')) { event.preventDefault(); setSelected(slot); } }} />)}
|
||||
</g>
|
||||
</svg>
|
||||
{status && <p role="status">{status}</p>}
|
||||
<div role="group" aria-label="Profile View">
|
||||
{Object.entries({ IN: 'Zoom In', OUT: 'Zoom Out', LEFT: 'Pan Left', RIGHT: 'Pan Right', UP: 'Pan Up', DOWN: 'Pan Down' }).map(([direction, label]) =>
|
||||
<button key={direction} type="button" onClick={() => commit({ action: 'VIEW', direction })}>{label}</button>)}
|
||||
<button type="button" onClick={() => commit({ action: 'RESET_VIEW' })}>Reset View</button>
|
||||
</div>
|
||||
<label>Preset <select defaultValue="" onChange={event => {
|
||||
if (event.target.value) commit({ action: 'PRESET', preset: event.target.value });
|
||||
event.target.value = '';
|
||||
}}><option value="" disabled>Choose Preset</option>
|
||||
{Object.entries({ LINE: 'Line', SUPPORTS: 'Support Loops', CORNICE: 'Cornice Molding', CROWN: 'Crown Molding', STEPS: 'Steps' }).map(([id, label]) => <option key={id} value={id}>{label}</option>)}
|
||||
</select></label>
|
||||
<button type="button" onClick={() => commit({ action: 'RESET' })}>Reset</button>
|
||||
<button type="button" onClick={() => commit({ action: 'REVERSE' })}>Reverse</button>
|
||||
<label>Point <select value={index} onChange={event => setSelected(Number(event.target.value))}>
|
||||
{value.points.map((_, slot) => <option key={slot} value={slot}>{slot + 1}{slot === 0 || slot === value.points.length - 1 ? ' (Endpoint)' : ''}</option>)}
|
||||
</select></label>
|
||||
{coordinates('Point', point.location, 'MOVE', endpoint)}
|
||||
<label>Handle Type <select value={point.handleType} onChange={event => commit({ action: 'HANDLE_TYPE', index, handleType: event.target.value })}>
|
||||
<option value="AUTO">Auto</option><option value="VECTOR">Vector</option><option value="FREE">Free</option><option value="ALIGN">Aligned</option>
|
||||
</select></label>
|
||||
{(point.handleType === 'FREE' || point.handleType === 'ALIGN') && <>
|
||||
{coordinates('First Handle', point.handle1, 'HANDLE1', false)}
|
||||
{coordinates('Second Handle', point.handle2, 'HANDLE2', false)}
|
||||
</>}
|
||||
<button type="button" disabled={endpoint} onClick={() => commit({ action: 'REMOVE', index })}>Remove Point</button>
|
||||
<form onSubmit={event => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const x = (form.elements.namedItem('profileX') as HTMLInputElement).valueAsNumber;
|
||||
const y = (form.elements.namedItem('profileY') as HTMLInputElement).valueAsNumber;
|
||||
if (form.checkValidity() && Number.isFinite(x) && Number.isFinite(y)) commit({ action: 'ADD', location: [x, y] });
|
||||
}}>
|
||||
<label>New Point X <input name="profileX" type="number" required step="any" min={-100000} max={100000} defaultValue="0.5" /></label>
|
||||
<label>New Point Y <input name="profileY" type="number" required step="any" min={-100000} max={100000} defaultValue="0.5" /></label>
|
||||
<button type="submit" disabled={value.points.length >= 1024}>Add Point</button>
|
||||
</form>
|
||||
{(['use_clip', 'use_sample_straight_edges', 'use_sample_even_lengths'] as const).map(key => <label key={key}>
|
||||
<input type="checkbox" checked={value[key]} onChange={event => commit({ action: 'SETTING', key, value: event.target.checked })} />
|
||||
{{ use_clip: 'Clip', use_sample_straight_edges: 'Sample Straight Edges', use_sample_even_lengths: 'Sample Even Lengths' }[key]}
|
||||
</label>)}
|
||||
</fieldset>;
|
||||
}
|
||||
67
web/app/src/app/ModifierParameterField.css
Normal file
@@ -0,0 +1,67 @@
|
||||
.modifier-stack-authoring .modifier-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 8px;
|
||||
padding: 10px 0;
|
||||
border-top: 1px solid #505050;
|
||||
}
|
||||
|
||||
.modifier-stack-authoring .modifier-row-heading {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.modifier-stack-authoring .modifier-type {
|
||||
color: #b3b3b3;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.modifier-stack-authoring .modifier-order-controls,
|
||||
.modifier-stack-authoring .modifier-visibility-controls,
|
||||
.modifier-stack-authoring .modifier-authoring-controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.modifier-stack-authoring .modifier-parameter-controls {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.modifier-stack-authoring .modifier-parameter-controls .property-grid {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.modifier-stack-authoring .modifier-parameter-controls label {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 88px;
|
||||
justify-content: normal;
|
||||
gap: 8px;
|
||||
text-align: left;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.modifier-stack-authoring input[type="number"] {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.modifier-stack-authoring .modifier-parameter-controls input[type="checkbox"] {
|
||||
justify-self: end;
|
||||
}
|
||||
|
||||
.modifier-stack-authoring [data-modifier-type-input] {
|
||||
flex: 1 1 100px;
|
||||
min-width: 0;
|
||||
}
|
||||
1053
web/app/src/app/ModifierParameterField.tsx
Normal file
67
web/app/src/app/NDOFControl.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import type {WebEngineClient} from '../engine-client/WebEngineClient';
|
||||
import {DEFAULT_NDOF_SETTINGS,type NDOFCamera,type NDOFSettings,type NDOFViewportEvent} from '../../../protocol/ndof';
|
||||
import {DesktopDialog} from './DesktopMenus';
|
||||
|
||||
interface Device {opened:boolean;productName:string;vendorId:number;productId:number;open():Promise<void>;close():Promise<void>;addEventListener(type:string,callback:(event:ReportEvent)=>void):void;removeEventListener(type:string,callback:(event:ReportEvent)=>void):void}
|
||||
interface ReportEvent {device:Device;reportId:number;data:DataView}
|
||||
interface HID {requestDevice(options:{filters:{vendorId:number;usagePage:number;usage:number}[]}):Promise<Device[]>;addEventListener(type:string,callback:(event:{device:Device})=>void):void;removeEventListener(type:string,callback:(event:{device:Device})=>void):void}
|
||||
function savedSettings():NDOFSettings{try{const value=JSON.parse(localStorage.getItem('blender-ndof-v1')??'{}');return {...DEFAULT_NDOF_SETTINGS,...Object.fromEntries(Object.entries(value).filter(([key,value])=>key in DEFAULT_NDOF_SETTINGS&&(typeof value===typeof DEFAULT_NDOF_SETTINGS[key as keyof NDOFSettings])&&(typeof value!=='number'||Number.isFinite(value))))};}catch{return {...DEFAULT_NDOF_SETTINGS};}}
|
||||
|
||||
export function NDOFControl({client}:{client:WebEngineClient|null}){
|
||||
const [open,setOpen]=useState(false),[settings,setSettings]=useState(savedSettings),[name,setName]=useState(''),[error,setError]=useState(''),[busy,setBusy]=useState(false);
|
||||
const device=useRef<Device|null>(null),listener=useRef<((event:ReportEvent)=>void)|null>(null),latest=useRef(settings),generation=useRef(0),mounted=useRef(true);
|
||||
const focusEpoch=useRef(0);
|
||||
const hid=(navigator as Navigator&{hid?:HID}).hid;
|
||||
useEffect(()=>{latest.current=settings;try{localStorage.setItem('blender-ndof-v1',JSON.stringify(settings));}catch(reason){setError(String(reason));}},[settings]);
|
||||
const disconnect=async()=>{generation.current++;const current=device.current;device.current=null;if(current&&listener.current)current.removeEventListener('inputreport',listener.current);listener.current=null;if(mounted.current)setName('');if(current?.opened)await current.close();};
|
||||
useEffect(()=>{mounted.current=true;const blur=()=>{focusEpoch.current++;};const detached=(event:{device:Device})=>{if(event.device===device.current)void disconnect().catch(()=>undefined);};window.addEventListener('blur',blur);hid?.addEventListener('disconnect',detached);return()=>{mounted.current=false;window.removeEventListener('blur',blur);hid?.removeEventListener('disconnect',detached);void disconnect().catch(()=>undefined);};},[hid]);
|
||||
const connect=async()=>{
|
||||
if(!hid||!client||busy)return;setBusy(true);setError('');
|
||||
const requestGeneration=generation.current;
|
||||
try{
|
||||
const devices=await hid.requestDevice({filters:[{vendorId:0x046d,usagePage:1,usage:8},{vendorId:0x256f,usagePage:1,usage:8}]});
|
||||
if(!devices.length||!mounted.current||requestGeneration!==generation.current)return;
|
||||
await disconnect();const selected=devices[0],openingGeneration=generation.current;await selected.open();
|
||||
if(!mounted.current||openingGeneration!==generation.current){await selected.close();return;}
|
||||
device.current=selected;const token=++generation.current;setName(selected.productName||'NDOF');
|
||||
let translation:[number,number,number]=[0,0,0],rotation:[number,number,number]=[0,0,0],buttons=0,lastTime=0,processing=false;
|
||||
const queue:{id:number;bytes:number[];time:number;epoch:number}[]=[];
|
||||
const twoButtons=(selected.vendorId===0x046d&&[0xc626,0xc628].includes(selected.productId))||(selected.vendorId===0x256f&&[0xc62e,0xc62f,0xc658].includes(selected.productId));
|
||||
const process=async()=>{if(processing)return;processing=true;
|
||||
try{while(queue.length&&generation.current===token){
|
||||
const packet=queue.shift()!;
|
||||
if(packet.epoch!==focusEpoch.current)continue;
|
||||
const decoded=(await client.callJson<{fields:number;buttons:number;translation:[number,number,number];rotation:[number,number,number]}>('ndofDecode',{reportId:packet.id,bytes:packet.bytes})).result;
|
||||
if(generation.current!==token)return;
|
||||
if(packet.epoch!==focusEpoch.current){translation=[0,0,0];rotation=[0,0,0];lastTime=0;continue;}
|
||||
const canvas=[...document.querySelectorAll<HTMLCanvasElement>('canvas.viewport-canvas')].find(item=>document.activeElement===item||item.matches(':hover'));
|
||||
const focused=document.hasFocus()&&canvas&&(canvas.matches(':hover')||document.activeElement===canvas);
|
||||
if(!focused){translation=[0,0,0];rotation=[0,0,0];lastTime=0;buttons=decoded.buttons;continue;}
|
||||
if(decoded.fields&1)translation=decoded.translation;
|
||||
if(decoded.fields&2)rotation=decoded.rotation;
|
||||
if(decoded.fields&4){if(twoButtons){if((decoded.buttons&1)&&!(buttons&1))setOpen(true);if((decoded.buttons&2)&&!(buttons&2))canvas.dispatchEvent(new CustomEvent('viewport-command',{detail:'FRAME_SELECTED'}));}buttons=decoded.buttons;continue;}
|
||||
if([...translation,...rotation].every(value=>Math.abs(value)<=latest.current.deadZone)){lastTime=0;continue;}
|
||||
const now=packet.time,dt=lastTime?Math.min(.1,Math.max(0,(now-lastTime)/1000)):.0125;lastTime=now;
|
||||
const detail:NDOFViewportEvent={translation:[...translation],rotation:[...rotation],dt,settings:{...latest.current},apply:async request=>{const result=(await client.callJson<NDOFCamera>('ndofNavigate',request as unknown as Record<string,unknown>)).result;if(generation.current!==token)throw new Error('NDOF_DISCONNECTED');return result;},onError:reason=>{if(mounted.current&&generation.current===token){setError(String(reason));void disconnect().catch(()=>undefined);}}};
|
||||
canvas.dispatchEvent(new CustomEvent('viewport-ndof',{detail}));
|
||||
}}catch(reason){queue.length=0;translation=[0,0,0];rotation=[0,0,0];lastTime=0;if(mounted.current)setError(String(reason));void disconnect().catch(()=>undefined);}finally{processing=false;}
|
||||
};
|
||||
listener.current=event=>{
|
||||
if(![1,2,3].includes(event.reportId))return;
|
||||
if(!document.hasFocus()){queue.length=0;translation=[0,0,0];rotation=[0,0,0];lastTime=0;return;}
|
||||
if(queue.length>=128){queue.length=0;translation=[0,0,0];rotation=[0,0,0];lastTime=0;setError('NDOF 输入积压,运动已复位');return;}
|
||||
queue.push({id:event.reportId,bytes:Array.from(new Uint8Array(event.data.buffer,event.data.byteOffset,event.data.byteLength)),time:performance.now(),epoch:focusEpoch.current});void process();
|
||||
};selected.addEventListener('inputreport',listener.current);
|
||||
}catch(reason){setError(String(reason));}finally{if(mounted.current)setBusy(false);}
|
||||
};
|
||||
return <><button title="NDOF 三维鼠标" aria-label="NDOF 三维鼠标" aria-pressed={!!name} onClick={()=>setOpen(true)}>NDOF</button>{open?<DesktopDialog title="NDOF 三维鼠标" onClose={()=>setOpen(false)}>
|
||||
<output>{name||'未连接'}</output><div className="desktop-dialog-actions"><button disabled={!hid||!client||busy} onClick={()=>void connect()}>连接设备</button><button disabled={!name||busy} onClick={()=>void disconnect().catch(reason=>setError(String(reason)))}>断开</button></div>
|
||||
{!hid?<output>浏览器未提供 WebHID</output>:null}
|
||||
<label>平移速度<input type="number" min={.01} max={10} step={.1} value={settings.speed} onChange={event=>setSettings({...settings,speed:Math.max(.01,Math.min(10,Number(event.target.value)))})}/></label>
|
||||
<label>旋转速度<input type="number" min={.01} max={10} step={.1} value={settings.rotationSpeed} onChange={event=>setSettings({...settings,rotationSpeed:Math.max(.01,Math.min(10,Number(event.target.value)))})}/></label>
|
||||
<label>死区<input type="number" min={0} max={1} step={.01} value={settings.deadZone} onChange={event=>setSettings({...settings,deadZone:Math.max(0,Math.min(1,Number(event.target.value)))})}/></label>
|
||||
<label><input type="checkbox" checked={settings.rotate} onChange={event=>setSettings({...settings,rotate:event.target.checked})}/>旋转</label><label><input type="checkbox" checked={settings.zoom} onChange={event=>setSettings({...settings,zoom:event.target.checked})}/>纵向缩放</label><label>导航<select value={settings.objectMode?'OBJECT':'CAMERA'} onChange={event=>setSettings({...settings,objectMode:event.target.value==='OBJECT'})}><option value="OBJECT">对象</option><option value="CAMERA">相机</option></select></label>
|
||||
{error?<output role="alert">{error}</output>:null}
|
||||
</DesktopDialog>:null}</>;
|
||||
}
|
||||
48
web/app/src/app/NativeExportPanel.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import type {NativeExportFormat,NativeWorkflowInput} from '../../../protocol/native-workflow';
|
||||
import type {BlenderOperatorPropertySpec,BlenderOperatorPropertyValue} from '../../../protocol/blender-operator';
|
||||
import type {NativeWorkflowControls,NativeWorkflowFile} from './NativeWorkflowPanels';
|
||||
|
||||
export const EXPORT_FORMATS: {id:NativeExportFormat;label:string;operator:string}[] = [
|
||||
{id:'GLB',label:'glTF Binary (.glb)',operator:'export_scene.gltf'},
|
||||
{id:'GLTF',label:'glTF Separate (.gltf)',operator:'export_scene.gltf'},
|
||||
{id:'FBX',label:'FBX (.fbx)',operator:'export_scene.fbx'},
|
||||
{id:'OBJ',label:'Wavefront OBJ (.obj)',operator:'wm.obj_export'},
|
||||
{id:'STL',label:'STL (.stl)',operator:'wm.stl_export'},
|
||||
{id:'PLY',label:'Stanford PLY (.ply)',operator:'wm.ply_export'},
|
||||
{id:'USD',label:'Universal Scene Description (.usdc)',operator:'wm.usd_export'},
|
||||
{id:'ALEMBIC',label:'Alembic (.abc)',operator:'wm.alembic_export'},
|
||||
];
|
||||
const managed=new Set(['filepath','directory','filename','files','check_existing','filter_glob','batch_mode','use_batch_own_dir','as_background_job','export_format','export_texture_dir','export_animation','use_selection','export_selected_objects','selected_objects_only','selected']);
|
||||
|
||||
export function NativeExportPanel({client,snapshot,busy,output,files,onRun,onCancel,initialFormat}:NativeWorkflowControls&{files:NativeWorkflowFile[];initialFormat:NativeExportFormat}) {
|
||||
const [format,setFormat]=useState(initialFormat),[selectedOnly,setSelectedOnly]=useState(false),[query,setQuery]=useState('');
|
||||
const [schema,setSchema]=useState<BlenderOperatorPropertySpec[]>([]),[values,setValues]=useState<Record<string,BlenderOperatorPropertyValue>>({});
|
||||
const [loading,setLoading]=useState(true),[error,setError]=useState(''),[submitted,setSubmitted]=useState(false);
|
||||
useEffect(()=>{
|
||||
let active=true;setLoading(true);setError('');setValues(format==='FBX'?{embed_textures:true}:format==='USD'?{export_textures:true}:{});setSchema([]);setSubmitted(false);
|
||||
if(!client){setLoading(false);return;}
|
||||
void client.describeDesktopOperator(EXPORT_FORMATS.find(item=>item.id===format)!.operator).then(descriptor=>{
|
||||
if(active)setSchema(descriptor.properties.filter(property=>!managed.has(property.name)&&!/(path|directory|filename)/i.test(property.name)));
|
||||
}).catch(reason=>{if(active)setError(String(reason));}).finally(()=>{if(active)setLoading(false);});
|
||||
return()=>{active=false;};
|
||||
},[client,format]);
|
||||
const field=(property:BlenderOperatorPropertySpec)=>{
|
||||
const value=values[property.name]??property.defaultValue;
|
||||
const change=(next:BlenderOperatorPropertyValue)=>setValues(current=>({...current,[property.name]:next}));
|
||||
const label=property.label??property.name;
|
||||
if(property.type==='boolean')return <label key={property.name} title={property.description}><input type="checkbox" checked={Boolean(value)} onChange={e=>change(e.target.checked)}/>{label}</label>;
|
||||
if(property.type==='enum-set')return <fieldset key={property.name}><legend>{label}</legend>{property.enumItems?.map(item=><label key={item.value}><input type="checkbox" checked={Array.isArray(value)&&value.some(entry=>entry===item.value)} onChange={e=>change(e.target.checked?[...(Array.isArray(value)?value as string[]:[]),item.value]:(Array.isArray(value)?value as string[]:[]).filter(v=>v!==item.value))}/>{item.label}</label>)}</fieldset>;
|
||||
if(property.type==='enum')return <label key={property.name} title={property.description}>{label}<select value={String(value??'')} onChange={e=>change(e.target.value)}><option value="" disabled>Default</option>{property.enumItems?.map(item=><option key={item.value} value={item.value}>{item.label}</option>)}</select></label>;
|
||||
if(property.type==='number-array'||property.type==='boolean-array')return <fieldset key={property.name}><legend>{label}</legend>{Array.from({length:property.arrayLength??0},(_,index)=><input key={index} aria-label={`${label} ${index+1}`} type={property.type==='boolean-array'?'checkbox':'number'} min={property.min} max={property.max} step={property.integer?1:'any'} checked={property.type==='boolean-array'?Boolean((value as boolean[])?.[index]):undefined} value={property.type==='number-array'?Number((value as number[])?.[index]??0):undefined} onChange={e=>{const next=Array.from({length:property.arrayLength??0},(_,i)=>(value as number[]|boolean[])?.[i]??(property.type==='boolean-array'?false:0));next[index]=property.type==='boolean-array'?e.target.checked:Number(e.target.value);change(next as number[]|boolean[]);}}/>)}</fieldset>;
|
||||
return <label key={property.name} title={property.description}>{label}<input type={property.type==='number'?'number':'text'} value={String(value??'')} min={property.min} max={property.max} step={property.integer?1:'any'} onChange={e=>change(property.type==='number'?Number(e.target.value):e.target.value)}/></label>;
|
||||
};
|
||||
return <form className="native-export-form" onSubmit={e=>{e.preventDefault();setSubmitted(true);void onRun({kind:'EXPORT',context:{mode:'OBJECT',meshSelection:undefined},export:{format,selectedOnly,properties:values}} satisfies NativeWorkflowInput);}}>
|
||||
<fieldset disabled={busy}><label>格式<select aria-label="导出格式" value={format} onChange={e=>setFormat(e.target.value as NativeExportFormat)}>{EXPORT_FORMATS.map(item=><option key={item.id} value={item.id}>{item.label}</option>)}</select></label>
|
||||
<label><input type="checkbox" checked={selectedOnly} onChange={e=>setSelectedOnly(e.target.checked)}/>仅选中对象</label>
|
||||
<details><summary>导出选项</summary><input type="search" aria-label="筛选导出选项" value={query} onChange={e=>setQuery(e.target.value)}/>{schema.filter(p=>`${p.name} ${p.label}`.toLowerCase().includes(query.toLowerCase())).map(field)}</details></fieldset>
|
||||
{error?<output role="alert">{error}</output>:null}
|
||||
<div className="desktop-dialog-actions"><button type="button" disabled={!busy} onClick={onCancel}>取消导出</button><button type="submit" disabled={busy||loading||!!error||!snapshot}>{loading?'加载选项…':busy?'正在导出…':'导出'}</button></div>
|
||||
{submitted?<><pre className="native-workflow-output" role="status">{output}</pre><div className="native-workflow-artifacts">{!busy&&files.map(file=><a key={file.artifact.id} href={file.url} download={file.artifact.name}>{file.artifact.name}</a>)}</div></>:null}
|
||||
</form>;
|
||||
}
|
||||
80
web/app/src/app/NativeSessionPanel.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import type {WebEngineClient} from '../engine-client/WebEngineClient';
|
||||
import type {NativeDesktopEvent,NativeSessionCommand,NativeWorkflowContext} from '../../../protocol/native-workflow';
|
||||
import type {NativeWorkflowFile} from './NativeWorkflowPanels';
|
||||
import {NATIVE_EDITORS} from './native-editors';
|
||||
|
||||
type Props={client:WebEngineClient|null;context:NativeWorkflowContext;desktop?:boolean;initialOperator?:Extract<NativeSessionCommand,{kind:'invoke'}>;onApplied:(scene:Awaited<ReturnType<WebEngineClient['applyServerBlendResult']>>)=>void;onCommandStatus?:(status:'CANCELLED'|'FAILED')=>void};
|
||||
export function NativeSessionPanel({client,context,desktop=false,initialOperator,onApplied,onCommandStatus}:Props){
|
||||
const [status,setStatus]=useState('DISCONNECTED'),[output,setOutput]=useState(''),[source,setSource]=useState(''),[busy,setBusy]=useState(false),[screen,setScreen]=useState(''),[files,setFiles]=useState<NativeWorkflowFile[]>([]);
|
||||
const [commandStatus,setCommandStatus]=useState(''),[sessionFiles,setSessionFiles]=useState<{path:string;bytes:number}[]>([]);
|
||||
const [editor,setEditor]=useState<NonNullable<NativeWorkflowContext['areaType']>>(context.areaType??'VIEW_3D');
|
||||
const session=client?.nativeSession(desktop?'desktop':'python');
|
||||
const imageRef=useRef<HTMLImageElement>(null),events=useRef<NativeDesktopEvent[]>([]),active=useRef(true);
|
||||
useEffect(()=>{active.current=true;return()=>{active.current=false;events.current=[];void session?.close();};},[session]);
|
||||
useEffect(()=>()=>{for(const file of files)URL.revokeObjectURL(file.url);},[files]);
|
||||
const consume=async(command:NativeSessionCommand)=>{
|
||||
if(!session)return;setBusy(true);
|
||||
try{while(events.current.length)await session.events(events.current.splice(0,64));const result=await session.execute(command);if(result.scene)onApplied(result.scene);if(!active.current)return;
|
||||
const receipt=result.mainReceipt?`\n[MainReceipt] ${JSON.stringify(result.mainReceipt)}`:'';setOutput(old=>(old+'\n'+result.output+receipt).slice(-65536));setStatus('READY');
|
||||
setCommandStatus(result.pythonError?'PYTHON_ERROR':'SUCCEEDED');
|
||||
if(command.kind==='editor')setEditor(command.areaType);
|
||||
if(result.files.length)setFiles(result.files.map(file=>({artifact:file.artifact,url:URL.createObjectURL(new Blob([file.bytes],{type:file.artifact.mime}))})));
|
||||
}catch(error){const cancelled=typeof error==='object'&&error!==null&&'status' in error&&(error as {status?:unknown}).status==='CANCELLED';if(active.current){onCommandStatus?.(cancelled?'CANCELLED':'FAILED');setOutput(cancelled?'CANCELLED\n'+String(error):String(error));setCommandStatus(cancelled?'CANCELLED':'FAILED');setStatus(session.handle?'READY':'RESET_REQUIRED');if(cancelled)imageRef.current?.focus();}}finally{if(active.current)setBusy(false);}
|
||||
};
|
||||
const refreshFiles=async()=>{if(!session)return;const listed=await session.files();if(active.current)setSessionFiles(listed.files.map(file=>({path:file.path,bytes:file.bytes})));};
|
||||
const uploadSessionFile=async(file:File|null)=>{if(!file||!session)return;setBusy(true);try{await session.upload(file,`uploads/${crypto.randomUUID()}-${file.name}`);await refreshFiles();}catch(error){if(active.current)setOutput(String(error));}finally{if(active.current)setBusy(false);}};
|
||||
const connect=async()=>{
|
||||
if(!session||!client)return;setBusy(true);setStatus('STARTING');setCommandStatus('');
|
||||
try{await session.start({...context,areaType:desktop?editor:'CONSOLE'},await client.resourceBinding());if(active.current){setStatus('READY');void refreshFiles();}
|
||||
if(desktop&&initialOperator)await consume(initialOperator);
|
||||
}catch(error){if(active.current){setStatus('FAILED');setOutput(String(error));}}finally{if(active.current)setBusy(false);}
|
||||
};
|
||||
useEffect(()=>{
|
||||
if(status!=='READY'||!session||!desktop)return;
|
||||
let stopped=false,url='';const controller=new AbortController();
|
||||
const loop=async()=>{try{
|
||||
if(!session.handle){if(!stopped)setStatus('DISCONNECTED');return;}
|
||||
const picture=await session.screen(controller.signal);
|
||||
if(picture&&!stopped){const next=URL.createObjectURL(picture);setScreen(next);if(url)URL.revokeObjectURL(url);url=next;}
|
||||
}catch(error){if(!stopped){setOutput(String(error));setStatus('FAILED');}}finally{if(!stopped)timer=setTimeout(()=>void loop(),400);}};
|
||||
let timer:ReturnType<typeof setTimeout>;void loop();
|
||||
return()=>{stopped=true;controller.abort();clearTimeout(timer);if(url)URL.revokeObjectURL(url);};
|
||||
},[status,session,desktop]);
|
||||
useEffect(()=>{
|
||||
if(!desktop||!session||status!=='READY')return;
|
||||
let sending=false;
|
||||
const timer=setInterval(()=>{if(sending||!events.current.length||session.busy)return;const batch=events.current.splice(0,64);sending=true;
|
||||
void session.events(batch).catch(error=>{setOutput(String(error));setStatus('FAILED');}).finally(()=>{sending=false;});},35);
|
||||
return()=>{clearInterval(timer);events.current=[];};
|
||||
},[desktop,session,status]);
|
||||
const push=(event:NativeDesktopEvent)=>{if(busy||status!=='READY')return;
|
||||
if(event.type==='move'&&events.current.at(-1)?.type==='move')events.current[events.current.length-1]=event;
|
||||
else if(events.current.length<256)events.current.push(event);
|
||||
else{events.current=[{type:'release'}];setOutput('INPUT_BACKLOG: input released');}
|
||||
};
|
||||
const point=(event:React.PointerEvent<HTMLImageElement>)=>{const rect=event.currentTarget.getBoundingClientRect();const width=session?.handle?.width??1280,height=session?.handle?.height??900;const nativeWidth=Number.isFinite(width)&&width>0?Math.round(width):1280,nativeHeight=Number.isFinite(height)&&height>0?Math.round(height):900;return {x:Math.max(0,Math.min(nativeWidth-1,Math.round((event.clientX-rect.left)/rect.width*nativeWidth))),y:Math.max(0,Math.min(nativeHeight-1,Math.round((event.clientY-rect.top)/rect.height*nativeHeight)))};};
|
||||
return <div className="native-session-panel" data-command-status={commandStatus}>
|
||||
<div className="native-workflow-controls"><button disabled={!client||busy} onClick={()=>void connect()}>{session?.handle?'Reset Session':'Connect'}</button><button disabled={!session?.handle} onClick={()=>{void session?.close();setStatus('DISCONNECTED');setScreen('');}}>Disconnect / Stop</button>
|
||||
{desktop?<><label>编辑器<select aria-label="原生编辑器" disabled={busy} value={editor} onChange={e=>{const areaType=e.target.value as typeof editor;if(status==='READY')void consume({kind:'editor',areaType});else setEditor(areaType);}}>{NATIVE_EDITORS.map(item=><option key={item.id} value={item.id}>{item.label}</option>)}</select></label><label>上传恢复文件<input type="file" disabled={busy||status!=='READY'} onChange={e=>{const file=e.target.files?.[0]??null;e.target.value='';void uploadSessionFile(file);}}/></label><button disabled={busy||status!=='READY'} onClick={()=>void consume({kind:'preferences-save'})}>保存偏好设置</button></>:null}
|
||||
{desktop?<><button disabled={status!=='READY'} onClick={()=>void session?.cancelModal()}>Cancel Tool</button><button disabled={busy||status!=='READY'} onClick={()=>void consume({kind:'commit'})}>Apply to Web Scene</button></>:<><button disabled={busy||status!=='READY'||!source.trim()} onClick={()=>{setOutput(old=>old+'\n>>> '+source);void consume({kind:'python',source});}}>Execute</button><button disabled={busy||status!=='READY'} onClick={()=>void consume({kind:'undo'})}>Undo Main</button><button disabled={busy||status!=='READY'} onClick={()=>void consume({kind:'redo'})}>Redo Main</button><button disabled={busy||status!=='READY'} onClick={()=>void consume({kind:'commit'})}>Apply to Web Scene</button></>}<output role="status">{busy?'RUNNING':status}</output></div>
|
||||
{desktop?<div className="native-desktop-view">{screen?<img ref={imageRef} src={screen} alt="Live native Blender desktop" draggable={false} tabIndex={0}
|
||||
onPointerMove={e=>push({type:'move',...point(e)})} onPointerDown={e=>{e.preventDefault();e.currentTarget.focus();e.currentTarget.setPointerCapture(e.pointerId);push({type:'button',...point(e),button:e.button===1?2:e.button===2?3:1,down:true});}}
|
||||
onPointerUp={e=>{push({type:'button',...point(e),button:e.button===1?2:e.button===2?3:1,down:false});e.currentTarget.releasePointerCapture(e.pointerId);}}
|
||||
onPointerCancel={()=>push({type:'release'})} onBlur={()=>push({type:'release'})} onContextMenu={e=>e.preventDefault()}
|
||||
onWheel={e=>{e.preventDefault();push({type:'wheel',delta:e.deltaY<0?-1:1});}}
|
||||
onKeyDown={e=>{e.preventDefault();e.stopPropagation();push({type:'key',code:e.code,down:true});}} onKeyUp={e=>{e.preventDefault();e.stopPropagation();push({type:'key',code:e.code,down:false});}}/>:<span>{status}</span>}</div>
|
||||
:<textarea aria-label="Persistent Python command" value={source} onChange={e=>setSource(e.target.value)} onKeyDown={e=>{if(e.key==='Enter'&&!e.shiftKey&&!busy&&status==='READY'){e.preventDefault();setOutput(old=>old+'\n>>> '+source);void consume({kind:'python',source});}}} spellCheck={false}/>}
|
||||
{commandStatus==='PYTHON_ERROR'?<span role="alert" aria-label="Last Python command">PYTHON_ERROR</span>:commandStatus==='CANCELLED'?<span role="status" aria-label="Last native command">CANCELLED</span>:null}
|
||||
<pre className="native-workflow-output">{output}</pre>{desktop&&sessionFiles.length?<output aria-label="原生会话文件">{sessionFiles.map(file=>`${file.path} (${file.bytes} bytes)`).join('\n')}</output>:null}<div className="native-workflow-artifacts">{files.map(file=><a key={file.artifact.id} href={file.url} download={file.artifact.name}>{file.artifact.name}</a>)}</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function NativeResourcesPanel({client}:{client:WebEngineClient|null}){
|
||||
const [files,setFiles]=useState<{file:File;path:string;sourcePath?:string}[]>([]),[status,setStatus]=useState(''),[busy,setBusy]=useState(false);
|
||||
const add=(selected:FileList|null,directory:boolean)=>{if(!selected)return;setFiles([...selected].map(file=>({file,path:directory?file.webkitRelativePath.split('/').slice(1).join('/'):file.name})));setStatus('');};
|
||||
return <div className="native-resources-panel"><div className="native-workflow-controls"><label>Project folder<input type="file" multiple {...{webkitdirectory:''}} onChange={e=>add(e.target.files,true)}/></label><label>Resource files<input type="file" multiple onChange={e=>add(e.target.files,false)}/></label>
|
||||
<button disabled={!client||busy||!files.length} onClick={()=>{if(!client)return;setBusy(true);void client.uploadNativeResources(files).then(result=>setStatus(`${result.files.length} files synchronized`)).catch(error=>setStatus(String(error))).finally(()=>setBusy(false));}}>Sync Resources</button>
|
||||
<button disabled={!client||busy} onClick={()=>{if(!client)return;setBusy(true);void client.clearNativeResources().then(()=>{setFiles([]);setStatus('Resources cleared');}).catch(error=>setStatus(String(error))).finally(()=>setBusy(false));}}>Clear Resources</button><output>{busy?'UPLOADING':status}</output></div>
|
||||
<div className="native-resource-list">{files.map((item,index)=><div key={index}><span>{item.file.name}</span><input aria-label={`Project path ${index+1}`} value={item.path} onChange={e=>setFiles(current=>current.map((entry,i)=>i===index?{...entry,path:e.target.value}:entry))}/><input aria-label={`Original Blender path ${index+1}`} placeholder="//textures/image.png" value={item.sourcePath??''} onChange={e=>setFiles(current=>current.map((entry,i)=>i===index?{...entry,sourcePath:e.target.value||undefined}:entry))}/></div>)}</div></div>;
|
||||
}
|
||||
73
web/app/src/app/NativeWorkflowPanels.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import type {SceneSnapshotIR} from '../../../protocol/scene-ir';
|
||||
import type {NativeWorkflowInput,NativeWorkflowArtifact} from '../../../protocol/native-workflow';
|
||||
import {NativeResourcesPanel} from './NativeSessionPanel';
|
||||
import type {WebEngineClient} from '../engine-client/WebEngineClient';
|
||||
|
||||
export interface NativeWorkflowFile { artifact: NativeWorkflowArtifact; url: string }
|
||||
export interface NativeWorkflowControls {
|
||||
client?:WebEngineClient|null;
|
||||
snapshot: SceneSnapshotIR | null;
|
||||
busy: boolean;
|
||||
output: string;
|
||||
onRun: (input: NativeWorkflowInput) => Promise<void>;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export function NativeRenderPanel({snapshot,busy,output,onRun,onCancel,files,client}:NativeWorkflowControls&{files:NativeWorkflowFile[]}) {
|
||||
const scenes=snapshot?.scenes??[];
|
||||
const activeScene=scenes.find(scene=>scene.id===snapshot?.sceneId)??scenes[0];
|
||||
const [sceneName,setSceneName]=useState(activeScene?.name??'');
|
||||
const scene=scenes.find(item=>item.name===sceneName)??activeScene;
|
||||
const sceneStart=scene?.renderSettings?.frameStart??snapshot?.frame.start??1;
|
||||
const sceneEnd=scene?.renderSettings?.frameEnd??snapshot?.frame.end??sceneStart;
|
||||
const sceneStep=scene?.timelineSettings?.frameStep??1;
|
||||
const sceneScale=scene?.renderSettings?.resolutionPercentage??100;
|
||||
const [engine,setEngine]=useState<NonNullable<NativeWorkflowInput['render']>['engine']>('SCENE');
|
||||
const [format,setFormat]=useState<'PNG'|'OPEN_EXR'|'FFMPEG'>('PNG');
|
||||
const [start,setStart]=useState(sceneStart);
|
||||
const [end,setEnd]=useState(sceneEnd);
|
||||
const [step,setStep]=useState(sceneStep);
|
||||
const [scale,setScale]=useState(sceneScale);
|
||||
const [selected,setSelected]=useState('');
|
||||
useEffect(()=>{if(!scenes.some(s=>s.name===sceneName))setSceneName(activeScene?.name??'');},[scenes,sceneName,activeScene?.name]);
|
||||
useEffect(()=>{setStart(sceneStart);setEnd(sceneEnd);setStep(sceneStep);setScale(sceneScale);},[scene?.id,sceneStart,sceneEnd,sceneStep,sceneScale]);
|
||||
const images=files.filter(f=>f.artifact.mime==='image/png');
|
||||
const image=images.find(f=>f.artifact.id===selected)??images[0];
|
||||
const video=files.find(f=>f.artifact.mime==='video/mp4');
|
||||
const render=(animation:boolean)=>onRun({kind:'RENDER',context:{sceneName},render:{engine,format,frameStart:animation?start:snapshot?.frame.current??start,frameEnd:animation?end:snapshot?.frame.current??start,step:animation?step:1,resolutionPercentage:scale}});
|
||||
return <div className="native-render-panel">
|
||||
<NativeResourcesPanel client={client??null}/>
|
||||
<div className="native-workflow-controls"><label>Scene<select aria-label="Scene" value={sceneName} onChange={e=>setSceneName(e.target.value)}>{scenes.map(s=><option key={s.id} value={s.name}>{s.name}</option>)}</select></label>
|
||||
<label>Engine<select aria-label="Engine" value={engine} onChange={e=>setEngine(e.target.value as typeof engine)}><option value="SCENE">Scene</option><option value="CYCLES">Cycles CPU</option><option value="BLENDER_EEVEE">Eevee</option><option value="BLENDER_WORKBENCH">Workbench</option></select></label>
|
||||
<label>Format<select aria-label="Format" value={format} onChange={e=>setFormat(e.target.value as typeof format)}><option value="PNG">PNG</option><option value="OPEN_EXR">OpenEXR</option><option value="FFMPEG">MP4 / H.264</option></select></label>
|
||||
<label>Resolution %<input type="number" min={1} max={100} value={scale} onChange={e=>setScale(Number(e.target.value))}/></label>
|
||||
<label>Start<input type="number" value={start} onChange={e=>setStart(Number(e.target.value))}/></label><label>End<input type="number" value={end} onChange={e=>setEnd(Number(e.target.value))}/></label><label>Step<input type="number" min={1} max={1000} value={step} onChange={e=>setStep(Number(e.target.value))}/></label>
|
||||
<button type="button" disabled={busy||!snapshot} onClick={()=>void render(false)}>Render Frame</button><button type="button" disabled={busy||!snapshot||end<start} onClick={()=>void render(true)}>Render Animation</button><button type="button" disabled={!busy} onClick={onCancel}>Cancel</button>
|
||||
</div>
|
||||
<div className="native-render-image">{image?<img src={image.url} alt={`Blender render frame ${image.artifact.frame??''}`}/>:video?<video src={video.url} controls/>:<output>{busy?'Rendering…':'Render Result'}</output>}</div>
|
||||
<div className="native-workflow-artifacts">{images.length>1?<label>Frame<select value={image?.artifact.id??''} onChange={e=>setSelected(e.target.value)}>{images.map(f=><option key={f.artifact.id} value={f.artifact.id}>{f.artifact.frame}</option>)}</select></label>:null}{files.map(f=><a key={f.artifact.id} href={f.url} download={f.artifact.name}>{f.artifact.name}</a>)}</div>
|
||||
<pre className="native-workflow-output" role="status">{output}</pre>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function NativePythonPanel({snapshot,busy,output,onRun,onCancel,consoleMode=false,client}:NativeWorkflowControls&{consoleMode?:boolean}) {
|
||||
const texts=(snapshot?.texts??[]).filter(t=>!t.internal);
|
||||
const [name,setName]=useState(consoleMode?'WebConsole.py':'WebScript.py');
|
||||
const [source,setSource]=useState(consoleMode?'bpy.context.scene.name':'import bpy\nprint(bpy.context.scene.name)\n');
|
||||
const [history,setHistory]=useState<string[]>([]);
|
||||
const [historyIndex,setHistoryIndex]=useState(-1);
|
||||
const run=async()=>{if(!source.trim())return;setHistory(current=>[...current.slice(-99),source]);setHistoryIndex(-1);await onRun({kind:'PYTHON',context:{},python:{source,textName:name,console:consoleMode}});};
|
||||
return <div className="native-python-panel">
|
||||
{!consoleMode?<NativeResourcesPanel client={client??null}/>:null}
|
||||
<div className="native-workflow-controls">{!consoleMode?<><label>Text<select value={texts.some(t=>t.name===name)?name:''} onChange={e=>{const text=texts.find(t=>t.name===e.target.value);if(text){setName(text.name);setSource(text.source??'');}}}><option value="">New script</option>{texts.map(t=><option key={t.id} value={t.name}>{t.name}</option>)}</select></label><label>Name<input value={name} maxLength={128} onChange={e=>setName(e.target.value)}/></label><label>Open .py<input type="file" accept=".py,text/x-python" onChange={e=>{const file=e.target.files?.[0];if(file&&file.size<=65536){void file.text().then(text=>{setName(file.name);setSource(text);});}}}/></label></>:null}
|
||||
<button type="button" disabled={busy||!snapshot||!source.trim()||!name.trim()} onClick={()=>void run()}>{consoleMode?'Execute':'Run Script'}</button><button type="button" disabled={!busy} onClick={onCancel}>Cancel</button>
|
||||
</div>
|
||||
{consoleMode?<pre className="native-workflow-output" aria-label="Python output">{output}</pre>:null}
|
||||
<textarea aria-label={consoleMode?'Python Console command':'Python script source'} value={source} maxLength={65536} spellCheck={false} onChange={e=>setSource(e.target.value)} onKeyDown={e=>{
|
||||
if(consoleMode&&e.key==='Enter'&&!e.shiftKey&&!busy){e.preventDefault();void run();}
|
||||
if(consoleMode&&e.key==='ArrowUp'&&e.altKey&&history.length){e.preventDefault();const index=historyIndex<0?history.length-1:Math.max(0,historyIndex-1);setHistoryIndex(index);setSource(history[index]);}
|
||||
}}/>
|
||||
{!consoleMode?<pre className="native-workflow-output" aria-label="Python output">{output}</pre>:null}
|
||||
</div>;
|
||||
}
|
||||
35
web/app/src/app/OBJImportPanel.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { EDITOR_RESOURCE_MAX_BYTES, modelResourcePath } from '../../../protocol/editor-resource-path';
|
||||
export type OBJBundleFile = { file: File; path: string };
|
||||
export type OBJBundleTransfer = { signal: AbortSignal; progress: (count: number) => void };
|
||||
export function OBJImportPanel({ disabled, initialFile, onPrepare }: { disabled: boolean; initialFile?: File | null; onPrepare: (files: OBJBundleFile[], entry: string, batchId: string, transfer: OBJBundleTransfer) => Promise<void> }) {
|
||||
const [files, setFiles] = useState<OBJBundleFile[]>(initialFile ? [{ file: initialFile, path: initialFile.name }] : []), [entry, setEntry] = useState(initialFile?.name ?? ''), [batchId, setBatchId] = useState(() => crypto.randomUUID());
|
||||
const [busy, setBusy] = useState(false), [message, setMessage] = useState(''); const pending = useRef(false), controller = useRef<AbortController | null>(null);
|
||||
useEffect(() => () => controller.current?.abort(), []);
|
||||
const select = (selected: FileList | null) => {
|
||||
if (!selected?.length || pending.current) return;
|
||||
try {
|
||||
const next = Array.from(selected, file => ({ file, path: file.webkitRelativePath || file.name })), id = crypto.randomUUID(), names = new Set<string>();
|
||||
if (next.length > 256 || next.reduce((bytes, item) => bytes + item.file.size, 0) > EDITOR_RESOURCE_MAX_BYTES) throw new Error('请选择不超过 256 个、合计不超过 256 MiB 的文件');
|
||||
for (const item of next) { modelResourcePath(id, item.path); if (names.has(item.path)) throw new Error(`文件路径重复:${item.path}`); names.add(item.path); }
|
||||
const models = next.filter(item => /\.obj$/i.test(item.path) && item.file.size > 0);
|
||||
if (!models.length) throw new Error('所选文件中没有可用的 OBJ 模型');
|
||||
setFiles(next); setEntry(models[0].path); setBatchId(id); setMessage('');
|
||||
} catch (error) { setFiles([]); setEntry(''); setMessage(String(error instanceof Error ? error.message : error)); }
|
||||
};
|
||||
const prepare = async () => {
|
||||
if (disabled || pending.current || !entry) return;
|
||||
const request = new AbortController(); controller.current = request; pending.current = true; setBusy(true); setMessage('正在准备模型文件…');
|
||||
try { await onPrepare(files, entry, batchId, { signal: request.signal, progress: count => setMessage(`已准备 ${count}/${files.length} 个文件`) }); }
|
||||
catch (error) { setMessage(request.signal.aborted ? '已取消文件准备,当前场景未导入模型。' : String(error instanceof Error ? error.message : error)); }
|
||||
finally { if (controller.current === request) controller.current = null; pending.current = false; setBusy(false); }
|
||||
};
|
||||
return <form onSubmit={event => { event.preventDefault(); void prepare(); }}>
|
||||
<p>一起选择 OBJ、MTL 和贴图。有子目录时请选择共同的上级文件夹,保留文件名和层级。下一步在 Blender 文件窗口中确认导入。</p>
|
||||
<label>选择文件夹<input type="file" multiple ref={input => { input?.setAttribute('webkitdirectory', ''); }} disabled={disabled || busy} onChange={event => { select(event.currentTarget.files); event.currentTarget.value = ''; }} /></label>
|
||||
<label>选择文件<input type="file" multiple disabled={disabled || busy} onChange={event => { select(event.currentTarget.files); event.currentTarget.value = ''; }} /></label>
|
||||
<label>OBJ 模型<select aria-label="OBJ 模型" value={entry} disabled={disabled || busy} onChange={event => setEntry(event.target.value)}>{files.filter(item => /\.obj$/i.test(item.path) && item.file.size > 0).map(item => <option key={item.path} value={item.path}>{item.path}</option>)}</select></label>
|
||||
<output role="status">{message}</output>
|
||||
<div className="desktop-dialog-actions"><button type="button" disabled={!busy} onClick={() => controller.current?.abort()}>取消准备</button><button type="submit" disabled={disabled || busy || !entry}>打开导入选项</button></div>
|
||||
</form>;
|
||||
}
|
||||
6
web/app/src/app/PhysicsSettingsEditor.css
Normal file
@@ -0,0 +1,6 @@
|
||||
.physics-settings-editor { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
|
||||
.physics-settings-editor > label { display: grid; grid-template-columns: minmax(0, 1fr) 110px; align-items: center; gap: 6px; overflow-wrap: anywhere; }
|
||||
.physics-settings-editor input:not([type="checkbox"]), .physics-settings-editor select { box-sizing: border-box; min-width: 0; width: 100%; }
|
||||
.physics-settings-editor input[type="checkbox"] { justify-self: end; }
|
||||
.physics-settings-editor > button { align-self: start; min-height: 24px; padding: 3px 7px; color: #e2e2e2; background: #454545; border: 1px solid #575757; border-radius: 2px; }
|
||||
.physics-settings-editor > button:hover { background: #555; }
|
||||
252
web/app/src/app/PhysicsSettingsEditor.tsx
Normal file
@@ -0,0 +1,252 @@
|
||||
import { useState } from "react";
|
||||
import type { PhysicsSimulationManifestIR, PhysicsNativeCacheTargetIR } from "../../../protocol/physics-simulation";
|
||||
import type { WebEngineEditCommand } from "../../../protocol/web-engine";
|
||||
import type { CollectionIR } from "../../../protocol/scene-ir";
|
||||
|
||||
type Family = "RIGID_BODY" | "SOFT_BODY" | "CLOTH" | "FLUID" | "PARTICLE";
|
||||
export type PointCacheOperation = "BAKE_ALL" | "FREE_ALL";
|
||||
export type SoftBodyCacheRequest = { objectId: string; target: PhysicsNativeCacheTargetIR } & ({ operation: "BAKE" | "CALCULATE" | "FREE" | "ADD" | "REMOVE" } | { operation: "SELECT"; slotIndex: number } | { operation: "RENAME"; name: string });
|
||||
const FLUID_CACHE_STAGES = [
|
||||
["all", "All"], ["data", "Data"], ["noise", "Noise"],
|
||||
["mesh", "Mesh"], ["particles", "Particles"], ["guides", "Guides"],
|
||||
] as const;
|
||||
export type FluidCacheOperation = `${"bake" | "free"}_${typeof FLUID_CACHE_STAGES[number][0]}`;
|
||||
type Field = { key: string; label: string; min?: number; max?: number; integer?: boolean; options?: [number, string][]; requiresEdges?: boolean; requiresSelfCollision?: boolean; requiresPressure?: boolean; requiresPressureVolume?: boolean };
|
||||
const SOFT_EFFECTOR_FIELDS: Field[] = ([
|
||||
["effectorGravity", "Gravity"], ["effectorAll", "All Fields"], ["effectorForce", "Force"],
|
||||
["effectorVortex", "Vortex"], ["effectorMagnetic", "Magnetic"], ["effectorWind", "Wind"],
|
||||
["effectorCurveGuide", "Curve Guide"], ["effectorTexture", "Texture"], ["effectorHarmonic", "Harmonic"],
|
||||
["effectorCharge", "Charge"], ["effectorLennardJones", "Lennard-Jones"], ["effectorBoid", "Boid"],
|
||||
["effectorTurbulence", "Turbulence"], ["effectorDrag", "Drag"], ["effectorSmokeFlow", "Fluid Flow"],
|
||||
] as const).map(([key, label]) => ({ key, label: `${label} Weight`, min: -200, max: 200 }));
|
||||
|
||||
const commands = {
|
||||
SOFT_BODY: "setRigidBodySettings",
|
||||
RIGID_BODY: "setRigidBodySettings", CLOTH: "setClothSettings",
|
||||
FLUID: "setFluidSettings", PARTICLE: "setParticleCache",
|
||||
} as const;
|
||||
const fields: Record<Family, Field[]> = {
|
||||
SOFT_BODY: [
|
||||
{ key: "nodeMass", label: "Mass", min: 0, max: 50000 },
|
||||
{ key: "mediaFriction", label: "Friction", min: 0, max: 50 },
|
||||
{ key: "physicsSpeed", label: "Speed", min: 0.01, max: 100 },
|
||||
{ key: "goalSpring", label: "Goal Stiffness", min: 0, max: 0.999 },
|
||||
{ key: "goalFriction", label: "Goal Damping", min: 0, max: 50 },
|
||||
{ key: "goalDefault", label: "Goal Default", min: 0, max: 1 },
|
||||
{ key: "goalMin", label: "Goal Minimum", min: 0, max: 1 },
|
||||
{ key: "goalMax", label: "Goal Maximum", min: 0, max: 1 },
|
||||
{ key: "pull", label: "Pull", min: 0, max: 0.999, requiresEdges: true },
|
||||
{ key: "push", label: "Push", min: 0, max: 0.999, requiresEdges: true },
|
||||
{ key: "damping", label: "Edge Damping", min: 0, max: 50, requiresEdges: true },
|
||||
{ key: "bending", label: "Bending", min: 0, max: 10, requiresEdges: true },
|
||||
{ key: "shear", label: "Shear", min: 0, max: 1, requiresEdges: true },
|
||||
{ key: "plasticity", label: "Plasticity", min: 0, max: 100, integer: true, requiresEdges: true },
|
||||
{ key: "springLength", label: "Spring Length (%, 0 off)", min: 0, max: 200, integer: true, requiresEdges: true },
|
||||
{ key: "aero", label: "Aerodynamic Force", min: 0, max: 30000, integer: true, requiresEdges: true },
|
||||
{ key: "aerodynamicsType", label: "Aerodynamics", options: [[0, "Simple"], [1, "Lift Force"]], requiresEdges: true },
|
||||
{ key: "collisionType", label: "Collision Size Method", options: [[0, "Manual"], [1, "Average"], [2, "Minimum"], [3, "Maximum"], [4, "Average Min/Max"]], requiresSelfCollision: true },
|
||||
{ key: "ballSize", label: "Ball Size / Factor", min: -10, max: 10, requiresSelfCollision: true },
|
||||
{ key: "ballStiffness", label: "Ball Stiffness", min: 0.001, max: 100, requiresSelfCollision: true },
|
||||
{ key: "ballDamping", label: "Ball Damping", min: 0.001, max: 1, requiresSelfCollision: true },
|
||||
{ key: "errorThreshold", label: "Solver Error Limit", min: 0.001, max: 10 },
|
||||
{ key: "stepMin", label: "Minimum Steps per Frame", min: 0, max: 30000, integer: true },
|
||||
{ key: "stepMax", label: "Maximum Steps per Frame", min: 0, max: 30000, integer: true },
|
||||
{ key: "choke", label: "Collision Choke", min: 0, max: 100, integer: true },
|
||||
{ key: "fuzzy", label: "Collision Fuzziness", min: 1, max: 100, integer: true },
|
||||
...SOFT_EFFECTOR_FIELDS,
|
||||
{ key: "cacheFrameStart", label: "Cache Start", min: -1048574, max: 1048574, integer: true },
|
||||
{ key: "cacheFrameEnd", label: "Cache End", min: 1, max: 1048574, integer: true },
|
||||
{ key: "cacheFrameStep", label: "Cache Step", min: 1, max: 20, integer: true },
|
||||
],
|
||||
RIGID_BODY: [
|
||||
{ key: "type", label: "Type", options: [[0, "Active"], [1, "Passive"]] },
|
||||
{ key: "mass", label: "Mass", min: 0.000001 },
|
||||
{ key: "collisionShape", label: "Shape", options: [[0, "Box"], [1, "Sphere"], [2, "Capsule"], [3, "Cylinder"], [4, "Cone"], [5, "Convex Hull"], [6, "Mesh"]] },
|
||||
{ key: "friction", label: "Friction", min: 0, max: 100 },
|
||||
{ key: "restitution", label: "Restitution", min: 0, max: 1 },
|
||||
{ key: "linearDamping", label: "Linear Damping", min: 0, max: 1 },
|
||||
{ key: "angularDamping", label: "Angular Damping", min: 0, max: 1 },
|
||||
{ key: "substepsPerFrame", label: "Substeps", min: 1, max: 32767, integer: true },
|
||||
{ key: "solverIterations", label: "Solver Iterations", min: 1, max: 32767, integer: true },
|
||||
],
|
||||
CLOTH: [
|
||||
{ key: "quality", label: "Quality", min: 1, max: 32767, integer: true },
|
||||
{ key: "mass", label: "Vertex Mass", min: 0 },
|
||||
{ key: "airDamping", label: "Air Damping", min: 0, max: 10 },
|
||||
{ key: "tensionStiffness", label: "Tension", min: 0, max: 10000 },
|
||||
{ key: "compressionStiffness", label: "Compression", min: 0, max: 10000 },
|
||||
{ key: "shearStiffness", label: "Shear", min: 0, max: 10000 },
|
||||
{ key: "bendingStiffness", label: "Bending", min: 0, max: 10000 },
|
||||
{ key: "springDamping", label: "Spring Damping", min: 0, max: 1000 },
|
||||
{ key: "pinStiffness", label: "Pin Stiffness", min: 0, max: 50 },
|
||||
{ key: "uniformPressureForce", label: "Pressure", min: -10000, max: 10000, requiresPressure: true },
|
||||
{ key: "targetVolume", label: "Target Volume", min: 0, max: 10000, requiresPressure: true, requiresPressureVolume: true },
|
||||
{ key: "pressureFactor", label: "Pressure Scale", min: 0, max: 10000, requiresPressure: true },
|
||||
{ key: "fluidDensity", label: "Fluid Density", requiresPressure: true },
|
||||
],
|
||||
FLUID: [
|
||||
{ key: "fluidType", label: "Type", options: [[1, "Domain"], [2, "Flow"], [4, "Effector"]] },
|
||||
{ key: "domainType", label: "Domain", options: [[0, "Gas"], [1, "Liquid"]] },
|
||||
{ key: "resolution", label: "Resolution", min: 6, max: 10000, integer: true },
|
||||
{ key: "timeScale", label: "Time Scale", min: 0.0001, max: 10 },
|
||||
{ key: "viscosity", label: "Viscosity", min: 0, max: 10 },
|
||||
{ key: "cacheFrameStart", label: "Cache Start", min: 1, max: 1048574, integer: true },
|
||||
{ key: "cacheFrameEnd", label: "Cache End", min: 1, max: 1048574, integer: true },
|
||||
{ key: "cacheType", label: "Cache", options: [[0, "Replay"], [1, "Modular"], [2, "All"]] },
|
||||
],
|
||||
PARTICLE: [
|
||||
{ key: "frameStart", label: "Cache Start", min: 1, max: 1048574, integer: true },
|
||||
{ key: "frameEnd", label: "Cache End", min: 1, max: 1048574, integer: true },
|
||||
{ key: "compression", label: "Compression", options: [[0, "None"], [3, "Zstandard"]] },
|
||||
],
|
||||
};
|
||||
|
||||
export function PhysicsSettingsEditor({ objectId, manifest, collections = [], onCommand, onPointCacheOperation, onSoftBodyCacheOperation, onFluidCacheOperation, softBodyOnly = false, pointCacheBusy = false }: {
|
||||
objectId: string;
|
||||
manifest?: PhysicsSimulationManifestIR;
|
||||
collections?: readonly CollectionIR[];
|
||||
onCommand: (command: WebEngineEditCommand) => Promise<boolean> | void;
|
||||
onPointCacheOperation?: (operation: PointCacheOperation) => void;
|
||||
onSoftBodyCacheOperation?: (request: SoftBodyCacheRequest) => void;
|
||||
onFluidCacheOperation?: (objectId: string, operation: FluidCacheOperation) => void;
|
||||
pointCacheBusy?: boolean;
|
||||
softBodyOnly?: boolean;
|
||||
}) {
|
||||
const [selectedFamily, setFamily] = useState<Family>("RIGID_BODY");
|
||||
const [softGroupDraft, setSoftGroupDraft] = useState<Record<string, string>>({});
|
||||
const [cacheNameDraft, setCacheNameDraft] = useState<{ key: string; name: string } | null>(null);
|
||||
const family = softBodyOnly ? "SOFT_BODY" : selectedFamily;
|
||||
const system = manifest?.systems.find(item => item.ownerObjectId === objectId &&
|
||||
(item.family === family || (family === "PARTICLE" && item.family === "HAIR")));
|
||||
const values = system?.settings ?? {};
|
||||
const nativeCache = family === "SOFT_BODY" ? system?.nativeCache : undefined;
|
||||
const cacheSlots = nativeCache?.slots;
|
||||
const activeCacheName = cacheSlots?.items.find(slot => slot.index === nativeCache?.target?.slotIndex)?.name;
|
||||
const cacheNameKey = JSON.stringify([objectId, nativeCache?.target, activeCacheName]);
|
||||
const cacheNameValue = cacheNameDraft?.key === cacheNameKey ? cacheNameDraft.name : activeCacheName ?? "";
|
||||
const cacheNameInvalid = cacheNameValue.includes("\0") || new TextEncoder().encode(cacheNameValue).length > 63;
|
||||
const selectCacheSlot = (slotIndex: number) => {
|
||||
if (!onSoftBodyCacheOperation || !nativeCache?.target || !cacheSlots || pointCacheBusy || nativeCache.baking || !Number.isInteger(slotIndex) || slotIndex < 0 || slotIndex >= cacheSlots.count || slotIndex === nativeCache.target.slotIndex) return;
|
||||
onSoftBodyCacheOperation({ objectId, target: nativeCache.target, operation: "SELECT", slotIndex });
|
||||
};
|
||||
const settingsLocked = family === "SOFT_BODY" && (pointCacheBusy || nativeCache?.baked === true || nativeCache?.baking === true);
|
||||
const collectionChoices = collections.filter(collection => !collection.isMaster);
|
||||
const fluidStages = FLUID_CACHE_STAGES.filter(([stage]) => stage === "guides" || (values.cacheType === 2 ? stage === "all" : values.cacheType === 1 && stage !== "all" && (stage !== "noise" || values.domainType === 0) && (!(["mesh", "particles"] as string[]).includes(stage) || values.domainType === 1)));
|
||||
const send = (settings: Record<string, unknown>) => settingsLocked ? Promise.resolve(false) : onCommand({ type: commands[family], objectId, settings, ...(family === "SOFT_BODY" ? { family } : {}) } as WebEngineEditCommand);
|
||||
const applySoftGroup = (key: "massVertexGroup" | "goalVertexGroup" | "springVertexGroup", name: string) => {
|
||||
const clear = () => setSoftGroupDraft(draft => { if (draft[key] !== name) return draft; const next = { ...draft }; delete next[key]; return next; });
|
||||
if (name === (typeof values[key] === "string" ? values[key] : "")) { clear(); return; }
|
||||
void Promise.resolve(send({ [key]: name })).then(clear, clear);
|
||||
};
|
||||
const collectionControl = (key: "collisionCollectionId" | "effectorCollectionId", label: string, emptyLabel: string) => {
|
||||
const id = typeof values[key] === "string" ? values[key] as string : "";
|
||||
return <label key={key}>{label}<select aria-label={`SOFT_BODY ${label}`} value={id} disabled={pointCacheBusy} onChange={event => send({ [key]: event.target.value || null })}>
|
||||
<option value="">{emptyLabel}</option>
|
||||
{id && !collectionChoices.some(collection => collection.id === id) && <option value={id}>{collections.find(collection => collection.id === id)?.name ?? "Current collection (not listed)"}</option>}
|
||||
{collectionChoices.map(collection => <option key={collection.id} value={collection.id}>{collection.name}{collection.sourceLibrary ? ` · ${collection.sourceLibrary}` : ""}</option>)}
|
||||
</select></label>;
|
||||
};
|
||||
const add = () => send(family === "SOFT_BODY" ? { nodeMass: 1 } : family === "RIGID_BODY" ? { type: 0, mass: 1 } :
|
||||
family === "CLOTH" ? { quality: 5 } : { fluidType: 1, resolution: 32 });
|
||||
const toggles: [string, string][] = family === "SOFT_BODY" ? [["useGoal", "Use Goal"], ["useEdges", "Use Edges"], ["useStiffQuads", "Stiff Quads"], ["useEdgeCollision", "Edge Collision"], ["useFaceCollision", "Face Collision"], ["useSelfCollision", "Self Collision"]] : family === "RIGID_BODY" ? [["enabled", "Enabled"], ["kinematic", "Animated"]] :
|
||||
family === "CLOTH" ? [["usePressure", "Use Pressure"], ["usePressureVolume", "Custom Volume"]] : family === "PARTICLE" ? [["useDiskCache", "Disk Cache"]] : [];
|
||||
return <div className="physics-settings-editor">
|
||||
<label>System<select aria-label="Physics system" value={family} onChange={event => setFamily(event.target.value as Family)}>
|
||||
<option value="SOFT_BODY">Soft Body</option>
|
||||
{!softBodyOnly && <>
|
||||
<option value="RIGID_BODY">Rigid Body</option><option value="CLOTH">Cloth</option>
|
||||
<option value="FLUID">Fluid</option><option value="PARTICLE">Particle Cache</option>
|
||||
</>}
|
||||
</select></label>
|
||||
<fieldset disabled={settingsLocked}><legend>Simulation Settings</legend>
|
||||
{!system && (family === "PARTICLE" ? <span>No particle cache</span> : <button type="button" onClick={add}>Add</button>)}
|
||||
{system && fields[family].filter(field => family !== "FLUID" || field.key === "fluidType" || values.fluidType === 1).map(field => {
|
||||
const value = typeof values[field.key] === "number" ? values[field.key] as number : undefined;
|
||||
const disabled = (family === "SOFT_BODY" && ((field.key.startsWith("goal") && values.useGoal === false) || (field.requiresEdges === true && values.useEdges === false) || (field.key === "shear" && values.useStiffQuads === false) || (field.requiresSelfCollision === true && values.useSelfCollision === false))) ||
|
||||
(field.requiresPressure === true && values.usePressure !== true) || (field.requiresPressureVolume === true && values.usePressureVolume !== true) ||
|
||||
(family === "CLOTH" && field.key === "pinStiffness" && !values.pinVertexGroup);
|
||||
return <label key={`${objectId}:${family}:${field.key}:${value}`}>{field.label}
|
||||
{field.options ? <select aria-label={`${family} ${field.label}`} disabled={disabled} value={value ?? ""} onChange={event => send({ [field.key]: Number(event.target.value) })}>
|
||||
{value === undefined && <option value="" disabled />}
|
||||
{field.options.map(([id, label]) => <option key={id} value={id}>{label}</option>)}
|
||||
</select> : <input aria-label={`${family} ${field.label}`} type="number" min={field.min} max={field.max} disabled={disabled}
|
||||
step={field.integer ? 1 : "any"} defaultValue={value === undefined ? "" : Number(value.toPrecision(7))}
|
||||
onKeyDown={event => { if (event.key === "Enter") event.currentTarget.blur(); }}
|
||||
onBlur={event => {
|
||||
const input = event.currentTarget, next = Number(input.value);
|
||||
if (input.value === "" || !Number.isFinite(next) || !input.checkValidity()) { input.value = value === undefined ? "" : String(value); return; }
|
||||
if (next !== value && (value === undefined || Math.fround(next) !== Math.fround(value))) send({ [field.key]: next });
|
||||
}} />}
|
||||
</label>;
|
||||
})}
|
||||
{system && toggles.map(([key, label]) => <label key={key}>{label}<input type="checkbox"
|
||||
aria-label={`${family} ${label}`} disabled={(family === "SOFT_BODY" && ["useStiffQuads", "useEdgeCollision", "useFaceCollision"].includes(key) && values.useEdges === false) || (key === "usePressureVolume" && values.usePressure !== true)} checked={Boolean(values[key])} onChange={event => send({ [key]: event.target.checked })} /></label>)}
|
||||
{system && family === "SOFT_BODY" && collectionControl("collisionCollectionId", "Collision Collection", "All scene colliders")}
|
||||
{system && family === "SOFT_BODY" && collectionControl("effectorCollectionId", "Effector Collection", "All scene effectors")}
|
||||
{system && family === "SOFT_BODY" && values.vertexGroupsSupported === true && ([["massVertexGroup", "Mass Vertex Group"], ["goalVertexGroup", "Goal Vertex Group"], ["springVertexGroup", "Spring Vertex Group"]] as const).map(([key, label]) => <label key={key}>{label}
|
||||
<input type="text" aria-label={`SOFT_BODY ${label}`} maxLength={63} disabled={pointCacheBusy || (key === "goalVertexGroup" && values.useGoal === false) || (key === "springVertexGroup" && values.useEdges === false)} value={softGroupDraft[key] ?? (typeof values[key] === "string" ? values[key] as string : "")}
|
||||
onChange={event => setSoftGroupDraft(draft => ({ ...draft, [key]: event.target.value }))}
|
||||
onKeyDown={event => { if (event.key === "Enter") event.currentTarget.blur(); }}
|
||||
onBlur={event => applySoftGroup(key, event.currentTarget.value)}/>
|
||||
</label>)}
|
||||
{system && family === "CLOTH" && <label>Pin Group<input aria-label="Cloth pin group" type="text" maxLength={63} placeholder="No pinning"
|
||||
key={`${objectId}:${values.pinVertexGroup}`} defaultValue={typeof values.pinVertexGroup === "string" ? values.pinVertexGroup : ""}
|
||||
onKeyDown={event => { if (event.key === "Enter") event.currentTarget.blur(); }}
|
||||
onBlur={event => { const name = event.currentTarget.value; if (name !== (values.pinVertexGroup ?? "")) send({ pinVertexGroup: name }); }} /></label>}
|
||||
{system && family === "CLOTH" && <label>Pressure Vertex Group<input aria-label="Cloth pressure vertex group" type="text" maxLength={63}
|
||||
key={`${objectId}:${values.pressureVertexGroup}`} defaultValue={typeof values.pressureVertexGroup === "string" ? values.pressureVertexGroup : ""}
|
||||
disabled={values.usePressure !== true} placeholder="All vertices"
|
||||
onKeyDown={event => { if (event.key === "Enter") event.currentTarget.blur(); }}
|
||||
onBlur={event => { const name = event.currentTarget.value; if (name !== (values.pressureVertexGroup ?? "")) send({ pressureVertexGroup: name }); }} /></label>}
|
||||
{system && family === "CLOTH" && <p>Assign a Pin Group to pin its vertices; clear the name to remove pinning. Pressure simulates a closed mesh. Leave the pressure group empty to use all vertices. Finish or cancel baking and free the cloth cache before changing simulation settings.</p>}
|
||||
{system && family === "SOFT_BODY" && ([[1, "Print Performance to Console"], [2, "Automatic Step Size"], [4, "Estimate Transforms"]] as const).map(([bit, label]) => <label key={bit}>{label}
|
||||
<input type="checkbox" aria-label={`SOFT_BODY ${label}`} checked={Boolean(Number(values.solverFlags ?? 0) & bit)}
|
||||
onChange={event => send({ solverFlags: event.target.checked ? Number(values.solverFlags ?? 0) | bit : Number(values.solverFlags ?? 0) & ~bit })}/>
|
||||
</label>)}
|
||||
{system && family === "SOFT_BODY" && <label>Disk Cache<input type="checkbox" aria-label="SOFT_BODY Disk Cache" checked={values.cacheUseDisk === true} onChange={event => send({ cacheUseDisk: event.target.checked })}/></label>}
|
||||
</fieldset>
|
||||
{system && family === "SOFT_BODY" && <div>
|
||||
<output aria-live="polite">{nativeCache ? nativeCache.baking ? "Cache is baking" : nativeCache.baked ? "Cache is baked; free it before editing settings" : "Cache is not baked" : "Native cache status unavailable"}{nativeCache?.outdated ? " · Outdated" : ""}{nativeCache?.framesSkipped ? " · Some frames skipped" : ""}</output>
|
||||
<p>{values.cacheUseDisk === true ? "Disk cache uses separate files; saving the .blend alone does not include those files." : "Memory cache data is included by Blender when saving the .blend."}</p>
|
||||
</div>}
|
||||
{onFluidCacheOperation && family === "FLUID" && values.fluidType === 1 && <fieldset disabled={pointCacheBusy}>
|
||||
<legend>Fluid Domain Cache</legend>
|
||||
<p>Opens Blender desktop; Esc pauses baking. Enable optional stages in Blender domain settings first.</p>
|
||||
{values.cacheType === 0 && <p>Replay data is cached during playback.</p>}
|
||||
{fluidStages.map(([stage, label]) => <div key={stage}>
|
||||
<button type="button" onClick={() => onFluidCacheOperation(objectId, `bake_${stage}`)}>Bake {label}</button>
|
||||
<button type="button" onClick={() => onFluidCacheOperation(objectId, `free_${stage}`)}>Free {label}</button>
|
||||
</div>)}
|
||||
</fieldset>}
|
||||
{onSoftBodyCacheOperation && system && family === "SOFT_BODY" && <fieldset disabled={pointCacheBusy || nativeCache?.baking === true || !nativeCache?.target}>
|
||||
<legend>Active Soft Body Cache{nativeCache?.target ? ` · Slot ${nativeCache.target.slotIndex + 1}` : ""}</legend>
|
||||
{activeCacheName !== undefined && <form onSubmit={event => {
|
||||
event.preventDefault();
|
||||
if (!nativeCache?.target || pointCacheBusy || nativeCache.baking || cacheNameInvalid || cacheNameValue === activeCacheName) return;
|
||||
onSoftBodyCacheOperation({ objectId, target: nativeCache.target, operation: "RENAME", name: cacheNameValue }); setCacheNameDraft(null);
|
||||
}}>
|
||||
<label>Cache Name<input aria-label="SOFT_BODY Cache Name" type="text" maxLength={63} value={cacheNameValue} onChange={event => setCacheNameDraft({ key: cacheNameKey, name: event.target.value })}/></label>
|
||||
<button type="submit" disabled={cacheNameInvalid || cacheNameValue === activeCacheName}>Rename Cache</button>
|
||||
<button type="button" onClick={() => setCacheNameDraft(null)}>Reset Name</button>
|
||||
{cacheNameInvalid && <output role="alert">Cache name is too long or contains an invalid character.</output>}
|
||||
<p>Blender normalizes cache names; the resulting name appears in the slot list.</p>
|
||||
</form>}
|
||||
{cacheSlots && nativeCache?.target && <label>Cache Slot<select aria-label="SOFT_BODY Cache Slot" value={nativeCache.target.slotIndex} onChange={event => selectCacheSlot(Number(event.target.value))}>
|
||||
{cacheSlots.items.map(slot => <option key={slot.index} value={slot.index}>{slot.index + 1}: {slot.name || "Unnamed Cache"}{slot.baked ? " · Baked" : ""}</option>)}
|
||||
</select></label>}
|
||||
{cacheSlots && nativeCache?.target && cacheSlots.count > cacheSlots.items.length && <label>Choose by number (1–{cacheSlots.count})<input aria-label="SOFT_BODY Cache Slot Number" type="number" min={1} max={cacheSlots.count} step={1} key={`${nativeCache.target.slotIndex}:${cacheSlots.count}`} defaultValue={nativeCache.target.slotIndex + 1}
|
||||
onKeyDown={event => { if (event.key === "Enter") event.currentTarget.blur(); }} onBlur={event => { const input = event.currentTarget; if (input.value && input.checkValidity()) selectCacheSlot(Number(input.value) - 1); input.value = String(nativeCache.target!.slotIndex + 1); }}/></label>}
|
||||
<p>Applies to this object's active cache. Opens Blender desktop; Esc cancels baking.</p>
|
||||
<button type="button" onClick={() => { if (nativeCache?.target) onSoftBodyCacheOperation({ objectId, target: nativeCache.target, operation: "ADD" }); }}>Add Cache Slot</button>
|
||||
<button type="button" disabled={!cacheSlots || cacheSlots.count <= 1} title="Remove the active cache slot and its cached data" onClick={() => { if (nativeCache?.target) onSoftBodyCacheOperation({ objectId, target: nativeCache.target, operation: "REMOVE" }); }}>Remove Active Slot</button>
|
||||
{([["BAKE", "Bake Active Cache"], ["CALCULATE", "Calculate to Current Frame"], ["FREE", "Free Active Cache"]] as const).map(([operation, label]) => <button type="button" key={operation} disabled={operation !== "FREE" && nativeCache?.baked === true}
|
||||
onClick={() => { if (nativeCache?.target) onSoftBodyCacheOperation({ objectId, target: nativeCache.target, operation }); }}>{label}</button>)}
|
||||
</fieldset>}
|
||||
{onPointCacheOperation && family !== "FLUID" && <fieldset disabled={pointCacheBusy}>
|
||||
<legend>Scene Point Caches</legend>
|
||||
<p>Applies to all scene objects. Opens Blender desktop; press Esc to cancel baking.</p>
|
||||
<button type="button" onClick={() => onPointCacheOperation("BAKE_ALL")}>Bake Scene Point Caches</button>
|
||||
<button type="button" title="Delete point-cache bakes for all objects in this scene" onClick={() => onPointCacheOperation("FREE_ALL")}>Delete Scene Point Caches</button>
|
||||
</fieldset>}
|
||||
</div>;
|
||||
}
|
||||
57
web/app/src/app/PropertiesStackName.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import { finishModifierInput } from './modifier-input-keyboard';
|
||||
import { useId, useRef, useState } from 'react';
|
||||
|
||||
/** Names stay authoritative until the native RNA transaction refreshes them. */
|
||||
export function PropertiesStackName({ name, label, disabled = false, onRename, onCancel }: {
|
||||
name: string; label: string; disabled?: boolean; onRename: (name: string) => void | Promise<boolean>;
|
||||
onCancel?: () => void;
|
||||
}) {
|
||||
const [error, setError] = useState('');
|
||||
const pending = useRef(false);
|
||||
const composing = useRef(false), deferredBlur = useRef(false);
|
||||
const [compositionActive, setCompositionActive] = useState(false);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const feedbackId = useId();
|
||||
return <span><input ref={inputRef} key={name} aria-label={label} aria-invalid={Boolean(error) && !pending.current} aria-describedby={error ? feedbackId : undefined} defaultValue={name} maxLength={63} disabled={disabled || pending.current}
|
||||
title="Enter or leave the field to rename; Escape restores the current name" aria-busy={pending.current}
|
||||
onCompositionStart={() => { composing.current = true; deferredBlur.current = false; setCompositionActive(true); }}
|
||||
onCompositionEnd={() => {
|
||||
composing.current = false; setCompositionActive(false);
|
||||
if (deferredBlur.current) { deferredBlur.current = false; setError('Composition finished. Review the retained name, then retry or cancel.'); }
|
||||
}}
|
||||
onKeyUp={event => event.stopPropagation()}
|
||||
onKeyDown={event => {
|
||||
event.stopPropagation();
|
||||
if (composing.current) return;
|
||||
if (event.key === 'Escape' && !event.nativeEvent.isComposing && event.nativeEvent.keyCode !== 229) { setError(''); onCancel?.(); }
|
||||
finishModifierInput(event, name);
|
||||
}}
|
||||
onBlur={async event => {
|
||||
if (event.currentTarget.parentElement?.contains(event.relatedTarget as Node | null)) return;
|
||||
if (pending.current || disabled) return;
|
||||
// Blur may precede compositionend: never send provisional IME text to RNA.
|
||||
if (composing.current) { deferredBlur.current = true; return; }
|
||||
const input = event.currentTarget;
|
||||
const requested = input.value;
|
||||
// Blender stores these names in 64 UTF-8 bytes, not 64 JS characters.
|
||||
// Preserve intentional whitespace just as the original RNA setter does.
|
||||
if (requested === name) { if (error) { setError(''); onCancel?.(); } return; }
|
||||
if (!requested.length || requested.includes('\0') || new TextEncoder().encode(requested).byteLength > 63) {
|
||||
setError('Enter a nonempty name of at most 63 UTF-8 bytes.');
|
||||
return;
|
||||
}
|
||||
pending.current = true; setError('Renaming…');
|
||||
try {
|
||||
if (await onRename(requested) === false) setError('Name was not changed. Your draft is kept; retry or press Escape to cancel. See the Properties error.');
|
||||
else { input.value = name; setError(''); }
|
||||
} catch (failure) { setError(`${failure instanceof Error ? failure.message : String(failure)} Your draft is kept; retry or press Escape to cancel.`); }
|
||||
finally { pending.current = false; }
|
||||
}} />{compositionActive && <small role="status">Finish composing before renaming.</small>}
|
||||
{error && <small id={feedbackId} role={pending.current ? 'status' : 'alert'}>{error}</small>}
|
||||
{error && !pending.current && <span role="group" aria-label={`Recover ${label} rename`} onKeyUp={event => event.stopPropagation()} onKeyDown={event => { event.stopPropagation(); if (event.key !== 'Escape' || disabled || compositionActive || event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return; event.preventDefault(); if (inputRef.current) { inputRef.current.value = name; inputRef.current.focus(); } setError(''); onCancel?.(); }}>
|
||||
<button type="button" disabled={disabled || compositionActive} title="Retry the retained name through the native rename transaction"
|
||||
onClick={() => { inputRef.current?.focus(); inputRef.current?.blur(); }}>Retry Rename</button>
|
||||
<button type="button" disabled={disabled || compositionActive} title="Discard this draft and restore the current name"
|
||||
onClick={() => { if (inputRef.current) { inputRef.current.value = name; inputRef.current.focus(); } setError(''); onCancel?.(); }}>Cancel Rename</button>
|
||||
</span>}</span>;
|
||||
}
|
||||
32
web/app/src/app/SimplifyReport.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
import type { SceneSnapshotIR } from '../../../protocol/scene-ir';
|
||||
import type { SimplifyResult } from '../../../protocol/simplify';
|
||||
export interface SimplifyWorkbenchReport {
|
||||
result: SimplifyResult; phase: 'preview' | 'applied'; projectId: string; logicalRevision: number;
|
||||
vertices: [number, number]; uvLayers: [number, number]; materialSlots: [number, number];
|
||||
retained: string[]; removed: string[];
|
||||
}
|
||||
export function buildSimplifyReport(result: SimplifyResult, phase: 'preview' | 'applied', before: SceneSnapshotIR, after: SceneSnapshotIR, projectId: string, logicalRevision: number): SimplifyWorkbenchReport | null {
|
||||
const source = before.meshes.find(mesh => mesh.id === result.evaluatedMeshId), output = after.meshes.find(mesh => mesh.id === result.evaluatedMeshId);
|
||||
if (!source || !output) return null;
|
||||
const names = new Set(output.attributes?.map(attribute => attribute.name) ?? []);
|
||||
const previous = source.attributes?.map(attribute => attribute.name) ?? [];
|
||||
return { result, phase, projectId, logicalRevision, vertices: [source.vertexCount, output.vertexCount],
|
||||
uvLayers: [source.uvLayers?.length ?? 0, output.uvLayers?.length ?? 0], materialSlots: [source.materialSlotIds?.length ?? 0, output.materialSlotIds?.length ?? 0],
|
||||
retained: previous.filter(name => names.has(name)), removed: previous.filter(name => !names.has(name)) };
|
||||
}
|
||||
export function SimplifyReportPanel({ report, cacheLevels }: { report: SimplifyWorkbenchReport | null; cacheLevels: number }) {
|
||||
const result = report?.result;
|
||||
return <div className="property-section" data-testid="simplify-report" style={{ display: 'grid', gap: 4, overflowWrap: 'anywhere' }}>
|
||||
<h4>简化报告</h4><output data-testid="simplify-cache-status">LOD 缓存:{cacheLevels ? `已加载 ${cacheLevels} 级` : '未加载'}</output>
|
||||
{result && report ? <>
|
||||
<output data-testid="simplify-result-phase">{report.phase === 'preview' ? '预览结果,尚未应用' : '上次应用结果'}</output>
|
||||
<output data-testid="simplify-triangle-counts">三角形 {result.originalTriangleCount} → {result.outputTriangleCount}</output>
|
||||
<output data-testid="simplify-result-ratio">实际保留 {(100 * result.outputTriangleCount / Math.max(1, result.originalTriangleCount)).toFixed(2)}%</output>
|
||||
<output data-testid="simplify-result-target">目标三角形:{result.triangleBudget ?? '按比例'}</output>
|
||||
<output>顶点 {report.vertices[0]} → {report.vertices[1]}</output>
|
||||
<output data-testid="simplify-channel-counts">UV 层 {report.uvLayers[0]} → {report.uvLayers[1]};材质槽 {report.materialSlots[0]} → {report.materialSlots[1]}</output>
|
||||
<output data-testid="simplify-retained-attributes">保留的属性层:{report.retained.join('、') || '无'}</output>
|
||||
<output data-testid="simplify-removed-attributes">不再单独存储的属性层:{report.removed.join('、') || '无'}</output>
|
||||
<small>以上为结构变化统计;几何误差未估算。</small>
|
||||
</> : <output data-testid="simplify-report-empty">预览或应用后显示结果。</output>}</div>;
|
||||
}
|
||||
27
web/app/src/app/UVCustomRegionControls.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import type {NativeUVEdit} from '../../../protocol/editor-workflow';
|
||||
import {parseNativeUVBounds,type NativeUVCustomRegion} from '../../../protocol/uv-custom-region';
|
||||
|
||||
export function UVCustomRegionControls({region,disabled,onApply}:{region?:NativeUVCustomRegion;disabled:boolean;onApply:(intent:NativeUVEdit)=>Promise<void>}){
|
||||
const [draft,setDraft]=useState<string[]|null>(null),[error,setError]=useState('');
|
||||
const identity=JSON.stringify(region);
|
||||
useEffect(()=>{setDraft(null);setError('');},[identity]);
|
||||
const values=draft??region?.bounds.map(String)??['','','',''];
|
||||
const submit=async()=>{
|
||||
if(disabled||!region)return;
|
||||
try{
|
||||
if(values.some(value=>!value.trim()))throw new Error('请填写完整的 UV 区域边界');
|
||||
const bounds=parseNativeUVBounds(values.map(Number));setError('');
|
||||
await onApply({operation:'CUSTOM_REGION_SET',bounds});
|
||||
}catch(reason){setError(reason instanceof Error?reason.message:String(reason));}
|
||||
};
|
||||
return <details><summary>UV 自定义区域</summary><form onSubmit={event=>{event.preventDefault();void submit();}}><fieldset disabled={disabled||!region}>
|
||||
<legend>打包目标边界</legend>
|
||||
{['最小 U','最小 V','最大 U','最大 V'].map((label,index)=><label key={label}>{label}<input aria-label={`UV 区域${label}`} type="number" step="any" required value={values[index]}
|
||||
onChange={event=>{const next=[...values];next[index]=event.target.value;setDraft(next);}}/></label>)}
|
||||
<label><input type="checkbox" checked={region?.enabled??false} onChange={event=>void onApply({operation:'CUSTOM_REGION_ENABLE',enabled:event.target.checked})}/>启用自定义区域</label>
|
||||
<button type="submit">设置并启用区域</button><button type="button" onClick={()=>{setDraft(null);setError('');}}>恢复当前边界</button>
|
||||
<p>数值使用 UV 坐标。打包时选择“自定义区域”;关闭区域后该目标使用单位方格。橙色虚线显示已启用的原生边界。</p>
|
||||
{error&&<output role="alert">{error}</output>}
|
||||
</fieldset></form></details>;
|
||||
}
|
||||
31
web/app/src/app/UVPackControls.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import {useState} from 'react';
|
||||
import {UV_PACK_ENUMS,UV_PACK_BOOLEANS,parseNativeUVPackOptions,type NativeUVPackOptions} from '../../../protocol/uv-pack-options';
|
||||
|
||||
export function UVPackControls({disabled,onApply}:{disabled:boolean;onApply:(options:NativeUVPackOptions)=>Promise<void>}){
|
||||
const [draft,setDraft]=useState<Record<string,string>>({}),[error,setError]=useState('');
|
||||
const update=(key:string,value:string)=>setDraft(current=>({...current,[key]:value}));
|
||||
const labels:Record<string,string>={udim_source:'打包到',rotate_method:'旋转方式',margin_method:'间距方式',pin_method:'固定岛约束',shape_method:'形状方式',rotate:'允许旋转',scale:'缩放以填充',merge_overlap:'合并重叠岛',pin:'约束固定岛'};
|
||||
const choices:Record<string,string>={CLOSEST_UDIM:'最近 UDIM',ACTIVE_UDIM:'活动 UDIM',ORIGINAL_AABB:'原始包围盒',CUSTOM_REGION:'自定义区域',ANY:'任意角度',CARDINAL:'仅 90 度',AXIS_ALIGNED:'轴对齐',AXIS_ALIGNED_X:'水平对齐',AXIS_ALIGNED_Y:'垂直对齐',SCALED:'按 UV 比例',ADD:'直接添加',FRACTION:'最终占比',SCALE:'锁定缩放',ROTATION:'锁定旋转',ROTATION_SCALE:'锁定旋转和缩放',LOCKED:'全部锁定',CONCAVE:'精确形状',CONVEX:'凸边界',AABB:'包围盒'};
|
||||
const submit=async()=>{
|
||||
if(disabled)return;
|
||||
const options:Record<string,unknown>={};
|
||||
for(const key of Object.keys(UV_PACK_ENUMS))if(draft[key])options[key]=draft[key];
|
||||
for(const key of UV_PACK_BOOLEANS)if(draft[key])options[key]=draft[key]==='true';
|
||||
if(draft.margin?.trim())options.margin=Number(draft.margin);
|
||||
try{const parsed=parseNativeUVPackOptions(options);setError('');await onApply(parsed);}catch(reason){setError(reason instanceof Error?reason.message:String(reason));}
|
||||
};
|
||||
return <details><summary>打包 UV 岛屿</summary><form onSubmit={event=>{event.preventDefault();void submit();}}><fieldset disabled={disabled}>
|
||||
<legend>打包所选 UV 岛屿</legend>
|
||||
{(Object.keys(UV_PACK_ENUMS) as Array<keyof typeof UV_PACK_ENUMS>).map(key=><label key={key}>{labels[key]}<select aria-label={`UV 打包${labels[key]}`} value={draft[key]??''}
|
||||
disabled={(key==='rotate_method'&&draft.rotate==='false')||(key==='pin_method'&&draft.pin!=='true')} onChange={event=>update(key,event.target.value)}>
|
||||
<option value="">使用默认值</option>{UV_PACK_ENUMS[key].map(value=><option key={value} value={value}>{choices[value]}</option>)}
|
||||
</select></label>)}
|
||||
{UV_PACK_BOOLEANS.map(key=><label key={key}>{labels[key]}<select aria-label={`UV 打包${labels[key]}`} value={draft[key]??''} onChange={event=>update(key,event.target.value)}>
|
||||
<option value="">使用默认值</option><option value="true">开启</option><option value="false">关闭</option>
|
||||
</select></label>)}
|
||||
<label>间距<input aria-label="UV 打包间距" type="number" min="0" max="1" step="any" value={draft.margin??''} placeholder="使用场景间距" onChange={event=>update('margin',event.target.value)}/></label>
|
||||
<p>作用于原生选择,包括预览未显示的岛屿。活动 UDIM 和自定义区域取自原生 UV 编辑器;未设置自定义区域时使用单位方格。</p>
|
||||
<button type="button" onClick={()=>{setDraft({});setError('');}}>恢复默认</button><button type="submit">打包岛屿</button>
|
||||
{error&&<output role="alert">{error}</output>}
|
||||
</fieldset></form></details>;
|
||||
}
|
||||
25
web/app/src/app/UVPackTargetControls.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import type {NativeUVEdit} from '../../../protocol/editor-workflow';
|
||||
import type {NativeUVPackTarget} from '../../../protocol/uv-pack-target';
|
||||
|
||||
export function UVPackTargetControls({target,disabled,onApply}:{target?:NativeUVPackTarget;disabled:boolean;onApply:(intent:NativeUVEdit)=>Promise<void>}){
|
||||
const [draft,setDraft]=useState<string|null>(null),[error,setError]=useState('');
|
||||
const identity=JSON.stringify(target);
|
||||
useEffect(()=>{setDraft(null);setError('');},[identity]);
|
||||
const submit=async()=>{
|
||||
if(disabled||!target)return;
|
||||
try{
|
||||
const tile=Number(draft??target.tile);
|
||||
if(!Number.isSafeInteger(tile)||tile<1001||tile>(target.tiled?2147483647:2000))throw new Error('请输入有效的 UDIM 编号,网格目标范围为 1001–2000');
|
||||
setError('');await onApply({operation:'SET_PACK_TILE',tile});
|
||||
}catch(reason){setError(reason instanceof Error?reason.message:String(reason));}
|
||||
};
|
||||
return <details><summary>活动 UDIM 目标</summary><form onSubmit={event=>{event.preventDefault();void submit();}}><fieldset disabled={disabled||!target}>
|
||||
<legend>原生活动打包目标</legend><output>当前:{target?.tile??'不可用'} · {target?.tiled?'平铺图像活动瓦片':'UV 网格与二维游标'}</output>
|
||||
<label>UDIM 编号<input aria-label="活动 UDIM 编号" type="number" min="1001" max={target?.tiled?2147483647:2000} step="1" required value={draft??String(target?.tile??'')} onChange={event=>setDraft(event.target.value)}/></label>
|
||||
<button type="submit">设置活动目标</button><button type="button" onClick={()=>{setDraft(null);setError('');}}>恢复当前值</button>
|
||||
<p>{target?.tiled?'仅选择当前图像中已有的瓦片。':'设置后网格按需扩展,二维游标移到目标格中心。'}打包时选择“活动 UDIM”。</p>
|
||||
{target&&!target.tiled&&<output>网格 {target.grid.join(' × ')} · UV 游标 {target.cursor.join(', ')}</output>}
|
||||
{error&&<output role="alert">{error}</output>}
|
||||
</fieldset></form></details>;
|
||||
}
|
||||
20
web/app/src/app/UVSelectionControls.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import {UV_SELECTION_MODES,UV_STICKY_MODES,type NativeUVEdit,type NativeUVSelection} from '../../../protocol/editor-workflow';
|
||||
|
||||
export function UVSelectionControls({selection,disabled,onApply}:{selection?:NativeUVSelection;disabled:boolean;onApply:(intent:NativeUVEdit)=>Promise<void>}){
|
||||
const labels={VERTEX:'顶点',EDGE:'边',FACE:'面'},bits={VERTEX:1,EDGE:2,FACE:4};
|
||||
const stickyLabels={DISABLED:'禁用',SHARED_LOCATION:'共享位置',SHARED_VERTEX:'共享顶点'};
|
||||
const current=(mode:typeof UV_SELECTION_MODES[number])=>selection?.syncSelection?Boolean((selection.meshSelectMode??0)&bits[mode]):selection?.selectionMode===mode;
|
||||
return <fieldset disabled={disabled||!selection}><legend>UV 选择设置</legend>
|
||||
{UV_SELECTION_MODES.map(mode=><button key={mode} type="button" aria-pressed={current(mode)} disabled={selection?.syncSelection?selection.meshSelectMode===undefined:selection?.selectionMode===undefined}
|
||||
onClick={()=>void onApply({operation:'SELECT_MODE',mode})}>{labels[mode]}</button>)}
|
||||
<label><input type="checkbox" checked={selection?.syncSelection??false} onChange={event=>void onApply({operation:'SELECT_SYNC',enabled:event.target.checked})}/>同步网格选择</label>
|
||||
<label><input type="checkbox" checked={selection?.islandSelection??false} disabled={selection?.islandSelection===undefined} onChange={event=>void onApply({operation:'SELECT_ISLAND',enabled:event.target.checked})}/>岛选择</label>
|
||||
<span>{selection?.syncSelection?'模式切换作用于同步的网格选择':'模式切换作用于独立 UV 选择'}</span>
|
||||
<label>粘连选择<select aria-label="UV 粘连选择" value={selection?.stickyMode??''} disabled={selection?.stickyMode===undefined}
|
||||
onChange={event=>void onApply({operation:'SELECT_STICKY',mode:event.target.value as typeof UV_STICKY_MODES[number]})}>
|
||||
{selection?.stickyMode===undefined&&<option value="" disabled>不可用</option>}
|
||||
{UV_STICKY_MODES.map(mode=><option key={mode} value={mode}>{stickyLabels[mode]}</option>)}
|
||||
</select></label>
|
||||
<span>共享位置选择同一网格顶点且 UV 位置重合的点;共享顶点也包括 UV 位置分离的点。</span>
|
||||
</fieldset>;
|
||||
}
|
||||
25
web/app/src/app/UVStitchControls.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import {useState} from 'react';
|
||||
import {parseNativeUVStitchOptions,UV_STITCH_BOOLEANS,type NativeUVStitchOptions} from '../../../protocol/editor-workflow';
|
||||
|
||||
export function UVStitchControls({disabled,onApply}:{disabled:boolean;onApply:(options:NativeUVStitchOptions)=>Promise<void>}){
|
||||
const [draft,setDraft]=useState<Record<string,string>>({}),[error,setError]=useState('');
|
||||
const submit=async()=>{
|
||||
if(disabled)return;
|
||||
const options:Record<string,unknown>={};
|
||||
if(draft.mode)options.mode=draft.mode;
|
||||
for(const key of UV_STITCH_BOOLEANS)if(draft[key])options[key]=draft[key]==='true';
|
||||
for(const key of ['limit','static_island','active_object_index'])if(draft[key]?.trim())options[key]=Number(draft[key]);
|
||||
try{const parsed=parseNativeUVStitchOptions(options);setError('');await onApply(parsed);}catch(reason){setError(reason instanceof Error?reason.message:String(reason));}
|
||||
};
|
||||
const update=(key:string,value:string)=>setDraft(current=>({...current,[key]:value}));
|
||||
return <details><summary>缝合 UV</summary><form onSubmit={event=>{event.preventDefault();void submit();}}><fieldset disabled={disabled}>
|
||||
<legend>缝合所选 UV</legend>
|
||||
<label>模式<select aria-label="UV 缝合模式" value={draft.mode??''} onChange={event=>update('mode',event.target.value)}><option value="">跟随 UV 选择模式</option><option value="VERTEX">顶点</option><option value="EDGE">边</option></select></label>
|
||||
{([['use_limit','使用距离限制'],['snap_islands','吸附岛屿'],['midpoint_snap','缝合到中点'],['clear_seams','清除已缝合边的接缝']] as const).map(([key,label])=><label key={key}>{label}<select aria-label={`UV ${label}`} value={draft[key]??''} onChange={event=>update(key,event.target.value)}><option value="">使用默认值</option><option value="true">开启</option><option value="false">关闭</option></select></label>)}
|
||||
<label>距离限制<input aria-label="UV 缝合距离限制" type="number" min="0" step="any" value={draft.limit??''} placeholder="默认 0.01" onChange={event=>update('limit',event.target.value)}/></label>
|
||||
{([['static_island','固定岛屿索引'],['active_object_index','固定对象索引']] as const).map(([key,label])=><label key={key}>{label}<input aria-label={`UV ${label}`} type="number" min="0" max="2147483647" step="1" value={draft[key]??''} placeholder="默认 0" onChange={event=>update(key,event.target.value)}/></label>)}
|
||||
<p>索引从 0 开始,由 Blender 按当前可缝合对象和岛屿解析。操作作用于原生选择,包括未显示部分。</p>
|
||||
<button type="button" onClick={()=>{setDraft({});setError('');}}>恢复默认</button>
|
||||
<button type="submit">执行缝合</button>{error?<output role="alert">{error}</output>:null}
|
||||
</fieldset></form></details>;
|
||||
}
|
||||
24
web/app/src/app/UVTransformControls.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import {useState} from 'react';
|
||||
import {parseNativeUVTransform,type NativeUVTransform} from '../../../protocol/editor-workflow';
|
||||
|
||||
export function UVTransformControls({disabled,onApply}:{disabled:boolean;onApply:(transform:NativeUVTransform)=>Promise<void>}){
|
||||
const [mode,setMode]=useState<NativeUVTransform['mode']>('TRANSLATE'),[customCenter,setCustomCenter]=useState(false),[error,setError]=useState('');
|
||||
const [draft,setDraft]=useState({u:'0',v:'0',angle:'0',centerU:'0',centerV:'0'});
|
||||
const submit=async()=>{
|
||||
if(disabled)return;
|
||||
try{
|
||||
const value=mode==='ROTATE'?{mode,angle:Number(draft.angle)*Math.PI/180}:{mode,value:[Number(draft.u),Number(draft.v)]};
|
||||
const transform=parseNativeUVTransform({...value,...(mode!=='TRANSLATE'&&customCenter?{center:[Number(draft.centerU),Number(draft.centerV)]}:{})});
|
||||
setError('');await onApply(transform);
|
||||
}catch(reason){setError(reason instanceof Error?reason.message:String(reason));}
|
||||
};
|
||||
const field=(key:keyof typeof draft,label:string)=><label>{label}<input aria-label={label} type="number" step="any" required value={draft[key]} onChange={event=>setDraft(current=>({...current,[key]:event.target.value}))}/></label>;
|
||||
return <details><summary>移动 / 旋转 / 缩放 UV</summary><form onSubmit={event=>{event.preventDefault();void submit();}}><fieldset disabled={disabled}>
|
||||
<legend>所选 UV 数值变换</legend>
|
||||
<label>操作<select aria-label="UV 变换操作" value={mode} onChange={event=>{const next=event.target.value as NativeUVTransform['mode'];setMode(next);setDraft(current=>({...current,u:next==='SCALE'?'1':'0',v:next==='SCALE'?'1':'0'}));setError('');}}><option value="TRANSLATE">移动</option><option value="ROTATE">旋转</option><option value="SCALE">缩放</option></select></label>
|
||||
{mode==='ROTATE'?field('angle','UV 旋转角度(度)'):<>{field('u',mode==='SCALE'?'UV 缩放 U':'UV 位移 U')}{field('v',mode==='SCALE'?'UV 缩放 V':'UV 位移 V')}</>}
|
||||
{mode!=='TRANSLATE'?<><label><input type="checkbox" checked={customCenter} onChange={event=>setCustomCenter(event.target.checked)}/>指定 UV 中心</label>{customCenter?<>{field('centerU','UV 中心 U')}{field('centerV','UV 中心 V')}</>:<span>使用当前枢轴</span>}</>:null}
|
||||
<p>作用于所有选中的 UV;比例编辑关闭。未显示的选中项也会变换。</p>
|
||||
<button type="submit">应用变换</button>{error?<output role="alert">{error}</output>:null}
|
||||
</fieldset></form></details>;
|
||||
}
|
||||
27
web/app/src/app/UVUnwrapControls.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import {useState} from 'react';
|
||||
import {parseNativeUVUnwrapOptions,UV_UNWRAP_BOOLEANS,type NativeUVUnwrapOptions} from '../../../protocol/editor-workflow';
|
||||
|
||||
export function UVUnwrapControls({disabled,onApply}:{disabled:boolean;onApply:(options:NativeUVUnwrapOptions)=>Promise<void>}){
|
||||
const [draft,setDraft]=useState<Record<string,string>>({}),[weightGroupOverride,setWeightGroupOverride]=useState(false),[error,setError]=useState('');
|
||||
const submit=async()=>{
|
||||
if(disabled)return;
|
||||
const options:Record<string,unknown>={};
|
||||
for(const key of ['method','margin_method'])if(draft[key])options[key]=draft[key];
|
||||
for(const key of UV_UNWRAP_BOOLEANS)if(draft[key])options[key]=draft[key]==='true';
|
||||
for(const key of ['margin','iterations','weight_factor'])if(draft[key]?.trim())options[key]=Number(draft[key]);
|
||||
if(weightGroupOverride)options.weight_group=draft.weight_group??'';
|
||||
try{const parsed=parseNativeUVUnwrapOptions(options);setError('');await onApply(parsed);}catch(reason){setError(reason instanceof Error?reason.message:String(reason));}
|
||||
};
|
||||
const update=(key:string,value:string)=>setDraft(current=>({...current,[key]:value}));
|
||||
return <details><summary>展开 UV</summary><form onSubmit={event=>{event.preventDefault();void submit();}}><fieldset disabled={disabled}>
|
||||
<legend>展开设置</legend><p>留空或选择“沿用原生设置”,采用当前工程设置或 Blender 默认值。</p>
|
||||
<label>方法<select aria-label="UV 展开方法" value={draft.method??''} onChange={event=>update('method',event.target.value)}><option value="">沿用原生设置</option><option value="ANGLE_BASED">Angle Based</option><option value="CONFORMAL">Conformal</option><option value="MINIMUM_STRETCH">Minimum Stretch</option></select></label>
|
||||
<label>间距方式<select aria-label="UV 展开间距方式" value={draft.margin_method??''} onChange={event=>update('margin_method',event.target.value)}><option value="">沿用原生设置</option><option value="SCALED">Scaled</option><option value="ADD">Add</option><option value="FRACTION">Fraction</option></select></label>
|
||||
{([['fill_holes','填补孔洞'],['correct_aspect','校正宽高比'],['use_subsurf_data','使用细分曲面'],['use_original_bounds','保留原始边界'],['no_flip','禁止翻转(Minimum Stretch)'],['use_weights','使用顶点组权重(Minimum Stretch)']] as const).map(([key,label])=><label key={key}>{label}<select aria-label={`UV ${label}`} value={draft[key]??''} onChange={event=>update(key,event.target.value)}><option value="">沿用原生设置</option><option value="true">开启</option><option value="false">关闭</option></select></label>)}
|
||||
{([['margin','间距',0,1,'0.001'],['iterations','迭代次数(Minimum Stretch)',0,10000,'1'],['weight_factor','权重影响(Minimum Stretch)',-10000,10000,'any']] as const).map(([key,label,min,max,step])=><label key={key}>{label}<input aria-label={`UV ${label}`} type="number" min={min} max={max} step={step} value={draft[key]??''} placeholder="沿用原生设置" onChange={event=>update(key,event.target.value)}/></label>)}
|
||||
<label><input type="checkbox" checked={weightGroupOverride} onChange={event=>setWeightGroupOverride(event.target.checked)}/>指定权重顶点组(留空可清除)</label>
|
||||
<input aria-label="UV 权重顶点组" disabled={!weightGroupOverride} maxLength={63} value={draft.weight_group??''} onChange={event=>update('weight_group',event.target.value)}/>
|
||||
<button type="button" onClick={()=>{setDraft({});setWeightGroupOverride(false);setError('');}}>沿用原生设置</button>
|
||||
<button type="submit">展开所选 UV</button>{error?<output role="alert">{error}</output>:null}
|
||||
</fieldset></form></details>;
|
||||
}
|
||||
597
web/app/src/app/WasmDesktopLayout.tsx
Normal file
@@ -0,0 +1,597 @@
|
||||
import { useState } from 'react';
|
||||
import type { EditorContextEdit, EditorWorkflowIR, NativeTimelineEdit, NativeView3DNavigation, NativeView3DSelection } from '../../../protocol/editor-workflow';
|
||||
import { isNativeTimelinePlayback, TIMELINE_KEY_TYPES, TIMELINE_PASTE_OFFSETS, TIMELINE_PASTE_MERGES } from '../../../protocol/editor-workflow';
|
||||
import type { WebEngineEditCommand } from '../../../protocol/web-engine';
|
||||
|
||||
const timelineKeyMenus = [
|
||||
['SET_KEY_INTERPOLATION', '插值'], ['SET_KEY_EASING', '缓动'],
|
||||
['SET_KEY_HANDLE', '控制柄类型'], ['SET_KEY_TYPE', '关键帧类型'],
|
||||
['SNAP_KEYS', '吸附所选关键帧'], ['MIRROR_KEYS', '镜像所选关键帧'],
|
||||
] as const;
|
||||
const timelineKeyLabels: Record<string, string> = {
|
||||
CONSTANT: '常量', LINEAR: '线性', BEZIER: '贝塞尔', SINE: '正弦', QUAD: '二次',
|
||||
CUBIC: '三次', QUART: '四次', QUINT: '五次', EXPO: '指数', CIRC: '圆形',
|
||||
BACK: '回退', BOUNCE: '弹跳', ELASTIC: '弹性', AUTO: '自动',
|
||||
EASE_IN: '渐入', EASE_OUT: '渐出', EASE_IN_OUT: '渐入渐出',
|
||||
FREE: '自由', ALIGNED: '对齐', VECTOR: '矢量', AUTO_CLAMPED: '自动钳制',
|
||||
KEYFRAME: '关键帧', BREAKDOWN: '过渡', MOVING_HOLD: '移动保持', EXTREME: '极值',
|
||||
JITTER: '抖动', GENERATED: '生成', CFRA: '当前帧', NEAREST_FRAME: '最近整帧',
|
||||
NEAREST_SECOND: '最近整秒', NEAREST_MARKER: '最近标记', MARKER: '首个选中标记',
|
||||
XAXIS: '零值(反转数值)',
|
||||
};
|
||||
const timelinePasteLabels: Record<string, string> = {
|
||||
START: '起点对齐当前帧', END: '终点对齐当前帧', RELATIVE: '相对复制时的当前帧', NONE: '保留原时间',
|
||||
MIX: '混合', OVER_ALL: '覆盖目标曲线全部关键帧', OVER_RANGE: '覆盖各曲线粘贴范围',
|
||||
OVER_RANGE_ALL: '覆盖全部复制关键帧的时间范围',
|
||||
};
|
||||
|
||||
const DETACHED_VIEW3D_SELECTION_OPERATIONS = new Set([
|
||||
'SELECT_ALL', 'DESELECT_ALL', 'INVERT_SELECTION',
|
||||
'GP_SELECT_MODE', 'GP_SELECT_LINKED', 'GP_SELECT_ALTERNATE', 'GP_SELECT_SIMILAR',
|
||||
'GP_SELECT_RANDOM', 'GP_SELECT_FILL', 'GP_SELECT_MATERIAL', 'GP_SELECT_BY_STROKE_TYPE',
|
||||
'GP_SELECT_ENDS', 'SET_PAINT_MASK', 'PAINT_HIDE', 'PAINT_REVEAL', 'PAINT_SELECT_UNGROUPED',
|
||||
'SELECT_NEXT_ACTIVE', 'SELECT_PREVIOUS_ACTIVE', 'SELECT_EDGE_LOOPS', 'SELECT_EDGE_RINGS',
|
||||
'SELECT_BOUNDARY_LOOPS', 'LOOP_TO_REGION', 'REGION_TO_LOOP', 'SELECT_SHORTEST_PATH',
|
||||
'SELECT_LINKED_FLAT_FACES', 'SELECT_MORE', 'SELECT_LESS', 'SELECT_HIERARCHY', 'SELECT_LINKED',
|
||||
'TEXT_SELECT_ALL', 'TEXT_DESELECT_ALL', 'TEXT_SELECT_WORD', 'TEXT_MOVE',
|
||||
]);
|
||||
|
||||
/** Commands reuse native editor storage; pointer/navigation still require the attached screen. */
|
||||
export function WasmDesktopLayout({ workflow, revision, attached, onCommand }: {
|
||||
workflow: EditorWorkflowIR | null;
|
||||
revision: number;
|
||||
attached: boolean;
|
||||
onCommand: (command: WebEngineEditCommand) => Promise<boolean>;
|
||||
}) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [factor, setFactor] = useState(50);
|
||||
const [joinTarget, setJoinTarget] = useState('');
|
||||
const [edgeDelta, setEdgeDelta] = useState(32);
|
||||
const [edgeSnap, setEdgeSnap] = useState(false);
|
||||
const [regionSize, setRegionSize] = useState(240);
|
||||
const [regionId, setRegionId] = useState('');
|
||||
const [timelineId, setTimelineId] = useState('');
|
||||
const [pasteOffset, setPasteOffset] = useState<typeof TIMELINE_PASTE_OFFSETS[number]>('START');
|
||||
const [pasteMerge, setPasteMerge] = useState<typeof TIMELINE_PASTE_MERGES[number]>('MIX');
|
||||
const [pasteFlipped, setPasteFlipped] = useState(false);
|
||||
const [keyOffset, setKeyOffset] = useState(1);
|
||||
const [keyScale, setKeyScale] = useState(1);
|
||||
const [markerName, setMarkerName] = useState('Marker');
|
||||
const [markerOffset, setMarkerOffset] = useState(1);
|
||||
const [frameAllRegions, setFrameAllRegions] = useState(false);
|
||||
const [alignActive, setAlignActive] = useState(false);
|
||||
const [lassoMode, setLassoMode] = useState<Extract<NativeView3DSelection, { operation: 'LASSO' }>['mode']>('SET');
|
||||
const [linkedType, setLinkedType] = useState<Extract<NativeView3DSelection, { operation: 'SELECT_LINKED' }>['objectType']>('OBDATA');
|
||||
const [linkedExtend, setLinkedExtend] = useState(false);
|
||||
const [selectionFaceStep, setSelectionFaceStep] = useState(true);
|
||||
const [paintRevealSelect, setPaintRevealSelect] = useState(true);
|
||||
const [paintUngroupedExtend, setPaintUngroupedExtend] = useState(false);
|
||||
const [paintPickSelect, setPaintPickSelect] = useState(true);
|
||||
const [linkedUseDelimit, setLinkedUseDelimit] = useState(false);
|
||||
const [linkedDelimit, setLinkedDelimit] = useState<NonNullable<Extract<NativeView3DSelection, { operation: 'SELECT_LINKED' }>['delimit']>>(['SEAM']);
|
||||
const [loopUseDelimit, setLoopUseDelimit] = useState(false);
|
||||
const [loopDelimit, setLoopDelimit] = useState<NonNullable<Extract<NativeView3DSelection, { operation: 'SELECT_EDGE_LOOPS' }>['delimit']>>(['NGONS', 'OUTER_CORNERS']);
|
||||
const [ringUseDelimit, setRingUseDelimit] = useState(false);
|
||||
const [ringDelimit, setRingDelimit] = useState<NonNullable<Extract<NativeView3DSelection, { operation: 'SELECT_EDGE_RINGS' }>['delimit']>>(['NGONS']);
|
||||
const [boundaryExtend, setBoundaryExtend] = useState(true);
|
||||
const [loopSelectBigger, setLoopSelectBigger] = useState(false);
|
||||
const [shortestPath, setShortestPath] = useState<Extract<NativeView3DSelection, { operation: 'SELECT_SHORTEST_PATH' }>>({
|
||||
operation: 'SELECT_SHORTEST_PATH', useFaceStep: false, useTopologyDistance: false, useFill: false,
|
||||
skip: 0, nth: 1, offset: 0,
|
||||
});
|
||||
const [flatSharpness, setFlatSharpness] = useState(1);
|
||||
const [textExtend, setTextExtend] = useState(true);
|
||||
const [gpDeselectEnds, setGpDeselectEnds] = useState(false);
|
||||
const [gpAmountStart, setGpAmountStart] = useState(0);
|
||||
const [gpAmountEnd, setGpAmountEnd] = useState(1);
|
||||
const [gpSimilarMode, setGpSimilarMode] = useState<Extract<NativeView3DSelection, { operation: 'GP_SELECT_SIMILAR' }>['mode']>('LAYER');
|
||||
const [gpSimilarThreshold, setGpSimilarThreshold] = useState(0.1);
|
||||
const [gpRandomRatio, setGpRandomRatio] = useState(0.5);
|
||||
const [gpRandomSeed, setGpRandomSeed] = useState(0);
|
||||
const workspace = workflow?.workspaces.find(item => item.id === workflow.context.workspaceId);
|
||||
const area = workspace?.areas.find(item => item.id === workflow?.context.activeAreaId) ?? workspace?.areas[0];
|
||||
const layout = area?.nativeLayout;
|
||||
const timelines = workspace?.areas.filter(item => ['TIMELINE', 'DOPE_SHEET'].includes(item.editor) &&
|
||||
item.regions.some(region => region.kind === 'MAIN' && region.visible)) ?? [];
|
||||
const timeline = timelines.find(item => item.id === timelineId) ?? timelines.find(item => item.id === area?.id) ?? timelines[0];
|
||||
const neighbors = workspace?.areas.filter(item => layout?.joinTargets.includes(item.id)) ?? [];
|
||||
const target = neighbors.find(item => item.id === joinTarget)?.id ?? neighbors[0]?.id ?? '';
|
||||
const resizableRegions = area?.regions.filter(item => item.visible && item.alignment && item.alignment !== 'OTHER') ?? [];
|
||||
const selectedRegion = resizableRegions.find(item => item.id === regionId)?.id ?? resizableRegions[0]?.id ?? '';
|
||||
const mainRegions = area?.regions.filter(item => item.kind === 'MAIN' && item.visible) ?? [];
|
||||
const activeMain = mainRegions.find(item => item.active) ?? mainRegions[0];
|
||||
const detachedSelection = (edit: EditorContextEdit): boolean =>
|
||||
edit.action === 'VIEW3D_SELECT' && DETACHED_VIEW3D_SELECTION_OPERATIONS.has(edit.operation);
|
||||
const apply = async (edit: EditorContextEdit) => {
|
||||
const detachedTimeline = edit.action === 'TIMELINE_EDIT' && !isNativeTimelinePlayback(edit);
|
||||
const nativeFocus = edit.action === 'SET_ACTIVE_AREA' || edit.action === 'SET_ACTIVE_REGION';
|
||||
const nativeRegionEdit = edit.action === 'RESIZE_REGION' || edit.action === 'TOGGLE_HEADER_MENUS' ||
|
||||
edit.action === 'TOGGLE_REGION' || edit.action === 'FLIP_REGION' || edit.action === 'SET_EDITOR_TYPE' ||
|
||||
edit.action === 'TOGGLE_QUAD_VIEW' || edit.action === 'SWAP_AREAS' || edit.action === 'MOVE_AREA_EDGE' ||
|
||||
edit.action === 'SPLIT_AREA' || edit.action === 'JOIN_AREA' ||
|
||||
edit.action === 'TOGGLE_MAXIMIZE_AREA' || edit.action === 'TOGGLE_FULLSCREEN_AREA';
|
||||
if (busy || (!attached && !nativeFocus && !nativeRegionEdit && !detachedSelection(edit) && !detachedTimeline)) return;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
if (!await onCommand({ type: 'editEditorContext', baseRevision: revision, edit })) {
|
||||
setError('编辑器操作未完成,请查看状态栏。');
|
||||
}
|
||||
setJoinTarget('');
|
||||
} catch (reason) {
|
||||
setError(reason instanceof Error ? reason.message : String(reason));
|
||||
} finally { setBusy(false); }
|
||||
};
|
||||
if (!workspace?.screenId || !area) return null;
|
||||
const owner = { workspaceId: workspace.id, screenId: workspace.screenId, areaId: area.id };
|
||||
const label = (item: typeof area) => item.nativeLayout?.editorTypes.find(type => type.id === item.nativeLayout?.editorType)?.label ?? item.editor;
|
||||
const animate = (edit: NativeTimelineEdit) => timeline && void apply({ ...owner, areaId: timeline.id, action: 'TIMELINE_EDIT', ...edit });
|
||||
const navigate = (edit: NativeView3DNavigation) => {
|
||||
if (!attached || !activeMain) return;
|
||||
void apply({ ...owner, action: 'VIEW3D_NAVIGATE', regionId: activeMain.id, ...edit });
|
||||
};
|
||||
const select = (edit: NativeView3DSelection) => activeMain && void apply({
|
||||
...owner, action: 'VIEW3D_SELECT', regionId: activeMain.id, ...edit,
|
||||
});
|
||||
const navigation = [
|
||||
['JUMP_START', '起始帧'], ['PREVIOUS_KEYFRAME', '上一关键帧'], ['FRAME_BACK', '上一帧'],
|
||||
['FRAME_NEXT', '下一帧'], ['NEXT_KEYFRAME', '下一关键帧'], ['JUMP_END', '结束帧'],
|
||||
['PREVIOUS_MARKER', '上一标记'], ['NEXT_MARKER', '下一标记'],
|
||||
] as const;
|
||||
const validOffset = Number.isSafeInteger(markerOffset) && Math.abs(markerOffset) <= 1_000_000;
|
||||
const validPathInterval = Number.isSafeInteger(shortestPath.skip) && shortestPath.skip >= 0 && shortestPath.skip <= 1_000_000 &&
|
||||
Number.isSafeInteger(shortestPath.nth) && shortestPath.nth >= 1 && shortestPath.nth <= 1_000_000 &&
|
||||
Number.isSafeInteger(shortestPath.offset) && Math.abs(shortestPath.offset) <= 1_000_000;
|
||||
return <div onKeyDown={event => event.stopPropagation()} onKeyUp={event => event.stopPropagation()} style={{ flexShrink: 0 }}>
|
||||
{layout?.editorType === 'VIEW_3D' && activeMain && <details style={{ padding: '4px 8px' }}>
|
||||
<summary>视图操作</summary>
|
||||
<fieldset aria-label="三维视图操作" disabled={busy || !workspace.writable}
|
||||
style={{ display: 'flex', flexWrap: 'wrap', gap: 6, border: 0, margin: 0, padding: 4 }}>
|
||||
{mainRegions.length > 1 && <label>目标视图 <select value={activeMain.id}
|
||||
onChange={event => void apply({ ...owner, action: 'SET_ACTIVE_REGION', regionId: event.target.value })}>
|
||||
{mainRegions.map((item, index) => <option key={item.id} value={item.id}>视图 {index + 1}</option>)}
|
||||
</select></label>}
|
||||
<button type="button" onClick={() => select({ operation: 'SELECT_ALL' })}>全选</button>
|
||||
<button type="button" onClick={() => select({ operation: 'DESELECT_ALL' })}>取消全选</button>
|
||||
<button type="button" onClick={() => select({ operation: 'INVERT_SELECTION' })}>反选</button>
|
||||
<details>
|
||||
<summary>绘制遮罩与选择</summary>
|
||||
<div>
|
||||
<button type="button" title="顶点绘制、权重绘制或纹理绘制:启用面选择遮罩后可选择关联面、扩大或缩小选择"
|
||||
onClick={() => select({ operation: 'SET_PAINT_MASK', domain: 'FACE' })}>启用面遮罩</button>
|
||||
<button type="button" title="顶点绘制或权重绘制:启用顶点选择遮罩后可选择关联顶点、扩大或缩小选择"
|
||||
onClick={() => select({ operation: 'SET_PAINT_MASK', domain: 'VERTEX' })}>启用顶点遮罩</button>
|
||||
<button type="button" title="关闭绘制的面/顶点选择遮罩;权重绘制恢复骨骼选择"
|
||||
onClick={() => select({ operation: 'SET_PAINT_MASK', domain: 'NONE' })}>关闭遮罩</button>
|
||||
</div>
|
||||
<div>
|
||||
<button type="button" title="绘制模式需启用面或顶点遮罩;从已选元素扩展到相连元素"
|
||||
onClick={() => select({ operation: 'SELECT_LINKED', objectType: linkedType,
|
||||
extend: linkedExtend })}>选择关联项</button>
|
||||
<button type="button" title="绘制模式需启用面或顶点遮罩;向外扩大当前选择"
|
||||
onClick={() => select({ operation: 'SELECT_MORE', useFaceStep: selectionFaceStep })}>扩大选择</button>
|
||||
<button type="button" title="绘制模式需启用面或顶点遮罩;取消选择当前选择区域边界上的元素"
|
||||
onClick={() => select({ operation: 'SELECT_LESS', useFaceStep: selectionFaceStep })}>缩小选择</button>
|
||||
<label title="使用当前面/顶点选择算子的面步进规则">
|
||||
<input type="checkbox" checked={selectionFaceStep}
|
||||
onChange={event => setSelectionFaceStep(event.target.checked)}/>按面步进</label>
|
||||
</div>
|
||||
<div>
|
||||
<button type="button" title="绘制模式:隐藏当前面或顶点遮罩中的已选元素"
|
||||
onClick={() => select({ operation: 'PAINT_HIDE', unselected: false })}>隐藏已选</button>
|
||||
<button type="button" title="绘制模式:隐藏当前面或顶点遮罩中的未选元素"
|
||||
onClick={() => select({ operation: 'PAINT_HIDE', unselected: true })}>隐藏未选</button>
|
||||
<button type="button" title="显示绘制中隐藏的面/顶点;权重或顶点绘制关闭遮罩后也可恢复显示"
|
||||
onClick={() => select({ operation: 'PAINT_REVEAL', select: paintRevealSelect })}>显示隐藏元素</button>
|
||||
<label><input type="checkbox" checked={paintRevealSelect}
|
||||
onChange={event => setPaintRevealSelect(event.target.checked)}/>选中新显示的元素</label>
|
||||
</div>
|
||||
<div>
|
||||
<button type="button" title="启用顶点绘制或权重绘制的顶点遮罩,选择未分配到顶点组的顶点;对象需有权重与顶点组"
|
||||
onClick={() => select({ operation: 'PAINT_SELECT_UNGROUPED', extend: paintUngroupedExtend })}>选择未分组顶点</button>
|
||||
<label><input type="checkbox" checked={paintUngroupedExtend}
|
||||
onChange={event => setPaintUngroupedExtend(event.target.checked)}/>扩展未分组选择</label>
|
||||
</div>
|
||||
<div>
|
||||
<button type="button" title="在主区域下一次真实指针点击处选择相连面或顶点;Esc 可取消等待"
|
||||
disabled={!attached}
|
||||
onClick={() => select({ operation: 'SELECT_LINKED_PICK', select: paintPickSelect, x: 0, y: 0 })}>
|
||||
{paintPickSelect ? '指针选择关联项' : '指针取消关联项'}</button>
|
||||
<label><input type="checkbox" checked={paintPickSelect}
|
||||
onChange={event => setPaintPickSelect(event.target.checked)}/>选择(关闭则取消)</label>
|
||||
</div>
|
||||
</details>
|
||||
{workflow?.context.mode === 'EDIT' && <>
|
||||
<details>
|
||||
<summary>蜡笔选择</summary>
|
||||
<div>
|
||||
{([['POINT', '点选择'], ['STROKE', '笔画选择'], ['SEGMENT', '线段选择']] as const).map(([mode, title]) =>
|
||||
<button key={mode} type="button" onClick={() => select({ operation: 'GP_SELECT_MODE', mode })}>{title}</button>)}
|
||||
<button type="button" title="点/线段选择模式:扩大已选范围"
|
||||
onClick={() => select({ operation: 'SELECT_MORE', useFaceStep: false })}>扩大蜡笔选择</button>
|
||||
<button type="button" title="点/线段选择模式:缩小已选范围"
|
||||
onClick={() => select({ operation: 'SELECT_LESS', useFaceStep: false })}>缩小蜡笔选择</button>
|
||||
<button type="button" onClick={() => select({ operation: 'GP_SELECT_LINKED', deselect: false })}>选择相连笔画</button>
|
||||
<button type="button" onClick={() => select({ operation: 'GP_SELECT_LINKED', deselect: true })}>取消相连笔画选择</button>
|
||||
<button type="button" title="选择与当前已选笔画属于同一填充组的全部曲线"
|
||||
onClick={() => select({ operation: 'GP_SELECT_FILL' })}>选择同一填充</button>
|
||||
</div>
|
||||
<div>
|
||||
<button type="button" title="选择使用活动蜡笔对象当前材质槽的可编辑笔画"
|
||||
onClick={() => select({ operation: 'GP_SELECT_MATERIAL', deselect: false })}>按当前材质选择</button>
|
||||
<button type="button" title="取消使用当前材质槽的笔画选择,保留其他选择"
|
||||
onClick={() => select({ operation: 'GP_SELECT_MATERIAL', deselect: true })}>取消当前材质选择</button>
|
||||
{([['STROKE', '描边'], ['FILL', '填充']] as const).map(([type, title]) =>
|
||||
<span key={type}>
|
||||
<button type="button" onClick={() => select({ operation: 'GP_SELECT_BY_STROKE_TYPE', type, deselect: false })}>选择全部{title}</button>
|
||||
<button type="button" onClick={() => select({ operation: 'GP_SELECT_BY_STROKE_TYPE', type, deselect: true })}>取消{title}选择</button>
|
||||
</span>)}
|
||||
</div>
|
||||
<div>
|
||||
<button type="button" onClick={() => select({ operation: 'GP_SELECT_ALTERNATE', deselectEnds: gpDeselectEnds })}>交替选择点</button>
|
||||
<label><input type="checkbox" checked={gpDeselectEnds}
|
||||
onChange={event => setGpDeselectEnds(event.target.checked)}/>排除首尾点</label>
|
||||
<label>起始点数 <input type="number" min={0} max={2147483647} step={1} value={gpAmountStart}
|
||||
onChange={event => setGpAmountStart(event.target.valueAsNumber)}/></label>
|
||||
<label>末尾点数 <input type="number" min={0} max={2147483647} step={1} value={gpAmountEnd}
|
||||
onChange={event => setGpAmountEnd(event.target.valueAsNumber)}/></label>
|
||||
<button type="button" disabled={![gpAmountStart, gpAmountEnd].every(value =>
|
||||
Number.isSafeInteger(value) && value >= 0 && value <= 2147483647)}
|
||||
onClick={() => select({ operation: 'GP_SELECT_ENDS', amountStart: gpAmountStart, amountEnd: gpAmountEnd })}>选择端点</button>
|
||||
</div>
|
||||
<div>
|
||||
<label>相似依据 <select value={gpSimilarMode}
|
||||
onChange={event => setGpSimilarMode(event.target.value as typeof gpSimilarMode)}>
|
||||
<option value="LAYER">图层</option>
|
||||
<option value="MATERIAL">材质</option>
|
||||
<option value="VERTEX_COLOR">顶点颜色</option>
|
||||
<option value="RADIUS">半径</option>
|
||||
<option value="OPACITY">不透明度</option>
|
||||
</select></label>
|
||||
<label>阈值 <input type="number" min={0} max={3.4028234663852886e38} step="any"
|
||||
disabled={gpSimilarMode === 'LAYER'} value={gpSimilarThreshold}
|
||||
onChange={event => setGpSimilarThreshold(event.target.valueAsNumber)}/></label>
|
||||
<button type="button" disabled={gpSimilarMode !== 'LAYER' &&
|
||||
(!Number.isFinite(gpSimilarThreshold) || gpSimilarThreshold < 0 || gpSimilarThreshold > 3.4028234663852886e38)}
|
||||
onClick={() => select({ operation: 'GP_SELECT_SIMILAR', mode: gpSimilarMode,
|
||||
threshold: gpSimilarMode === 'LAYER' ? 0.1 : gpSimilarThreshold })}>选择相似项</button>
|
||||
</div>
|
||||
<div>
|
||||
<label>随机比例 <input type="number" min={0} max={1} step="any" value={gpRandomRatio}
|
||||
onChange={event => setGpRandomRatio(event.target.valueAsNumber)}/></label>
|
||||
<label>随机种子 <input type="number" min={0} max={2147483647} step={1} value={gpRandomSeed}
|
||||
onChange={event => setGpRandomSeed(event.target.valueAsNumber)}/></label>
|
||||
<button type="button" title="按比例重新选择可编辑点或笔画;相同种子重复使用相同随机分布"
|
||||
disabled={!Number.isFinite(gpRandomRatio) || gpRandomRatio < 0 || gpRandomRatio > 1 ||
|
||||
!Number.isSafeInteger(gpRandomSeed) || gpRandomSeed < 0 || gpRandomSeed > 2147483647}
|
||||
onClick={() => select({ operation: 'GP_SELECT_RANDOM', ratio: gpRandomRatio, seed: gpRandomSeed })}>随机选择</button>
|
||||
</div>
|
||||
</details>
|
||||
<details>
|
||||
<summary>文本对象选择与光标</summary>
|
||||
<div>
|
||||
<button type="button" onClick={() => select({ operation: 'TEXT_SELECT_ALL' })}>全选文本</button>
|
||||
<button type="button" title="清除文本选择并将光标收拢到选择末尾"
|
||||
onClick={() => select({ operation: 'TEXT_DESELECT_ALL' })}>取消文本选择</button>
|
||||
<button type="button" onClick={() => select({ operation: 'TEXT_SELECT_WORD' })}>选择光标所在词</button>
|
||||
<button type="button" disabled={!attached} title="在目标视图点击放置文本光标,左键拖动选择文本;等待点击时 Esc 取消,拖选中 Esc 结束并保留选择"
|
||||
onClick={() => select({ operation: 'TEXT_SELECT_POINTER' })}>指针定位/拖选文本</button>
|
||||
<label><input type="checkbox" checked={textExtend}
|
||||
onChange={event => setTextExtend(event.target.checked)}/>移动时扩展选择</label>
|
||||
{([['TEXT_BEGIN', '文本开头'], ['TEXT_END', '文本末尾'],
|
||||
['LINE_BEGIN', '行首'], ['LINE_END', '行尾'],
|
||||
['PREVIOUS_CHARACTER', '上一字符'], ['NEXT_CHARACTER', '下一字符'],
|
||||
['PREVIOUS_WORD', '上一词'], ['NEXT_WORD', '下一词'],
|
||||
['PREVIOUS_LINE', '上一行'], ['NEXT_LINE', '下一行'],
|
||||
['PREVIOUS_PAGE', '上一页'], ['NEXT_PAGE', '下一页']] as const).map(([type, title]) =>
|
||||
<button key={type} type="button" onClick={() => select({ operation: 'TEXT_MOVE', type,
|
||||
extend: textExtend })}>{title}</button>)}
|
||||
</div>
|
||||
</details>
|
||||
<button type="button" title="网格编辑:选择与当前顶点、边或面相连的更多元素"
|
||||
onClick={() => select({ operation: 'SELECT_MORE', useFaceStep: selectionFaceStep })}>扩大网格选择</button>
|
||||
<button type="button" title="网格编辑:取消选择当前选择区域边界上的元素"
|
||||
onClick={() => select({ operation: 'SELECT_LESS', useFaceStep: selectionFaceStep })}>缩小网格选择</button>
|
||||
<label><input type="checkbox" checked={selectionFaceStep}
|
||||
onChange={event => setSelectionFaceStep(event.target.checked)}/>按面步进</label>
|
||||
<button type="button" title="网格编辑:根据最后两个选择元素的顺序选择下一个元素"
|
||||
onClick={() => select({ operation: 'SELECT_NEXT_ACTIVE' })}>下一活动元素</button>
|
||||
<button type="button" title="网格编辑:取消最后选择的元素,返回上一个活动元素"
|
||||
onClick={() => select({ operation: 'SELECT_PREVIOUS_ACTIVE' })}>上一活动元素</button>
|
||||
<details>
|
||||
<summary>网格循环选择</summary>
|
||||
<div>
|
||||
<button type="button" title="从每条已选边扩展选择相连的边循环"
|
||||
onClick={() => select({ operation: 'SELECT_EDGE_LOOPS',
|
||||
...(loopUseDelimit ? { delimit: loopDelimit } : {}) })}>边循环</button>
|
||||
<button type="button" title="从已选边界边扩展到整条边界循环;需要至少一条已选边界边"
|
||||
onClick={() => select({ operation: 'SELECT_BOUNDARY_LOOPS', extend: boundaryExtend,
|
||||
...(loopUseDelimit ? { delimit: loopDelimit } : {}) })}>边界循环</button>
|
||||
<label><input type="checkbox" checked={boundaryExtend}
|
||||
onChange={event => setBoundaryExtend(event.target.checked)}/>扩展边界选择</label>
|
||||
<label title="未指定时各操作使用自己的默认分隔;指定后全部不勾选表示无分隔">
|
||||
<input type="checkbox" checked={loopUseDelimit}
|
||||
onChange={event => setLoopUseDelimit(event.target.checked)}/>指定循环/边界分隔</label>
|
||||
{loopUseDelimit && ([['SEAM', '缝合边'], ['SHARP', '锐边'], ['NGONS', '多边面'],
|
||||
['INNER_CORNERS', '内角'], ['OUTER_CORNERS', '外角']] as const).map(([value, title]) =>
|
||||
<label key={value}><input type="checkbox" checked={loopDelimit.includes(value)} onChange={event =>
|
||||
setLoopDelimit(current => event.target.checked ? [...current, value] : current.filter(item => item !== value))}/>{title}</label>)}
|
||||
</div>
|
||||
<div>
|
||||
<button type="button" title="从每条已选边扩展选择边环"
|
||||
onClick={() => select({ operation: 'SELECT_EDGE_RINGS',
|
||||
...(ringUseDelimit ? { delimit: ringDelimit } : {}) })}>边环</button>
|
||||
<label><input type="checkbox" checked={ringUseDelimit}
|
||||
onChange={event => setRingUseDelimit(event.target.checked)}/>指定边环分隔</label>
|
||||
{ringUseDelimit && ([['SEAM', '缝合边'], ['SHARP', '锐边'], ['MATERIAL', '材质'],
|
||||
['NGONS', '跨过偶数边多边面']] as const).map(([value, title]) =>
|
||||
<label key={value}><input type="checkbox" checked={ringDelimit.includes(value)} onChange={event =>
|
||||
setRingDelimit(current => event.target.checked ? [...current, value] : current.filter(item => item !== value))}/>{title}</label>)}
|
||||
</div>
|
||||
<div>
|
||||
<button type="button" title="选择已选边循环围成的面区域"
|
||||
onClick={() => select({ operation: 'LOOP_TO_REGION', selectBigger: loopSelectBigger })}>循环内区域</button>
|
||||
<label><input type="checkbox" checked={loopSelectBigger}
|
||||
onChange={event => setLoopSelectBigger(event.target.checked)}/>选择较大区域</label>
|
||||
<button type="button" title="选择已选面的边界;纯面选择模式会切换为边选择"
|
||||
onClick={() => select({ operation: 'REGION_TO_LOOP' })}>所选区域的边界</button>
|
||||
</div>
|
||||
</details>
|
||||
</>}
|
||||
{workflow?.context.mode === 'POSE' && <>
|
||||
<button type="button" onClick={() => select({ operation: 'SELECT_HIERARCHY', direction: 'PARENT', extend: false })}>选择父骨骼</button>
|
||||
<button type="button" onClick={() => select({ operation: 'SELECT_HIERARCHY', direction: 'CHILD', extend: false })}>选择子骨骼</button>
|
||||
<button type="button" onClick={() => select({ operation: 'SELECT_HIERARCHY', direction: 'PARENT', extend: true })}>扩展到父骨骼</button>
|
||||
<button type="button" onClick={() => select({ operation: 'SELECT_HIERARCHY', direction: 'CHILD', extend: true })}>扩展到子骨骼</button>
|
||||
</>}
|
||||
{workflow?.context.mode === 'OBJECT' && <>
|
||||
<label>关联类型 <select value={linkedType} onChange={event => setLinkedType(event.target.value as typeof linkedType)}>
|
||||
{([['OBDATA', '物体数据'], ['MATERIAL', '材质'], ['DUPGROUP', '实例集合'],
|
||||
['PARTICLE', '粒子系统'], ['LIBRARY', '库'], ['LIBRARY_OBDATA', '库(物体数据)']] as const).map(([value, title]) =>
|
||||
<option key={value} value={value}>{title}</option>)}
|
||||
</select></label>
|
||||
<label><input type="checkbox" checked={linkedExtend} onChange={event => setLinkedExtend(event.target.checked)}/>扩展关联选择</label>
|
||||
</>}
|
||||
{workflow?.context.mode === 'EDIT' && <>
|
||||
<details>
|
||||
<summary>网格关联选择</summary>
|
||||
<div>
|
||||
<button type="button" disabled={!validPathInterval}
|
||||
title="在网格编辑模式先选择两个同类型顶点、边或面;优先使用最后两个选择记录"
|
||||
onClick={() => select(shortestPath)}>最短路径</button>
|
||||
<label><input type="checkbox" checked={shortestPath.useFaceStep}
|
||||
onChange={event => setShortestPath(current => ({ ...current, useFaceStep: event.target.checked }))}/>跨面步进</label>
|
||||
<label><input type="checkbox" checked={shortestPath.useTopologyDistance}
|
||||
onChange={event => setShortestPath(current => ({ ...current, useTopologyDistance: event.target.checked }))}/>使用拓扑距离</label>
|
||||
<label><input type="checkbox" checked={shortestPath.useFill}
|
||||
onChange={event => setShortestPath(current => ({ ...current, useFill: event.target.checked }))}/>填充路径区域</label>
|
||||
<label title="边选择模式下可标记路径;默认沿用当前工具的边标记设置">边标记 <select
|
||||
value={shortestPath.edgeMode ?? ''} onChange={event => setShortestPath(current => ({ ...current,
|
||||
edgeMode: (event.target.value || undefined) as typeof current.edgeMode }))}>
|
||||
<option value="">沿用当前工具</option>
|
||||
{([['SELECT', '选择'], ['SEAM', '缝合边'], ['SHARP', '锐边'], ['CREASE', '折痕'],
|
||||
['BEVEL', '倒角权重'], ['FREESTYLE', 'Freestyle 边']] as const).map(([value, title]) =>
|
||||
<option key={value} value={value}>{title}</option>)}
|
||||
</select></label>
|
||||
{([['skip', '间隔跳过', 0], ['nth', '间隔选中', 1], ['offset', '间隔偏移', -1_000_000]] as const).map(([key, title, min]) =>
|
||||
<label key={key}>{title} <input type="number" min={min} max={1_000_000} step={1}
|
||||
value={Number.isFinite(shortestPath[key]) ? shortestPath[key] : ''}
|
||||
onChange={event => setShortestPath(current => ({ ...current, [key]: event.target.valueAsNumber }))}/></label>)}
|
||||
</div>
|
||||
<div>
|
||||
<button type="button" disabled={!Number.isFinite(flatSharpness) || flatSharpness < 0.01 || flatSharpness > 180}
|
||||
title="从已选面出发,按相邻面的夹角扩展;需要先选中至少一个面"
|
||||
onClick={() => select({ operation: 'SELECT_LINKED_FLAT_FACES', sharpnessDegrees: flatSharpness })}>连接共面面</button>
|
||||
<label>夹角阈值(度) <input type="number" min={0.01} max={180} step={0.1}
|
||||
value={Number.isFinite(flatSharpness) ? flatSharpness : ''}
|
||||
onChange={event => setFlatSharpness(event.target.valueAsNumber)}/></label>
|
||||
</div>
|
||||
</details>
|
||||
<label><input type="checkbox" checked={linkedUseDelimit} onChange={event => setLinkedUseDelimit(event.target.checked)}/>指定网格关联分隔</label>
|
||||
{linkedUseDelimit && ([['NORMAL', '法线'], ['MATERIAL', '材质'], ['SEAM', '缝合边'], ['SHARP', '锐边'], ['UV', 'UV']] as const).map(([value, title]) =>
|
||||
<label key={value}><input type="checkbox" checked={linkedDelimit.includes(value)} onChange={event =>
|
||||
setLinkedDelimit(current => event.target.checked ? [...current, value] : current.filter(item => item !== value))}/>{title}</label>)}
|
||||
</>}
|
||||
<button type="button" title="物体模式按关联类型选择;网格编辑或绘制遮罩模式扩展相连元素;姿态模式选择相连骨骼"
|
||||
onClick={() => select({ operation: 'SELECT_LINKED', objectType: linkedType, extend: linkedExtend,
|
||||
...(linkedUseDelimit ? { delimit: linkedDelimit } : {}) })}>选择关联项</button>
|
||||
<button type="button" disabled={!attached} title="左键拖框选择,中键拖框取消选择;Esc 或右键取消手势"
|
||||
onClick={() => select({ operation: 'BOX' })}>框选</button>
|
||||
<button type="button" disabled={!attached} title="左键涂选,中键取消选择,滚轮调整半径;Esc 或右键结束并保留选择"
|
||||
onClick={() => select({ operation: 'CIRCLE' })}>圈选</button>
|
||||
<label>套索方式 <select value={lassoMode} onChange={event => setLassoMode(event.target.value as typeof lassoMode)}>
|
||||
{([['SET', '替换'], ['ADD', '添加'], ['SUB', '减去'], ['XOR', '切换'], ['AND', '交集']] as const).map(([mode, title]) =>
|
||||
<option key={mode} value={mode}>{title}</option>)}
|
||||
</select></label>
|
||||
<button type="button" disabled={!attached} title="在目标视图左键按下后绘制,松开应用;Esc 取消"
|
||||
onClick={() => select({ operation: 'LASSO', mode: lassoMode })}>套索选择</button>
|
||||
<button type="button" onClick={() => navigate({ operation: 'FRAME_SELECTED', allRegions: frameAllRegions })}>聚焦选择</button>
|
||||
<button type="button" onClick={() => navigate({ operation: 'FRAME_ALL', allRegions: frameAllRegions })}>显示全部</button>
|
||||
<label><input type="checkbox" checked={frameAllRegions} onChange={event => setFrameAllRegions(event.target.checked)}/>同时调整区域内全部视图</label>
|
||||
{([['FRONT', '前'], ['BACK', '后'], ['LEFT', '左'], ['RIGHT', '右'], ['TOP', '顶'], ['BOTTOM', '底']] as const).map(([axis, title]) =>
|
||||
<button key={axis} type="button" onClick={() => navigate({ operation: 'VIEW_AXIS', axis, alignActive })}>{title}视图</button>)}
|
||||
<label><input type="checkbox" checked={alignActive} onChange={event => setAlignActive(event.target.checked)}/>对齐活动物体</label>
|
||||
{([['LEFT', '左'], ['RIGHT', '右'], ['UP', '上'], ['DOWN', '下']] as const).map(([direction, title]) =>
|
||||
<button key={`pan-${direction}`} type="button" onClick={() => navigate({ operation: 'PAN', direction })}>向{title}平移</button>)}
|
||||
{([['LEFT', '左'], ['RIGHT', '右'], ['UP', '上'], ['DOWN', '下']] as const).map(([direction, title]) =>
|
||||
<button key={`orbit-${direction}`} type="button" onClick={() => navigate({ operation: 'ORBIT', direction })}>向{title}环绕</button>)}
|
||||
<button type="button" onClick={() => navigate({ operation: 'ZOOM', delta: 1 })}>放大视图</button>
|
||||
<button type="button" onClick={() => navigate({ operation: 'ZOOM', delta: -1 })}>缩小视图</button>
|
||||
<button type="button" title="在目标视图中左键拖框放大,中键拖框缩小;Esc 或右键取消"
|
||||
onClick={() => navigate({ operation: 'ZOOM_BORDER' })}>框选缩放</button>
|
||||
<button type="button" onClick={() => navigate({ operation: 'ROLL', direction: 'LEFT' })}>向左滚转</button>
|
||||
<button type="button" onClick={() => navigate({ operation: 'ROLL', direction: 'RIGHT' })}>向右滚转</button>
|
||||
<button type="button" onClick={() => navigate({ operation: 'TOGGLE_PROJECTION' })}>透视/正交</button>
|
||||
<button type="button" onClick={() => navigate({ operation: 'TOGGLE_CAMERA' })}>进入/退出相机视图</button>
|
||||
<button type="button" onClick={() => navigate({ operation: 'TOGGLE_LOCAL_VIEW' })}>进入/退出局部视图</button>
|
||||
<button type="button" onClick={() => navigate({ operation: 'REMOVE_FROM_LOCAL_VIEW' })}>从局部视图移除所选</button>
|
||||
</fieldset>
|
||||
</details>}
|
||||
{timeline && <fieldset aria-label="时间线操作" disabled={busy || !workspace.writable}
|
||||
style={{ display: 'flex', flexWrap: 'wrap', gap: 6, border: 0, margin: 0, padding: '4px 8px' }}>
|
||||
<label>时间线 <select value={timeline.id} onChange={event => setTimelineId(event.target.value)}>
|
||||
{timelines.map(item => <option key={item.id} value={item.id}>{workspace.areas.indexOf(item) + 1}: {label(item)}</option>)}
|
||||
</select></label>
|
||||
<button type="button" disabled={!attached} title={attached ? "播放中再次点击会停止" : "请打开 Blender 桌面播放动画"}
|
||||
onClick={() => animate({ operation: 'PLAY_REVERSE' })}>反向播放/停止</button>
|
||||
<button type="button" disabled={!attached} title={attached ? "播放中再次点击会停止" : "请打开 Blender 桌面播放动画"}
|
||||
onClick={() => animate({ operation: 'PLAY_FORWARD' })}>播放/停止</button>
|
||||
<button type="button" disabled={!attached} onClick={() => animate({ operation: 'PAUSE_PLAYBACK' })}>暂停在当前帧</button>
|
||||
<button type="button" disabled={!attached} onClick={() => animate({ operation: 'CANCEL_PLAYBACK' })}>取消播放并返回起始帧</button>
|
||||
{navigation.map(([operation, title]) => <button key={operation} type="button" onClick={() => animate(
|
||||
operation === 'FRAME_BACK' || operation === 'FRAME_NEXT' ? { operation: 'FRAME_OFFSET', delta: operation === 'FRAME_BACK' ? -1 : 1 } : { operation }
|
||||
)}>{title}</button>)}
|
||||
<details><summary>关键帧与预览范围</summary><div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
|
||||
<button type="button" onClick={() => animate({ operation: 'SELECT_ALL_KEYS' })}>全选关键帧</button>
|
||||
<button type="button" onClick={() => animate({ operation: 'DESELECT_ALL_KEYS' })}>取消关键帧选择</button>
|
||||
<button type="button" onClick={() => animate({ operation: 'INVERT_KEYS' })}>反选关键帧</button>
|
||||
<button type="button" onClick={() => animate({ operation: 'FRAME_ALL_KEYS' })}>框定全部关键帧</button>
|
||||
<button type="button" onClick={() => animate({ operation: 'FRAME_SELECTED_KEYS' })}>框定所选关键帧</button>
|
||||
<button type="button" onClick={() => animate({ operation: 'CENTER_CURRENT_FRAME' })}>居中当前帧</button>
|
||||
<button type="button" onClick={() => animate({ operation: 'PREVIEW_SELECTED_KEYS' })}>按所选设置预览范围</button>
|
||||
<button type="button" onClick={() => animate({ operation: 'CLEAR_PREVIEW_RANGE' })}>清除预览范围</button>
|
||||
</div></details>
|
||||
<details><summary>编辑所选关键帧</summary><div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
|
||||
<label>移动帧数 <input type="number" step="any" min={-1_000_000} max={1_000_000}
|
||||
value={keyOffset} onChange={event => setKeyOffset(event.target.valueAsNumber)}/></label>
|
||||
<button type="button" disabled={!Number.isFinite(keyOffset) || Math.abs(keyOffset) > 1_000_000}
|
||||
onClick={() => animate({ operation: 'MOVE_KEYS', delta: keyOffset })}>移动所选关键帧</button>
|
||||
<button type="button" disabled={!Number.isFinite(keyOffset) || Math.abs(keyOffset) > 1_000_000}
|
||||
onClick={() => animate({ operation: 'DUPLICATE_MOVE_KEYS', delta: keyOffset })}>复制并移动关键帧</button>
|
||||
<label>时间缩放倍数 <input type="number" step="any" min={-1000} max={1000}
|
||||
value={keyScale} onChange={event => setKeyScale(event.target.valueAsNumber)}/></label>
|
||||
<button type="button" disabled={!Number.isFinite(keyScale) || Math.abs(keyScale) > 1000}
|
||||
onClick={() => animate({ operation: 'SCALE_KEYS', factor: keyScale })}>围绕当前帧缩放时间</button>
|
||||
<button type="button" onClick={() => animate({ operation: 'COPY_KEYS' })}>复制所选关键帧</button>
|
||||
<label>粘贴时间 <select value={pasteOffset} onChange={event => setPasteOffset(event.target.value as typeof pasteOffset)}>
|
||||
{TIMELINE_PASTE_OFFSETS.map(value => <option key={value} value={value}>{timelinePasteLabels[value]}</option>)}
|
||||
</select></label>
|
||||
<label>合并方式 <select value={pasteMerge} onChange={event => setPasteMerge(event.target.value as typeof pasteMerge)}>
|
||||
{TIMELINE_PASTE_MERGES.map(value => <option key={value} value={value}>{timelinePasteLabels[value]}</option>)}
|
||||
</select></label>
|
||||
<label><input type="checkbox" checked={pasteFlipped} onChange={event => setPasteFlipped(event.target.checked)}/>
|
||||
粘贴到镜像骨骼</label>
|
||||
<button type="button" onClick={() => animate({ operation: 'PASTE_KEYS', offset: pasteOffset,
|
||||
merge: pasteMerge, flipped: pasteFlipped })}>粘贴关键帧</button>
|
||||
{timelineKeyMenus.map(([operation, title]) => <label key={operation}>{title} <select value=""
|
||||
onChange={event => {
|
||||
// Choices and the operation/type union share the original RNA IDs.
|
||||
const type = event.target.value;
|
||||
if ((TIMELINE_KEY_TYPES[operation] as readonly string[]).includes(type)) {
|
||||
animate({ operation, type } as NativeTimelineEdit);
|
||||
}
|
||||
}}>
|
||||
<option value="" disabled>选择并应用…</option>
|
||||
{TIMELINE_KEY_TYPES[operation].map(type => <option key={type} value={type}>{timelineKeyLabels[type]}</option>)}
|
||||
</select></label>)}
|
||||
<button type="button" onClick={() => animate({ operation: 'JUMP_SELECTED_KEYS' })}>跳至所选关键帧平均位置</button>
|
||||
<button type="button" onClick={() => animate({ operation: 'DELETE_KEYS' })}>删除所选关键帧</button>
|
||||
</div></details>
|
||||
<details><summary>标记</summary><div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
|
||||
<button type="button" onClick={() => animate({ operation: 'ADD_MARKER' })}>在当前帧添加</button>
|
||||
<button type="button" onClick={() => animate({ operation: 'SELECT_ALL_MARKERS' })}>全选标记</button>
|
||||
<button type="button" onClick={() => animate({ operation: 'DESELECT_ALL_MARKERS' })}>取消选择</button>
|
||||
<button type="button" onClick={() => animate({ operation: 'INVERT_MARKERS' })}>反选标记</button>
|
||||
<label>名称 <input value={markerName} onChange={event => setMarkerName(event.target.value)}/></label>
|
||||
<button type="button" disabled={!markerName.trim() || markerName.includes('\0') || new TextEncoder().encode(markerName).byteLength > 63}
|
||||
onClick={() => animate({ operation: 'RENAME_MARKER', name: markerName })}>重命名首个选中标记</button>
|
||||
<label>偏移帧 <input type="number" min={-1_000_000} max={1_000_000} value={markerOffset} style={{ width: 80 }}
|
||||
onChange={event => setMarkerOffset(Number(event.target.value))}/></label>
|
||||
<button type="button" disabled={!validOffset} onClick={() => animate({ operation: 'MOVE_MARKERS', delta: markerOffset })}>移动所选</button>
|
||||
<button type="button" disabled={!validOffset} onClick={() => animate({ operation: 'DUPLICATE_MARKERS', delta: markerOffset })}>复制所选</button>
|
||||
<button type="button" onClick={() => animate({ operation: 'DELETE_MARKERS' })}>删除所选</button>
|
||||
</div></details>
|
||||
</fieldset>}
|
||||
<details style={{ padding: '4px 8px' }}>
|
||||
<summary>工作区布局</summary>
|
||||
<fieldset disabled={busy || !workspace.writable} style={{ display: 'flex', flexWrap: 'wrap', gap: 8, border: 0, margin: 0, padding: 4 }}>
|
||||
<label>区域 <select value={area.id} onChange={event => void apply({ ...owner, action: 'SET_ACTIVE_AREA', areaId: event.target.value })}>
|
||||
{workspace.areas.map((item, index) => <option key={item.id} value={item.id}
|
||||
disabled={item.editor === 'UNSUPPORTED' || !item.regions.some(region => region.kind === 'MAIN' && region.visible)}>
|
||||
{index + 1}: {label(item)}</option>)}
|
||||
</select></label>
|
||||
{mainRegions.length > 1 && activeMain && <label>视图焦点 <select value={activeMain.id}
|
||||
onChange={event => void apply({ ...owner, action: 'SET_ACTIVE_REGION', regionId: event.target.value })}>
|
||||
{mainRegions.map((item, index) => <option key={item.id} value={item.id}>视图 {index + 1}</option>)}
|
||||
</select></label>}
|
||||
</fieldset>
|
||||
<fieldset disabled={busy || !workspace.writable} style={{ display: 'flex', flexWrap: 'wrap', gap: 8, border: 0, margin: 0, padding: 4 }}>
|
||||
{area.regions.some(item => item.kind === 'HEADER') && <button type="button"
|
||||
onClick={() => void apply({ ...owner, action: 'TOGGLE_HEADER_MENUS' })}>
|
||||
{layout?.headerMenusVisible === false ? '展开标题菜单' : '折叠标题菜单'}
|
||||
</button>}
|
||||
<details><summary>编辑器面板</summary><div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
|
||||
{area.regions.filter(item => item.toggleable || item.flippable).map((item, index) => <span key={item.id}>
|
||||
{item.toggleable ? <label><input type="checkbox" checked={item.visible}
|
||||
onChange={event => void apply({ ...owner, action: 'TOGGLE_REGION', regionId: item.id, visible: event.target.checked })}/>
|
||||
{item.kind} {index + 1}</label> : <span>{item.kind} {index + 1}</span>}
|
||||
{item.flippable && <button type="button" onClick={() => void apply({ ...owner, action: 'FLIP_REGION', regionId: item.id })}>
|
||||
翻转位置 ({item.alignment})
|
||||
</button>}
|
||||
</span>)}
|
||||
</div></details>
|
||||
</fieldset>
|
||||
<fieldset disabled={busy || !workspace.writable} style={{ display: 'flex', flexWrap: 'wrap', gap: 8, border: 0, margin: 0, padding: 4 }}>
|
||||
<label>编辑器 <select value={layout?.editorType ?? ''} disabled={!layout?.editorTypes.length}
|
||||
onChange={event => void apply({ ...owner, action: 'SET_EDITOR_TYPE', editorType: event.target.value })}>
|
||||
{!layout?.editorType && <option value="" disabled>选择编辑器</option>}
|
||||
{layout?.editorTypes.map(item => <option key={item.id} value={item.id}>{item.label}</option>)}
|
||||
</select></label>
|
||||
{layout?.editorType === 'VIEW_3D' && activeMain && <button type="button"
|
||||
onClick={() => void apply({ ...owner, action: 'TOGGLE_QUAD_VIEW', regionId: activeMain.id })}>
|
||||
{activeMain.quadView ? '退出四分视图' : '四分视图'}
|
||||
</button>}
|
||||
</fieldset>
|
||||
<fieldset disabled={busy || !workspace.writable} style={{ display: 'flex', flexWrap: 'wrap', gap: 8, border: 0, margin: 0, padding: 4 }}>
|
||||
<label>相邻区域 <select value={target} disabled={!neighbors.length} onChange={event => setJoinTarget(event.target.value)}>
|
||||
{!neighbors.length && <option value="">无相邻区域</option>}
|
||||
{neighbors.map(item => <option key={item.id} value={item.id}>{workspace.areas.indexOf(item) + 1}: {label(item)}</option>)}
|
||||
</select></label>
|
||||
<button type="button" disabled={!layout?.editable || !target}
|
||||
onClick={() => void apply({ ...owner, action: 'SWAP_AREAS', targetAreaId: target })}>交换编辑器</button>
|
||||
</fieldset>
|
||||
<fieldset disabled={busy || !workspace.writable} style={{ display: 'flex', flexWrap: 'wrap', gap: 8, border: 0, margin: 0, padding: 4 }}>
|
||||
<label>分割位置 <input type="number" min={5} max={95} step={5} value={factor} style={{ width: 52 }}
|
||||
onChange={event => setFactor(Number(event.target.value))}/>%</label>
|
||||
{(['HORIZONTAL', 'VERTICAL'] as const).map(direction => <button key={direction} type="button"
|
||||
disabled={!layout?.editable || !Number.isFinite(factor) || factor < 5 || factor > 95}
|
||||
onClick={() => void apply({ ...owner, action: 'SPLIT_AREA', direction, factor: factor / 100 })}>
|
||||
{direction === 'HORIZONTAL' ? '上下分割' : '左右分割'}
|
||||
</button>)}
|
||||
<button type="button" disabled={!layout?.editable || !target}
|
||||
title="保留当前区域的编辑器,移除选中的相邻区域"
|
||||
onClick={() => void apply({ ...owner, action: 'JOIN_AREA', targetAreaId: target })}>合并并保留当前编辑器</button>
|
||||
<label>分界移动像素 <input type="number" min={1} max={8192} value={edgeDelta} style={{ width: 64 }}
|
||||
onChange={event => setEdgeDelta(Number(event.target.value))}/></label>
|
||||
<label><input type="checkbox" checked={edgeSnap} onChange={event => setEdgeSnap(event.target.checked)}/>吸附</label>
|
||||
{([-1, 1] as const).map(sign => <button key={sign} type="button"
|
||||
disabled={!layout?.editable || !target || !Number.isSafeInteger(edgeDelta) || edgeDelta < 1 || edgeDelta > 8192}
|
||||
title="移动共享分界;相连分界、最小编辑器尺寸和吸附由 Blender 处理"
|
||||
onClick={() => void apply({ ...owner, action: 'MOVE_AREA_EDGE', targetAreaId: target, delta: sign * edgeDelta, snap: edgeSnap })}>
|
||||
{sign < 0 ? '分界向左/下' : '分界向右/上'}
|
||||
</button>)}
|
||||
<button type="button" disabled={layout?.screenState !== 'MAXIMIZED' && (!layout?.editable || workspace.areas.length < 2)}
|
||||
onClick={() => void apply({ ...owner, action: 'TOGGLE_MAXIMIZE_AREA' })}>
|
||||
{layout?.screenState === 'MAXIMIZED' ? '恢复区域' : '最大化区域'}
|
||||
</button>
|
||||
<button type="button" disabled={!layout?.editable && layout?.screenState !== 'FULLSCREEN'}
|
||||
onClick={() => void apply({ ...owner, action: 'TOGGLE_FULLSCREEN_AREA' })}>
|
||||
{layout?.screenState === 'FULLSCREEN' ? '退出专注模式' : '专注模式'}
|
||||
</button>
|
||||
</fieldset>
|
||||
<fieldset disabled={busy || !workspace.writable} style={{ display: 'flex', flexWrap: 'wrap', gap: 8, border: 0, margin: 0, padding: 4 }}>
|
||||
<label>区域尺寸 <select value={selectedRegion} disabled={!resizableRegions.length}
|
||||
onChange={event => setRegionId(event.target.value)}>
|
||||
{!resizableRegions.length && <option value="">无可调整区域</option>}
|
||||
{resizableRegions.map(item => <option key={item.id} value={item.id}>{item.kind} ({item.alignment})</option>)}
|
||||
</select></label>
|
||||
<input aria-label="区域尺寸像素" type="number" min={1} max={8192} step={8} value={regionSize} style={{ width: 64 }}
|
||||
onChange={event => setRegionSize(Number(event.target.value))}/>
|
||||
<button type="button" disabled={!selectedRegion || !Number.isSafeInteger(regionSize) || regionSize < 1 || regionSize > 8192}
|
||||
onClick={() => void apply({ ...owner, action: 'RESIZE_REGION', regionId: selectedRegion, size: regionSize })}>调整区域</button>
|
||||
</fieldset>
|
||||
</details>
|
||||
{error && <output role="alert">{error}</output>}
|
||||
</div>;
|
||||
}
|
||||
2886
web/app/src/app/WasmEditorContext.tsx
Normal file
946
web/app/src/app/WasmGPUCanvas.tsx
Normal file
@@ -0,0 +1,946 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { WebEngineGPUCursor, WebEngineGPUInput, WebEngineEditCommand } from "../../../protocol/web-engine";
|
||||
import type { EditorWorkflowIR } from "../../../protocol/editor-workflow";
|
||||
import type { BlendOpenResult, WebEngineClient } from "../engine-client/WebEngineClient";
|
||||
import { WasmDesktopLayout } from './WasmDesktopLayout';
|
||||
import { DesktopFileTransfer, stageDesktopFiles } from './DesktopFileTransfer';
|
||||
|
||||
export function WasmGPUCanvas({ client, active = true, playing = false, onApplied, onModalActive, onExport, workflow, revision, onCommand, menuCommandRef, onReady, onCleanup }: {
|
||||
client: WebEngineClient;
|
||||
active?: boolean;
|
||||
playing?: boolean;
|
||||
onApplied: (scene: BlendOpenResult) => void;
|
||||
onModalActive?: (active: boolean) => void;
|
||||
onExport?: (path: string, saveCopy?: boolean, revision?: number, saveAs?: boolean) => Promise<void>;
|
||||
workflow: EditorWorkflowIR | null;
|
||||
revision: number;
|
||||
onCommand: (command: WebEngineEditCommand) => Promise<boolean>;
|
||||
menuCommandRef?: { current: ((command: WebEngineEditCommand) => Promise<boolean>) | null };
|
||||
onReady?: (ready: boolean) => void;
|
||||
onCleanup?: (cleanup: Promise<void>) => void;
|
||||
}) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const applied = useRef(onApplied);
|
||||
applied.current = onApplied;
|
||||
const cleanupCaller = useRef(onCleanup);
|
||||
cleanupCaller.current = onCleanup;
|
||||
const exportCaller = useRef(onExport);
|
||||
exportCaller.current = onExport;
|
||||
const commandCaller = useRef(onCommand);
|
||||
commandCaller.current = onCommand;
|
||||
const currentRevision = useRef(revision);
|
||||
currentRevision.current = revision;
|
||||
const activeRef = useRef(active);
|
||||
activeRef.current = active;
|
||||
const playingRef = useRef(playing);
|
||||
playingRef.current = playing;
|
||||
const deactivateRef = useRef(false);
|
||||
useEffect(() => { if (!active) { deactivateRef.current = true; cancelDropTransfer.current?.(); } }, [active]);
|
||||
const startMenuGesture = useRef<((command: WebEngineEditCommand) => Promise<boolean>) | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [retry, setRetry] = useState(0), [retrying, setRetrying] = useState(false);
|
||||
const retrySurface = useRef<(() => Promise<void>) | null>(null);
|
||||
const [ready, setReady] = useState(false), [nativeAttached, setNativeAttached] = useState(false);
|
||||
const [fileSession, setFileSession] = useState('');
|
||||
const [filesOpen, setFilesOpen] = useState(false);
|
||||
const [dropStatus, setDropStatus] = useState('');
|
||||
const [dropError, setDropError] = useState('');
|
||||
const [dropTransferring, setDropTransferring] = useState(false);
|
||||
const cancelDropTransfer = useRef<(() => void) | null>(null);
|
||||
const [grabNotice, setGrabNotice] = useState('');
|
||||
const [operationNotice, setOperationNotice] = useState('');
|
||||
const [compositionText, setCompositionText] = useState('');
|
||||
const [compositionError, setCompositionError] = useState('');
|
||||
// WheelEvent does not identify the physical device (mice also report pixels).
|
||||
// Keep the desktop wheel keymap by default and let trackpad users select the
|
||||
// original Blender pan/pinch keymap without guessing from delta magnitude.
|
||||
const scrollDevice = useRef<'mouse' | 'trackpad'>('mouse');
|
||||
|
||||
useEffect(() => {
|
||||
const container = host.current;
|
||||
if (!container) return;
|
||||
// Each mount owns a new element: a transferred canvas cannot be transferred again.
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.tabIndex = 0;
|
||||
canvas.setAttribute("aria-label", "Blender desktop");
|
||||
canvas.dataset.nativeInputReady = 'false';
|
||||
// Chromium needs an editable host to start platform IME composition. This
|
||||
// fallback DOM is only the input-method buffer; Blender owns all text edits.
|
||||
canvas.contentEditable = 'plaintext-only';
|
||||
canvas.spellcheck = false;
|
||||
canvas.setAttribute('autocapitalize', 'off');
|
||||
Object.assign(canvas.style, { display: "block", width: "100%", height: "100%", touchAction: "none" });
|
||||
container.appendChild(canvas);
|
||||
const session = crypto.randomUUID();
|
||||
setFileSession(session);
|
||||
setDropTransferring(false);
|
||||
const listeners = new AbortController();
|
||||
let disposed = false;
|
||||
let attached = false; setNativeAttached(false);
|
||||
let pendingCleanup: Promise<void> | null = null;
|
||||
const trackCleanup = (cleanup: Promise<void>) => { pendingCleanup = cleanup; cleanupCaller.current?.(cleanup); return cleanup; };
|
||||
let readyPublished = false;
|
||||
let ownerGeneration = 0;
|
||||
let readyOwnerGeneration = 0;
|
||||
let readyOwnerFrames = 0;
|
||||
let stopped = false;
|
||||
let cancelPending = false;
|
||||
let contextLost = false;
|
||||
let dropPending = false;
|
||||
let dropAttempt = 0;
|
||||
let frame = 0;
|
||||
let resizeRetry = 0;
|
||||
let redrawRetry = 0;
|
||||
let selectionRecoveryRetry = 0;
|
||||
let events: WebEngineGPUInput[] = [];
|
||||
let pendingInvoke: { ownerGeneration: number;
|
||||
idleOnly: boolean;
|
||||
run: (session: string, ownerGeneration: number) => Promise<boolean>;
|
||||
resolve: () => void; reject: (reason: unknown) => void } | null = null;
|
||||
const invokeQueue: { ownerGeneration: number; idleOnly: boolean;
|
||||
run: (session: string, ownerGeneration: number) => Promise<boolean>;
|
||||
resolve: () => void; reject: (reason: unknown) => void }[] = [];
|
||||
const unregisterInvoke = client.registerGPUInvokeScheduler((run, idleOnly = false) => new Promise<void>((resolve, reject) => {
|
||||
if (disposed || stopped || !attached || contextLost || menuGesture) {
|
||||
reject(new Error(`原生画布尚未就绪或已有操作等待处理 [disposed=${disposed} stopped=${stopped} attached=${attached} lost=${contextLost} menu=${Boolean(menuGesture)} invoke=${Boolean(pendingInvoke)} idle=${pendingInvoke?.idleOnly} events=${events.length}]`));
|
||||
return;
|
||||
}
|
||||
// F3 must drain the same blur/cancel tail as native menu gestures before
|
||||
// starting a new modal operator. The frame pump owns both orderings.
|
||||
const entry = { ownerGeneration, idleOnly, run, resolve, reject };
|
||||
/* Manual and scheduled checkpoints share one paused-frame slot;
|
||||
* queue the newcomer instead of failing it while the first runs. */
|
||||
if (pendingInvoke) invokeQueue.push(entry); else pendingInvoke = entry;
|
||||
}));
|
||||
let menuGesture: { command: WebEngineEditCommand; ownerGeneration: number;
|
||||
pickSize?: { width: number; height: number; pixelRatio: number }; resolve: (changed: boolean) => void;
|
||||
reject: (reason: unknown) => void } | null = null;
|
||||
startMenuGesture.current = command => new Promise<boolean>((resolve, reject) => {
|
||||
if (disposed || stopped || !attached || contextLost || menuGesture || pendingInvoke) {
|
||||
reject(new Error('画布尚未就绪或已有视图操作等待处理'));
|
||||
return;
|
||||
}
|
||||
// The existing frame pump drains old input, including the menu click's
|
||||
// blur/cancel event, before invoking a native operator. Timeline commands
|
||||
// must see the key selection/frame produced by that input as well.
|
||||
menuGesture = { command, ownerGeneration, resolve, reject };
|
||||
});
|
||||
// App menus share the native layout menu's input drain and owner checks.
|
||||
// Register once per canvas lifetime; no new event pump or pending queue.
|
||||
const menuCommand = startMenuGesture.current;
|
||||
if (menuCommandRef) menuCommandRef.current = menuCommand;
|
||||
let pointerId: number | null = null;
|
||||
let consumedPickPointer: number | null = null;
|
||||
let pressedButtons = 0;
|
||||
let pointerType = 'mouse';
|
||||
let penMode: 1 | 2 = 1;
|
||||
let tabletInputAvailable = false;
|
||||
let cursorGrabAvailable = false;
|
||||
let normalGrabAvailable = false;
|
||||
let cursorGrab = 0;
|
||||
let nativeCursor: WebEngineGPUCursor | undefined;
|
||||
let cursorURL = '', cursorEpoch = 0;
|
||||
const clearNativeCursor = () => { ++cursorEpoch; if (cursorURL) URL.revokeObjectURL(cursorURL); cursorURL = ''; canvas.style.cursor = 'default'; };
|
||||
let cursorScale = 0;
|
||||
let compositionOwner: number | null = null;
|
||||
const abandonComposition = () => {
|
||||
compositionOwner = null;
|
||||
canvas.textContent = '';
|
||||
if (!disposed) setCompositionText('');
|
||||
};
|
||||
const updateCursor = (cursor: WebEngineGPUCursor | undefined, pixelRatio: number) => {
|
||||
if (!cursor && cursorScale === pixelRatio) return;
|
||||
const epoch = ++cursorEpoch;
|
||||
if (cursor) nativeCursor = cursor;
|
||||
cursorScale = pixelRatio;
|
||||
if (!nativeCursor?.visible) { clearNativeCursor(); canvas.style.cursor = nativeCursor ? 'none' : 'default'; return; }
|
||||
const { width, height, hotspotX, hotspotY, rgba } = nativeCursor;
|
||||
if (!width || !height) { clearNativeCursor(); return; }
|
||||
// This is a native WM bitmap, not a host-rendered approximation of a tool.
|
||||
// CSS cursor coordinates are logical pixels; WM's raster is in backing pixels.
|
||||
const source = document.createElement('canvas');
|
||||
source.width = width; source.height = height;
|
||||
const sourceContext = source.getContext('2d');
|
||||
if (!sourceContext) throw new Error('Native cursor bitmap transport is unavailable');
|
||||
sourceContext.putImageData(new ImageData(Uint8ClampedArray.from(rgba), width, height), 0, 0);
|
||||
const scale = Math.min(1 / pixelRatio, 128 / width, 128 / height);
|
||||
const target = document.createElement('canvas');
|
||||
target.width = Math.max(1, Math.round(width * scale));
|
||||
target.height = Math.max(1, Math.round(height * scale));
|
||||
const targetContext = target.getContext('2d');
|
||||
if (!targetContext) throw new Error('Native cursor bitmap transport is unavailable');
|
||||
targetContext.drawImage(source, 0, 0, target.width, target.height);
|
||||
const x = Math.min(target.width - 1, Math.round(hotspotX * target.width / width));
|
||||
const y = Math.min(target.height - 1, Math.round(hotspotY * target.height / height));
|
||||
target.toBlob(blob => {
|
||||
if (disposed || stopped || epoch !== cursorEpoch) return;
|
||||
if (!blob) { clearNativeCursor(); return; }
|
||||
const previous = cursorURL;
|
||||
cursorURL = URL.createObjectURL(blob);
|
||||
canvas.style.cursor = `url("${cursorURL}") ${x} ${y}, default`;
|
||||
if (previous) URL.revokeObjectURL(previous);
|
||||
}, 'image/png');
|
||||
};
|
||||
let lockPending = false;
|
||||
let lockFailed = false;
|
||||
let hadPointerLock = false;
|
||||
let releasingLock = false;
|
||||
const releasePointerLock = () => {
|
||||
if (document.pointerLockElement === canvas) {
|
||||
releasingLock = true;
|
||||
document.exitPointerLock();
|
||||
}
|
||||
};
|
||||
// Tablet WM events are absolute. Pointer Lock only supplies MouseEvents,
|
||||
// which would discard pressure/tilt and turn a pen stroke into mouse input.
|
||||
const wantsPointerLock = () => pointerType !== 'pen' && cursorGrabAvailable &&
|
||||
((normalGrabAvailable && cursorGrab === 1) || cursorGrab === 2 || cursorGrab === 3);
|
||||
const lockError = () => {
|
||||
lockPending = false;
|
||||
lockFailed = true;
|
||||
if (!disposed && !stopped && wantsPointerLock()) {
|
||||
setGrabNotice('持续拖动未取得鼠标锁定;点击画布重试,或按 Esc 取消操作。');
|
||||
}
|
||||
};
|
||||
const requestPointerLock = (trustedGesture = false) => {
|
||||
if (disposed || stopped || contextLost || !attached || !wantsPointerLock() ||
|
||||
document.activeElement !== canvas || lockPending ||
|
||||
document.pointerLockElement || (lockFailed && !trustedGesture)) return;
|
||||
if (!canvas.requestPointerLock) { lockError(); return; }
|
||||
lockPending = true;
|
||||
lockFailed = false;
|
||||
try {
|
||||
// Only host input transport: Blender's native operator decides when a
|
||||
// grab is needed. Retry a denied asynchronous request on a real gesture.
|
||||
Promise.resolve(canvas.requestPointerLock()).then(() => {
|
||||
if (disposed || stopped || contextLost || !wantsPointerLock()) releasePointerLock();
|
||||
}).catch(lockError);
|
||||
} catch { lockError(); }
|
||||
};
|
||||
const size = () => {
|
||||
const bounds = canvas.getBoundingClientRect();
|
||||
const pixelRatio = Math.min(8, Math.max(0.25, window.devicePixelRatio || 1));
|
||||
return { width: Math.min(16384, Math.max(1, Math.round(bounds.width * pixelRatio))),
|
||||
height: Math.min(16384, Math.max(1, Math.round(bounds.height * pixelRatio))), pixelRatio };
|
||||
};
|
||||
const detach = async () => {
|
||||
const result = await client.detachGPUCanvas(session);
|
||||
// Cancellation may restore Main after the canvas component has unmounted.
|
||||
if (result.scene) applied.current(result.scene);
|
||||
if (result.error) throw result.error;
|
||||
};
|
||||
const fail = (reason: unknown) => {
|
||||
pendingInvoke?.reject(reason);
|
||||
pendingInvoke = null;
|
||||
menuGesture?.reject(reason);
|
||||
menuGesture = null;
|
||||
if (disposed || stopped) return;
|
||||
onReady?.(false);
|
||||
setReady(false);
|
||||
stopped = true;
|
||||
cancelDropTransfer.current?.();
|
||||
abandonComposition();
|
||||
clearNativeCursor();
|
||||
releasePointerLock();
|
||||
listeners.abort();
|
||||
cancelAnimationFrame(frame);
|
||||
setError(reason instanceof Error ? reason.message :
|
||||
typeof reason === "object" && reason && "message" in reason ? String(reason.message) : "GPU surface failed");
|
||||
attached = false; setNativeAttached(false);
|
||||
const cleanupError = (reason: unknown) => {
|
||||
const detail = reason && typeof reason === 'object' && 'message' in reason ? String(reason.message) : String(reason);
|
||||
if (!disposed) setError(current => `${current}\n原生桌面清理失败:${detail}`);
|
||||
};
|
||||
const cleanup = trackCleanup(detach());
|
||||
void cleanup.catch(cleanupError);
|
||||
let retryPending = false;
|
||||
retrySurface.current = async () => {
|
||||
if (disposed || retryPending) return;
|
||||
retryPending = true; setRetrying(true);
|
||||
try {
|
||||
try { await cleanup; } catch { await trackCleanup(detach()); }
|
||||
if (!disposed) setRetry(attempt => attempt + 1);
|
||||
} catch (reason) { cleanupError(reason); }
|
||||
finally { retryPending = false; if (!disposed) setRetrying(false); }
|
||||
};
|
||||
};
|
||||
const push = (event: WebEngineGPUInput) => {
|
||||
if (disposed || stopped || !attached || contextLost) return;
|
||||
if (event.type !== 7 && event.type !== 8) setOperationNotice('');
|
||||
// WM retains intermediate motion as INBETWEEN_MOUSEMOVE. Native lasso
|
||||
// and stroke operators consume that path, including under pointer lock;
|
||||
// replacing positions or summing deltas here destroys its shape.
|
||||
// Drain in protocol-sized batches without discarding later releases.
|
||||
if (events.length < 4096) events.push(event);
|
||||
else fail(new Error("GPU input queue exceeded its limit"));
|
||||
};
|
||||
const modifiers = (event: MouseEvent | KeyboardEvent) =>
|
||||
Number(event.shiftKey) | (Number(event.ctrlKey) << 1) | (Number(event.altKey) << 2) | (Number(event.metaKey) << 3);
|
||||
const pointer = (event: PointerEvent, type: 1 | 2 | 3) => {
|
||||
// Chromium supplies MouseEvents during Pointer Lock. Consume them once
|
||||
// from the document listeners below, including button chords.
|
||||
if (document.pointerLockElement === canvas) return;
|
||||
if (!event.isPrimary || (pointerId !== null && pointerId !== event.pointerId)) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (dropPending || !attached || stopped || contextLost) return;
|
||||
if (event.pointerType === 'pen' && !tabletInputAvailable) {
|
||||
setOperationNotice('当前 WASM 尚未提供原生数位笔输入,请加载匹配的应用构件。');
|
||||
return;
|
||||
}
|
||||
pointerType = event.pointerType;
|
||||
if (event.pointerType === 'pen') {
|
||||
if (event.button === 5 || (event.buttons & 32)) penMode = 2;
|
||||
else if (type === 2) penMode = 1;
|
||||
}
|
||||
const tabletSample = (sample: PointerEvent): WebEngineGPUInput['tablet'] =>
|
||||
event.pointerType === 'pen' ? { mode: penMode, pressure: sample.pressure,
|
||||
tiltX: sample.tiltX / 90, tiltY: sample.tiltY / 90 } : undefined;
|
||||
// The menu consumes the whole click, including coalesced motion and
|
||||
// button chords. Never let its tail start a paint stroke or native pick.
|
||||
if (consumedPickPointer === event.pointerId) {
|
||||
if (event.buttons === 0 || type === 3) {
|
||||
consumedPickPointer = null;
|
||||
pointerId = null;
|
||||
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (type === 2) {
|
||||
// A click may activate another native text field or editor. Never send
|
||||
// an unfinished composition to the newly selected native context.
|
||||
abandonComposition();
|
||||
pointerId = event.pointerId;
|
||||
canvas.focus();
|
||||
canvas.setPointerCapture(event.pointerId);
|
||||
if (!menuGesture) requestPointerLock(true);
|
||||
}
|
||||
const rect = canvas.getBoundingClientRect(), dimensions = size();
|
||||
const position = { x: Math.max(-32768, Math.min(32768, (event.clientX - rect.left) * dimensions.width / Math.max(1, rect.width))),
|
||||
y: Math.max(-32768, Math.min(32768, (event.clientY - rect.top) * dimensions.height / Math.max(1, rect.height))),
|
||||
value: 0, modifiers: modifiers(event), tablet: tabletSample(event) };
|
||||
const pendingPick = menuGesture?.command.type === 'editEditorContext' &&
|
||||
menuGesture.command.edit.action === 'VIEW3D_SELECT' &&
|
||||
['SELECT_LINKED_PICK', 'GP_SELECT_PICK'].includes(menuGesture.command.edit.operation);
|
||||
if (type === 2 && event.button === 0 && pendingPick) {
|
||||
const pending = menuGesture!;
|
||||
if (pending.command.type === 'editEditorContext' && pending.command.edit.action === 'VIEW3D_SELECT' &&
|
||||
(pending.command.edit.operation === 'SELECT_LINKED_PICK' || pending.command.edit.operation === 'GP_SELECT_PICK') && !pending.pickSize) {
|
||||
pending.command = { ...pending.command, edit: { ...pending.command.edit,
|
||||
x: Math.floor(position.x), y: Math.floor(position.y), coordinateSpace: 'WINDOW' } };
|
||||
pending.pickSize = dimensions;
|
||||
setOperationNotice('正在使用主区域指针位置执行原生拾取…');
|
||||
}
|
||||
consumedPickPointer = event.pointerId;
|
||||
// draw() drains preceding focus/WM input and checks ownership before
|
||||
// submitting this command, just as it does for other menu operations.
|
||||
return;
|
||||
}
|
||||
// Pointer Events report chord changes as pointermove; pointerup occurs
|
||||
// only when the last button is released. WM needs every native button
|
||||
// transition to confirm MMB navigation even when LMB is still held.
|
||||
// The eraser end reports browser button 5 / bit 32. GHOST represents
|
||||
// it as a left contact with TabletModeEraser, not a sixth mouse button.
|
||||
const buttons = pointerId === null ? 0 :
|
||||
(event.buttons & 7) | (event.pointerType === 'pen' && (event.buttons & 32) ? 1 : 0);
|
||||
const buttonEvents: WebEngineGPUInput[] = [];
|
||||
for (const [bit, key] of [[1, 0], [4, 1], [2, 2]] as const) {
|
||||
if ((buttons & bit) !== (pressedButtons & bit)) {
|
||||
buttonEvents.push({ ...position, type: buttons & bit ? 2 : 3, key });
|
||||
}
|
||||
}
|
||||
pressedButtons = buttons;
|
||||
if (type === 1) {
|
||||
const samples = event.getCoalescedEvents?.() ?? [];
|
||||
for (const sample of samples.length ? samples : [event]) {
|
||||
push({ ...position, type: 1, key: 0, tablet: tabletSample(sample),
|
||||
x: Math.max(-32768, Math.min(32768, (sample.clientX - rect.left) * dimensions.width / Math.max(1, rect.width))),
|
||||
y: Math.max(-32768, Math.min(32768, (sample.clientY - rect.top) * dimensions.height / Math.max(1, rect.height))) });
|
||||
}
|
||||
}
|
||||
// Historical motion must reach WM before the current chord changes its modal state.
|
||||
for (const buttonEvent of buttonEvents) push(buttonEvent);
|
||||
if (type === 3) {
|
||||
pointerId = null;
|
||||
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
|
||||
}
|
||||
};
|
||||
const focus = (type: 7 | 8) => {
|
||||
if (type === 8) {
|
||||
abandonComposition();
|
||||
const captured = pointerId;
|
||||
pressedButtons = 0; pointerId = null; consumedPickPointer = null;
|
||||
if (captured !== null && canvas.hasPointerCapture(captured)) canvas.releasePointerCapture(captured);
|
||||
releasePointerLock();
|
||||
}
|
||||
push({ type, x: 0, y: 0, key: 0, value: 0, modifiers: 0 });
|
||||
};
|
||||
document.addEventListener('pointerlockchange', () => {
|
||||
const locked = document.pointerLockElement === canvas;
|
||||
const unexpectedlyLost = hadPointerLock && !locked && !releasingLock;
|
||||
hadPointerLock = locked;
|
||||
lockPending = false;
|
||||
releasingLock = false;
|
||||
if (locked) {
|
||||
if (disposed || stopped || contextLost || !wantsPointerLock()) { releasePointerLock(); return; }
|
||||
lockFailed = false;
|
||||
setGrabNotice('');
|
||||
const captured = pointerId;
|
||||
pointerId = null;
|
||||
if (captured !== null && canvas.hasPointerCapture(captured)) canvas.releasePointerCapture(captured);
|
||||
} else if (unexpectedlyLost) {
|
||||
client.cancelGPUOperation(session);
|
||||
// Browser Escape may never produce keydown on this canvas. Cancel in
|
||||
// the native Main transaction instead of leaving a live transform.
|
||||
lockFailed = true;
|
||||
push({ type: 11, x: 0, y: 0, key: 0, value: 0, modifiers: 0 });
|
||||
focus(8);
|
||||
if (document.activeElement === canvas) focus(7);
|
||||
}
|
||||
}, { signal: listeners.signal });
|
||||
document.addEventListener('pointerlockerror', lockError, { signal: listeners.signal });
|
||||
for (const name of ['mousemove', 'mousedown', 'mouseup'] as const) {
|
||||
document.addEventListener(name, event => {
|
||||
if (document.pointerLockElement !== canvas) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (dropPending || !attached || stopped || contextLost) return;
|
||||
const position = { x: 0, y: 0, value: 0, modifiers: modifiers(event), relative: true,
|
||||
deltaX: 0, deltaY: 0 };
|
||||
const buttons = event.buttons & 7;
|
||||
const buttonEvents: WebEngineGPUInput[] = [];
|
||||
for (const [bit, key] of [[1, 0], [4, 1], [2, 2]] as const) {
|
||||
if ((buttons & bit) !== (pressedButtons & bit)) {
|
||||
buttonEvents.push({ ...position, type: buttons & bit ? 2 : 3, key });
|
||||
}
|
||||
}
|
||||
pressedButtons = buttons;
|
||||
if (name === 'mousemove') {
|
||||
const rect = canvas.getBoundingClientRect(), dimensions = size();
|
||||
const dx = event.movementX * dimensions.width / Math.max(1, rect.width);
|
||||
const dy = event.movementY * dimensions.height / Math.max(1, rect.height);
|
||||
// Split only transport limits; no editor/navigation math lives here.
|
||||
const pieces = Math.max(1, Math.ceil(Math.max(Math.abs(dx), Math.abs(dy)) / 32768));
|
||||
if (!Number.isFinite(pieces) || pieces > 256) { fail(new Error('Mouse displacement exceeds input capacity')); return; }
|
||||
for (let i = 0; i < pieces; i++) push({ ...position, type: 1, key: 0, deltaX: dx / pieces, deltaY: dy / pieces });
|
||||
}
|
||||
for (const buttonEvent of buttonEvents) push(buttonEvent);
|
||||
}, { signal: listeners.signal });
|
||||
}
|
||||
canvas.addEventListener("pointermove", event => pointer(event, 1), { signal: listeners.signal });
|
||||
canvas.addEventListener("pointerdown", event => pointer(event, 2), { signal: listeners.signal });
|
||||
canvas.addEventListener("pointerup", event => pointer(event, 3), { signal: listeners.signal });
|
||||
canvas.addEventListener("pointercancel", event => { if (event.pointerId === pointerId) { focus(8); canvas.blur(); } }, { signal: listeners.signal });
|
||||
canvas.addEventListener("lostpointercapture", event => { if (event.pointerId !== pointerId) return;
|
||||
if (document.pointerLockElement === canvas || lockPending) return;
|
||||
if (pointerId !== null) { focus(8); canvas.blur(); }
|
||||
}, { signal: listeners.signal });
|
||||
canvas.addEventListener("focus", () => focus(7), { signal: listeners.signal });
|
||||
canvas.addEventListener("blur", () => focus(8), { signal: listeners.signal });
|
||||
window.addEventListener("blur", () => { focus(8); canvas.blur(); }, { signal: listeners.signal });
|
||||
canvas.addEventListener("contextmenu", event => event.preventDefault(), { signal: listeners.signal });
|
||||
canvas.addEventListener('dragover', event => {
|
||||
if (!event.dataTransfer?.types.includes('Files')) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
event.dataTransfer.dropEffect = attached && !stopped && !contextLost && !dropPending ? 'copy' : 'none';
|
||||
}, { signal: listeners.signal });
|
||||
canvas.addEventListener('drop', event => {
|
||||
if (!event.dataTransfer?.types.includes('Files')) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (disposed || stopped || !attached || contextLost || dropPending) return;
|
||||
if (canvas.dataset.nativeInputReady !== 'true' || events.length) { setDropError('原生桌面正在同步,请稍候后重新拖放'); return; }
|
||||
const files = Array.from(event.dataTransfer.files);
|
||||
if (!files.length) { setDropError('请拖入文件;文件夹请使用桌面文件传输上传。'); return; }
|
||||
const rect = canvas.getBoundingClientRect(), dimensions = size();
|
||||
const xRatio = (event.clientX - rect.left) / Math.max(1, rect.width), yRatio = (event.clientY - rect.top) / Math.max(1, rect.height);
|
||||
let x = xRatio * dimensions.width, y = yRatio * dimensions.height;
|
||||
const mask = modifiers(event);
|
||||
const dropOwner = ownerGeneration;
|
||||
const attempt = ++dropAttempt;
|
||||
const controller = new AbortController(), cancelTransfer = () => controller.abort();
|
||||
cancelDropTransfer.current = cancelTransfer; setDropTransferring(true);
|
||||
dropPending = true;
|
||||
setDropError('');
|
||||
setDropStatus(`正在传输 ${files.length} 个文件…`);
|
||||
// The files remain alive for native modal placement and later save/reopen.
|
||||
// Each batch gets its own directory while retaining relative companion paths.
|
||||
void stageDesktopFiles(client, session, files, `drop-${crypto.randomUUID()}/`,
|
||||
() => controller.signal.aborted || disposed || stopped || contextLost || dropOwner !== ownerGeneration || attempt !== dropAttempt,
|
||||
{ signal: controller.signal, progress: message => { if (!disposed && attempt === dropAttempt) setDropStatus(message); } }).then(paths => {
|
||||
controller.signal.throwIfAborted();
|
||||
if (disposed || stopped || !attached || contextLost) throw new Error('桌面已断开,未执行拖放');
|
||||
if (dropOwner !== ownerGeneration || attempt !== dropAttempt) throw new Error('传输期间工程或原生窗口已切换,请重新拖放');
|
||||
const current = size();
|
||||
if (current.width !== dimensions.width || current.height !== dimensions.height || current.pixelRatio !== dimensions.pixelRatio) {
|
||||
x = xRatio * current.width; y = yRatio * current.height;
|
||||
}
|
||||
cancelDropTransfer.current = null; setDropTransferring(false);
|
||||
canvas.focus();
|
||||
push({ type: 9, x, y, key: 0, value: 0, modifiers: mask, paths });
|
||||
setDropStatus('文件已传输,正在交给 Blender 处理…');
|
||||
}).catch(reason => {
|
||||
if (attempt !== dropAttempt) return;
|
||||
dropPending = false;
|
||||
if (disposed) return;
|
||||
if (controller.signal.aborted) { setDropStatus('文件传输已取消,未向 Blender 提交拖放。'); setDropError(''); return; }
|
||||
setDropStatus('');
|
||||
setDropError(reason instanceof Error ? reason.message :
|
||||
typeof reason === 'object' && reason && 'message' in reason ? String(reason.message) : String(reason));
|
||||
}).finally(() => { if (cancelDropTransfer.current === cancelTransfer) { cancelDropTransfer.current = null; if (!disposed) setDropTransferring(false); } });
|
||||
}, { signal: listeners.signal });
|
||||
canvas.addEventListener("wheel", event => {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (dropPending || !attached || stopped || contextLost) return;
|
||||
// Wheel/trackpad navigation belongs to this native window as well. Keep
|
||||
// subsequent shortcuts and Escape on its WM route after using HTML menus.
|
||||
// The following event supplies position and authoritative modifier state.
|
||||
canvas.focus({ preventScroll: true });
|
||||
const rect = canvas.getBoundingClientRect(), dimensions = size();
|
||||
const position = { x: (event.clientX - rect.left) * dimensions.width / Math.max(1, rect.width),
|
||||
y: (event.clientY - rect.top) * dimensions.height / Math.max(1, rect.height),
|
||||
value: 0, modifiers: modifiers(event) };
|
||||
if (scrollDevice.current === 'mouse') {
|
||||
// Preserve vertical zoom and expose the desktop horizontal-wheel pan.
|
||||
push({ ...position, type: 10, key: 0,
|
||||
deltaX: Math.sign(event.deltaX), deltaY: -Math.sign(event.deltaY) });
|
||||
} else {
|
||||
const unit = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? 16 :
|
||||
event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? rect.height : 1;
|
||||
const dx = event.deltaX * unit * dimensions.width / Math.max(1, rect.width);
|
||||
const dy = event.deltaY * unit * dimensions.height / Math.max(1, rect.height);
|
||||
const bounded = (delta: number) => Math.max(-32768, Math.min(32768, delta));
|
||||
// Chromium encodes trackpad pinch as Ctrl+wheel. GHOST magnify carries
|
||||
// its amount on X; do not leave the synthetic Ctrl in the native keymap.
|
||||
push({ ...position, type: 10, key: event.ctrlKey ? 2 : 1,
|
||||
modifiers: event.ctrlKey ? position.modifiers & ~2 : position.modifiers,
|
||||
deltaX: bounded(event.ctrlKey ? -dy : -dx), deltaY: event.ctrlKey ? 0 : bounded(-dy) });
|
||||
}
|
||||
}, { signal: listeners.signal, passive: false });
|
||||
canvas.addEventListener('compositionstart', () => {
|
||||
compositionOwner = !disposed && attached && !stopped && !contextLost && !dropPending
|
||||
? ownerGeneration : null;
|
||||
setCompositionText('');
|
||||
setCompositionError('');
|
||||
}, { signal: listeners.signal });
|
||||
canvas.addEventListener('compositionupdate', event => {
|
||||
if (compositionOwner !== null) setCompositionText(event.data);
|
||||
}, { signal: listeners.signal });
|
||||
canvas.addEventListener('compositionend', event => {
|
||||
const owner = compositionOwner;
|
||||
abandonComposition();
|
||||
if (owner === null || owner !== ownerGeneration || disposed || stopped ||
|
||||
!attached || contextLost || dropPending || document.activeElement !== canvas) return;
|
||||
// Submit committed Unicode through the existing native GHOST/WM key path.
|
||||
// Preedit and IME navigation keys never reach native shortcuts. Reserve
|
||||
// the whole commit before enqueueing so a queue limit cannot insert half.
|
||||
const points = Array.from(event.data, value => value.codePointAt(0)!);
|
||||
if (points.some(value => value < 32 || value === 127 || (value >= 0xd800 && value <= 0xdfff))) {
|
||||
setCompositionError('输入法提交包含不支持的控制字符,未提交;请重新输入');
|
||||
return;
|
||||
}
|
||||
if (events.length + points.length * 2 > 4096) {
|
||||
setCompositionError('输入法提交超过原生输入队列容量,未提交;请稍后分段输入');
|
||||
return;
|
||||
}
|
||||
for (const codepoint of points) {
|
||||
push({ type: 5, x: 0, y: 0, key: 0, value: 0, modifiers: 0, codepoint, location: 0 });
|
||||
push({ type: 6, x: 0, y: 0, key: 0, value: 0, modifiers: 0, codepoint: 0, location: 0 });
|
||||
}
|
||||
}, { signal: listeners.signal });
|
||||
canvas.addEventListener('beforeinput', event => {
|
||||
// Let the platform own its temporary preedit only. The committed result
|
||||
// is already queued above; ordinary keys use the established key handler.
|
||||
if (!event.isComposing) event.preventDefault();
|
||||
}, { signal: listeners.signal });
|
||||
canvas.addEventListener('input', () => {
|
||||
if (compositionOwner === null) canvas.textContent = '';
|
||||
}, { signal: listeners.signal });
|
||||
canvas.addEventListener('native-cancel', () => {
|
||||
if (cancelDropTransfer.current) { cancelDropTransfer.current(); return; }
|
||||
if (client.cancelGPUOperation(session)) return;
|
||||
push({ type: 5, x: 0, y: 0, key: 27, value: 0, modifiers: 0 });
|
||||
push({ type: 6, x: 0, y: 0, key: 27, value: 0, modifiers: 0 });
|
||||
}, { signal: listeners.signal });
|
||||
for (const name of ["keydown", "keyup"] as const) canvas.addEventListener(name, event => {
|
||||
event.stopPropagation();
|
||||
if (compositionOwner !== null || event.isComposing || event.keyCode === 229 ||
|
||||
event.key === "Dead" || event.key === "Process") return;
|
||||
event.preventDefault();
|
||||
if (event.key === 'Escape' && cancelDropTransfer.current) { if (name === 'keydown') cancelDropTransfer.current(); return; }
|
||||
if (name === 'keydown' && event.key === 'Escape' &&
|
||||
menuGesture?.command.type === 'editEditorContext' &&
|
||||
menuGesture.command.edit.action === 'VIEW3D_SELECT' &&
|
||||
['SELECT_LINKED_PICK', 'GP_SELECT_PICK'].includes(menuGesture.command.edit.operation)) {
|
||||
const pending = menuGesture;
|
||||
menuGesture = null;
|
||||
pending.resolve(false);
|
||||
setOperationNotice('原生拾取已取消');
|
||||
return;
|
||||
}
|
||||
if (name === 'keydown' && event.key === 'Escape' && client.cancelGPUOperation(session)) {
|
||||
setOperationNotice('已请求取消原生操作');
|
||||
return;
|
||||
}
|
||||
if (dropPending) return;
|
||||
if (name === 'keydown' && event.key !== 'Escape') requestPointerLock(true);
|
||||
const character = [...event.key];
|
||||
const allowsText = !event.metaKey && (!event.ctrlKey || event.getModifierState("AltGraph"));
|
||||
const codepoint = name === "keydown" && allowsText && character.length === 1
|
||||
? event.key.codePointAt(0) ?? 0 : 0;
|
||||
push({ type: name === "keydown" ? 5 : 6, x: 0, y: 0, key: event.keyCode,
|
||||
value: Number(name === "keydown" && event.repeat), modifiers: modifiers(event),
|
||||
codepoint, location: event.location });
|
||||
}, { signal: listeners.signal });
|
||||
const draw = async () => {
|
||||
if (disposed || stopped) return;
|
||||
if (!activeRef.current && !playingRef.current && !deactivateRef.current && !cancelPending && !pendingInvoke && events.length === 0) { window.setTimeout(() => void draw(), 100); return; }
|
||||
if (deactivateRef.current) { deactivateRef.current = false; cancelPending = true; focus(8); canvas.blur(); }
|
||||
const dimensions = size(), batch = events.splice(0, 256);
|
||||
if (batch.length) canvas.dataset.nativeInputReady = 'false';
|
||||
try {
|
||||
const result = await client.gpuUIFrame(session, dimensions.width, dimensions.height, dimensions.pixelRatio, batch, ownerGeneration);
|
||||
const { scene, error } = result;
|
||||
if (!disposed && !stopped && typeof result.modalActive === 'boolean') onModalActive?.(result.modalActive);
|
||||
canvas.dataset.nativeDisplay = result.displayAcknowledged ? 'acknowledged' : 'pending';
|
||||
canvas.dataset.nativeFrameSize = result.displayAcknowledged ? `${dimensions.width}x${dimensions.height}` : '';
|
||||
// A committed Main edit must still reach the app if the surface was closed meanwhile.
|
||||
if (scene) { applied.current(scene); if (activeRef.current) canvas.focus({ preventScroll: true }); }
|
||||
const deliverExport = exportCaller.current;
|
||||
if (result.exportPath && deliverExport) {
|
||||
void deliverExport(result.exportPath, result.exportSaveCopy, result.exportRevision, result.exportSaveAs).catch(reason => {
|
||||
if (!(reason && typeof reason === 'object' && 'fileDeliveryRetained' in reason)) setOperationNotice(`文件交付失败:${reason instanceof Error ? reason.message : String(reason)}`);
|
||||
});
|
||||
}
|
||||
const selectionCancelled = error?.message.startsWith('NATIVE_GPU_SELECTION_CANCELLED:');
|
||||
const depthCancelled = error?.message.startsWith('NATIVE_GPU_DEPTH_CANCELLED:');
|
||||
const selectionRecoveryPending = error?.message.includes('NATIVE_GPU_SELECTION_RECOVERY_PENDING');
|
||||
if (error?.code === 'COMMAND_FAILED' && error.message === 'GPU surface resize failed' && resizeRetry < 2) {
|
||||
resizeRetry += 1; events = [...batch, ...events];
|
||||
setOperationNotice(`画布尺寸更新失败,正在重试(${resizeRetry}/2)…`);
|
||||
frame = requestAnimationFrame(() => void draw()); return;
|
||||
}
|
||||
if (resizeRetry && !error && !result.contextLost && !result.inputDiscarded) setOperationNotice(notice => notice.startsWith('画布尺寸更新失败,正在重试(') ? '' : notice);
|
||||
resizeRetry = 0;
|
||||
if (error && !selectionCancelled && !depthCancelled && !result.inputDiscarded) {
|
||||
/* Quota exhaustion keeps the native files in memory and only asks the
|
||||
* operator to retry or download a backup, so the surface stays live. */
|
||||
if (error.message.startsWith('NATIVE_FILES_PERSISTENCE_PENDING')) setOperationNotice('原生文件未写入浏览器存储:请重试或先下载备份');
|
||||
else { fail(error); return; }
|
||||
}
|
||||
if (disposed || stopped) return;
|
||||
// Committed IME text uses the synthetic GHOST unknown-key route. Capture
|
||||
// its presence before native cancellation/ownership cleanup drops queues.
|
||||
const isCompositionInput = (input: WebEngineGPUInput) =>
|
||||
input.type === 5 && input.key === 0 && Boolean(input.codepoint);
|
||||
const hadCompositionInput = compositionOwner !== null ||
|
||||
batch.some(isCompositionInput) || events.some(isCompositionInput);
|
||||
if (selectionCancelled || depthCancelled) {
|
||||
// WM already unwound the interrupted native gesture. A queued mouse-up
|
||||
// belongs to that gesture, not to the next edit in the same region.
|
||||
abandonComposition();
|
||||
menuGesture?.resolve(false);
|
||||
menuGesture = null;
|
||||
events = [];
|
||||
const captured = pointerId;
|
||||
pressedButtons = 0; pointerId = null;
|
||||
if (captured !== null && canvas.hasPointerCapture(captured)) canvas.releasePointerCapture(captured);
|
||||
cursorGrab = 0;
|
||||
releasePointerLock();
|
||||
lockFailed = false;
|
||||
cancelDropTransfer.current?.();
|
||||
++dropAttempt;
|
||||
dropPending = false;
|
||||
setDropStatus('');
|
||||
// Reuse GHOST deactivation's native pressed-key/button reset. These
|
||||
// are fresh lifecycle events, after WM cancelled the old gesture.
|
||||
focus(8);
|
||||
if (document.activeElement === canvas) focus(7);
|
||||
setOperationNotice(depthCancelled ? '工具深度请求已中止,可以继续编辑' :
|
||||
'选择操作已中止,可以继续编辑');
|
||||
}
|
||||
const ownerChanged = result.ownerGeneration !== undefined && result.ownerGeneration !== ownerGeneration;
|
||||
if (ownerChanged) {
|
||||
abandonComposition();
|
||||
ownerGeneration = result.ownerGeneration!;
|
||||
readyOwnerGeneration = ownerGeneration;
|
||||
readyOwnerFrames = 0;
|
||||
readyPublished = false;
|
||||
onReady?.(false);
|
||||
cancelDropTransfer.current?.();
|
||||
++dropAttempt;
|
||||
if (dropPending) {
|
||||
dropPending = false;
|
||||
setDropStatus('');
|
||||
setDropError('工程、场景、视图层或原生窗口已切换,未执行旧拖放,请重新拖放');
|
||||
}
|
||||
// Pointer input queued while this frame waited belongs to the old native
|
||||
// window/scene/view layer, including a release confirming a different gizmo.
|
||||
// Keys typed after the reset are new intent: desktop WM delivers the Escape
|
||||
// that dismisses the popup a failed operator just raised.
|
||||
const keptKeys = events.filter(input => input.type === 5 || input.type === 6);
|
||||
events = keptKeys;
|
||||
const captured = pointerId;
|
||||
pressedButtons = 0; pointerId = null;
|
||||
if (captured !== null && canvas.hasPointerCapture(captured)) canvas.releasePointerCapture(captured);
|
||||
cursorGrab = 0;
|
||||
releasePointerLock();
|
||||
lockFailed = false;
|
||||
nativeCursor = undefined; cursorScale = 0; clearNativeCursor();
|
||||
setGrabNotice('');
|
||||
// Native ownership reset cleared GHOST's pressed state without
|
||||
// running old releases. Resume focus as fresh input for this owner.
|
||||
if (document.activeElement === canvas) focus(7);
|
||||
}
|
||||
// Accept new drops only after the current owner has acknowledged its display and input tail.
|
||||
if (readyOwnerGeneration !== ownerGeneration) { readyOwnerGeneration = ownerGeneration; readyOwnerFrames = 0; }
|
||||
const ownerReady = Boolean(result.displayAcknowledged && !ownerChanged && !result.inputDiscarded && !error && attached && !contextLost && !events.length);
|
||||
readyOwnerFrames = ownerReady ? readyOwnerFrames + 1 : 0;
|
||||
canvas.dataset.nativeInputReady = String(Boolean(!disposed && !stopped && ownerReady && readyOwnerFrames >= 2));
|
||||
if (!readyPublished && canvas.dataset.nativeInputReady === 'true') { readyPublished = true; setReady(true); onReady?.(true); }
|
||||
const redrawPending = error?.code === 'CAPABILITY_MISSING' && (error.message.includes('Browser region requires redraw') || error.message.includes('Browser region draw buffer is unavailable'));
|
||||
if (result.inputDiscarded && !ownerChanged) {
|
||||
events = [];
|
||||
const captured = pointerId; pressedButtons = 0; pointerId = null;
|
||||
if (captured !== null && canvas.hasPointerCapture(captured)) canvas.releasePointerCapture(captured);
|
||||
cursorGrab = 0; releasePointerLock(); lockFailed = false;
|
||||
const redrawExhausted = redrawPending && redrawRetry >= 2;
|
||||
setOperationNotice(selectionRecoveryPending ? '原生选择正在恢复,请稍候后重试' : redrawExhausted ? '画布重绘未恢复,请重新点击或按快捷键操作' : redrawPending ? '画布正在恢复,请稍候…' : error?.message || '原生输入已丢弃,请重新操作');
|
||||
if (document.activeElement === canvas) focus(7);
|
||||
}
|
||||
if (result.inputDiscarded && redrawPending && redrawRetry < 2) {
|
||||
redrawRetry += 1;
|
||||
frame = requestAnimationFrame(() => void draw());
|
||||
return;
|
||||
}
|
||||
if (result.inputDiscarded && selectionRecoveryPending && selectionRecoveryRetry < 2) {
|
||||
selectionRecoveryRetry += 1;
|
||||
frame = requestAnimationFrame(() => void draw());
|
||||
return;
|
||||
}
|
||||
if (!result.inputDiscarded) { if (redrawRetry && !error && !result.contextLost) setOperationNotice(notice => notice === '画布正在恢复,请稍候…' || notice === '画布重绘未恢复,请重新点击或按快捷键操作' ? '' : notice); redrawRetry = 0; }
|
||||
if (!result.inputDiscarded) selectionRecoveryRetry = 0;
|
||||
const wasLost = contextLost;
|
||||
contextLost = Boolean(result.contextLost);
|
||||
if (contextLost) cancelDropTransfer.current?.();
|
||||
if (contextLost) {
|
||||
if (!wasLost) setOperationNotice('原生 GPU 画布已中断,正在等待恢复并重绘');
|
||||
abandonComposition();
|
||||
nativeCursor = undefined; cursorScale = 0; clearNativeCursor();
|
||||
} else {
|
||||
updateCursor(result.cursor, dimensions.pixelRatio);
|
||||
if (wasLost) setOperationNotice('原生 GPU 画布已恢复,可以继续编辑');
|
||||
}
|
||||
const previousGrab = cursorGrab;
|
||||
cursorGrab = result.cursorGrab ?? 0;
|
||||
if (!wantsPointerLock() || contextLost) {
|
||||
releasePointerLock();
|
||||
lockFailed = false;
|
||||
setGrabNotice('');
|
||||
} else {
|
||||
if (previousGrab !== cursorGrab) lockFailed = false;
|
||||
requestPointerLock();
|
||||
}
|
||||
if (batch.some(event => event.type === 9)) {
|
||||
dropPending = false;
|
||||
setDropStatus('');
|
||||
if (contextLost || result.inputDiscarded) setDropError('原生窗口已更新,未执行旧拖放,请重新拖放');
|
||||
}
|
||||
setReady(!contextLost);
|
||||
onReady?.(!contextLost);
|
||||
if (contextLost) { events = []; pressedButtons = 0; pointerId = null; }
|
||||
else if ((wasLost || ownerChanged) && document.activeElement === canvas) focus(7);
|
||||
if (hadCompositionInput && (selectionCancelled || depthCancelled || ownerChanged ||
|
||||
contextLost || result.inputDiscarded)) {
|
||||
// A preceding batch may already have edited the field. Never replay
|
||||
// the whole commit into a new native owner or duplicate retained text.
|
||||
setCompositionError('原生输入已中断,请检查目标字段后重新输入未完成内容');
|
||||
}
|
||||
if (menuGesture && (contextLost || !attached || menuGesture.ownerGeneration !== ownerGeneration)) {
|
||||
menuGesture.reject(new Error('工程、场景或原生窗口已切换,请重新选择目标视图'));
|
||||
menuGesture = null;
|
||||
}
|
||||
// Read/save barriers use their caller's Main/project guards, not a target window.
|
||||
if (pendingInvoke && (contextLost || !attached)) {
|
||||
pendingInvoke.reject(new Error('原生画布已断开,请恢复后重新操作'));
|
||||
pendingInvoke = null;
|
||||
}
|
||||
// The worker advances ownerGeneration whenever native input ownership
|
||||
// changes, including a plain focus move. Re-stamp the queued invoke so
|
||||
// it runs against the current owner instead of being dropped.
|
||||
else if (pendingInvoke && !pendingInvoke.idleOnly) pendingInvoke.ownerGeneration = ownerGeneration;
|
||||
if (pendingInvoke && !events.length && !disposed && !stopped && (!pendingInvoke.idleOnly || result.modalActive !== true)) {
|
||||
const pending = pendingInvoke;
|
||||
pendingInvoke = null;
|
||||
try {
|
||||
// Pause subsequent frames until bpy has installed the native modal
|
||||
// handler. Its next motion/Enter/Escape remains ordinary WM input.
|
||||
const invoked = await pending.run(session, ownerGeneration);
|
||||
if (invoked && !disposed && !stopped) canvas.focus({ preventScroll: true });
|
||||
pending.resolve();
|
||||
} catch (reason) { pending.reject(reason); }
|
||||
if (!disposed && !stopped && invokeQueue.length) pendingInvoke = invokeQueue.shift()!;
|
||||
}
|
||||
const waitingForPick = !menuGesture?.pickSize && menuGesture?.command.type === 'editEditorContext' &&
|
||||
menuGesture.command.edit.action === 'VIEW3D_SELECT' &&
|
||||
['SELECT_LINKED_PICK', 'GP_SELECT_PICK'].includes(menuGesture.command.edit.operation);
|
||||
if (menuGesture && !waitingForPick && !events.length && !disposed && !stopped) {
|
||||
const pending = menuGesture;
|
||||
menuGesture = null;
|
||||
try {
|
||||
if (contextLost || !attached) throw new Error('原生画布已断开,请恢复后重新执行视图操作');
|
||||
if (pending.ownerGeneration !== ownerGeneration) {
|
||||
throw new Error('工程、场景或原生窗口已切换,请重新选择目标视图');
|
||||
}
|
||||
const currentSize = size();
|
||||
if (pending.pickSize && (pending.pickSize.width !== currentSize.width ||
|
||||
pending.pickSize.height !== currentSize.height || pending.pickSize.pixelRatio !== currentSize.pixelRatio ||
|
||||
pending.pickSize.width !== dimensions.width || pending.pickSize.height !== dimensions.height ||
|
||||
pending.pickSize.pixelRatio !== dimensions.pixelRatio)) {
|
||||
throw new Error('拾取期间画布尺寸发生变化,请重新点击目标区域');
|
||||
}
|
||||
// Earlier input may have edited Main while this menu waited. Use
|
||||
// the now-current revision, then keep the pump paused until the
|
||||
// native operation returns (instant selection does not invoke a
|
||||
// gesture). Pointer input collected meanwhile belongs to next frame.
|
||||
const command = { ...pending.command, baseRevision: scene?.snapshot.revision ?? currentRevision.current };
|
||||
const changed = await commandCaller.current(command);
|
||||
if (changed && !disposed && !stopped) {
|
||||
canvas.focus({ preventScroll: true });
|
||||
const edit = pending.command.type === 'editEditorContext' ? pending.command.edit : null;
|
||||
setOperationNotice(edit?.action === 'VIEW3D_SELECT'
|
||||
? edit.operation === 'BOX'
|
||||
? '在目标视图左键拖框选择、中键拖框取消选择;Esc 或右键取消手势'
|
||||
: edit.operation === 'CIRCLE'
|
||||
? '左键涂选、中键取消选择、滚轮调整半径;Esc 或右键结束并保留选择'
|
||||
: edit.operation === 'LASSO'
|
||||
? '在目标视图左键按下后绘制套索,松开应用;Esc 取消'
|
||||
: edit.operation === 'TEXT_SELECT_POINTER'
|
||||
? '在目标视图点击定位文本光标,左键拖选、松开完成;等待点击时 Esc 取消,拖选中 Esc 或右键结束并保留选择'
|
||||
: edit.operation === 'GP_SELECT_MODE'
|
||||
? `Grease Pencil 已切换为${edit.mode === 'POINT' ? '点' : edit.mode === 'STROKE' ? '笔画' : '段'}选择模式`
|
||||
: edit.operation === 'GP_SELECT_LINKED'
|
||||
? (edit.deselect ? '已取消选择关联 Grease Pencil 元素' : '已选择关联 Grease Pencil 元素')
|
||||
: edit.operation === 'GP_SELECT_PICK' ? 'Grease Pencil 已完成点/曲线拾取' : ''
|
||||
: edit?.action === 'VIEW3D_NAVIGATE' && edit.operation === 'ZOOM_BORDER'
|
||||
? '在目标视图左键拖框放大、中键拖框缩小;Esc 或右键取消' : '');
|
||||
}
|
||||
pending.resolve(changed);
|
||||
} catch (reason) { pending.reject(reason); }
|
||||
}
|
||||
if (!activeRef.current && cancelPending) {
|
||||
if (!result.inputDiscarded && !result.contextLost && result.modalActive === false && !error) cancelPending = false;
|
||||
else if (result.inputDiscarded && result.modalActive) focus(8);
|
||||
}
|
||||
if (!disposed && !stopped) frame = requestAnimationFrame(() => void draw());
|
||||
} catch (reason) {
|
||||
/* A frame rejected only because the browser refused to persist /browser
|
||||
* keeps the native files in memory; surface it and keep the pump alive. */
|
||||
const quotaPending = reason && typeof reason === 'object' && 'message' in reason &&
|
||||
String((reason as { message?: unknown }).message).startsWith('NATIVE_FILES_PERSISTENCE_PENDING');
|
||||
if (quotaPending) { setOperationNotice('原生文件未写入浏览器存储:请重试或先下载备份'); if (!disposed && !stopped) frame = requestAnimationFrame(() => void draw()); return; }
|
||||
fail(reason);
|
||||
}
|
||||
};
|
||||
setError("");
|
||||
retrySurface.current = null; setRetrying(false);
|
||||
setOperationNotice('');
|
||||
setCompositionText('');
|
||||
setReady(false);
|
||||
onReady?.(false);
|
||||
const startup = (async () => {
|
||||
const capabilities = await client.gpuUICapabilities();
|
||||
if (disposed) return;
|
||||
if (!capabilities.surfaceAvailable) throw new Error("The loaded WASM has no GPU surface backend");
|
||||
cursorGrabAvailable = Boolean(capabilities.cursorGrabAvailable);
|
||||
normalGrabAvailable = Boolean(capabilities.normalGrabAvailable);
|
||||
tabletInputAvailable = Boolean(capabilities.tabletInputAvailable);
|
||||
if (!canvas.transferControlToOffscreen) throw new Error("OffscreenCanvas is unavailable");
|
||||
const dimensions = size();
|
||||
ownerGeneration = await client.attachGPUCanvas(session, canvas.transferControlToOffscreen(), dimensions.width, dimensions.height, dimensions.pixelRatio);
|
||||
if (disposed) { await detach(); return; }
|
||||
attached = true;
|
||||
setNativeAttached(true);
|
||||
if (document.activeElement === canvas) focus(7);
|
||||
else canvas.focus();
|
||||
frame = requestAnimationFrame(() => void draw());
|
||||
})(); void startup.catch(fail);
|
||||
// Keep worker notifications within this canvas effect's lifecycle.
|
||||
const onWorkerMessage = (event: MessageEvent) => {
|
||||
const type = event.data?.type;
|
||||
if (type === "gpu-frame" || type === "blender-gpu-frame" || type === "blender-local-invoke") window.dispatchEvent(new CustomEvent(type, { detail: event.data }));
|
||||
};
|
||||
window.addEventListener("message", onWorkerMessage);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("message", onWorkerMessage);
|
||||
cancelDropTransfer.current?.(); cancelDropTransfer.current = null;
|
||||
disposed = true;
|
||||
clearNativeCursor();
|
||||
retrySurface.current = null;
|
||||
onReady?.(false);
|
||||
if (menuCommandRef && menuCommandRef.current === menuCommand) menuCommandRef.current = null;
|
||||
startMenuGesture.current = null;
|
||||
unregisterInvoke();
|
||||
pendingInvoke?.reject(new Error('原生画布已关闭,未启动操作'));
|
||||
pendingInvoke = null;
|
||||
menuGesture?.reject(new Error('原生画布已关闭,未启动视图操作'));
|
||||
menuGesture = null;
|
||||
abandonComposition();
|
||||
releasePointerLock();
|
||||
listeners.abort();
|
||||
cancelAnimationFrame(frame);
|
||||
canvas.remove();
|
||||
const cleanup = attached ? detach() : pendingCleanup ?? startup;
|
||||
cleanupCaller.current?.(cleanup);
|
||||
void cleanup.catch(() => {});
|
||||
};
|
||||
}, [client, menuCommandRef, retry]);
|
||||
|
||||
return <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>
|
||||
{(ready || nativeAttached) && active && <button type="button" aria-expanded={filesOpen} aria-controls={`desktop-files-${fileSession}`} style={{ position:'absolute', top:36, right:8, zIndex:30 }} onClick={() => { if (document.pointerLockElement) document.exitPointerLock(); setFilesOpen(open => !open); if (filesOpen) host.current?.querySelector('canvas')?.focus({ preventScroll:true }); }}>{filesOpen ? '关闭文件传输' : '文件传输'}</button>}
|
||||
<div id={`desktop-files-${fileSession}`} role="region" aria-label="桌面文件传输面板" hidden={!filesOpen || !ready || !active} style={{ position:'absolute', top:72, right:8, zIndex:30, width:'min(560px, calc(100% - 16px))', maxHeight:'calc(100% - 88px)', overflowY:'auto', background:'#303030', color:'#eee', border:'1px solid #666' }}>
|
||||
<DesktopFileTransfer key={fileSession} client={client} session={fileSession} attached={nativeAttached && active && !error} initiallyOpen />
|
||||
</div>
|
||||
<div style={!ready && !error ? { position: 'absolute', top: 0, left: 0, right: 0, zIndex: 1 } : { display: 'contents' }}>
|
||||
{!ready && <label>滚动设备 <select aria-label="桌面滚动设备" defaultValue="mouse" onChange={event => {
|
||||
scrollDevice.current = event.target.value === 'trackpad' ? 'trackpad' : 'mouse';
|
||||
host.current?.querySelector('canvas')?.focus({ preventScroll: true });
|
||||
}}><option value="mouse">鼠标滚轮</option><option value="trackpad">触控板(双指旋转,Shift 平移,捏合缩放)</option></select></label>}
|
||||
<div style={{ position: 'absolute', top: 48, left: 8, right: 8, zIndex: 31, pointerEvents: 'none' }}>
|
||||
{dropStatus && <output role="status">{dropStatus}</output>}
|
||||
{dropTransferring && <button type="button" style={{ pointerEvents: 'auto' }} onClick={() => cancelDropTransfer.current?.()}>取消文件传输</button>}
|
||||
{dropError && <output role="alert">{dropError}</output>}
|
||||
</div>
|
||||
{grabNotice && <output role="status">{grabNotice}</output>}
|
||||
{operationNotice && <output role="status">{operationNotice}</output>}
|
||||
{compositionText && <output role="status" aria-label="输入法组合文字">{compositionText}</output>}
|
||||
{compositionError && <div role="alert" aria-label="输入法提交失败">{compositionError}
|
||||
<button type="button" disabled={!ready || Boolean(error)}
|
||||
title="返回原生桌面检查目标字段,再重新输入未完成内容" onClick={() => {
|
||||
setCompositionError('');
|
||||
host.current?.querySelector('canvas')?.focus({ preventScroll: true });
|
||||
}}>返回桌面重新输入</button>
|
||||
</div>}
|
||||
{retry > 0 && !ready && !error && <output role="status">正在重新连接原生桌面…</output>}
|
||||
{!ready && <WasmDesktopLayout workflow={workflow} revision={revision} attached={ready} onCommand={async command => {
|
||||
if (command.type === 'editEditorContext' && (command.edit.action === 'VIEW3D_SELECT' ||
|
||||
command.edit.action === 'TIMELINE_EDIT' ||
|
||||
(command.edit.action === 'VIEW3D_NAVIGATE' && command.edit.operation === 'ZOOM_BORDER'))) {
|
||||
if (!startMenuGesture.current) throw new Error('原生画布尚未就绪');
|
||||
return startMenuGesture.current(command);
|
||||
}
|
||||
const changed = await onCommand(command);
|
||||
// The operation selected a real native region. Return keyboard ownership
|
||||
// to its canvas without injecting a pointer move into a different region.
|
||||
if (changed) host.current?.querySelector('canvas')?.focus({ preventScroll: true });
|
||||
return changed;
|
||||
}}/>}
|
||||
</div>
|
||||
<div style={{ position: 'relative', flex: 1, minHeight: 0 }}>
|
||||
<div ref={host} style={{ position: "absolute", inset: 0 }} />
|
||||
{error ? <div role="alert" aria-busy={retrying} style={{ position: "absolute", inset: 0, padding: 16, background: "#202020", color: "#ffffff", overflow: "auto" }}>{error}
|
||||
<button type="button" disabled={retrying} title="等待原生清理完成后重新连接当前工程" onClick={() => void retrySurface.current?.()}>
|
||||
{retrying ? '正在恢复原生桌面…' : '重试原生桌面'}
|
||||
</button></div> : null}
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
195
web/app/src/app/WasmImageView.tsx
Normal file
@@ -0,0 +1,195 @@
|
||||
import {useEffect,useRef,useState,type PointerEvent} from 'react';
|
||||
import type {SceneSnapshotIR} from '../../../protocol/scene-ir';
|
||||
import type {GPUTextureAsset} from '../../../protocol/render-assets';
|
||||
import type {NativeImageView,NativeImageViewEdit} from '../../../protocol/editor-workflow';
|
||||
|
||||
export function WasmImageView({snapshot,assets,selectedImageId,onSelectImage,imageView,onNativeView}:{
|
||||
snapshot:SceneSnapshotIR|null;assets:GPUTextureAsset[];selectedImageId?:string|null;
|
||||
onSelectImage?:(id:string|null)=>Promise<boolean>;imageView?:NativeImageView;
|
||||
onNativeView?:(edit:NativeImageViewEdit)=>Promise<boolean>;
|
||||
}){
|
||||
const [selected,setSelected]=useState(''),[url,setUrl]=useState('');
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const [dragging,setDragging]=useState(false);
|
||||
const [dragMode,setDragMode]=useState<'PAN'|'BOX_IN'|'BOX_OUT'>('PAN');
|
||||
const [box,setBox]=useState<[number,number,number,number]|null>(null);
|
||||
const viewport=useRef<HTMLDivElement>(null),pending=useRef(false);
|
||||
const drag=useRef<{pointerId:number;x:number;y:number;dataId:string;view:NativeImageView;
|
||||
mode:'PAN'|'BOX_IN'|'BOX_OUT';width:number;height:number;left:number;top:number;start:[number,number]}|null>(null);
|
||||
const image=selectedImageId!==undefined?snapshot?.images.find(item=>item.id===selectedImageId):snapshot?.images.find(item=>item.id===selected)??snapshot?.images[0],asset=assets.find(item=>item.imageId===image?.id&&['image/png','image/jpeg','image/webp'].includes(item.mimeType));
|
||||
useEffect(()=>{if(!asset){setUrl('');return;}const value=URL.createObjectURL(new Blob([asset.data],{type:asset.mimeType}));setUrl(value);return()=>URL.revokeObjectURL(value);},[asset]);
|
||||
const submit=async(action:()=>Promise<boolean>)=>{
|
||||
if(pending.current)return;
|
||||
pending.current=true;setBusy(true);setError('');
|
||||
try{if(!await action())setError('Image operation was not applied');}
|
||||
catch(reason){setError(String(reason));}
|
||||
finally{pending.current=false;setBusy(false);}
|
||||
};
|
||||
const view=(operation:'FRAME_ALL'|'FIT'|'ZOOM_RATIO',ratio=1)=>{
|
||||
const element=viewport.current;
|
||||
if(!element||!image||!imageView||!onNativeView)return;
|
||||
const size={width:element.clientWidth,height:element.clientHeight};
|
||||
if(size.width<2||size.height<2||size.width>16384||size.height>16384)return;
|
||||
const edit:NativeImageViewEdit=operation==='ZOOM_RATIO'
|
||||
?{operation,ratio,dataId:image.id,viewport:size}:{operation,dataId:image.id,viewport:size};
|
||||
void submit(()=>onNativeView(edit));
|
||||
};
|
||||
const cancelPan=()=>{
|
||||
const pointerId=drag.current?.pointerId;
|
||||
drag.current=null;setDragging(false);setBox(null);
|
||||
if(pointerId!==undefined&&viewport.current?.hasPointerCapture(pointerId))viewport.current.releasePointerCapture(pointerId);
|
||||
};
|
||||
useEffect(()=>{
|
||||
const element=viewport.current;
|
||||
return()=>{
|
||||
const pointerId=drag.current?.pointerId;
|
||||
drag.current=null;
|
||||
if(pointerId!==undefined&&element?.hasPointerCapture(pointerId))element.releasePointerCapture(pointerId);
|
||||
};
|
||||
},[]);
|
||||
const pan=(pixelDelta:[number,number])=>{
|
||||
const element=viewport.current;
|
||||
if(!element||!image||!imageView||!onNativeView||pending.current)return;
|
||||
const size={width:element.clientWidth,height:element.clientHeight};
|
||||
if(size.width<2||size.height<2||size.width>16384||size.height>16384||
|
||||
!pixelDelta.every(value=>Number.isFinite(value)&&Math.abs(value)<=65536)){
|
||||
setError('Image pan is outside the supported bounds');return;
|
||||
}
|
||||
if(pixelDelta[0]===0&&pixelDelta[1]===0)return;
|
||||
void submit(()=>onNativeView({operation:'PAN',pixelDelta,dataId:image.id,viewport:size}));
|
||||
};
|
||||
const zoomStep=(operation:'ZOOM_IN'|'ZOOM_OUT',position?:[number,number])=>{
|
||||
const element=viewport.current;
|
||||
if(!element||!image||!imageView||!onNativeView||pending.current||drag.current)return;
|
||||
const size={width:element.clientWidth,height:element.clientHeight};
|
||||
if(size.width<2||size.height<2||size.width>16384||size.height>16384)return;
|
||||
const pixelPosition:[number,number]=position??[Math.floor(size.width/2),Math.floor(size.height/2)];
|
||||
if(!pixelPosition.every((value,axis)=>Number.isSafeInteger(value)&&value>=0&&value<(axis===0?size.width:size.height)))return;
|
||||
void submit(()=>onNativeView({operation,pixelPosition,dataId:image.id,viewport:size}));
|
||||
};
|
||||
const beginPan=(event:PointerEvent<HTMLDivElement>)=>{
|
||||
if(!enabled||pending.current||drag.current||!image||!imageView||!event.isPrimary||
|
||||
!(event.button===1||(event.button===0&&(dragMode!=='PAN'||event.pointerType==='touch'||event.altKey))))return;
|
||||
const element=event.currentTarget,rect=element.getBoundingClientRect();
|
||||
const width=element.clientWidth,height=element.clientHeight;
|
||||
if(width<2||height<2||width>16384||height>16384)return;
|
||||
const left=rect.left+element.clientLeft,top=rect.top+element.clientTop;
|
||||
const start:[number,number]=[Math.floor(event.clientX-left),Math.floor(event.clientY-top)];
|
||||
if(start[0]<0||start[0]>=width||start[1]<0||start[1]>=height)return;
|
||||
event.preventDefault();event.stopPropagation();
|
||||
event.currentTarget.focus({preventScroll:true});
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
const mode=event.button===1?'PAN':dragMode;
|
||||
drag.current={pointerId:event.pointerId,x:event.clientX,y:event.clientY,dataId:image.id,view:{...imageView},
|
||||
mode,width,height,left,top,start};
|
||||
if(mode!=='PAN')setBox([start[0],start[1],start[0],start[1]]);
|
||||
setDragging(true);setError('');
|
||||
};
|
||||
const borderAt=(start:NonNullable<typeof drag.current>,x:number,y:number):[number,number,number,number]=>{
|
||||
const endX=Math.max(0,Math.min(start.width-1,Math.floor(x-start.left)));
|
||||
const endY=Math.max(0,Math.min(start.height-1,Math.floor(y-start.top)));
|
||||
return [Math.min(start.start[0],endX),Math.min(start.start[1],endY),
|
||||
Math.max(start.start[0],endX),Math.max(start.start[1],endY)];
|
||||
};
|
||||
const movePan=(event:PointerEvent<HTMLDivElement>)=>{
|
||||
const start=drag.current;
|
||||
if(!start||start.pointerId!==event.pointerId||start.mode==='PAN')return;
|
||||
event.preventDefault();event.stopPropagation();
|
||||
setBox(borderAt(start,event.clientX,event.clientY));
|
||||
};
|
||||
const endPan=(event:PointerEvent<HTMLDivElement>)=>{
|
||||
const start=drag.current;
|
||||
if(!start||start.pointerId!==event.pointerId)return;
|
||||
event.preventDefault();event.stopPropagation();cancelPan();
|
||||
const element=event.currentTarget,rect=element.getBoundingClientRect();
|
||||
if(start.dataId!==image?.id||!imageView||!onNativeView||start.view.zoom!==imageView.zoom||
|
||||
start.view.offsetX!==imageView.offsetX||start.view.offsetY!==imageView.offsetY||
|
||||
start.view.width!==imageView.width||start.view.height!==imageView.height||
|
||||
start.view.aspectX!==imageView.aspectX||start.view.aspectY!==imageView.aspectY||
|
||||
start.width!==element.clientWidth||start.height!==element.clientHeight||
|
||||
start.left!==rect.left+element.clientLeft||start.top!==rect.top+element.clientTop){
|
||||
setError('Image view changed during the gesture');return;
|
||||
}
|
||||
// Only native results move the image. One gesture creates one Main history entry.
|
||||
if(start.mode==='PAN')pan([event.clientX-start.x,event.clientY-start.y]);
|
||||
else {
|
||||
const pixelBounds=borderAt(start,event.clientX,event.clientY);
|
||||
if(pixelBounds[2]-pixelBounds[0]<2||pixelBounds[3]-pixelBounds[1]<2)return;
|
||||
void submit(()=>onNativeView({operation:'ZOOM_BORDER',pixelBounds,zoomOut:start.mode==='BOX_OUT',
|
||||
dataId:start.dataId,viewport:{width:start.width,height:start.height}}));
|
||||
}
|
||||
};
|
||||
const ratios=[0.125,0.25,0.5,1,2,4,8,16];
|
||||
const enabled=Boolean(onNativeView&&imageView&&asset)&&!busy&&!dragging;
|
||||
useEffect(()=>{
|
||||
const element=viewport.current;
|
||||
if(!element||!onNativeView||!imageView||!asset)return;
|
||||
const wheel=(event:WheelEvent)=>{
|
||||
if(event.ctrlKey||event.metaKey||event.altKey||!Number.isFinite(event.deltaY)||event.deltaY===0)return;
|
||||
event.preventDefault();event.stopPropagation();
|
||||
if(!enabled||pending.current||drag.current)return;
|
||||
const rect=element.getBoundingClientRect();
|
||||
zoomStep(event.deltaY<0?'ZOOM_IN':'ZOOM_OUT',[
|
||||
Math.floor(event.clientX-rect.left-element.clientLeft),
|
||||
Math.floor(event.clientY-rect.top-element.clientTop),
|
||||
]);
|
||||
};
|
||||
element.addEventListener('wheel',wheel,{passive:false});
|
||||
return()=>element.removeEventListener('wheel',wheel);
|
||||
});
|
||||
return <section className="wasm-image-editor" aria-busy={busy}>
|
||||
<header>
|
||||
<select aria-label="图像" value={image?.id??''} disabled={busy||dragging} onChange={event=>{
|
||||
const id=event.target.value;
|
||||
if(!onSelectImage){setSelected(id);return;}
|
||||
void submit(()=>onSelectImage(id||null));
|
||||
}}><option value="">无图像</option>{snapshot?.images.map(item=><option key={item.id} value={item.id}>{item.name}</option>)}</select>
|
||||
{onNativeView?<>
|
||||
<select aria-label="Image drag mode" disabled={!enabled} value={dragMode}
|
||||
onChange={event=>setDragMode(event.target.value as typeof dragMode)}>
|
||||
<option value="PAN">Pan</option><option value="BOX_IN">Zoom Border</option><option value="BOX_OUT">Zoom Out Border</option>
|
||||
</select>
|
||||
<button type="button" disabled={!enabled} onClick={()=>view('FRAME_ALL')}>Frame All</button>
|
||||
<button type="button" disabled={!enabled} onClick={()=>view('FIT')}>Fit View</button>
|
||||
<select className="image-zoom" aria-label="Image zoom ratio" disabled={!enabled} value={imageView?.zoom??''}
|
||||
onChange={event=>view('ZOOM_RATIO',Number(event.target.value))}>
|
||||
{!imageView?<option value="">Zoom</option>:!ratios.includes(imageView.zoom)?<option value={imageView.zoom}>{(imageView.zoom*100).toFixed(1)}%</option>:null}
|
||||
{ratios.map(ratio=><option key={ratio} value={ratio}>{ratio*100}%</option>)}
|
||||
</select>
|
||||
</>:null}
|
||||
</header>
|
||||
{error?<output role="alert">{error}</output>:null}
|
||||
<div ref={viewport} className={imageView?'native-image-view':''}
|
||||
tabIndex={onNativeView?0:undefined} aria-label="Image view" data-panning={dragging&&!box} data-box-zoom={dragMode!=='PAN'}
|
||||
onPointerDown={beginPan} onPointerMove={movePan} onPointerUp={endPan}
|
||||
onPointerCancel={event=>{if(drag.current?.pointerId===event.pointerId)cancelPan();}}
|
||||
onLostPointerCapture={event=>{if(drag.current?.pointerId===event.pointerId)cancelPan();}}
|
||||
onBlur={cancelPan}
|
||||
onAuxClick={event=>{if(onNativeView&&event.button===1)event.preventDefault();}}
|
||||
onKeyDown={event=>{
|
||||
if(event.key==='Escape'&&drag.current){event.preventDefault();event.stopPropagation();cancelPan();return;}
|
||||
if(!enabled||event.altKey||event.ctrlKey||event.metaKey)return;
|
||||
if(event.key.toLowerCase()==='b'){
|
||||
event.preventDefault();event.stopPropagation();setDragMode(event.shiftKey?'BOX_OUT':'BOX_IN');return;
|
||||
}
|
||||
if(event.key==='Escape'&&dragMode!=='PAN'){
|
||||
event.preventDefault();event.stopPropagation();setDragMode('PAN');return;
|
||||
}
|
||||
if(event.key==='+'||event.key==='='||event.key==='-'){
|
||||
event.preventDefault();event.stopPropagation();
|
||||
zoomStep(event.key==='-'?'ZOOM_OUT':'ZOOM_IN');return;
|
||||
}
|
||||
const step=event.shiftKey?160:40;
|
||||
const deltas:Record<string,[number,number]>={ArrowLeft:[step,0],ArrowRight:[-step,0],ArrowUp:[0,step],ArrowDown:[0,-step]};
|
||||
const delta=deltas[event.key];
|
||||
if(delta){event.preventDefault();event.stopPropagation();pan(delta);}
|
||||
}}>
|
||||
{url?<img src={url} alt={image?.name??'Image'} width={asset?.width} height={asset?.height} draggable={false}
|
||||
style={imageView?{width:imageView.width*imageView.aspectX*imageView.zoom,height:imageView.height*imageView.aspectY*imageView.zoom,
|
||||
left:`calc(50% - ${imageView.offsetX*imageView.zoom}px)`,top:`calc(50% + ${imageView.offsetY*imageView.zoom}px)`}:undefined}/>
|
||||
:<output>{image?'图像数据尚未载入':'无图像'}</output>}
|
||||
{box?<div className="image-zoom-border" aria-hidden="true"
|
||||
style={{left:box[0],top:box[1],width:box[2]-box[0],height:box[3]-box[1]}}/>:null}
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
57
web/app/src/app/WasmPythonConsole.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import type { PythonSessionClient } from '../engine-client/PythonSessionClient';
|
||||
export type PythonConsoleDraft = { source: string; history: string[]; index: number; draft: string };
|
||||
|
||||
export function WasmPythonConsole({session,enabled,beforeExecute,preserved}:{session:PythonSessionClient;enabled:boolean;beforeExecute?:()=>Promise<boolean>;preserved?:PythonConsoleDraft}) {
|
||||
const state = useSyncExternalStore(session.subscribe, session.getSnapshot);
|
||||
const [source,setSource] = useState(preserved?.source ?? '');
|
||||
const [history,setHistory] = useState<string[]>(preserved?.history ?? []);
|
||||
const index = useRef(preserved?.index ?? 0);
|
||||
const draft = useRef(preserved?.draft ?? '');
|
||||
const currentDraft = useRef({ source, history }); currentDraft.current = { source, history };
|
||||
useEffect(() => { const save=()=>{if(preserved)Object.assign(preserved,currentDraft.current,{index:index.current,draft:draft.current});};save();return save; }, [preserved,source,history]);
|
||||
const output = useRef<HTMLPreElement>(null);
|
||||
const pendingRef=useRef(false),[pending,setPending]=useState(false);
|
||||
const [notice,setNotice]=useState('');
|
||||
const executionToken=useRef(0);
|
||||
useEffect(()=>()=>{executionToken.current++;},[]);
|
||||
const busy = pending || state.status === 'running' || state.status === 'stopping';
|
||||
useEffect(() => { if(output.current) output.current.scrollTop = output.current.scrollHeight; },[state.output]);
|
||||
const run = async () => {
|
||||
/* Every refusal must be visible: a silent return shows no echo, no error and
|
||||
* no request, which is indistinguishable from a hang in the console. */
|
||||
if(busy || pendingRef.current || !enabled){setNotice(`PYTHON_INPUT_BLOCKED: ${busy?'busy':pendingRef.current?'pending':'disabled'}`);return;}
|
||||
pendingRef.current=true;setPending(true);setNotice('');
|
||||
const token=++executionToken.current;
|
||||
try {
|
||||
/* A workspace that rejects the context switch must say so: a silent return
|
||||
* leaves the user (and any automated run) with no dispatch and no reason. */
|
||||
if(beforeExecute&&!await beforeExecute()){setNotice('PYTHON_CONTEXT_UNAVAILABLE: 当前编辑器区域未激活,未执行');return;}
|
||||
if(token!==executionToken.current)return;
|
||||
const next = [...history,source].slice(-100);
|
||||
setHistory(next); index.current = next.length; draft.current = ''; setSource('');
|
||||
await session.run(source);
|
||||
} finally {pendingRef.current=false;setPending(false);}
|
||||
};
|
||||
return <section className="wasm-python-console" aria-label="Python Console">
|
||||
<header><span title={state.version}>{state.version ? `Python ${state.version.split(' ')[0]}` : 'Python'}</span>
|
||||
<select aria-label="Python 运行时" value={state.backend} disabled={busy} onChange={event=>void session.setBackend(event.target.value as 'WEBENGINE'|'PYODIDE')}><option value="WEBENGINE">3.13 / WebEngine</option><option value="PYODIDE">3.14 / Pyodide</option></select>
|
||||
<span role="status">{state.status}</span>{notice?<span role="alert">{notice}</span>:null}<span className="header-spacer"/>
|
||||
<button title="执行" aria-label="执行 Python" disabled={busy||!enabled} onClick={run}>▶</button>
|
||||
<button title="停止并重置会话" aria-label="停止 Python" disabled={!busy||!session.canInterrupt()} onClick={()=>{executionToken.current++;void session.stop();}}>■</button>
|
||||
<button title="重置会话" aria-label="重置 Python 会话" disabled={busy} onClick={()=>{setSource('');void session.reset();}}>↻</button>
|
||||
<button title="清空控制台" aria-label="清空 Python 控制台" onClick={session.clearOutput}>⌫</button>
|
||||
<button title="下载控制台记录" aria-label="下载 Python 控制台记录" disabled={!state.output} onClick={()=>{
|
||||
const url=URL.createObjectURL(new Blob([state.output],{type:'text/plain;charset=utf-8'}));
|
||||
const link=document.createElement('a');link.href=url;link.download='python-console.txt';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
|
||||
}}>↓</button>
|
||||
</header>
|
||||
<pre ref={output} tabIndex={0}>{state.output}</pre>
|
||||
<div className="wasm-python-input"><span>{state.more?'...':'>>>'}</span><textarea aria-label="Python 输入" rows={3} spellCheck={false} value={source} disabled={busy||!enabled} onChange={event=>setSource(event.target.value)} onKeyDown={event=>{
|
||||
if(event.nativeEvent.isComposing)return;
|
||||
if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();run();}
|
||||
if(event.key==='ArrowUp'&&event.currentTarget.selectionStart===0&&index.current>0){event.preventDefault();if(index.current===history.length)draft.current=source;setSource(history[--index.current]);}
|
||||
if(event.key==='ArrowDown'&&event.currentTarget.selectionEnd===source.length&&index.current<history.length){event.preventDefault();index.current++;setSource(index.current===history.length?draft.current:history[index.current]);}
|
||||
}}/></div>
|
||||
</section>;
|
||||
}
|
||||
65
web/app/src/app/WasmShaderEditor.tsx
Normal file
@@ -0,0 +1,65 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import type {MaterialNodeIR,SceneSnapshotIR} from '../../../protocol/scene-ir';
|
||||
import type {ShaderNodeEdit} from '../../../protocol/shader-graph';
|
||||
import type {WebEngineEditCommand} from '../../../protocol/web-engine';
|
||||
import {shaderGraphCommands} from '../../../protocol/shader-graph-commands';
|
||||
import {DesktopMenu} from './DesktopMenus';
|
||||
|
||||
type Socket=NonNullable<MaterialNodeIR['sockets']>[number];
|
||||
const primary=new Set(['Base Color','Metallic','Roughness','Alpha','IOR','Surface','Color','Strength','Vector','Value','Value_001']);
|
||||
function ValueField({socket,disabled,onApply}:{socket:Socket;disabled:boolean;onApply:(value:number|boolean|number[])=>void}){
|
||||
const [value,setValue]=useState(socket.value);
|
||||
useEffect(()=>setValue(socket.value),[JSON.stringify(socket.value)]);
|
||||
const commit=()=>{const finite=typeof value==='number'?Number.isFinite(value):Array.isArray(value)?value.every(item=>Number.isFinite(item)):true;if(finite&&JSON.stringify(value)!==JSON.stringify(socket.value)&&value!==undefined)onApply(value);};
|
||||
if(typeof value==='boolean')return <input type="checkbox" aria-label={socket.name} disabled={disabled} checked={value} onChange={event=>{setValue(event.target.checked);onApply(event.target.checked);}}/>;
|
||||
if(Array.isArray(value))return <span className="shader-vector-input">{value.map((component,index)=><input key={index} aria-label={`${socket.name} ${index+1}`} type="number" step="any" disabled={disabled} value={component} onChange={event=>setValue(value.map((number,i)=>i===index?Number(event.target.value):number))} onBlur={commit}/>)}</span>;
|
||||
if(typeof value==='number')return <input aria-label={socket.name} type="number" step={socket.integer?1:'any'} disabled={disabled} value={value} onChange={event=>setValue(Number(event.target.value))} onBlur={commit} onKeyDown={event=>{if(event.key==='Enter')event.currentTarget.blur();}}/>;
|
||||
return null;
|
||||
}
|
||||
|
||||
export function WasmShaderEditor({snapshot,onCommand}:{snapshot:SceneSnapshotIR|null;onCommand:(command:WebEngineEditCommand)=>Promise<boolean>}){
|
||||
const [materialId,setMaterialId]=useState(''),[selected,setSelected]=useState(''),[busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const [view,setView]=useState({x:240,y:220,zoom:.8}),[positions,setPositions]=useState<Record<string,[number,number]>>({});
|
||||
const [from,setFrom]=useState(''),[to,setTo]=useState('');
|
||||
const drag=useRef<{id?:string;x:number;y:number;location:[number,number];latest:[number,number]}|null>(null),canvas=useRef<HTMLDivElement>(null);
|
||||
const material=snapshot?.materials.find(item=>item.id===materialId)??snapshot?.materials[0],nodes=material?.nodes??[],links=material?.links??[];
|
||||
const node=nodes.find(item=>item.id===selected),readonly=material?.sourceLibrary!=null;
|
||||
useEffect(()=>{setPositions({});if(!nodes.some(item=>item.id===selected))setSelected(nodes[0]?.id??'');},[material?.id,snapshot?.revision]);
|
||||
const location=(item:MaterialNodeIR)=>positions[item.id]??item.location??[0,0];
|
||||
const ports=(item:MaterialNodeIR)=>(item.sockets??[]).filter(socket=>socket.direction==='OUTPUT'||socket.linked||primary.has(socket.id)||links.some(link=>link.toNodeId===item.id&&link.toSocket===socket.id));
|
||||
const execute=async(edit:ShaderNodeEdit)=>{
|
||||
if(!snapshot||!material||busy||readonly)return;setBusy(true);setError('');
|
||||
try{if(!await onCommand({type:'editShaderNode',materialId:material.id,edit,baseRevision:snapshot.revision}))setError('节点修改未提交');}
|
||||
catch(reason){setError(String(reason));}finally{setBusy(false);setPositions({});}
|
||||
};
|
||||
const endpoint=(id:string,socketId:string,direction:'INPUT'|'OUTPUT')=>{const item=nodes.find(n=>n.id===id);if(!item)return [0,0];const p=location(item),index=ports(item).findIndex(s=>s.id===socketId&&s.direction===direction);return [p[0]+(direction==='OUTPUT'?224:0),-p[1]+48+Math.max(0,index)*24];};
|
||||
const option=(item:MaterialNodeIR,socket:Socket)=>({value:JSON.stringify({nodeId:item.id,socketId:socket.id}),label:`${item.name} · ${socket.name}`});
|
||||
return <section className="wasm-shader-editor" aria-label="着色器编辑器">
|
||||
<header><select aria-label="材质" value={material?.id??''} onChange={event=>{setMaterialId(event.target.value);setFrom('');setTo('');}}>{snapshot?.materials.map(item=><option key={item.id} value={item.id}>{item.name}</option>)}</select>
|
||||
<DesktopMenu label="添加" items={(['RGB','VALUE','MATH','MIX','MAPPING','TEX_COORD','IMAGE_TEXTURE','NORMAL_MAP','BUMP','PRINCIPLED','OUTPUT'] as const).map(type=>({label:type,disabled:busy||readonly,action:()=>void execute({action:'ADD',nodeType:type,location:[(160-view.x)/view.zoom,-(120-view.y)/view.zoom]})}))}/>
|
||||
<button title="框显节点" aria-label="框显节点" onClick={()=>{if(!nodes.length)return;const xs=nodes.map(n=>location(n)[0]),ys=nodes.map(n=>-location(n)[1]);const width=Math.max(...xs)-Math.min(...xs)+240,height=Math.max(...ys)-Math.min(...ys)+250;const zoom=Math.min(1,Math.max(.15,Math.min((canvas.current?.clientWidth??600)/width,(canvas.current?.clientHeight??350)/height)*.85));setView({x:30-Math.min(...xs)*zoom,y:30-Math.min(...ys)*zoom,zoom});}}>⌖</button>
|
||||
<button disabled={busy||readonly||!node} title="删除节点" aria-label="删除节点" onClick={()=>node&&void execute({action:'REMOVE',nodeId:node.id})}>×</button>
|
||||
{!nodes.length&&material?<button disabled={busy||readonly} onClick={()=>{if(readonly)return;setBusy(true);setError('');void onCommand({type:'setShaderGraph',materialId:material.id,graph:shaderGraphCommands.setPrincipledGraph(material.id,material.baseColor,material.roughness,material.metallic)}).then(ok=>{if(!ok)setError('节点图未创建');}).catch(reason=>setError(String(reason))).finally(()=>setBusy(false));}}>启用节点</button>:null}
|
||||
</header>
|
||||
<div className="wasm-shader-body"><div ref={canvas} className="wasm-node-canvas" onWheel={event=>{event.preventDefault();setView(current=>({...current,zoom:Math.max(.15,Math.min(2,current.zoom*Math.exp(-event.deltaY*.001)))}));}}
|
||||
onPointerDown={event=>{if(event.button!==1)return;event.preventDefault();event.currentTarget.setPointerCapture(event.pointerId);drag.current={x:event.clientX,y:event.clientY,location:[view.x,view.y],latest:[view.x,view.y]};}}
|
||||
onPointerMove={event=>{const item=drag.current;if(!item)return;if(item.id){item.latest=[item.location[0]+(event.clientX-item.x)/view.zoom,item.location[1]-(event.clientY-item.y)/view.zoom];setPositions(current=>({...current,[item.id!]:item.latest}));}else setView(current=>({...current,x:item.location[0]+event.clientX-item.x,y:item.location[1]+event.clientY-item.y}));}}
|
||||
onPointerUp={()=>{const item=drag.current;drag.current=null;if(item?.id&&JSON.stringify(item.latest)!==JSON.stringify(item.location))void execute({action:'MOVE',nodeId:item.id,location:item.latest});}}
|
||||
onPointerCancel={()=>{drag.current=null;setPositions({});}}>
|
||||
<div className="wasm-node-stage" style={{transform:`translate(${view.x}px,${view.y}px) scale(${view.zoom})`}}>
|
||||
<svg className="wasm-node-links" aria-label="节点连线">{links.map((link,index)=>{const a=endpoint(link.fromNodeId,link.fromSocket,'OUTPUT'),b=endpoint(link.toNodeId,link.toSocket,'INPUT');return <path key={index} d={`M${a[0]},${a[1]} C${a[0]+90},${a[1]} ${b[0]-90},${b[1]} ${b[0]},${b[1]}`}/>;})}</svg>
|
||||
{nodes.map(item=>{const p=location(item);return <article key={item.id} className={`wasm-shader-node ${item.id===selected?'selected':''}`} style={{left:p[0],top:-p[1]}} onClick={()=>setSelected(item.id)}>
|
||||
<header onPointerDown={event=>{if(event.button!==0||busy||readonly)return;event.stopPropagation();setSelected(item.id);canvas.current?.setPointerCapture(event.pointerId);drag.current={id:item.id,x:event.clientX,y:event.clientY,location:p,latest:p};}}>{item.name}</header>
|
||||
{ports(item).map(socket=><div key={socket.direction+socket.id} className={'shader-socket '+socket.direction.toLowerCase()}><i data-kind={socket.dataType}/><span>{socket.name}</span></div>)}
|
||||
</article>;})}
|
||||
</div>
|
||||
</div><aside className="wasm-node-properties">{node?<><input aria-label="节点名称" key={node.id} defaultValue={node.name} disabled={busy||readonly} maxLength={63} onBlur={event=>{if(event.target.value!==node.name)void execute({action:'RENAME',nodeId:node.id,name:event.target.value});}}/>
|
||||
{(node.sockets??[]).filter(socket=>socket.value!==undefined&&(socket.direction==='INPUT'||['RGB','VALUE'].includes(node.type))).map(socket=><label key={socket.direction+socket.id}><span>{socket.name}</span><ValueField socket={socket} disabled={busy||readonly||socket.linked} onApply={value=>void execute({action:'SET_SOCKET',nodeId:node.id,socketId:socket.id,direction:socket.direction,value})}/></label>)}</>:null}
|
||||
<label>输出<select aria-label="连线输出" value={from} onChange={event=>setFrom(event.target.value)}><option value="">选择输出</option>{nodes.flatMap(item=>(item.sockets??[]).filter(socket=>socket.direction==='OUTPUT').map(socket=>{const entry=option(item,socket);return <option key={entry.value} value={entry.value}>{entry.label}</option>;}))}</select></label>
|
||||
<label>输入<select aria-label="连线输入" value={to} onChange={event=>setTo(event.target.value)}><option value="">选择输入</option>{nodes.flatMap(item=>(item.sockets??[]).filter(socket=>socket.direction==='INPUT').map(socket=>{const entry=option(item,socket);return <option key={entry.value} value={entry.value}>{entry.label}</option>;}))}</select></label>
|
||||
<button disabled={!from||!to||busy||readonly} onClick={()=>{const output=JSON.parse(from),input=JSON.parse(to);void execute({action:'LINK',nodeId:input.nodeId,socketId:input.socketId,fromNodeId:output.nodeId,fromSocketId:output.socketId});}}>连接</button>
|
||||
{links.filter(link=>link.fromNodeId===selected||link.toNodeId===selected).map((link,index)=><button key={index} disabled={busy||readonly} onClick={()=>void execute({action:'UNLINK',nodeId:link.toNodeId,socketId:link.toSocket,fromNodeId:link.fromNodeId,fromSocketId:link.fromSocket})}>断开 {link.fromSocket} → {link.toSocket}</button>)}
|
||||
</aside></div>
|
||||
<footer>{readonly?<output>链接材质只读</output>:null}{error?<output role="alert">{error}</output>:null}<span>{nodes.length} 节点 · {links.length} 连线</span></footer>
|
||||
</section>;
|
||||
}
|
||||
266
web/app/src/app/WasmSpreadsheetFilters.tsx
Normal file
@@ -0,0 +1,266 @@
|
||||
import { useState } from 'react';
|
||||
import { SPREADSHEET_CONTEXT_PROPERTIES, validSpreadsheetRuleValue, type NativeSpreadsheetContext, type NativeSpreadsheetEdit,
|
||||
type NativeSpreadsheetColumn, type NativeSpreadsheetViewerNavigation, type SpreadsheetContextProperty, type SpreadsheetClosure,
|
||||
type NativeSpreadsheetRule, type SpreadsheetRuleEdit } from '../../../protocol/editor-workflow';
|
||||
|
||||
type RuleProperty = keyof NativeSpreadsheetRule;
|
||||
const valueFields: Array<[RuleProperty, string]> = [
|
||||
['value_float', 'Float'], ['value_int', 'Integer'], ['value_boolean', 'Boolean'],
|
||||
['value_string', 'Text / instance name'], ['value_float2', '2D vector'],
|
||||
['value_float3', '3D vector'], ['value_float4', '4D vector'], ['value_color', 'RGBA'],
|
||||
['value_int2', '2D integer vector'], ['value_int3', '3D integer vector'],
|
||||
];
|
||||
|
||||
function RuleValue({ property, value, label, disabled, onApply }: {
|
||||
property: RuleProperty; value: NativeSpreadsheetRule[RuleProperty]; label: string;
|
||||
disabled: boolean; onApply: (value: NativeSpreadsheetRule[RuleProperty]) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<string[]>(Array.isArray(value) ? value.map(String) : [String(value)]);
|
||||
const numeric = typeof value === 'number' || Array.isArray(value);
|
||||
const parsed = typeof value === 'boolean' ? draft[0] === 'true' : Array.isArray(value) ? draft.map(Number) : numeric ? Number(draft[0]) : draft[0];
|
||||
const valid = (!numeric || draft.every(item => item.trim() !== '')) && validSpreadsheetRuleValue(property, parsed);
|
||||
return <form className="wasm-spreadsheet-value" onSubmit={event => {
|
||||
event.preventDefault();
|
||||
if (valid && !disabled) onApply(parsed as NativeSpreadsheetRule[RuleProperty]);
|
||||
}}>
|
||||
<span>{label}</span>
|
||||
<div className="wasm-spreadsheet-inputs">
|
||||
{typeof value === 'boolean' ? <input type="checkbox" aria-label={label} checked={draft[0] === 'true'}
|
||||
disabled={disabled} onChange={event => setDraft([String(event.target.checked)])}/> :
|
||||
draft.map((item, index) => <input key={index} type={numeric ? 'number' : 'text'}
|
||||
aria-label={draft.length > 1 ? `${label} ${index + 1}` : label} value={item} disabled={disabled}
|
||||
step={property.startsWith('value_int') ? 1 : 'any'} min={property === 'threshold' ? 0 : undefined}
|
||||
aria-invalid={!valid} onChange={event => setDraft(previous => previous.map((part, axis) => axis === index ? event.target.value : part))}/>) }
|
||||
</div>
|
||||
<button type="submit" disabled={disabled || !valid || JSON.stringify(parsed) === JSON.stringify(value)}>Apply</button>
|
||||
</form>;
|
||||
}
|
||||
|
||||
function FilterRule({ rule, index, revision, disabled, columns, onEdit }: {
|
||||
rule: NativeSpreadsheetRule; index: number; revision: number; disabled: boolean;
|
||||
columns: NativeSpreadsheetColumn[];
|
||||
onEdit: (edit: NativeSpreadsheetEdit) => void;
|
||||
}) {
|
||||
const [valueProperty, setValueProperty] = useState<RuleProperty>('value_float');
|
||||
const column = columns.find(item => item.name === rule.column_name);
|
||||
const activeValueProperty = column ? column.valueProperty : valueProperty;
|
||||
const update = (property: RuleProperty, value: NativeSpreadsheetRule[RuleProperty]) => {
|
||||
if (validSpreadsheetRuleValue(property, value)) onEdit({operation:'UPDATE_RULE',index,property,value} as SpreadsheetRuleEdit);
|
||||
};
|
||||
const field = (property: RuleProperty, label: string) => <RuleValue
|
||||
key={`${property}:${revision}:${JSON.stringify(rule[property])}`} property={property} value={rule[property]}
|
||||
label={label} disabled={disabled} onApply={value => update(property, value)}/>;
|
||||
return <div className="wasm-spreadsheet-rule">
|
||||
<div className="wasm-spreadsheet-rule-heading">
|
||||
<label><input type="checkbox" checked={rule.enabled} disabled={disabled}
|
||||
onChange={event => update('enabled', event.target.checked)}/>Rule {index + 1}</label>
|
||||
{(!column || column.comparison) && <select aria-label={`Rule ${index + 1} comparison`} value={rule.operation} disabled={disabled}
|
||||
onChange={event => update('operation', event.target.value)}>
|
||||
<option value="EQUAL">Equal to</option><option value="GREATER">Greater than</option><option value="LESS">Less than</option>
|
||||
</select>}
|
||||
<label><input type="checkbox" checked={rule.show_expanded} disabled={disabled}
|
||||
onChange={event => update('show_expanded', event.target.checked)}/>Values</label>
|
||||
<button type="button" disabled={disabled} onClick={() => onEdit({operation:'REMOVE_RULE',index})}>Remove rule</button>
|
||||
</div>
|
||||
{columns.length > 0 && <label>Column <select aria-label={`Rule ${index + 1} column`}
|
||||
value={rule.column_name} disabled={disabled} onChange={event => update('column_name', event.target.value)}>
|
||||
{!column && <option value={rule.column_name}>{rule.column_name || 'Choose column'}</option>}
|
||||
{columns.map(item => <option key={item.name} value={item.name}
|
||||
disabled={item.valueProperty === null || !validSpreadsheetRuleValue('column_name', item.name)}>{item.name}</option>)}
|
||||
</select></label>}
|
||||
{!column && field('column_name', 'Column name')}
|
||||
{rule.show_expanded && <>
|
||||
{!column && <label>Value field <select value={valueProperty} disabled={disabled}
|
||||
onChange={event => setValueProperty(event.target.value as RuleProperty)}>
|
||||
{valueFields.map(([property, label]) => <option key={property} value={property}>{label}</option>)}
|
||||
</select></label>}
|
||||
{activeValueProperty && field(activeValueProperty, 'Value')}
|
||||
{(!column || column.threshold) && rule.operation === 'EQUAL' && field('threshold', 'Threshold')}
|
||||
</>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function ViewerOutputs({ viewer, disabled, onEdit }: {
|
||||
viewer: NativeSpreadsheetViewerNavigation; disabled: boolean;
|
||||
onEdit: (edit: NativeSpreadsheetEdit) => void;
|
||||
}) {
|
||||
if (!viewer.selection.active) return null;
|
||||
const selection = viewer.selection;
|
||||
const current = viewer.items.find(item => item.identifier === viewer.itemIdentifier);
|
||||
const select = (path: string[], closure: SpreadsheetClosure = 'NONE') => onEdit({
|
||||
operation:'SET_VIEWER_PATH',itemIdentifier:viewer.itemIdentifier,path,closure,
|
||||
});
|
||||
return <div className="wasm-spreadsheet-rule-heading">
|
||||
<label>Viewer output <select aria-label="Viewer output" value={current ? viewer.itemIdentifier : ''}
|
||||
disabled={disabled || !viewer.available || viewer.items.length === 0}
|
||||
onChange={event => onEdit({operation:'SET_VIEWER_PATH',itemIdentifier:Number(event.target.value),path:[],closure:'NONE'})}>
|
||||
{!current && <option value="" disabled>Unavailable</option>}
|
||||
{viewer.items.map(item => <option key={item.identifier} value={item.identifier}>
|
||||
{item.label || `Output ${item.identifier}`}
|
||||
</option>)}
|
||||
</select></label>
|
||||
{viewer.itemsPageCount > 1 && <span className="wasm-spreadsheet-page-controls">
|
||||
<button type="button" aria-label="Previous Viewer output page" disabled={disabled || viewer.itemsPage === 0}
|
||||
onClick={() => onEdit({operation:'SET_NAVIGATION_PAGE',target:'VIEWER_OUTPUTS',page:viewer.itemsPage - 1})}>Previous page</button>
|
||||
<span>{viewer.itemsPage + 1} / {viewer.itemsPageCount}</span>
|
||||
<button type="button" aria-label="Next Viewer output page" disabled={disabled || viewer.itemsPage + 1 >= viewer.itemsPageCount}
|
||||
onClick={() => onEdit({operation:'SET_NAVIGATION_PAGE',target:'VIEWER_OUTPUTS',page:viewer.itemsPage + 1})}>Next page</button>
|
||||
</span>}
|
||||
{selection.available && <>
|
||||
<label>Output path <select aria-label="Viewer output path" value={selection.path.length}
|
||||
disabled={disabled} onChange={event => select(selection.path.slice(0, Number(event.target.value)))}>
|
||||
<option value={0}>{current?.label || 'Output'}</option>
|
||||
{selection.path.map((key, index) => <option key={index} value={index + 1}>{key}</option>)}
|
||||
</select></label>
|
||||
{selection.children.length > 0 && <label>Output item <select aria-label="Enter Viewer output item"
|
||||
value="" disabled={disabled || !selection.pathValid || selection.path.length >= 64}
|
||||
onChange={event => select([...selection.path,event.target.value])}>
|
||||
<option value="" disabled>Choose item</option>
|
||||
{selection.children.map(key => <option key={key} value={key}>{key}</option>)}
|
||||
</select></label>}
|
||||
{selection.childrenPageCount > 1 && <span className="wasm-spreadsheet-page-controls">
|
||||
<button type="button" aria-label="Previous Viewer output item page" disabled={disabled || selection.childrenPage === 0}
|
||||
onClick={() => onEdit({operation:'SET_NAVIGATION_PAGE',target:'VIEWER_BUNDLE_CHILDREN',page:selection.childrenPage - 1})}>Previous page</button>
|
||||
<span>{selection.childrenPage + 1} / {selection.childrenPageCount}</span>
|
||||
<button type="button" aria-label="Next Viewer output item page" disabled={disabled || selection.childrenPage + 1 >= selection.childrenPageCount}
|
||||
onClick={() => onEdit({operation:'SET_NAVIGATION_PAGE',target:'VIEWER_BUNDLE_CHILDREN',page:selection.childrenPage + 1})}>Next page</button>
|
||||
</span>}
|
||||
{(selection.hasInputs || selection.hasOutputs) && <label>Output interface <select
|
||||
aria-label="Viewer output closure interface" value={selection.closure}
|
||||
disabled={disabled || !selection.pathValid}
|
||||
onChange={event => select(selection.path,event.target.value as SpreadsheetClosure)}>
|
||||
<option value="NONE">All</option>
|
||||
{selection.hasInputs && <option value="INPUT">Inputs</option>}
|
||||
{selection.hasOutputs && <option value="OUTPUT">Outputs</option>}
|
||||
</select></label>}
|
||||
{!selection.pathValid && <button type="button" disabled={disabled}
|
||||
onClick={() => select([])}>Reset output path</button>}
|
||||
</>}
|
||||
{!viewer.available && <span role="status">Viewer output unavailable</span>}
|
||||
{selection.available && !selection.pathValid && <span role="status">Output path unavailable</span>}
|
||||
{viewer.itemsTruncated && <span role="status">Viewer output list limited</span>}
|
||||
{selection.childrenTruncated && <span role="status">Output item list limited</span>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function WasmSpreadsheetFilters({ spreadsheet, revision, disabled, onEdit }: {
|
||||
spreadsheet: NativeSpreadsheetContext; revision: number; disabled: boolean;
|
||||
onEdit: (edit: NativeSpreadsheetEdit) => void;
|
||||
}) {
|
||||
const contextLabels: Record<SpreadsheetContextProperty, string> = {
|
||||
object_eval_state: 'Evaluation', geometry_component_type: 'Component', attribute_domain: 'Domain',
|
||||
};
|
||||
return <div className="wasm-spreadsheet-filters">
|
||||
{spreadsheet.viewer && <ViewerOutputs viewer={spreadsheet.viewer} disabled={disabled} onEdit={onEdit}/>}
|
||||
{spreadsheet.instances && <div className="wasm-spreadsheet-rule-heading">
|
||||
<label>Geometry path <select aria-label="Geometry path" value={spreadsheet.instances.path.length}
|
||||
disabled={disabled || (spreadsheet.instances.path.length === 0 && spreadsheet.instances.pathValid)}
|
||||
onChange={event => onEdit({operation:'SET_INSTANCE_PATH',
|
||||
path:spreadsheet.instances!.path.slice(0, Number(event.target.value))})}>
|
||||
{spreadsheet.instances.breadcrumbs.map((name, depth) =>
|
||||
<option key={depth} value={depth}>{depth === 0 ? name : `${depth}: ${name}`}</option>)}
|
||||
</select></label>
|
||||
{spreadsheet.instances.children.length > 0 && <label>Instance <select aria-label="Enter instance"
|
||||
value="" disabled={disabled || !spreadsheet.instances.pathValid || spreadsheet.instances.path.length >= 64}
|
||||
onChange={event => onEdit({operation:'SET_INSTANCE_PATH',
|
||||
path:[...spreadsheet.instances!.path, Number(event.target.value)]})}>
|
||||
<option value="" disabled>Choose instance</option>
|
||||
{spreadsheet.instances.children.map(child => <option key={child.referenceIndex} value={child.referenceIndex}>
|
||||
{child.referenceIndex}: {child.label} ({child.userCount})
|
||||
</option>)}
|
||||
</select></label>}
|
||||
{!spreadsheet.instances.pathValid && <button type="button" disabled={disabled}
|
||||
onClick={() => onEdit({operation:'SET_INSTANCE_PATH',path:[]})}>Reset geometry path</button>}
|
||||
{spreadsheet.instances.geometryAvailable && !spreadsheet.instances.pathValid && <span role="status">Instance path unavailable</span>}
|
||||
{spreadsheet.instances.childrenPageCount > 1 && <span className="wasm-spreadsheet-page-controls">
|
||||
<button type="button" aria-label="Previous instance reference page"
|
||||
disabled={disabled || spreadsheet.instances.childrenPage === 0}
|
||||
onClick={() => onEdit({operation:'SET_NAVIGATION_PAGE',target:'INSTANCE_REFERENCES',page:spreadsheet.instances!.childrenPage - 1})}>Previous page</button>
|
||||
<span>{spreadsheet.instances.childrenPage + 1} / {spreadsheet.instances.childrenPageCount}</span>
|
||||
<button type="button" aria-label="Next instance reference page"
|
||||
disabled={disabled || spreadsheet.instances.childrenPage + 1 >= spreadsheet.instances.childrenPageCount}
|
||||
onClick={() => onEdit({operation:'SET_NAVIGATION_PAGE',target:'INSTANCE_REFERENCES',page:spreadsheet.instances!.childrenPage + 1})}>Next page</button>
|
||||
</span>}
|
||||
{spreadsheet.instances.childrenTruncated && <span role="status">Instance reference list paginated</span>}
|
||||
</div>}
|
||||
{spreadsheet.bundle && <div className="wasm-spreadsheet-rule-heading">
|
||||
<button type="button" disabled={disabled || !spreadsheet.bundle.available}
|
||||
onClick={() => onEdit({operation:'SET_BUNDLE_PATH',path:[],closure:'NONE'})}>
|
||||
{spreadsheet.bundle.active ? 'Bundle root' : 'Open bundle'}
|
||||
</button>
|
||||
{spreadsheet.bundle.active && <>
|
||||
<label>Bundle path <select aria-label="Bundle path" value={spreadsheet.bundle.path.length}
|
||||
disabled={disabled || !spreadsheet.bundle.available}
|
||||
onChange={event => onEdit({operation:'SET_BUNDLE_PATH',
|
||||
path:spreadsheet.bundle!.path.slice(0, Number(event.target.value)),closure:'NONE'})}>
|
||||
<option value={0}>Bundle</option>
|
||||
{spreadsheet.bundle.path.map((key, index) => <option key={index} value={index + 1}>{key}</option>)}
|
||||
</select></label>
|
||||
{spreadsheet.bundle.children.length > 0 && <label>Bundle item <select aria-label="Enter bundle item"
|
||||
value="" disabled={disabled || !spreadsheet.bundle.pathValid || spreadsheet.bundle.path.length >= 64}
|
||||
onChange={event => onEdit({operation:'SET_BUNDLE_PATH',
|
||||
path:[...spreadsheet.bundle!.path,event.target.value],closure:'NONE'})}>
|
||||
<option value="" disabled>Choose item</option>
|
||||
{spreadsheet.bundle.children.map(key => <option key={key} value={key}>{key}</option>)}
|
||||
</select></label>}
|
||||
{spreadsheet.bundle.childrenPageCount > 1 && <span className="wasm-spreadsheet-page-controls">
|
||||
<button type="button" aria-label="Previous bundle item page" disabled={disabled || spreadsheet.bundle.childrenPage === 0}
|
||||
onClick={() => onEdit({operation:'SET_NAVIGATION_PAGE',target:'GEOMETRY_BUNDLE_CHILDREN',page:spreadsheet.bundle!.childrenPage - 1})}>Previous page</button>
|
||||
<span>{spreadsheet.bundle.childrenPage + 1} / {spreadsheet.bundle.childrenPageCount}</span>
|
||||
<button type="button" aria-label="Next bundle item page" disabled={disabled || spreadsheet.bundle.childrenPage + 1 >= spreadsheet.bundle.childrenPageCount}
|
||||
onClick={() => onEdit({operation:'SET_NAVIGATION_PAGE',target:'GEOMETRY_BUNDLE_CHILDREN',page:spreadsheet.bundle!.childrenPage + 1})}>Next page</button>
|
||||
</span>}
|
||||
{(spreadsheet.bundle.hasInputs || spreadsheet.bundle.hasOutputs) && <label>Closure interface <select
|
||||
aria-label="Closure interface" value={spreadsheet.bundle.closure}
|
||||
disabled={disabled || !spreadsheet.bundle.pathValid}
|
||||
onChange={event => onEdit({operation:'SET_BUNDLE_PATH',path:spreadsheet.bundle!.path,
|
||||
closure:event.target.value as SpreadsheetClosure})}>
|
||||
<option value="NONE">All</option>
|
||||
{spreadsheet.bundle.hasInputs && <option value="INPUT">Inputs</option>}
|
||||
{spreadsheet.bundle.hasOutputs && <option value="OUTPUT">Outputs</option>}
|
||||
</select></label>}
|
||||
<button type="button" disabled={disabled || !spreadsheet.context?.geometry_component_type.value}
|
||||
onClick={() => onEdit({operation:'SET_CONTEXT',property:'geometry_component_type',
|
||||
value:spreadsheet.context!.geometry_component_type.value!})}>Back to component data</button>
|
||||
{!spreadsheet.bundle.pathValid && <span role="status">Bundle path unavailable</span>}
|
||||
{spreadsheet.bundle.childrenTruncated && <span role="status">Bundle item list limited</span>}
|
||||
</>}
|
||||
</div>}
|
||||
{spreadsheet.viewState && <div className="wasm-spreadsheet-rule-heading">
|
||||
<label><input type="checkbox" checked={spreadsheet.viewState.pinned}
|
||||
disabled={disabled || (!spreadsheet.viewState.pinned && !spreadsheet.viewState.canPin)}
|
||||
onChange={event => onEdit({operation:'SET_PIN',pinned:event.target.checked})}/>Pin context</label>
|
||||
<label title={spreadsheet.viewState.selectionFilterAvailable ? undefined : 'Selection filtering unavailable for this data source'}>
|
||||
<input type="checkbox" checked={spreadsheet.viewState.showOnlySelected}
|
||||
disabled={disabled || (!spreadsheet.viewState.showOnlySelected && !spreadsheet.viewState.selectionFilterAvailable)}
|
||||
onChange={event => onEdit({operation:'SET_SELECTED_ONLY',enabled:event.target.checked})}/>Selected only
|
||||
</label>
|
||||
{!spreadsheet.viewState.dataSourceAvailable && <span role="status">No data source</span>}
|
||||
</div>}
|
||||
{spreadsheet.context && <div className="wasm-spreadsheet-rule-heading">
|
||||
{SPREADSHEET_CONTEXT_PROPERTIES.map(property => {
|
||||
const setting = spreadsheet.context![property];
|
||||
return <label key={property}>{contextLabels[property]} <select
|
||||
aria-label={contextLabels[property]} value={setting.value ?? ''}
|
||||
disabled={disabled || setting.choices.length === 0}
|
||||
onChange={event => onEdit({operation:'SET_CONTEXT',property,value:event.target.value})}>
|
||||
{setting.value === null && <option value="" disabled>Unavailable</option>}
|
||||
{setting.choices.map(choice => <option key={choice.id} value={choice.id}>{choice.label}</option>)}
|
||||
</select></label>;
|
||||
})}
|
||||
</div>}
|
||||
<details>
|
||||
<summary>Row filters ({spreadsheet.rules.length})</summary>
|
||||
<div className="wasm-spreadsheet-rule-heading">
|
||||
<label><input type="checkbox" checked={spreadsheet.useFilter} disabled={disabled}
|
||||
onChange={event => onEdit({operation:'SET_FILTER',enabled:event.target.checked})}/>Use filters</label>
|
||||
<button type="button" disabled={disabled || spreadsheet.rules.length >= 256}
|
||||
onClick={() => onEdit({operation:'ADD_RULE'})}>Add rule</button>
|
||||
</div>
|
||||
<div className="wasm-spreadsheet-rules">
|
||||
{spreadsheet.rules.map((rule, index) => <FilterRule key={index} rule={rule} index={index}
|
||||
revision={revision} disabled={disabled} columns={spreadsheet.columns ?? []} onEdit={onEdit}/>) }
|
||||
</div>
|
||||
</details>
|
||||
</div>;
|
||||
}
|
||||
105
web/app/src/app/WasmTextEditor.tsx
Normal file
@@ -0,0 +1,105 @@
|
||||
import {useEffect,useLayoutEffect,useRef,useState} from 'react';
|
||||
import type {SceneSnapshotIR} from '../../../protocol/scene-ir';
|
||||
import type {WebEngineEditCommand} from '../../../protocol/web-engine';
|
||||
import type {NativeTextEdit,TextCursorIR,TextSelectionIR} from '../../../protocol/editor-workflow';
|
||||
|
||||
function textCursor(source:string,offset:number):TextCursorIR {
|
||||
const preceding=source.slice(0,offset).split('\n');
|
||||
return {line:preceding.length-1,column:Array.from(preceding[preceding.length-1]).length};
|
||||
}
|
||||
|
||||
function textOffset(source:string,cursor:TextCursorIR):number {
|
||||
const lines=source.split('\n');
|
||||
const line=Math.min(cursor.line,lines.length-1);
|
||||
return lines.slice(0,line).reduce((offset,item)=>offset+item.length+1,0)+Array.from(lines[line]).slice(0,cursor.column).join('').length;
|
||||
}
|
||||
|
||||
export function WasmTextEditor({snapshot,onCommand,onNativeRun,onPythonRun,pythonBusy=false,projectBusy=false,canEditDraft,onDraftChanged,selectedTextId,onSelectText,onNativeEdit,textSelection}:{snapshot:SceneSnapshotIR|null;onCommand:(command:WebEngineEditCommand)=>Promise<boolean>;onNativeRun?:(name:string,source:string)=>void;onPythonRun?:(name:string,source:string)=>Promise<boolean>;pythonBusy?:boolean;projectBusy?:boolean;canEditDraft?:()=>boolean;onDraftChanged?:(dirty:boolean)=>void;selectedTextId?:string|null;onSelectText?:(id:string|null)=>Promise<boolean>;onNativeEdit?:(edit:NativeTextEdit)=>Promise<{source:string;selection:TextSelectionIR}|null>;textSelection?:TextSelectionIR}){
|
||||
const [id,setId]=useState(''),[source,setSource]=useState(''),[name,setName]=useState('Text.py'),[localBusy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const busy=localBusy||projectBusy;
|
||||
const texts=snapshot?.texts??[],text=selectedTextId!==undefined?texts.find(item=>item.id===selectedTextId):texts.find(item=>item.id===id)??texts[0];
|
||||
const creating=useRef<Set<string>|null>(null);
|
||||
const fileInput=useRef<HTMLInputElement>(null);
|
||||
const textarea=useRef<HTMLTextAreaElement>(null);
|
||||
const nativeEditing=useRef(false);
|
||||
const returnedSelection=useRef<{source:string;selection:TextSelectionIR}|null>(null);
|
||||
const selectText=async(value:string|null)=>{if(onSelectText){setBusy(true);setError('');try{if(!await onSelectText(value))setError('文本上下文未提交');}catch(reason){setError(String(reason));}finally{setBusy(false);}}else setId(value??'');};
|
||||
useEffect(()=>{if(!creating.current)return;const added=texts.find(item=>!creating.current!.has(item.id));if(added){creating.current=null;void selectText(added.id);}},[snapshot?.revision]);
|
||||
useEffect(()=>{setSource(text?.source??'');},[text?.id,text?.source]);
|
||||
useLayoutEffect(()=>{
|
||||
const field=textarea.current;
|
||||
const returned=returnedSelection.current;
|
||||
const selection=returned?.source===source?returned.selection:source===text?.source?textSelection:undefined;
|
||||
if(!field||!selection)return;
|
||||
const anchor=textOffset(source,selection.anchor),focus=textOffset(source,selection.focus);
|
||||
field.setSelectionRange(Math.min(anchor,focus),Math.max(anchor,focus),anchor>focus?'backward':'forward');
|
||||
if(returned&&returned.source===source&&!busy){returnedSelection.current=null;field.focus();}
|
||||
},[source,text?.id,text?.source,textSelection?.anchor.line,textSelection?.anchor.column,textSelection?.focus.line,textSelection?.focus.column,busy]);
|
||||
const changed=source!==(text?.source??'');
|
||||
useEffect(()=>{onDraftChanged?.(changed);const unload=(event:BeforeUnloadEvent)=>{if(changed){event.preventDefault();event.returnValue='';}};window.addEventListener('beforeunload',unload);return()=>{onDraftChanged?.(false);window.removeEventListener('beforeunload',unload);};},[changed]);
|
||||
const apply=async(command:WebEngineEditCommand)=>{setBusy(true);setError('');try{if(!await onCommand(command))setError('文本修改未提交');}catch(reason){setError(String(reason));}finally{setBusy(false);}};
|
||||
const editText=async(operation:NativeTextEdit['operation'])=>{
|
||||
const field=textarea.current;
|
||||
if(!onNativeEdit||!text||!field||busy||pythonBusy||nativeEditing.current)return; if(canEditDraft&&!canEditDraft()){setError('工程操作进行中,请稍后编辑文本。');return;}
|
||||
const start=textCursor(source,field.selectionStart),end=textCursor(source,field.selectionEnd);
|
||||
const selection=field.selectionDirection==='backward'?{anchor:end,focus:start}:{anchor:start,focus:end};
|
||||
nativeEditing.current=true;setBusy(true);setError('');
|
||||
try{
|
||||
const result=await onNativeEdit({operation,dataId:text.id,source,selection});
|
||||
if(!result){returnedSelection.current={source,selection};setError('文本操作未提交');return;}
|
||||
returnedSelection.current=result;setSource(result.source);
|
||||
}catch(reason){returnedSelection.current={source,selection};setError(String(reason));}
|
||||
finally{nativeEditing.current=false;setBusy(false);}
|
||||
};
|
||||
return <section className="wasm-text-editor" aria-label="文本编辑器">
|
||||
<header><select aria-label="文本数据块" value={text?.id??''} disabled={busy} onChange={event=>{if(changed&&!window.confirm('放弃未提交的文本修改?'))return;void selectText(event.target.value||null);}}><option value="">文本</option>{texts.map(item=><option key={item.id} value={item.id}>{item.name}</option>)}</select>
|
||||
<input aria-label="新文本名称" value={name} maxLength={63} onChange={event=>setName(event.target.value)}/>
|
||||
<button disabled={busy||!snapshot||!name.trim()} onClick={()=>{if(changed&&!window.confirm('放弃未提交的文本修改?'))return;creating.current=new Set(texts.map(item=>item.id));void apply({type:'createText',name:name.trim(),source:''});}}>新建</button>
|
||||
<button title="打开 Python 或文本文件" aria-label="打开文本文件" disabled={busy||!snapshot} onClick={()=>fileInput.current?.click()}>↑</button>
|
||||
<input ref={fileInput} type="file" accept=".py,.txt" hidden onChange={event=>{const file=event.target.files?.[0];event.target.value='';if(!file)return;if(changed&&!window.confirm('放弃未提交的文本修改?'))return;
|
||||
void(async()=>{setBusy(true);setError('');try{
|
||||
if(file.size>1048576)throw new Error('文本文件超过 1 MiB');
|
||||
const contents=new TextDecoder('utf-8',{fatal:true}).decode(await file.arrayBuffer());
|
||||
let filename=file.name;while(new TextEncoder().encode(filename).length>63)filename=Array.from(filename).slice(0,-1).join('');
|
||||
creating.current=new Set(texts.map(item=>item.id));
|
||||
if(!await onCommand({type:'createText',name:filename||'Text.py',source:contents})){creating.current=null;throw new Error('文本导入未提交');}
|
||||
}catch(reason){setError(String(reason));}finally{setBusy(false);}})();
|
||||
}}/>
|
||||
<button disabled={busy||!text||!changed||new TextEncoder().encode(source).length>1048576} onClick={()=>text&&void apply({type:'setTextSource',dataId:text.id,source})}>应用</button>
|
||||
{onNativeEdit?<>
|
||||
<button disabled={busy||pythonBusy||!text} onMouseDown={event=>event.preventDefault()} onClick={()=>void editText('INDENT')}>缩进</button>
|
||||
<button disabled={busy||pythonBusy||!text} onMouseDown={event=>event.preventDefault()} onClick={()=>void editText('UNINDENT')}>取消缩进</button>
|
||||
<button disabled={busy||pythonBusy||!text} onMouseDown={event=>event.preventDefault()} onClick={()=>void editText('DUPLICATE_LINE')}>复制行</button>
|
||||
{([['COMMENT_TOGGLE','切换注释'],['COMMENT','添加注释'],['UNCOMMENT','取消注释'],
|
||||
['LINE_BREAK','换行并保持缩进'],['WHITESPACE_SPACES','全文缩进转空格'],['WHITESPACE_TABS','全文缩进转制表符'],
|
||||
['DELETE_PREVIOUS_CHARACTER','删除前一字符'],['DELETE_NEXT_CHARACTER','删除后一字符'],
|
||||
['DELETE_PREVIOUS_WORD','删除前一单词'],['DELETE_NEXT_WORD','删除后一单词']] as const).map(([operation,label])=>
|
||||
<button key={operation} disabled={busy||pythonBusy||!text} onMouseDown={event=>event.preventDefault()}
|
||||
onClick={()=>void editText(operation)}>{label}</button>)}
|
||||
</>:null}
|
||||
<button disabled={!text} title="下载文本" aria-label="下载文本" onClick={()=>{const url=URL.createObjectURL(new Blob([source],{type:'text/plain;charset=utf-8'}));const link=document.createElement('a');link.href=url;link.download=text?.name??'Text.py';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}}>↓</button>
|
||||
{onNativeRun?<button disabled={busy||!text} onClick={()=>onNativeRun(text!.name,source)}>原生运行</button>:null}
|
||||
{onPythonRun?<button title="运行脚本" aria-label="运行 Python 脚本" disabled={busy||pythonBusy||!text} onClick={()=>{void(async()=>{
|
||||
setBusy(true);setError('');try{
|
||||
if(changed&&!await onCommand({type:'setTextSource',dataId:text!.id,source})){setError('文本修改未提交');return;}
|
||||
if(!await onPythonRun(text!.name,source))setError('脚本未完成,请查看控制台');
|
||||
}catch(reason){setError(String(reason));}finally{setBusy(false);}
|
||||
})();}}>▶</button>:null}
|
||||
</header>
|
||||
<div className="wasm-text-body"><pre aria-hidden="true">{Array.from({length:source.split('\n').length},(_,i)=>i+1).join('\n')}</pre><textarea ref={textarea} aria-label="文本内容" disabled={busy||!text} value={source} maxLength={1048576} spellCheck={false} onScroll={event=>{const gutter=event.currentTarget.previousElementSibling;if(gutter)gutter.scrollTop=event.currentTarget.scrollTop;}} onChange={event=>{if(canEditDraft&&!canEditDraft()){setError('工程操作进行中,请稍后编辑文本。');return;}const value=event.target.value;onDraftChanged?.(value!==(text?.source??''));setSource(value);}} onKeyDown={event=>{
|
||||
if(event.nativeEvent.isComposing)return;
|
||||
if((event.ctrlKey||event.metaKey)&&event.key==='/'&&onNativeEdit){event.preventDefault();event.stopPropagation();void editText('COMMENT_TOGGLE');}
|
||||
if(event.key==='Enter'&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&onNativeEdit){event.preventDefault();event.stopPropagation();void editText('LINE_BREAK');}
|
||||
if(event.key==='Tab'&&onNativeEdit){event.preventDefault();event.stopPropagation();void editText(event.shiftKey?'UNINDENT':'INDENT');}
|
||||
if((event.ctrlKey||event.metaKey)&&event.shiftKey&&event.key.toLowerCase()==='d'&&onNativeEdit){event.preventDefault();event.stopPropagation();void editText('DUPLICATE_LINE');}
|
||||
if((event.key==='Backspace'||event.key==='Delete')&&onNativeEdit&&!event.altKey){
|
||||
const previous=event.key==='Backspace';
|
||||
const word=event.ctrlKey||event.metaKey;
|
||||
event.preventDefault();event.stopPropagation();
|
||||
void editText(previous?(word?'DELETE_PREVIOUS_WORD':'DELETE_PREVIOUS_CHARACTER'):(word?'DELETE_NEXT_WORD':'DELETE_NEXT_CHARACTER'));
|
||||
}
|
||||
if((event.ctrlKey||event.metaKey)&&event.key==='Enter'&&text){event.preventDefault();void apply({type:'setTextSource',dataId:text.id,source});}
|
||||
}}/></div>
|
||||
<footer><span>{text?.name??''}</span><span>{source.split('\n').length} 行</span><span>{changed?'未提交':''}</span>{error?<output role="alert">{error}</output>:null}</footer>
|
||||
</section>;
|
||||
}
|
||||
78
web/app/src/app/WasmUVView.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import type {PointerEvent as ReactPointerEvent} from 'react';
|
||||
import type {MeshGeometryBuffer} from '../../../protocol/web-engine';
|
||||
import type {SceneSnapshotIR} from '../../../protocol/scene-ir';
|
||||
import type {NativeUVEdit} from '../../../protocol/editor-workflow';
|
||||
import {UVUnwrapControls} from './UVUnwrapControls';
|
||||
import {UVTransformControls} from './UVTransformControls';
|
||||
import {UVStitchControls} from './UVStitchControls';
|
||||
import {UVSelectionControls} from './UVSelectionControls';
|
||||
import {UVPackControls} from './UVPackControls';
|
||||
import {UVCustomRegionControls} from './UVCustomRegionControls';
|
||||
import {UVPackTargetControls} from './UVPackTargetControls';
|
||||
import type {NativeUVPackTarget} from '../../../protocol/uv-pack-target';
|
||||
|
||||
export function WasmUVView({snapshot,geometryBuffers,onEdit,disabled=false,packTarget}:{snapshot:SceneSnapshotIR|null;geometryBuffers:MeshGeometryBuffer[];onEdit?:(intent:NativeUVEdit)=>Promise<boolean>;disabled?:boolean;packTarget?:NativeUVPackTarget}){
|
||||
const canvas=useRef<HTMLCanvasElement>(null),host=useRef<HTMLDivElement>(null),drag=useRef<{x:number;y:number;offsetX:number;offsetY:number}|null>(null);
|
||||
const [view,setView]=useState({zoom:1,x:0,y:0}),[size,setSize]=useState({width:300,height:300});
|
||||
const [busy,setBusy]=useState(false),[editStatus,setEditStatus]=useState('');
|
||||
const editing=useRef(false),editGeneration=useRef(0);
|
||||
useEffect(()=>()=>{editGeneration.current+=1;},[]);
|
||||
const edit=async(intent:NativeUVEdit)=>{
|
||||
const {operation}=intent;
|
||||
if(!onEdit||disabled||editing.current)return;
|
||||
const label=operation==='SET_PACK_TILE'?'UV 活动 UDIM 目标':operation==='CUSTOM_REGION_SET'||operation==='CUSTOM_REGION_ENABLE'?'UV 自定义区域':operation==='PACK_ISLANDS'?'打包 UV 岛屿':operation==='SELECT_STICKY'||operation==='SELECT_MODE'||operation==='SELECT_SYNC'||operation==='SELECT_ISLAND'?'UV 选择设置':intent.operation==='TRANSFORM'?(intent.transform.mode==='TRANSLATE'?'移动 UV':intent.transform.mode==='ROTATE'?'旋转 UV':'缩放 UV'):operation==='STITCH'?'缝合 UV':operation==='UNWRAP'?'展开 UV':operation==='PIN'?'固定 UV':operation==='UNPIN'?'取消固定 UV':operation==='INVERT_PIN'?'反转 UV 固定状态':'UV 选择';
|
||||
const generation=++editGeneration.current;editing.current=true;setBusy(true);setEditStatus(`正在提交${label}…`);
|
||||
try{const applied=await onEdit(intent);if(generation===editGeneration.current)setEditStatus(applied?`${label}已提交`:`${label}未提交,请查看引擎提示并确认网格处于编辑模式`);}
|
||||
catch(reason){if(generation===editGeneration.current)setEditStatus(reason instanceof Error?reason.message:String(reason));}
|
||||
finally{if(generation===editGeneration.current){editing.current=false;setBusy(false);}}
|
||||
};
|
||||
const active=snapshot?.nodes.find(node=>node.id===snapshot.activeObjectId),mesh=snapshot?.meshes.find(mesh=>mesh.id===active?.dataId),geometry=geometryBuffers.find(buffer=>buffer.meshId===mesh?.id);
|
||||
const uvSelection=snapshot?.editorWorkflow?.uvSelection;
|
||||
const selectUV=(event:ReactPointerEvent<HTMLCanvasElement>)=>{
|
||||
if(event.button!==0||event.ctrlKey||event.metaKey||event.altKey||!onEdit||disabled||editing.current)return;
|
||||
const rect=event.currentTarget.getBoundingClientRect();
|
||||
const scale=Math.min(size.width,size.height)*.8*view.zoom;
|
||||
if(rect.width<=0||rect.height<=0||!Number.isFinite(scale)||scale<=0)return;
|
||||
const ox=(size.width-scale)/2+view.x,oy=(size.height-scale)/2+view.y;
|
||||
const location:[number,number]=[((event.clientX-rect.left)*size.width/rect.width-ox)/scale,1-((event.clientY-rect.top)*size.height/rect.height-oy)/scale];
|
||||
event.preventDefault();event.stopPropagation();event.currentTarget.closest<HTMLElement>('.wasm-uv-editor')?.focus();
|
||||
void edit({operation:'SELECT',location,pixelsPerUV:scale,toggle:event.shiftKey});
|
||||
};
|
||||
useEffect(()=>{if(!host.current)return;const observer=new ResizeObserver(entries=>{const box=entries[0]?.contentRect;if(box)setSize({width:Math.max(1,Math.floor(box.width)),height:Math.max(1,Math.floor(box.height))});});observer.observe(host.current);return()=>observer.disconnect();},[]);
|
||||
useEffect(()=>{
|
||||
const context=canvas.current?.getContext('2d');if(!context)return;
|
||||
const scale=Math.min(size.width,size.height)*.8*view.zoom,ox=(size.width-scale)/2+view.x,oy=(size.height-scale)/2+view.y;
|
||||
context.fillStyle='#252525';context.fillRect(0,0,size.width,size.height);context.fillStyle='#303030';context.fillRect(ox,oy,scale,scale);context.strokeStyle='#727272';context.strokeRect(ox,oy,scale,scale);
|
||||
if(uvSelection?.customRegion?.enabled){
|
||||
const [minU,minV,maxU,maxV]=uvSelection.customRegion.bounds;
|
||||
context.save();context.setLineDash([5,4]);context.strokeStyle='#ffad4a';context.lineWidth=1.5;
|
||||
context.strokeRect(ox+minU*scale,oy+(1-maxV)*scale,(maxU-minU)*scale,(maxV-minV)*scale);context.restore();
|
||||
}
|
||||
if(uvSelection){
|
||||
const edges=uvSelection.objects.flatMap(object=>object.edges);
|
||||
let offset=0,pass=0,stopped=false,frame=0;
|
||||
const draw=()=>{
|
||||
if(stopped)return;
|
||||
const end=Math.min(edges.length,offset+4096);
|
||||
context.strokeStyle=pass===1?'#ffad4a':'#8e9399';context.lineWidth=pass===1?1.2:.7;context.beginPath();
|
||||
for(;offset<end;offset++){
|
||||
const [u,v,nextU,nextV,selected,edgeSelected,pinned]=edges[offset],x=ox+u*scale,y=oy+(1-v)*scale;
|
||||
if(pass<2){if(pass===1&&!edgeSelected)continue;context.moveTo(x,y);context.lineTo(ox+nextU*scale,oy+(1-nextV)*scale);}
|
||||
else{if(pass===3&&!selected&&!pinned)continue;context.fillStyle=pass===2?'#969ca3':pinned?'#ff6262':'#ffad4a';const radius=pass===2?1:2;context.fillRect(x-radius,y-radius,radius*2,radius*2);}
|
||||
}
|
||||
context.stroke();if(offset===edges.length){offset=0;pass++;}if(pass<4)frame=requestAnimationFrame(draw);
|
||||
};
|
||||
draw();return()=>{stopped=true;cancelAnimationFrame(frame);};
|
||||
}
|
||||
if(!geometry?.uvs)return;
|
||||
const uvs=new Float32Array(geometry.uvs),indices=new Uint32Array(geometry.indices),corners=geometry.triangleCornerIndices?new Uint32Array(geometry.triangleCornerIndices):undefined;
|
||||
const indexCount=indices.length-indices.length%3;
|
||||
let offset=0,stopped=false,frame=0;
|
||||
const draw=()=>{if(stopped)return;context.strokeStyle='#bdad87';context.lineWidth=.65;context.beginPath();const end=Math.min(indexCount,offset+12288);
|
||||
for(;offset+2<end;offset+=3){let valid=true;for(let corner=0;corner<3;corner++){const index=corners?corners[offset+corner]:indices[offset+corner];const u=uvs[index*2],v=uvs[index*2+1];if(!Number.isFinite(u)||!Number.isFinite(v)){valid=false;break;}const x=ox+u*scale,y=oy+(1-v)*scale;if(corner===0)context.moveTo(x,y);else context.lineTo(x,y);}if(valid)context.closePath();}
|
||||
context.stroke();if(offset<indexCount)frame=requestAnimationFrame(draw);
|
||||
};draw();return()=>{stopped=true;cancelAnimationFrame(frame);};
|
||||
},[geometry,size,view,uvSelection]);
|
||||
return <section className="wasm-uv-editor" tabIndex={onEdit&&!disabled&&!busy?0:-1} onKeyDown={event=>{if(event.target!==event.currentTarget||!onEdit||disabled||busy||event.repeat||event.ctrlKey||event.metaKey||event.shiftKey||event.key.toLowerCase()!=="a")return;event.preventDefault();event.stopPropagation();void edit({operation:event.altKey?"DESELECT_ALL":"SELECT_ALL"});}}><header><strong>UV</strong><span>{uvSelection?uvSelection.objects.map(object=>object.uvMap).join(" · "):mesh?.activeUVMap??''}</span>{onEdit&&<><button type="button" disabled={disabled||busy} onClick={()=>void edit({operation:'SELECT_ALL'})}>全选 UV</button><button type="button" disabled={disabled||busy} onClick={()=>void edit({operation:'DESELECT_ALL'})}>取消选择</button><button type="button" disabled={disabled||busy} onClick={()=>void edit({operation:'INVERT_SELECTION'})}>反选 UV</button>{([["PIN","固定 UV"],["UNPIN","取消固定"],["INVERT_PIN","反转固定"]] as const).map(([operation,label])=><button key={operation} type="button" disabled={disabled||busy} title={`${label}:作用于原生选择中的所有 UV,包括未显示部分`} onClick={()=>void edit({operation})}>{label}</button>)}</>}<button title="框显 UV" aria-label="框显 UV" onClick={()=>setView({zoom:1,x:0,y:0})}>⌖</button></header>{onEdit?<div className="uv-controls"><UVSelectionControls selection={uvSelection} disabled={disabled||busy} onApply={edit}/><UVTransformControls disabled={disabled||busy} onApply={transform=>edit({operation:'TRANSFORM',transform})}/><UVUnwrapControls disabled={disabled||busy} onApply={options=>edit({operation:'UNWRAP',options})}/><UVPackTargetControls target={packTarget} disabled={disabled||busy} onApply={edit}/><UVCustomRegionControls region={uvSelection?.customRegion} disabled={disabled||busy} onApply={edit}/><UVPackControls disabled={disabled||busy} onApply={options=>edit({operation:'PACK_ISLANDS',options})}/><UVStitchControls disabled={disabled||busy} onApply={options=>edit({operation:'STITCH',options})}/></div>:null}{uvSelection?<output>原生 UV 选择 · {uvSelection.objects.length} 个网格 · {uvSelection.syncSelection?"同步选择":"独立 UV 选择"} · 橙色为选中,红色为固定{uvSelection.truncated?" · 仅显示部分 UV":""}</output>:null}{editStatus?<output role="status">{editStatus}</output>:!onEdit?<output>请选择可编辑的原生 UV 区域以进行操作</output>:null}<div ref={host} onWheel={event=>{event.preventDefault();setView(current=>({...current,zoom:Math.max(.05,Math.min(50,current.zoom*Math.exp(-event.deltaY*.001)))}));}} onPointerDown={event=>{if(event.button!==1)return;event.preventDefault();event.currentTarget.setPointerCapture(event.pointerId);drag.current={x:event.clientX,y:event.clientY,offsetX:view.x,offsetY:view.y};}} onPointerMove={event=>{const origin=drag.current;if(origin)setView(current=>({...current,x:origin.offsetX+event.clientX-origin.x,y:origin.offsetY+event.clientY-origin.y}));}} onPointerUp={()=>{drag.current=null;}} onPointerCancel={()=>{drag.current=null;}}><canvas ref={canvas} onPointerDown={selectUV} width={size.width} height={size.height} aria-label="实际 UV 数据"/></div>{uvSelection?(!uvSelection.objects.some(object=>object.edges.length)?<output>当前没有可见的编辑 UV</output>:null):!geometry?.uvs?<output>无 UV 数据</output>:null}</section>;
|
||||
}
|
||||
63
web/app/src/app/WasmViewportBinding.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import {useEffect,useRef,useState,type ReactNode} from 'react';
|
||||
import type {BlenderViewportCamera,NativeViewportState} from '../../../protocol/viewport-camera';
|
||||
import type {WebEngineClient} from '../engine-client/WebEngineClient';
|
||||
|
||||
export function WasmViewportBinding({view,client,children,onSave}:{view:NativeViewportState|undefined;client:WebEngineClient|null;children:ReactNode;onSave:(view:NativeViewportState)=>Promise<boolean>}){
|
||||
const root=useRef<HTMLDivElement>(null),generation=useRef(0),motion=useRef(0);
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const [reset,setReset]=useState(0);
|
||||
const supported=Boolean(view&&!view.locked&&view.projection!=='CAMERA');
|
||||
const serialized=JSON.stringify(view);
|
||||
useEffect(()=>{
|
||||
const token=++generation.current;
|
||||
const canvas=root.current?.querySelector<HTMLCanvasElement>('canvas.viewport-canvas');
|
||||
if(!canvas||!client||!view||!supported)return;
|
||||
let disposed=false,request=0;
|
||||
let size={width:Math.max(1,canvas.clientWidth),height:Math.max(1,canvas.clientHeight)};
|
||||
let resizeTimer:ReturnType<typeof setTimeout>|undefined;
|
||||
const changed=()=>{motion.current++;};
|
||||
canvas.addEventListener('pointerdown',changed,true);canvas.addEventListener('wheel',changed,true);canvas.addEventListener('keydown',changed,true);canvas.addEventListener('viewport-command',changed);canvas.addEventListener('viewport-ndof',changed);
|
||||
const restore=async(resize:boolean)=>{
|
||||
const version=motion.current,sequence=++request;
|
||||
const next={width:Math.max(1,canvas.clientWidth),height:Math.max(1,canvas.clientHeight)};
|
||||
try{
|
||||
let state=view;
|
||||
if(resize){
|
||||
let camera:BlenderViewportCamera|undefined;
|
||||
canvas.dispatchEvent(new CustomEvent('viewport-capture',{detail:{reply:(value:BlenderViewportCamera)=>{camera=value;}}}));
|
||||
if(!camera)return;
|
||||
state=(await client.callJson<NativeViewportState>('viewportFromCamera',{state:view,camera,...size})).result;
|
||||
}
|
||||
const {result}=await client.callJson<BlenderViewportCamera>('viewportCamera',{state,...next});
|
||||
if(disposed||token!==generation.current||version!==motion.current||sequence!==request)return;
|
||||
canvas.dispatchEvent(new CustomEvent('viewport-restore',{detail:result}));size=next;setError('');
|
||||
}catch(reason){if(!disposed)setError(String(reason));}
|
||||
};
|
||||
void restore(false);
|
||||
const observer=new ResizeObserver(()=>{
|
||||
if(canvas.clientWidth===size.width&&canvas.clientHeight===size.height)return;
|
||||
clearTimeout(resizeTimer);resizeTimer=setTimeout(()=>void restore(true),120);
|
||||
});
|
||||
observer.observe(canvas);
|
||||
return()=>{disposed=true;generation.current++;observer.disconnect();clearTimeout(resizeTimer);canvas.removeEventListener('pointerdown',changed,true);canvas.removeEventListener('wheel',changed,true);canvas.removeEventListener('keydown',changed,true);canvas.removeEventListener('viewport-command',changed);canvas.removeEventListener('viewport-ndof',changed);};
|
||||
},[serialized,client,reset,supported]);
|
||||
const save=async()=>{
|
||||
const canvas=root.current?.querySelector<HTMLCanvasElement>('canvas.viewport-canvas');
|
||||
if(!canvas||!view||!client||busy||!supported)return;
|
||||
let camera:BlenderViewportCamera|undefined;
|
||||
canvas.dispatchEvent(new CustomEvent('viewport-capture',{detail:{reply:(value:BlenderViewportCamera)=>{camera=value;}}}));
|
||||
if(!camera){setError('VIEWPORT_CAPTURE_UNAVAILABLE');return;}
|
||||
setBusy(true);setError('');const token=generation.current;
|
||||
try{
|
||||
const {result}=await client.callJson<NativeViewportState>('viewportFromCamera',{state:view,camera,width:Math.max(1,canvas.clientWidth),height:Math.max(1,canvas.clientHeight)});
|
||||
if(token!==generation.current)return;
|
||||
if(!await onSave(result))setError('视角未提交');
|
||||
}catch(reason){setError(String(reason));}finally{setBusy(false);}
|
||||
};
|
||||
return <div ref={root} className="wasm-viewport-binding"><div className="wasm-view-state-controls">
|
||||
<button title="保存此区域视角到工程" aria-label="保存区域视角" disabled={!supported||busy} onClick={()=>void save()}>▣</button>
|
||||
<button title="恢复已保存视角" aria-label="恢复区域视角" disabled={!supported||busy} onClick={()=>setReset(value=>value+1)}>↻</button>
|
||||
{!supported?<output>{view?.projection==='CAMERA'?'相机视图尚未接入':view?.locked?'锁定视图尚未接入':'区域视角不可用'}</output>:null}
|
||||
{error?<output role="alert">{error}</output>:null}
|
||||
</div>{children}</div>;
|
||||
}
|
||||
45
web/app/src/app/WasmWorkspace.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import { Children, Fragment, isValidElement, useRef, useState, type ReactElement, type ReactNode } from 'react';
|
||||
import type { EditorAreaIR, EditorWorkflowIR } from '../../../protocol/editor-workflow';
|
||||
|
||||
function editorName(area: EditorAreaIR): string {
|
||||
if (area.editor === 'NODE') return area.space?.kind === 'GeometryNodeTree' ? 'Geometry Nodes' : area.space?.kind === 'CompositorNodeTree' ? 'Compositor' : area.space?.kind === 'ShaderNodeTree' ? 'Shader Editor' : 'NODE';
|
||||
if (area.editor === 'DOPE_SHEET') return area.space?.kind === 'TIMELINE' ? 'Timeline' : 'Dope Sheet';
|
||||
return ({VIEW_3D:'3D Viewport',OUTLINER:'Outliner',PROPERTIES:'Properties',TEXT:'Text Editor',CONSOLE:'Python Console',UV_IMAGE:'Image Editor',INFO:'Info',FILE_BROWSER:'File Browser',SPREADSHEET:'Spreadsheet'} as Record<string,string>)[area.editor] ?? area.editor;
|
||||
}
|
||||
|
||||
export function WasmWorkspace({enabled,workflow,children,renderArea,onActivate}:{
|
||||
enabled:boolean; workflow:EditorWorkflowIR|null; children:ReactNode;
|
||||
renderArea:(area:EditorAreaIR,content:ReactNode)=>ReactNode;
|
||||
onActivate:(area:EditorAreaIR)=>Promise<boolean>;
|
||||
}) {
|
||||
const [pending,setPending]=useState(false);
|
||||
const pendingRef=useRef(false);
|
||||
const workspace=workflow?.workspaces.find(item=>item.id===workflow.context.workspaceId);
|
||||
if(!enabled)return <div className="workspace-grid">{children}</div>;
|
||||
if(!workspace)return <div className="wasm-source-workspace"><output>Workspace unavailable</output></div>;
|
||||
const templates=new Map<string,ReactNode>();
|
||||
const collect=(nodes:ReactNode)=>Children.forEach(nodes,node=>{
|
||||
if(!isValidElement(node))return;
|
||||
const element=node as ReactElement<{editor?:string;children?:ReactNode}>;
|
||||
if(element.type===Fragment)collect(element.props.children);
|
||||
else if(element.props.editor&&!templates.has(element.props.editor))templates.set(element.props.editor,element.props.children);
|
||||
});
|
||||
collect(children);
|
||||
const activate=async(area:EditorAreaIR)=>{
|
||||
if(pendingRef.current||area.id===workflow?.context.activeAreaId)return;
|
||||
pendingRef.current=true;setPending(true);
|
||||
try{await onActivate(area);}finally{pendingRef.current=false;setPending(false);}
|
||||
};
|
||||
return <div className="wasm-source-workspace" data-screen-id={workspace.screenId}>
|
||||
<div className="wasm-source-canvas">
|
||||
{workspace.areas.map(area=>{
|
||||
const name=editorName(area),content=templates.get(name);
|
||||
return <section key={`${workspace.screenId}:${area.id}`} className="wasm-source-area" data-native-area-id={area.id} data-active={area.id===workflow?.context.activeAreaId} data-editor={name}
|
||||
style={{left:`${area.rect.x*100}%`,top:`${(1-area.rect.y-area.rect.height)*100}%`,width:`${area.rect.width*100}%`,height:`${area.rect.height*100}%`}}>
|
||||
<header><button title={name} aria-label={`Activate ${name}`} aria-pressed={area.id===workflow?.context.activeAreaId} disabled={pending||!workspace.writable||area.editor==='UNSUPPORTED'} onClick={()=>void activate(area)}>{name}</button></header>
|
||||
<div className="wasm-source-content">{content!==undefined?renderArea(area,content):<output>{name}: browser editor unavailable</output>}</div>
|
||||
</section>;
|
||||
})}
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
@import "./ModifierParameterField.css";
|
||||
@import "./PhysicsSettingsEditor.css";
|
||||
|
||||
:root {
|
||||
color: #d9d9d9;
|
||||
background: #181818;
|
||||
@@ -13,6 +16,9 @@ button { color: inherit; border: 0; cursor: pointer; }
|
||||
button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible, [tabindex]:focus-visible { outline: 2px solid #77b9f4; outline-offset: -2px; }
|
||||
|
||||
.blender-app { display: grid; grid-template-columns: minmax(0, 1fr); grid-template-rows: 28px 30px minmax(0, 1fr) 20px; width: 100%; height: 100vh; min-height: 480px; background: #202020; }
|
||||
.blender-app[data-native-canvas="true"] { grid-template-rows: minmax(0, 1fr); }
|
||||
.blender-app[data-native-canvas="true"] > .topbar, .blender-app[data-native-canvas="true"] > .workspace-toolbar, .blender-app[data-native-canvas="true"] > .status-bar { display: none; }
|
||||
.blender-app[data-native-canvas="true"] > section[aria-label="Blender desktop"] { grid-column: 1; grid-row: 1; }
|
||||
.topbar, .workspace-toolbar, .status-bar { display: flex; align-items: center; min-width: 0; background: #1d1d1d; border-bottom: 1px solid #0f0f0f; }
|
||||
.topbar { gap: 2px; padding: 0 5px; overflow: hidden; box-shadow: inset 0 -1px #303030; }
|
||||
.brand { display: flex; align-items: center; flex: none; gap: 5px; height: 100%; padding: 0 4px 0 2px; color: #f2f2f2; font-weight: 600; }
|
||||
@@ -23,7 +29,8 @@ button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-
|
||||
.brand-orbit { position: absolute; left: 0; top: 1px; width: 10px; height: 3px; border-top: 2px solid #ea7600; transform: rotate(17deg); }
|
||||
.menu-bar, .workspace-tabs, .topbar-actions { display: flex; align-items: center; min-width: 0; gap: 1px; }.menu-entry { position: relative; display: inline-flex; flex: none; }
|
||||
.menu-bar { flex: none; }
|
||||
.menu-bar button, .topbar-actions button, .workspace-tab, .workspace-add, .workspace-toolbar button { min-height: 24px; padding: 3px 7px; color: #c9c9c9; background: transparent; border-radius: 2px; }
|
||||
.menu-bar button, .topbar > button, .workspace-tabs > button, .topbar-actions button, .workspace-tab, .workspace-add, .workspace-toolbar button { min-height: 24px; padding: 3px 7px; color: #c9c9c9; background: transparent; border-radius: 2px; }
|
||||
.workspace-tabs > button { height: 24px; flex: none; line-height: 18px; }
|
||||
.menu-bar button:hover, .topbar-actions button:hover, .workspace-tab:hover, .workspace-add:hover, .workspace-toolbar button:hover { color: #fff; background: #3a3a3a; }
|
||||
.topbar-actions button:disabled { color: #606060; background: transparent; cursor: default; }
|
||||
.workspace-tabs { flex: 1 1 auto; align-self: stretch; overflow-x: auto; overflow-y: hidden; scrollbar-width: none; }
|
||||
@@ -63,7 +70,13 @@ button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-
|
||||
.viewport-message { position: absolute; top: 50%; left: 50%; z-index: 1; display: grid; gap: 5px; transform: translate(-50%, -50%); text-align: center; color: #c8cbd0; }
|
||||
.viewport-message strong { color: #f3f4f6; font-size: 15px; }
|
||||
.viewport-message span { color: #969ba4; }
|
||||
.axis-gizmo { position: absolute; top: 13px; right: 16px; z-index: 2; width: 54px; height: 54px; color: #c2c5ca; font-size: 11px; }
|
||||
.axis-gizmo { position: absolute; top: 7px; right: 12px; z-index: 3; width: 120px; height: 120px; color: #c2c5ca; font-size: 11px; }
|
||||
.axis-gizmo .view-axis{position:absolute;width:24px;height:24px;min-width:24px;padding:0;transform:translate(-50%,-50%);border:1px solid currentColor;border-radius:50%;background:#303634;right:auto;bottom:auto;cursor:pointer;font-size:10px;line-height:22px}
|
||||
.axis-gizmo .view-axis.negative{background:#202322;opacity:.72}.axis-gizmo .view-axis:hover{background:#55625a;opacity:1}
|
||||
.viewport-view-label{position:absolute;top:10px;left:54px;z-index:2;font-size:11px;color:#d1dbd3;pointer-events:none}
|
||||
.viewport-navigation-tools{position:absolute;right:22px;top:140px;display:flex;flex-direction:column;gap:5px;z-index:3}
|
||||
.viewport-navigation-tools button{width:28px;height:28px;padding:0;border:1px solid #637268;border-radius:4px;background:#29322dd9;color:#e3ece6;font-size:19px;line-height:25px;cursor:pointer}.viewport-navigation-tools button:hover{background:#536659}.viewport-navigation-tools button[aria-pressed=true]{background:#476456}
|
||||
.view-axis:focus-visible,.viewport-navigation-tools button:focus-visible{outline:2px solid #d5dfa4;outline-offset:2px}
|
||||
.axis-gizmo span { position: absolute; min-width: 18px; padding: 2px; text-align: center; border-radius: 50%; background: #353535; box-shadow: 0 0 0 1px #202020; }.axis-x { right: -3px; top: 23px; color: #ed6a6a; }.axis-y { left: 21px; top: -4px; color: #6fc47d; }.axis-z { left: 3px; bottom: 4px; color: #6e9ee8; }
|
||||
.viewport-toolbar { position: absolute; top: 12px; left: 7px; z-index: 2; display: grid; gap: 2px; padding: 3px; background: #292929e8; border: 1px solid #4a4a4a; border-radius: 3px; box-shadow: 0 2px 8px #0005; }.tool-button { width: 28px; height: 28px; background: transparent; color: #ccc; border-radius: 2px; }.tool-button:hover, .tool-button.active { color: #fff; background: #4775a3; }
|
||||
.tool-button:disabled { color: #666a72; cursor: default; }.tool-button:disabled:hover { background: transparent; }
|
||||
@@ -71,8 +84,11 @@ button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-
|
||||
.transform-gizmo.handle-local::before { position: absolute; left: 42px; top: 42px; width: 8px; height: 8px; border: 1px solid #fff; border-radius: 50%; background: #24262b; box-shadow: 0 0 0 2px #24262baa; content: ""; }
|
||||
.gizmo-axis { position: absolute; width: 28px; height: 28px; padding: 0; border: 2px solid currentColor; border-radius: 50%; background: #24262bcc; font-weight: 700; pointer-events: auto; touch-action: none; }
|
||||
.gizmo-axis.axis-x { left: 60px; top: 32px; color: #e35b55; }.gizmo-axis.axis-y { left: 32px; top: 4px; color: #65bb70; }.gizmo-axis.axis-z { left: 32px; top: 60px; color: #5d8ee8; }
|
||||
.viewport-sidebar { position: absolute; top: 72px; right: 0; z-index: 2; display: flex; gap: 1px; padding: 0; color: #c2c2c2; background: #292929e8; border: 1px solid #484848; border-right: 0; border-radius: 3px 0 0 3px; }.viewport-sidebar span { padding: 8px 5px; writing-mode: vertical-rl; }
|
||||
.viewport-sidebar { position: absolute; top: 312px; right: 0; z-index: 2; display: flex; gap: 1px; padding: 0; color: #c2c2c2; background: #292929e8; border: 1px solid #484848; border-right: 0; border-radius: 3px 0 0 3px; }.viewport-sidebar span { padding: 8px 5px; writing-mode: vertical-rl; }
|
||||
.outliner-content { padding: 3px 2px; color: #d0d0d0; }
|
||||
.tree-expand { width:16px;min-width:16px;height:22px;padding:0;background:transparent;color:inherit;border:0; }
|
||||
.tree-depth { white-space:pre;flex-shrink:0; }
|
||||
.tree-node-name { min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap; }
|
||||
.properties-content { position: relative; display: flex; flex-direction: column; min-height: 100%; padding: 4px 7px 12px 40px; color: #d0d0d0; background: #303030; }
|
||||
.outliner-tools { display: flex; gap: 3px; margin: 0 2px 4px; }.outliner-tools input { min-width: 0; height: 23px; flex: 1; padding: 3px 7px; color: #e4e4e4; background: #181818; border: 1px solid #454545; border-radius: 3px; outline: none; }.outliner-tools button { width: 27px; background: #383838; border-radius: 2px; }
|
||||
.tree-row { display: flex; align-items: center; gap: 5px; min-height: 24px; padding: 1px 4px; border-radius: 0; }.tree-row:hover { background: #353535; }.tree-row.child { padding-left: 26px; }.tree-row.selected { color: #fff; background: #4775a3; }.tree-icon { color: #d59b44; }.tree-icon.mesh { color: #6999c8; }.tree-action { width: 24px; min-width: 24px; height: 24px; margin-left: auto; padding: 1px 3px; color: #a6a6a6; background: transparent; border: 0; border-radius: 2px; }.tree-action:hover { color: #fff; background: #4a4a4a; }
|
||||
@@ -142,6 +158,13 @@ button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-
|
||||
.recent-project-repair-banner { position: fixed; top: 62px; left: 50%; z-index: 11; display: grid; gap: 6px; width: min(560px, calc(100vw - 24px)); padding: 9px 11px; transform: translateX(-50%); color: #f1f2f4; background: #332d22; border: 1px solid #b98a42; border-radius: 3px; box-shadow: 0 8px 24px #0008; }.recent-project-repair-list { display: grid; gap: 4px; max-height: 160px; overflow: auto; }.recent-project-repair-item { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-width: 0; color: #d9d1bd; }.recent-project-repair-item > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.recent-project-repair-item button { flex: none; padding: 4px 8px; color: #fff; background: #765729; border: 1px solid #c49c58; border-radius: 2px; }.recent-project-repair-item button:hover { background: #92703a; }
|
||||
.file-input-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
||||
.operator-search { position: fixed; top: 64px; left: 50%; z-index: 10; width: min(480px, calc(100vw - 24px)); padding: 7px; transform: translateX(-50%); background: #292929; border: 1px solid #5a5a5a; border-radius: 3px; box-shadow: 0 12px 30px #0008; }
|
||||
.operator-search-backdrop { position: fixed; inset: 0; z-index: 1000; display: flex; align-items: flex-start; justify-content: center; box-sizing: border-box; padding: 32px 16px; background: #0007; }
|
||||
.operator-search-dialog { box-sizing: border-box; width: min(640px, 100%); max-height: calc(100vh - 64px); overflow: auto; padding: 12px; color: #f4f5f6; background: #292929; border: 1px solid #5a5a5a; border-radius: 3px; box-shadow: 0 12px 30px #0008; }
|
||||
.operator-search-dialog > header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
|
||||
.operator-search-dialog > fieldset { min-width: 0; margin: 8px 0 0; padding: 0; border: 0; }
|
||||
.operator-search-dialog input[aria-label="搜索 Blender 操作"] { box-sizing: border-box; width: 100%; margin-bottom: 8px; }
|
||||
.operator-search-dialog .operator-search-results { display: grid; gap: 4px; max-height: 30vh; overflow: auto; }
|
||||
.operator-search-dialog .operator-search-results button { display: flex; justify-content: space-between; gap: 12px; text-align: left; }
|
||||
.main-menu-popover { position: absolute; top: 100%; left: 0; z-index: 14; display: grid; min-width: 128px; padding: 4px; background: #303238; border: 1px solid #545860; border-radius: 3px; box-shadow: 0 8px 20px #0008; }.main-menu-popover button { padding: 6px 10px; text-align: left; color: #d9dce1; background: transparent; border-radius: 2px; white-space: nowrap; }.main-menu-popover button:hover, .main-menu-popover button:focus-visible { color: #fff; background: #a55325; }
|
||||
.operator-search input { width: 100%; padding: 8px 10px; color: #f4f5f6; background: #1d1f22; border: 1px solid #5a5e66; border-radius: 3px; outline: none; }
|
||||
.operator-results { display: grid; gap: 2px; margin-top: 6px; }.operator-results button { padding: 8px 10px; text-align: left; color: #d9dce1; background: transparent; border-radius: 3px; }.operator-results button:hover { color: #fff; background: #a55325; }
|
||||
@@ -177,3 +200,9 @@ button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-
|
||||
.workspace-grid { grid-template-columns: minmax(0, 1fr) 290px; }
|
||||
.workspace-tab { padding-inline: 7px; }
|
||||
}
|
||||
|
||||
/* Native key selection and current time are separate states. */
|
||||
.timeline-content .key-dot { background: #737373; border-color: #d4d4d4; }
|
||||
.timeline-content .key-dot.selected { background: #f0b24f; border-color: #fff0bf; }
|
||||
.timeline-content .key-dot.active { outline: 2px solid #6da8e2; outline-offset: 2px; }
|
||||
.timeline-content .key-dot[data-selected-unknown="true"] { background: transparent; border-style: dashed; }
|
||||
|
||||
15
web/app/src/app/copy-project-assets.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import type {StorageClient} from '../storage/StorageClient';
|
||||
|
||||
export async function copyProjectAssets(storage:StorageClient,source:string,destination:string,assertCurrent:()=>void):Promise<void>{
|
||||
if(source===destination)throw new Error('另存为必须使用新的项目身份');
|
||||
const {assets}=await storage.listAssets(source);assertCurrent();
|
||||
for(const asset of assets){
|
||||
const loaded=await storage.readAsset(source,asset.sha256);assertCurrent();
|
||||
if(loaded.asset.sha256!==asset.sha256||loaded.data.byteLength!==asset.bytes)throw new Error('项目资源在复制期间发生变化');
|
||||
const paths=asset.sourcePaths?.length?asset.sourcePaths:[asset.sourcePath];
|
||||
for(const path of new Set(paths)){
|
||||
const saved=await storage.putAsset(destination,loaded.data.slice(0),asset.mimeType,path);assertCurrent();
|
||||
if(!saved.persisted||saved.sha256!==asset.sha256||saved.bytes!==asset.bytes)throw new Error('另存为资源未完整写入');
|
||||
}
|
||||
}
|
||||
}
|
||||
1
web/app/src/app/curve-icons/clipuv_dehlt.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg height="1600" viewBox="0 0 1600 1600" width="1600" xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"><sodipodi:namedview pagecolor="#303030" showgrid="true"><inkscape:grid id="grid5" units="px" spacingx="100" spacingy="100" color="#4772b3" opacity="0.2" visible="true" /></sodipodi:namedview><g fill="#fff"><path d="m342.5 158c-.27613.00003-.49997.22387-.5.5v13c.00003.27613.22387.49997.5.5h13c.27613-.00003.49997-.22387.5-.5v-13c-.00003-.27613-.22387-.49997-.5-.5zm6.5 3c2.20237 0 4 1.79764 4 4 0 2.20237-1.79763 4-4 4-2.20236 0-4-1.79763-4-4 0-2.20236 1.79764-4 4-4z" transform="matrix(100 0 0 100 -34100 -15700)"/></g></svg>
|
||||
|
After Width: | Height: | Size: 746 B |
1
web/app/src/app/curve-icons/clipuv_hlt.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg height="1600" viewBox="0 0 1600 1600" width="1600" xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"><sodipodi:namedview pagecolor="#303030" showgrid="true"><inkscape:grid id="grid5" units="px" spacingx="100" spacingy="100" color="#4772b3" opacity="0.2" visible="true" /></sodipodi:namedview><g fill="#fff"><g enable-background="new" opacity=".6" transform="matrix(100 0 0 100 -36200 -15700)"><path d="m369.99998 160.99999c-2.20236 0-4 1.79764-4 4 0 2.20237 1.79764 4 4 4 2.20237 0 4-1.79763 4-4 0-2.20236-1.79763-4-4-4z" opacity="1"/><path d="m363.5 158a.50005.50005 0 0 0 -.5.5v13a.50005.50005 0 0 0 .5.5h13a.50005.50005 0 0 0 .5-.5v-13a.50005.50005 0 0 0 -.5-.5zm.5 1h12v12h-12z" opacity=".3"/></g></g></svg>
|
||||
|
After Width: | Height: | Size: 830 B |
1
web/app/src/app/curve-icons/downarrow_hlt.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg height="700" viewBox="0 0 1100 700" width="1100" xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"><sodipodi:namedview pagecolor="#303030" showgrid="true"><inkscape:grid id="grid5" units="px" spacingx="100" spacingy="100" color="#4772b3" opacity="0.2" visible="true" /></sodipodi:namedview><g fill="#fff"><path d="m428.49023 603.99414a.50005.50005 0 0 0 -.34961.85938l4 4a.50005.50005 0 0 0 .70704 0l4-4a.50005.50005 0 1 0 -.70704-.70704l-3.64648 3.64649-3.64648-3.64649a.50005.50005 0 0 0 -.35743-.15234z" transform="matrix(100 0 0 100 -42699.474 -60299.645)"/></g></svg>
|
||||
|
After Width: | Height: | Size: 691 B |
1
web/app/src/app/curve-icons/handle_auto.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg id="svg3" height="1500" viewBox="0 0 1500 1500" width="1500" xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"><sodipodi:namedview pagecolor="#303030" showgrid="true"><inkscape:grid id="grid5" units="px" spacingx="100" spacingy="100" color="#4772b3" opacity="0.2" visible="true" /></sodipodi:namedview><g fill="#fff" transform="matrix(100 0 0 100 51300 -132799.6)"><path id="path1" d="m-505.5 1330.9023c-1.15049 0-2.30143.3893-3.30664 1.168-1.99911 1.5486-3.19334 4.2371-3.19336 7.2402v2.1817a.5.5 0 0 0 .5.5.5.5 0 0 0 .5-.5v-2.1817c.00002-2.7364 1.10112-5.1299 2.80664-6.4511 1.69425-1.3125 3.69247-1.3125 5.38672 0 1.6982 1.3155 2.80662 3.7968 2.80664 6.5332v2.0996a.5.5 0 0 0 .5.5.5.5 0 0 0 .5-.5v-2.0996c-.00002-3.003-1.1869-5.768-3.19336-7.3223-1.00521-.7787-2.15615-1.168-3.30664-1.168z" opacity=".7"/><path id="path2" d="m-504.5 1329a.50005.50005 0 0 0 -.5.5v2a.50005.50005 0 0 0 .5.5h2a.50005.50005 0 0 0 .5-.5v-2a.50005.50005 0 0 0 -.5-.5zm.5 1h1v1h-1z"/></g></svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
1
web/app/src/app/curve-icons/handle_autoclamped.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg id="svg4" height="1600" viewBox="0 0 1500 1600" width="1500" xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"><sodipodi:namedview pagecolor="#303030" showgrid="true"><inkscape:grid id="grid5" units="px" spacingx="100" spacingy="100" color="#4772b3" opacity="0.2" visible="true" /></sodipodi:namedview><g fill="#fff"><path id="path1" d="m-504.5 1330.0098c-1.14915 0-2.2974.3838-3.30273 1.1523-2.01782 1.5423-3.19727 4.3744-3.19727 7.0918a.50005.50005 0 0 0 0 0v.2382a.5.5 0 0 0 .5.5.5.5 0 0 0 .5-.5019v-.2383c0-2.4195 1.11591-5.0076 2.80273-6.2969 1.694-1.2948 3.70053-1.2948 5.39454 0 1.68683 1.2893 2.80273 3.8774 2.80273 6.2969v.2402a.5.5 0 0 0 .5.5.5.5 0 0 0 .5-.5v-.2402c0-2.7174-1.17944-5.5495-3.19727-7.0918-1.00533-.7685-2.15358-1.1523-3.30273-1.1523z" opacity=".7" transform="matrix(100 0 0 100 51200 -132399.66)"/><path id="path3" d="m-554 1265h3v-1h-3zm5 0h3v-1h-3zm5 0h3v-1h-3z" transform="matrix(100 0 0 100 55500 -126299.66)"/><path id="path2-0" d="m850.09271 400.05458a50.005 50.005 0 0 0 -50 50v200a50.005 50.005 0 0 0 50 50h199.99999a50.005 50.005 0 0 0 50-50v-200a50.005 50.005 0 0 0 -50-50zm50 100h99.99999v100h-99.99999z"/></g></svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
1
web/app/src/app/curve-icons/handle_vector.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg id="svg3" height="1600" viewBox="0 0 1500 1600" width="1500" xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"><sodipodi:namedview pagecolor="#303030" showgrid="true"><inkscape:grid id="grid5" units="px" spacingx="100" spacingy="100" color="#4772b3" opacity="0.2" visible="true" /></sodipodi:namedview><g fill="#fff"><path id="path2" d="m-469.3418 1327.0254c-.12553-.042-.26248-.032-.38086.027-.24799.1231-.34869.4244-.22461.6719l5.75 10.7306c.12312.2468.4229.3473.66993.2246.0108-.01.0212-.018.0312-.027.007.01.0153.018.0234.027.24703.1227.54681.022.66993-.2246l5.75-10.7306c.12408-.2475.0234-.5488-.22461-.6719-.24703-.1228-.54681-.022-.66993.2246l-5.55273 10.338-5.55273-10.338c-.059-.119-.16307-.2097-.28907-.2519z" opacity=".7" transform="matrix(100 0 0 -100 47100 134200.04)"/><path id="path2-8" d="m649.98893 96.140221a50.005 50.005 0 0 0 -50 49.999999v200a50.005 50.005 0 0 0 50 50h200a50.005 50.005 0 0 0 50-50v-200a50.005 50.005 0 0 0 -50-49.999999zm50 99.999999h100v100h-100z"/></g></svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
20
web/app/src/app/curve-icons/x.svg
Normal file
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
id="svg3"
|
||||
height="1000"
|
||||
viewBox="0 0 1000 1000"
|
||||
width="1000"
|
||||
version="1.1"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"><sodipodi:namedview pagecolor="#303030" showgrid="true"><inkscape:grid id="grid5" units="px" spacingx="100" spacingy="100" color="#4772b3" opacity="0.2" visible="true" /></sodipodi:namedview>
|
||||
<defs
|
||||
id="defs1" />
|
||||
<g
|
||||
id="g1">
|
||||
<path
|
||||
id="path2"
|
||||
d="m306.99023 241.72461a.66673335.66673335 0 0 0 -.65625.67578v5.93359h-5.93359a.66673335.66673335 0 1 0 0 1.33204h5.93359v5.93359a.66673335.66673335 0 1 0 1.33204 0v-5.93359h5.93359a.66673335.66673335 0 1 0 0-1.33204h-5.93359v-5.93359a.66673335.66673335 0 0 0 -.67579-.67578z"
|
||||
fill="#fff"
|
||||
transform="matrix(-53.033 -53.033 -53.033 53.033 29986.427 3575.989)" />
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1023 B |
28
web/app/src/app/curve-icons/zoom_in.svg
Normal file
@@ -0,0 +1,28 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
height="1600"
|
||||
viewBox="0 0 1600 1600"
|
||||
width="1600"
|
||||
version="1.1"
|
||||
id="svg3"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs3" />
|
||||
<g
|
||||
fill="#fff"
|
||||
id="g3">
|
||||
<g
|
||||
enable-background="new"
|
||||
transform="matrix(100 0 0 100 -19395 -57704.999)"
|
||||
id="g2">
|
||||
<path
|
||||
d="m 201.49298,578 c 3.57273,0 6.5,2.92727 6.5,6.5 0,1.60752 -0.59683,3.08042 -1.57422,4.21875 l 2.42774,2.42773 a 0.50005,0.50005 0 1 1 -0.70704,0.70704 l -2.42578,-2.42579 c -1.13822,0.977 -2.61355,1.57227 -4.2207,1.57227 -3.57273,0 -6.5,-2.92728 -6.5,-6.5 0,-3.57273 2.92727,-6.5 6.5,-6.5 z m 0,1 c -3.02727,0 -5.5,2.47272 -5.5,5.5 0,3.02727 2.47273,5.5 5.5,5.5 3.02727,0 5.5,-2.47273 5.5,-5.5 0,-3.02728 -2.47273,-5.5 -5.5,-5.5 z m 0.008,1.99219 a 0.50005,0.50005 0 0 1 0.492,0.50781 v 2.5 h 2.5 a 0.50005,0.50005 0 1 1 0,1 h -2.5 v 2.5 a 0.50005,0.50005 0 1 1 -1,0 V 585 h -2.5 a 0.50005,0.50005 0 1 1 0,-1 h 2.5 v -2.5 a 0.50005,0.50005 0 0 1 0.50781,-0.50781 z"
|
||||
id="path1" />
|
||||
<path
|
||||
d="m193.95 577.04999h16v16h-16z"
|
||||
opacity="0"
|
||||
id="path2" />
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
30
web/app/src/app/curve-icons/zoom_out.svg
Normal file
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
height="1600"
|
||||
viewBox="0 0 1600 1600"
|
||||
width="1600"
|
||||
version="1.1"
|
||||
id="svg3"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs3" />
|
||||
<g
|
||||
fill="#ffffff"
|
||||
id="g3"
|
||||
transform="matrix(-1,0,0,1,1600,0)">
|
||||
<g
|
||||
enable-background="new"
|
||||
transform="matrix(100,0,0,100,-19395,-57704.999)"
|
||||
id="g2">
|
||||
<path
|
||||
d="m 223.5,578 c -3.57273,0 -6.5,2.92727 -6.5,6.5 0,1.60752 0.59683,3.08042 1.57422,4.21875 l -2.42774,2.42773 a 0.50005,0.50005 0 1 0 0.70704,0.70704 l 2.42578,-2.42579 c 1.13822,0.977 2.61355,1.57227 4.2207,1.57227 3.57273,0 6.5,-2.92728 6.5,-6.5 0,-3.57273 -2.92727,-6.5 -6.5,-6.5 z m 0,1 c 3.02727,0 5.5,2.47272 5.5,5.5 0,3.02727 -2.47273,5.5 -5.5,5.5 -3.02727,0 -5.5,-2.47273 -5.5,-5.5 0,-3.02728 2.47273,-5.5 5.5,-5.5 z m -3,5 a 0.50005,0.50005 0 1 0 0,1 h 6 a 0.50005,0.50005 0 1 0 0,-1 z"
|
||||
transform="translate(-21)"
|
||||
id="path1" />
|
||||
<path
|
||||
d="m 193.95,577.04999 h 16 v 16 h -16 z"
|
||||
opacity="0"
|
||||
id="path2" />
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
56
web/app/src/app/desktop-folder-transfer.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import type { WebEngineClient } from '../engine-client/WebEngineClient';
|
||||
|
||||
export const DESKTOP_TRANSFER_MAX_FILES = 2048;
|
||||
export const DESKTOP_TRANSFER_MAX_BYTES = 256 * 1024 * 1024;
|
||||
export function desktopRelativeParts(path: string): string[] {
|
||||
const parts = path.split('/');
|
||||
if (path.length > 1024 || parts.length > 16 || parts.some(part => !part || part === '.' || part === '..' || /[\\\u0000-\u001f]/.test(part))) throw new Error('文件路径无效或层级过深'); // eslint-disable-line no-control-regex -- Reject control characters in file and resource paths.
|
||||
return parts;
|
||||
}
|
||||
|
||||
export async function saveDesktopFolder(client: WebEngineClient, session: string, cancelled: () => boolean, progress: (message: string) => void): Promise<string> {
|
||||
const picker = (window as Window & { showDirectoryPicker?: (options: { mode: 'readwrite' }) => Promise<FileSystemDirectoryHandle> }).showDirectoryPicker;
|
||||
if (!picker) throw new Error('当前浏览器不支持选择保存目录,请使用支持文件夹访问的浏览器。');
|
||||
const check = () => { if (cancelled()) throw new Error('文件夹保存已取消'); };
|
||||
const destination = await picker.call(window, { mode: 'readwrite' }); check();
|
||||
const listing = await client.desktopFiles(session, 'list'); check();
|
||||
if (!listing.entries.length || listing.entries.length > DESKTOP_TRANSFER_MAX_FILES) throw new Error('没有可保存的桌面文件,或文件数超过传输上限');
|
||||
const names = new Set<string>();
|
||||
for (const entry of listing.entries) {
|
||||
desktopRelativeParts(entry.path);
|
||||
if (names.has(entry.path) || !Number.isSafeInteger(entry.size) || entry.size < 0 || entry.size > DESKTOP_TRANSFER_MAX_BYTES) throw new Error(`文件无法传输:${entry.path}`);
|
||||
names.add(entry.path);
|
||||
}
|
||||
const folderName = `blender-${crypto.randomUUID()}`;
|
||||
const root = await destination.getDirectoryHandle(folderName, { create: true });
|
||||
let completed = 0;
|
||||
try {
|
||||
check();
|
||||
for (const entry of listing.entries) {
|
||||
check();
|
||||
const result = await client.desktopFiles(session, 'download', entry.path); check();
|
||||
if (!result.buffer || result.buffer.byteLength !== entry.size) throw new Error(`文件读取失败或传输期间大小发生变化:${entry.path}`);
|
||||
const parts = desktopRelativeParts(entry.path);
|
||||
let directory = root;
|
||||
for (const part of parts.slice(0, -1)) {
|
||||
directory = await directory.getDirectoryHandle(part, { create: true }); check();
|
||||
if (directory.name !== part) throw new Error(`目标文件系统不能保留目录名称:${entry.path}`);
|
||||
}
|
||||
const name = parts[parts.length - 1];
|
||||
const existing = await directory.getFileHandle(name).then(() => true, reason => { if (reason?.name === 'NotFoundError') return false; throw reason; }); check();
|
||||
if (existing) throw new Error(`目标路径已存在,停止写入:${entry.path}`);
|
||||
const handle = await directory.getFileHandle(name, { create: true }); check();
|
||||
if (handle.name !== name) throw new Error(`目标文件系统不能保留文件名称:${entry.path}`);
|
||||
const writable = await handle.createWritable();
|
||||
try { check(); await writable.write(result.buffer); check(); await writable.close(); }
|
||||
catch (reason) { await writable.abort().catch(() => undefined); throw reason; }
|
||||
completed++;
|
||||
progress(`已保存 ${completed}/${listing.entries.length} 个文件到 ${folderName}`);
|
||||
}
|
||||
check();
|
||||
} catch (reason) {
|
||||
const detail = typeof reason === 'object' && reason && 'message' in reason ? String(reason.message) : String(reason);
|
||||
throw new Error(`已保存 ${completed}/${listing.entries.length} 个文件到 ${folderName};${detail}`, { cause: reason });
|
||||
}
|
||||
return `已保存 ${completed} 个文件到 ${folderName}`;
|
||||
}
|
||||
5
web/app/src/app/desktop-menus.css
Normal file
@@ -0,0 +1,5 @@
|
||||
.desktop-menu-trigger{display:inline-flex;flex:none;position:relative}.desktop-menu-trigger>button{min-height:24px;padding:3px 7px;background:transparent;color:#d3d3d3;white-space:nowrap;border-radius:2px}.desktop-menu-trigger>button[aria-expanded=true]{background:#454545}.desktop-menu-panel{position:fixed;z-index:1500;width:280px;max-width:calc(100vw - 8px);padding:5px;background:#282b2a;color:#e0e3e1;border:1px solid #656b67;box-shadow:0 7px 20px #0007;border-radius:4px;overflow:auto}.desktop-menu-panel>button{display:flex;position:relative;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:7px;width:100%;min-height:28px;text-align:left;padding:5px 9px;color:inherit;background:transparent;border:0;border-radius:2px;font-size:12px}.desktop-menu-panel>button:hover:enabled,.desktop-menu-panel>button:focus-visible{background:#44644f;color:white;outline:1px solid #bdd7c4}.desktop-menu-panel>button:disabled{color:#949c96;cursor:default}.desktop-menu-panel small{display:block;flex-basis:100%;font-size:10px;color:#a7b1a9;white-space:normal;line-height:1.4}.desktop-menu-shortcut{color:#b2beb5;font-size:10px}.desktop-menu-panel [role=separator]{height:1px;background:#49514b;margin:5px 3px}.desktop-menu-back{border-bottom:1px solid #657268!important;margin-bottom:4px}.desktop-header-menus{display:flex;align-items:center;min-width:0;gap:1px}.desktop-selection-controls{display:flex;align-items:center;gap:3px;margin-left:8px}.desktop-header-label{color:#cbd4ce;min-width:0;overflow:hidden;text-overflow:ellipsis;font-size:11px}.desktop-dialog-backdrop{position:fixed;inset:0;z-index:1600;background:#0006;display:flex;align-items:center;justify-content:center;padding:14px}.desktop-dialog{background:#292d2a;border:1px solid #87948b;border-radius:5px;width:440px;max-width:100%;max-height:90vh;overflow:auto;padding:14px;color:#e3e8e4}.desktop-dialog header{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}.desktop-dialog h2{font-size:16px;margin:0}.desktop-dialog button{padding:6px 11px;color:inherit;background:#49534c;border:1px solid #7c8b81;border-radius:3px}.desktop-dialog header button{padding:2px;width:27px;height:27px}.desktop-dialog input:not([type=checkbox]){width:100%;padding:7px;background:#1e211f;border:1px solid #6d7c72;color:inherit}.desktop-dialog p{font-size:12px;line-height:1.7}.desktop-dialog-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:15px}.desktop-dialog label{display:flex;gap:8px;align-items:center;margin:12px 0}.workspace-toolbar{overflow:visible}.desktop-header-actions{display:flex;min-width:0;align-items:center;overflow-x:auto;scrollbar-width:none}.legacy-quick-toolbar{display:none}.blender-app:not([data-native-canvas=true]) .legacy-quick-toolbar,.blender-app[data-quick-tools=true] .legacy-quick-toolbar{display:flex;position:absolute;top:58px;left:0;right:0;z-index:10;background:#303532;overflow-x:auto;gap:4px;padding:4px}.legacy-quick-toolbar>button{white-space:nowrap;min-height:27px;padding:3px 7px;background:#414942}.blender-app[data-hide-status=true] .status-bar{display:none}.blender-app[data-hide-status=true]{grid-template-rows:28px 30px minmax(0,1fr) 0}.workspace-menu-control{flex:none}.workspace-tabs{min-width:90px}.workspace-tabs .workspace-menu-control{position:sticky;right:0;background:#222}.viewport-header-status{margin-left:auto;display:flex;align-items:center;gap:12px;font-size:11px;white-space:nowrap;padding-right:8px}.topbar-actions .extension-robot{color:#bbd4c3}
|
||||
@media(max-width:700px){.desktop-header-label{display:none}.viewport-header-status{gap:3px;font-size:10px}.desktop-selection-controls{margin-left:0}.desktop-header-menus{max-width:100%;overflow-x:auto;scrollbar-width:none}}
|
||||
@media(max-width:900px){.topbar .menu-bar{display:flex}.topbar .menu-bar button{padding-inline:5px}.topbar-actions>select,.topbar-actions>.topbar-context,.topbar-actions>.extension-robot{display:none}.workspace-tabs .workspace-tab:nth-child(n+4){display:initial}.workspace-tabs .workspace-tab{flex:none}.workspace-tabs{min-width:40px}.workspace-menu-control>button{font-size:0;width:26px;padding:3px}.workspace-menu-control>button::after{content:'▾';font-size:14px}}
|
||||
@media(max-width:550px){.topbar-actions{display:none}.workspace-tabs{min-width:48px}.brand{padding:0}.topbar .menu-bar button{padding-inline:4px;font-size:11px}}
|
||||
.desktop-history-list{display:grid;gap:3px;max-height:60vh;overflow:auto}.desktop-history-list button{display:flex;justify-content:space-between;gap:12px;text-align:left;min-height:30px}.desktop-history-list button[aria-current=step]{background:#365743}.native-export-form fieldset{border:0;padding:0;min-width:0}.native-export-form details{margin:12px 0}.native-export-form details>label{display:grid;grid-template-columns:minmax(0,1fr) minmax(90px,1fr)}.native-export-form label{overflow-wrap:anywhere}.native-export-form select{max-width:100%;min-width:0;color:inherit;background:#222;border:1px solid #727b75;padding:5px}.native-export-form fieldset fieldset{border:1px solid #626962;padding:7px;margin:6px 0}.native-export-form fieldset fieldset label{margin:4px}.native-export-form output{overflow-wrap:anywhere}.native-export-form .native-workflow-output{max-height:180px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere}
|
||||
34
web/app/src/app/desktop-workspace-storage.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
export interface DesktopRecovery {
|
||||
id:string;
|
||||
slot:string;
|
||||
savedAt:number;
|
||||
blend:Blob;
|
||||
resourceProject:string;
|
||||
}
|
||||
|
||||
async function database():Promise<IDBDatabase>{
|
||||
return new Promise((resolve,reject)=>{
|
||||
const request=indexedDB.open('blender-desktop-workspaces',1);
|
||||
request.onupgradeneeded=()=>request.result.createObjectStore('recovery',{keyPath:'id'});
|
||||
request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error);
|
||||
});
|
||||
}
|
||||
export async function recoverDesktop(slot:string):Promise<DesktopRecovery|undefined>{
|
||||
const db=await database();
|
||||
try{return await new Promise((resolve,reject)=>{
|
||||
const request=db.transaction('recovery').objectStore('recovery').getAll();
|
||||
request.onsuccess=()=>resolve((request.result as DesktopRecovery[]).filter(item=>item.slot===slot).sort((a,b)=>b.savedAt-a.savedAt)[0]);request.onerror=()=>reject(request.error);
|
||||
});}finally{db.close();}
|
||||
}
|
||||
export async function saveDesktop(record:DesktopRecovery):Promise<string[]>{
|
||||
const db=await database();
|
||||
try{return await new Promise((resolve,reject)=>{
|
||||
const tx=db.transaction('recovery','readwrite'),store=tx.objectStore('recovery'),old=store.getAll();const removed:string[]=[];
|
||||
old.onsuccess=()=>{
|
||||
const history=(old.result as DesktopRecovery[]).filter(item=>item.slot===record.slot).sort((a,b)=>b.savedAt-a.savedAt);
|
||||
for(const item of history.slice(2)){store.delete(item.id);removed.push(item.resourceProject);}
|
||||
store.put(record);
|
||||
};
|
||||
tx.oncomplete=()=>resolve(removed);tx.onerror=()=>reject(tx.error);tx.onabort=()=>reject(tx.error??new Error('DESKTOP_RECOVERY_ABORTED'));
|
||||
});}finally{db.close();}
|
||||
}
|
||||
16
web/app/src/app/desktop-workspace.css
Normal file
@@ -0,0 +1,16 @@
|
||||
.desktop-workspace{position:fixed;inset:0;display:grid;grid-template-rows:minmax(0,1fr) 30px;background:#252525;color:#ddd;font:12px sans-serif;letter-spacing:0}
|
||||
.desktop-workspace-surface{position:relative;min-width:0;min-height:0;overflow:auto;overscroll-behavior:contain;background:#202020}
|
||||
.desktop-workspace-surface.fit{display:flex;align-items:center;justify-content:center;overflow:hidden}
|
||||
.desktop-workspace-surface.fit>img{width:100%;height:100%;object-fit:contain;touch-action:none;user-select:none}
|
||||
.desktop-workspace-surface.pixels>img{display:block;max-width:none;max-height:none;touch-action:none;user-select:none}
|
||||
.desktop-workspace-surface .native-cursor{cursor:none}
|
||||
.desktop-keyboard-input{position:absolute;left:0;top:0;width:1px;height:1px;opacity:0;resize:none;overflow:hidden;padding:0;border:0}
|
||||
.desktop-browser-tools{display:flex;align-items:center;gap:6px;min-width:0;overflow-x:auto;white-space:nowrap;padding:2px 7px;background:#303030;border-top:1px solid #555;scrollbar-width:none}
|
||||
.desktop-browser-tools strong{font-size:12px;margin-right:6px}.desktop-browser-tools button,.desktop-file-drawer button,.desktop-workspace-error button{flex:none;min-width:26px;height:24px;padding:2px 5px;border:1px solid #606060;border-radius:3px;color:#eee;background:#414141;font-size:15px;line-height:18px}
|
||||
.desktop-browser-tools button:disabled{opacity:.4}.desktop-browser-tools button[aria-pressed=true]{background:#536d7d}.desktop-browser-tools a{color:#b5d4eb;padding:3px 6px}.desktop-recovery-time{margin-left:auto;color:#b7c9b7;font-size:11px}
|
||||
.desktop-workspace-start{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100%;gap:12px;width:100%}.desktop-workspace-start h1{font-size:28px;font-weight:500;margin:0}
|
||||
.desktop-file-drawer{position:absolute;right:0;top:0;bottom:30px;width:420px;max-width:100%;overflow:auto;background:#303030;border-left:1px solid #666;padding:12px;box-sizing:border-box}.desktop-file-drawer header{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}.desktop-file-drawer>div{display:grid;grid-template-columns:minmax(0,1fr) auto 26px;gap:8px;align-items:center;padding:8px 0;border-bottom:1px solid #484848}.desktop-file-drawer span{overflow-wrap:anywhere}.desktop-file-drawer small{color:#bbb}.desktop-file-drawer output{color:#b8c7d4}
|
||||
.desktop-workspace-error{position:absolute;bottom:40px;left:10px;right:10px;max-height:180px;overflow:auto;display:flex;align-items:flex-start;gap:12px;padding:10px;background:#492f2f;border:1px solid #976666;border-radius:4px}.desktop-workspace-error span{flex:1;overflow-wrap:anywhere;white-space:pre-wrap}
|
||||
@media(max-width:700px){.desktop-browser-tools{gap:4px}.desktop-recovery-time{display:none}}
|
||||
.desktop-file-drawer>div{grid-template-columns:minmax(0,1fr) auto auto}.desktop-file-actions{display:flex;gap:4px}
|
||||
.desktop-browser-links{position:absolute;left:8px;bottom:40px;display:flex;flex-wrap:wrap;gap:8px;max-width:calc(100% - 16px);padding:8px;background:#303030;border:1px solid #666}.desktop-browser-links a{color:#b8d6ee;overflow-wrap:anywhere}
|
||||
1
web/app/src/app/engine-client
Symbolic link
@@ -0,0 +1 @@
|
||||
../engine-client
|
||||
106
web/app/src/app/modifier-curve-tools.css
Normal file
@@ -0,0 +1,106 @@
|
||||
/* curvemap_buttons_layout dimensions and native uiWidgetColors snapshots.
|
||||
* Scoped to the existing curve operator controls, including older snapshots. */
|
||||
.curve-native-toolbar, .curve-native-selection {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0;
|
||||
}
|
||||
.curve-native-toolbar { justify-content: flex-end; }
|
||||
.curve-icon-button, .curve-menu-item, .curve-coordinate, .curve-clip-fields label {
|
||||
box-sizing: border-box;
|
||||
border: 1px solid var(--curve-border, #191919);
|
||||
border-radius: var(--curve-radius, 3px);
|
||||
background: var(--curve-bg, #545454);
|
||||
color: var(--curve-text, #ededed);
|
||||
font: inherit;
|
||||
min-height: var(--curve-unit, 20px);
|
||||
}
|
||||
.curve-icon-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 0 0 auto;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
width: var(--curve-unit, 20px);
|
||||
height: var(--curve-unit, 20px);
|
||||
min-width: 0;
|
||||
cursor: default;
|
||||
list-style: none;
|
||||
}
|
||||
.curve-icon-button::-webkit-details-marker { display: none; }
|
||||
.curve-native-icon {
|
||||
display: inline-block;
|
||||
width: var(--curve-icon-size, 16px);
|
||||
height: var(--curve-icon-size, 16px);
|
||||
background-color: currentColor;
|
||||
mask-size: contain;
|
||||
mask-repeat: no-repeat;
|
||||
mask-position: center;
|
||||
-webkit-mask-size: contain;
|
||||
-webkit-mask-repeat: no-repeat;
|
||||
-webkit-mask-position: center;
|
||||
}
|
||||
.curve-icon-button[aria-pressed="true"], .curve-icon-button:active:not(:disabled),
|
||||
.curve-tool-popover[open] > summary {
|
||||
background: var(--curve-selected, #4772b3);
|
||||
border-color: var(--curve-border-selected, #305080);
|
||||
color: var(--curve-text-selected, #fff);
|
||||
}
|
||||
button.curve-icon-button:hover:not(:disabled):not([aria-pressed="true"]):not(:active),
|
||||
.curve-tool-popover:not([open]) > summary:hover:not([aria-disabled="true"]),
|
||||
.curve-menu-item:focus-visible, .curve-menu-item:hover:not(:disabled) {
|
||||
background: var(--curve-hover, #646464);
|
||||
border-color: var(--curve-border-hover, #4772b3);
|
||||
color: var(--curve-text-hover, #fff);
|
||||
}
|
||||
.curve-icon-button:focus-visible, .curve-coordinate:focus-within, .curve-clip-fields label:focus-within {
|
||||
outline: 1px solid var(--curve-border-selected, #4772b3);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
.curve-icon-button:disabled, .curve-icon-button[aria-disabled="true"], .curve-menu-item:disabled {
|
||||
opacity: .5;
|
||||
cursor: default;
|
||||
}
|
||||
.curve-tool-popover { position: relative; }
|
||||
.curve-tool-popup {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: 100%;
|
||||
z-index: 5;
|
||||
box-sizing: content-box;
|
||||
max-width: calc(100vw - 32px);
|
||||
display: grid;
|
||||
gap: 0;
|
||||
border: 1px solid var(--curve-border, #191919);
|
||||
border-radius: var(--curve-radius, 4px);
|
||||
background: var(--curve-bg, #303030);
|
||||
color: var(--curve-text, #ededed);
|
||||
}
|
||||
.curve-tool-popup > label { min-height: var(--curve-unit, 20px); display: flex; align-items: center; gap: 4px; }
|
||||
.curve-tool-popup input[type="checkbox"] { accent-color: var(--curve-text, #ededed); }
|
||||
.curve-menu-item {
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
text-align: left;
|
||||
padding: 0 0 0 var(--curve-unit, 20px); /* ICON_BLANK1 slot */
|
||||
white-space: nowrap;
|
||||
border-color: transparent;
|
||||
}
|
||||
.curve-clip-fields { display: grid; gap: 0; }
|
||||
.curve-clip-fields label, .curve-coordinate { display: flex; align-items: center; gap: 2px; padding: 0 4px; }
|
||||
.curve-clip-fields input, .curve-coordinate input {
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
height: calc(var(--curve-unit, 20px) - 2px);
|
||||
outline: none;
|
||||
}
|
||||
.curve-coordinate { flex: 1 1 60px; min-width: 60px; }
|
||||
18
web/app/src/app/modifier-input-keyboard.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { KeyboardEvent } from 'react';
|
||||
|
||||
/** Keep text composition and field confirmation scoped to the edited control. */
|
||||
export function finishModifierInput(event: KeyboardEvent<HTMLInputElement>, original: string) {
|
||||
if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) {
|
||||
// Let the browser/IME finish composition, but keep workspace shortcuts and
|
||||
// enclosing form handlers from treating it as a committed Blender edit.
|
||||
event.stopPropagation();
|
||||
return;
|
||||
}
|
||||
if (event.key !== 'Enter' && event.key !== 'Escape') return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (event.key === 'Escape') event.currentTarget.value = original;
|
||||
// The existing blur path validates and commits through the native owner.
|
||||
// On cancel its value is the authoritative original, so no write is needed.
|
||||
event.currentTarget.blur();
|
||||
}
|
||||
19
web/app/src/app/native-editors.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type {NativeWorkflowContext} from '../../../protocol/native-workflow';
|
||||
|
||||
export const NATIVE_EDITORS: {id:NonNullable<NativeWorkflowContext['areaType']>;label:string}[] = [
|
||||
{id:'VIEW_3D',label:'3D 视图'}, {id:'IMAGE_EDITOR',label:'图像 / UV 编辑器'},
|
||||
{id:'NODE_EDITOR',label:'节点编辑器'}, {id:'GRAPH_EDITOR',label:'曲线编辑器'},
|
||||
{id:'DOPESHEET_EDITOR',label:'动画摄影表'}, {id:'NLA_EDITOR',label:'非线性动画'},
|
||||
{id:'SEQUENCE_EDITOR',label:'视频序列编辑器'}, {id:'CLIP_EDITOR',label:'影片剪辑编辑器'},
|
||||
{id:'TEXT_EDITOR',label:'文本编辑器'}, {id:'CONSOLE',label:'Python 控制台'},
|
||||
{id:'INFO',label:'信息'}, {id:'OUTLINER',label:'大纲视图'}, {id:'PROPERTIES',label:'属性'},
|
||||
{id:'FILE_BROWSER',label:'文件 / 资产浏览器'}, {id:'SPREADSHEET',label:'电子表格'},
|
||||
{id:'PREFERENCES',label:'偏好设置'},
|
||||
];
|
||||
|
||||
export function readWebInterfacePreferences():{showStatus:boolean;quickTools:boolean} {
|
||||
try {
|
||||
const saved=JSON.parse(localStorage.getItem('web-blender-interface-v1')??'{}');
|
||||
return {showStatus:typeof saved.showStatus==='boolean'?saved.showStatus:true,quickTools:saved.quickTools===true};
|
||||
} catch { return {showStatus:true,quickTools:false}; }
|
||||
}
|
||||
24
web/app/src/app/native-workflows.css
Normal file
@@ -0,0 +1,24 @@
|
||||
.native-render-panel,.native-python-panel{display:flex;flex-direction:column;min-width:0;height:100%;overflow:auto;background:#262829;color:#e4e5e5}
|
||||
.native-workflow-controls{display:flex;flex-wrap:wrap;align-items:end;gap:6px;padding:8px;border-bottom:1px solid #4b5050}
|
||||
.native-workflow-controls label{display:flex;flex-direction:column;gap:3px;font-size:11px;min-width:0;max-width:100%}
|
||||
.native-workflow-controls input,.native-workflow-controls select{max-width:180px;min-width:0;background:#343738;color:inherit;border:1px solid #666;padding:3px}
|
||||
.native-workflow-controls input[type=number]{width:68px}
|
||||
.native-workflow-controls button{background:#414849;color:#fff;border:1px solid #737d7d;padding:5px 9px;cursor:pointer}
|
||||
.native-workflow-controls button:disabled{opacity:.5;cursor:default}
|
||||
.native-render-image{flex:1;min-height:180px;display:flex;align-items:center;justify-content:center;overflow:auto}
|
||||
.native-render-image img,.native-render-image video{max-width:100%;max-height:100%;object-fit:contain;display:block}
|
||||
.native-workflow-artifacts{display:flex;flex-wrap:wrap;gap:8px;padding:8px;max-height:90px;overflow:auto}
|
||||
.native-workflow-artifacts a{color:#90d4cf;font-size:11px;overflow-wrap:anywhere}
|
||||
.native-workflow-output{margin:0;padding:8px;white-space:pre-wrap;overflow-wrap:anywhere;overflow:auto;max-height:180px;font-size:11px}
|
||||
.native-python-panel textarea{flex:1;min-height:100px;resize:vertical;border:0;padding:10px;background:#202223;color:#e7edeb;font:12px monospace;line-height:1.5;tab-size:4;box-sizing:border-box;width:100%}
|
||||
.native-session-panel{display:flex;flex-direction:column;height:100%;min-height:0;background:#262829;color:#e4e5e5;overflow:auto}
|
||||
.native-session-panel textarea{min-height:100px;resize:vertical;background:#202223;color:#e7edeb;padding:8px;box-sizing:border-box;width:100%;font:12px monospace}
|
||||
.native-desktop-view{min-height:0;overflow:auto;flex:1;background:#171919;display:flex;align-items:start;justify-content:center}
|
||||
.native-desktop-view img{display:block;width:100%;height:auto;aspect-ratio:1280/900;touch-action:none;user-select:none;outline-offset:-2px;object-fit:contain}
|
||||
.native-desktop-dialog{position:fixed;inset:3vh 3%;z-index:1000;display:flex;flex-direction:column;background:#262829;border:1px solid #727f7b}
|
||||
.native-desktop-dialog>header{display:flex;justify-content:space-between;padding:6px;color:#eee}
|
||||
.native-desktop-dialog>.native-session-panel{flex:1}
|
||||
.native-resource-list{max-height:120px;overflow:auto;padding:4px}
|
||||
.native-resource-list>div{display:grid;grid-template-columns:minmax(60px,1fr) minmax(80px,2fr) minmax(80px,2fr);gap:4px;margin-bottom:3px;font-size:11px}
|
||||
.native-resource-list input{min-width:0;background:#343738;color:#eee;border:1px solid #555}
|
||||
.native-resource-list span{overflow-wrap:anywhere}
|
||||
52
web/app/src/app/operator-properties.css
Normal file
@@ -0,0 +1,52 @@
|
||||
.operator-array-property,
|
||||
.operator-enum-set,
|
||||
.operator-nested-group {
|
||||
border: 1px solid #555;
|
||||
margin: 8px 0;
|
||||
padding: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.operator-nested-properties {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
padding-left: 8px;
|
||||
}
|
||||
|
||||
.operator-collection-item {
|
||||
border-left: 2px solid #666;
|
||||
margin: 8px 0;
|
||||
padding: 4px 0 4px 10px;
|
||||
}
|
||||
|
||||
.operator-collection-item > header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.operator-array-components {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(76px, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.operator-array-components label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.operator-array-components input[type="number"] {
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.operator-enum-set label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-right: 10px;
|
||||
}
|
||||
43
web/app/src/app/shader-include-paths.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
export type ShaderSourceFile = { file: File; path: string; sourcePath?: string };
|
||||
export function absoluteShaderPath(value: string): string {
|
||||
if (!/^(?:\/|[A-Za-z]:[\\/])/.test(value) || /[\u0000-\u001f\u007f"<>]/.test(value)) throw new Error('Enter an absolute include path without control characters or quotes'); // eslint-disable-line no-control-regex -- Reject control characters in file and resource paths.
|
||||
const parts: string[] = [];
|
||||
for (const part of value.replace(/\\/g, '/').split('/')) { if (part === '..') { if (!parts.length || /^[A-Za-z]:$/.test(parts.at(-1)!)) throw new Error('Include path escapes its root'); parts.pop(); } else if (part && part !== '.') parts.push(part); }
|
||||
return value.startsWith('/') ? '/' + parts.join('/') : parts.join('/');
|
||||
}
|
||||
function relativeInclude(from: string, target: string): string {
|
||||
const parent = from.split('/').slice(0, -1), destination = target.split('/');
|
||||
while (parent.length && parent[0] === destination[0]) { parent.shift(); destination.shift(); }
|
||||
return '../'.repeat(parent.length) + destination.join('/');
|
||||
}
|
||||
function rewriteIncludes(source: string, path: string, mappings: Map<string, string>): string {
|
||||
const visible = source.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, token => token.startsWith('/') ? token.replace(/[^\r\n]/g, ' ') : token);
|
||||
const replacements: { start: number; end: number; text: string }[] = [];
|
||||
for (const match of visible.matchAll(/^([\t ]*#[\t ]*include[\t ]*")([^"\r\n]+)"/gm)) {
|
||||
if (!/^(?:\/|[A-Za-z]:[\\/])/.test(match[2])) continue;
|
||||
const target = mappings.get(absoluteShaderPath(match[2]));
|
||||
if (target) replacements.push({ start: match.index! + match[1].length, end: match.index! + match[1].length + match[2].length, text: relativeInclude(path, target) });
|
||||
}
|
||||
for (const replacement of replacements.reverse()) source = source.slice(0, replacement.start) + replacement.text + source.slice(replacement.end);
|
||||
return source;
|
||||
}
|
||||
export async function prepareShaderIncludes(files: ShaderSourceFile[], signal: AbortSignal, entry: string): Promise<ShaderSourceFile[]> {
|
||||
const mappings = new Map<string, string>();
|
||||
for (const item of files) if (item.sourcePath) { const key = absoluteShaderPath(item.sourcePath); if (/["\r\n]/.test(item.path)) throw new Error('Mapped include filenames cannot contain quotes or newlines'); if (mappings.has(key)) throw new Error('Duplicate original include path: ' + key); mappings.set(key, item.path); }
|
||||
if (!mappings.size) return files;
|
||||
const prepared: ShaderSourceFile[] = [];
|
||||
for (const item of files) {
|
||||
if (signal.aborted) throw new DOMException('Shader preparation cancelled', 'AbortError');
|
||||
if (/\.oso$/i.test(item.path)) { prepared.push(item); continue; }
|
||||
const bytes = await item.file.arrayBuffer(); let source: string;
|
||||
try { source = new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { prepared.push(item); continue; }
|
||||
if (source.includes('\0')) { prepared.push(item); continue; }
|
||||
const rewritten = rewriteIncludes(source, item.path, mappings);
|
||||
const prefix = bytes.byteLength >= 3 && new Uint8Array(bytes, 0, 3).every((byte, index) => byte === [239, 187, 191][index]) ? '\uFEFF' : '';
|
||||
prepared.push(rewritten === source ? item : { ...item, file: new File([prefix, rewritten], item.file.name, { type: item.file.type, lastModified: item.file.lastModified }) });
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
}
|
||||
if (signal.aborted) throw new DOMException('Shader preparation cancelled', 'AbortError');
|
||||
if (entry.endsWith('.osl') && prepared.some((item, index) => item.file !== files[index].file)) return prepared.filter(item => item.path !== entry.slice(0, -4) + '.oso');
|
||||
return prepared;
|
||||
}
|
||||
63
web/app/src/app/wasm-editors.css
Normal file
@@ -0,0 +1,63 @@
|
||||
.wasm-text-editor,.wasm-shader-editor{height:100%;min-height:0;display:flex;flex-direction:column;background:#292929;color:#ddd;font-size:12px;letter-spacing:0}
|
||||
.wasm-text-editor>header,.wasm-shader-editor>header{display:flex;align-items:center;gap:5px;flex-wrap:wrap;flex:none;padding:4px;border-bottom:1px solid #555}
|
||||
.wasm-text-editor input,.wasm-text-editor select,.wasm-shader-editor input,.wasm-shader-editor select{min-width:0;max-width:100%;background:#202020;color:inherit;border:1px solid #555;border-radius:3px;padding:4px}
|
||||
.wasm-text-editor>header>input{width:100px}.wasm-text-editor button,.wasm-shader-editor button{background:#414141;padding:5px 7px;border-radius:3px;color:inherit}.wasm-text-editor button:disabled,.wasm-shader-editor button:disabled{opacity:.45}
|
||||
.wasm-text-body{display:flex;flex:1;min-height:0;overflow:auto;background:#242424}.wasm-text-body pre{margin:0;padding:9px 8px;color:#9b9b9b;background:#2e2e2e;line-height:20px;font:12px/20px monospace;text-align:right}.wasm-text-body textarea{flex:1;min-width:0;padding:9px;color:#dce3dc;background:transparent;border:0;resize:none;tab-size:4;white-space:pre;font:12px/20px monospace;outline:0}
|
||||
.wasm-text-editor>footer,.wasm-shader-editor>footer{display:flex;flex:none;gap:12px;padding:4px 8px;border-top:1px solid #484848;overflow-wrap:anywhere}
|
||||
.wasm-shader-body{display:flex;flex:1;min-height:0}.wasm-node-canvas{position:relative;flex:1;min-width:0;overflow:hidden;background:#242424;touch-action:none}.wasm-node-stage{position:absolute;left:0;top:0;transform-origin:0 0}.wasm-node-links{position:absolute;left:0;top:0;width:1px;height:1px;overflow:visible;pointer-events:none}.wasm-node-links path{fill:none;stroke:#a6b8a4;stroke-width:2}
|
||||
.wasm-shader-node{position:absolute;width:224px;min-height:60px;padding:0 0 7px;border:1px solid #777;border-radius:5px;background:#363636;color:#e3e3e3}.wasm-shader-node.selected{border:2px solid #dfaa60}.wasm-shader-node>header{padding:8px;min-height:35px;background:#455a4b;border-radius:4px 4px 0 0;overflow-wrap:anywhere;cursor:move}.shader-socket{height:24px;display:flex;align-items:center;gap:6px;padding:0 7px;overflow:hidden}.shader-socket span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.shader-socket.output{flex-direction:row-reverse}.shader-socket i{flex:none;width:9px;height:9px;border-radius:50%;background:#939393}.shader-socket i[data-kind=COLOR]{background:#d8c257}.shader-socket i[data-kind=SHADER]{background:#75a96e}.shader-socket i[data-kind=VECTOR]{background:#688eb0}
|
||||
.wasm-node-properties{width:210px;max-width:40%;flex:none;border-left:1px solid #555;padding:8px;overflow:auto}.wasm-node-properties>label{display:flex;flex-direction:column;gap:4px;margin:8px 0;overflow-wrap:anywhere}.wasm-node-properties>button{margin:4px 0;display:block;max-width:100%;overflow-wrap:anywhere}.shader-vector-input{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:3px}.shader-vector-input input{width:100%}
|
||||
@media(max-width:650px){.wasm-node-properties{width:155px}.wasm-shader-editor>header select{max-width:130px}}
|
||||
.wasm-shader-node>header{height:36px;min-height:36px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}
|
||||
.wasm-uv-editor{height:100%;min-height:0;display:flex;flex-direction:column;background:#292929;color:#ddd}.wasm-uv-editor>header{display:flex;align-items:center;gap:10px;padding:5px;border-bottom:1px solid #555}.wasm-uv-editor>header button{margin-left:auto;background:#454545;color:inherit}.wasm-uv-editor>div{position:relative;flex:1;min-height:0;overflow:hidden;touch-action:none}.wasm-uv-editor canvas{display:block}.wasm-uv-editor>output{padding:5px}.wasm-graph-records{display:flex;flex-direction:column;gap:4px;overflow:auto;padding:8px}.wasm-graph-records>div{display:flex;justify-content:space-between;gap:10px;padding:6px 0;border-bottom:1px solid #444;overflow-wrap:anywhere}.wasm-graph-records>div span{color:#aaa;font-size:11px}
|
||||
.wasm-uv-editor>.uv-controls{flex:0 1 auto;max-height:45%;min-height:0;overflow:auto;touch-action:auto}.wasm-uv-editor .uv-controls fieldset{display:flex;flex-wrap:wrap;align-items:center;gap:8px}.wasm-uv-editor .uv-controls label{display:flex;align-items:center;gap:4px}.wasm-uv-editor>header{flex-wrap:wrap}.wasm-uv-editor>header button{margin-left:0}
|
||||
.wasm-image-editor{height:100%;min-height:0;display:flex;flex-direction:column;background:#252525}.wasm-image-editor>header{display:flex;flex-wrap:wrap;gap:7px;padding:4px}.wasm-image-editor select{min-width:0;max-width:100%;flex:1;background:#333;color:#ddd}.wasm-image-editor button{background:#444;color:#ddd;min-height:26px;white-space:nowrap}.wasm-image-editor button:disabled{opacity:.45}.wasm-image-editor>div{flex:1;min-height:0;overflow:auto;display:flex;align-items:center;justify-content:center}.wasm-image-editor img{object-fit:contain;max-width:100%;max-height:100%}.wasm-image-editor .image-zoom{flex:0 1 78px;width:78px}.wasm-image-editor>.native-image-view{position:relative;overflow:hidden}.wasm-image-editor .native-image-view img{position:absolute;max-width:none;max-height:none;transform:translate(-50%,-50%);object-fit:fill}.wasm-image-editor>output{overflow-wrap:anywhere;padding:4px;color:#f1b4a8}
|
||||
.wasm-image-editor>.native-image-view{touch-action:none;user-select:none}
|
||||
.wasm-image-editor>.native-image-view[data-panning=true]{cursor:grabbing}
|
||||
.wasm-image-editor>.native-image-view:focus-visible{outline:1px solid #8ea89c;outline-offset:-1px}
|
||||
.wasm-image-editor>.native-image-view[data-box-zoom=true]{cursor:crosshair}
|
||||
.wasm-image-editor .image-zoom-border{position:absolute;box-sizing:border-box;border:1px dashed #fff;background:rgba(125,170,207,.15);pointer-events:none}
|
||||
.wasm-text-body{overflow:hidden}.wasm-text-body pre{flex:none;width:56px;overflow:hidden;user-select:none}.wasm-text-body textarea{height:100%;min-height:0}
|
||||
.wasm-editor-context { display: flex; flex-wrap: wrap; gap: 6px 12px; align-items: center; padding: 4px 8px; background: #303030; border-bottom: 1px solid #171717; font-size: 12px; }
|
||||
.blender-app:has(> .wasm-editor-context) { grid-template-rows: 28px 30px auto minmax(0, 1fr) 20px; }
|
||||
.wasm-editor-context label { display: flex; align-items: center; gap: 5px; min-width: 0; }
|
||||
.wasm-editor-context select { color: #ddd; background: #242424; border: 1px solid #505050; max-width: 220px; min-width: 0; }
|
||||
.wasm-editor-region { display: flex; align-items: center; gap: 5px; }
|
||||
.wasm-editor-region button { min-width: 38px; height: 24px; padding: 2px 5px; }
|
||||
.wasm-editor-region-alignment { width: 6ch; font-size: 10px; color: #aaa; }
|
||||
.wasm-spreadsheet-filters { flex: 1 1 340px; min-width: 0; max-width: 640px; }
|
||||
.wasm-spreadsheet-filters summary { cursor: pointer; padding: 3px 0; }
|
||||
.wasm-spreadsheet-rule-heading { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; padding: 4px 0; }
|
||||
.wasm-spreadsheet-rules { max-height: 240px; overflow: auto; }
|
||||
.wasm-spreadsheet-rule { border-top: 1px solid #505050; padding: 5px 0; }
|
||||
.wasm-spreadsheet-value { display: grid; grid-template-columns: 64px minmax(0, 1fr) 52px; gap: 6px; align-items: center; margin: 5px 0; }
|
||||
.wasm-spreadsheet-inputs { display: flex; flex-wrap: wrap; gap: 4px; min-width: 0; }
|
||||
.wasm-spreadsheet-inputs input:not([type=checkbox]) { flex: 1 1 58px; width: 58px; min-width: 0; max-width: 100%; box-sizing: border-box; background: #242424; color: #ddd; border: 1px solid #505050; padding: 3px; }
|
||||
.wasm-spreadsheet-inputs input[aria-invalid=true] { border-color: #ca746b; }
|
||||
.wasm-spreadsheet-filters button { background: #414141; color: #ddd; border-radius: 3px; padding: 4px 6px; }
|
||||
.wasm-spreadsheet-filters button:disabled { opacity: .45; }
|
||||
.wasm-python-console { display: flex; flex-direction: column; height: 100%; min-height: 0; background: #232323; color: #ddd; font: 12px/1.5 monospace; }
|
||||
.wasm-python-console header { display: flex; align-items: center; gap: 6px; padding: 3px 5px; border-bottom: 1px solid #4a4a4a; flex-wrap: wrap; }
|
||||
.wasm-python-console header button { width: 26px; height: 25px; background: #3c3c3c; color: #ddd; border-radius: 3px; padding: 0; }
|
||||
.wasm-python-console header button:disabled { opacity: .4; }
|
||||
.wasm-python-console pre { flex: 1; min-height: 40px; margin: 0; padding: 7px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
|
||||
.wasm-python-input { display: flex; align-items: flex-start; gap: 6px; padding: 5px; border-top: 1px solid #4a4a4a; }
|
||||
.wasm-python-input textarea { flex: 1; min-width: 0; color: inherit; background: transparent; border: 0; resize: vertical; max-height: 180px; font: inherit; }
|
||||
.blender-app:has(> .wasm-source-workspace) { grid-template-rows: 28px 30px auto auto minmax(0, 1fr) 20px; }
|
||||
.wasm-source-workspace { min-height: 0; min-width: 0; overflow: auto; background: #181818; }
|
||||
.wasm-source-content .wasm-editor-context fieldset { min-width: 0; max-width: 100%; box-sizing: border-box; flex-wrap: wrap; }
|
||||
.wasm-source-content .wasm-editor-context input { min-width: 0; max-width: 100%; }
|
||||
.wasm-source-canvas { position: relative; width: 100%; height: 100%; min-width: 960px; min-height: 600px; }
|
||||
.wasm-source-area { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; border: 1px solid #111; overflow: hidden; background: #292929; }
|
||||
.wasm-source-area > header { display: flex; flex: none; height: 25px; min-width: 0; border-bottom: 1px solid #171717; background: #353535; }
|
||||
.wasm-source-area > header button { background: transparent; color: #d8d8d8; padding: 3px 8px; max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: 12px; }
|
||||
.wasm-source-area[data-active=true] > header { background: #45554a; }
|
||||
.wasm-source-content { flex: 1; min-height: 0; min-width: 0; overflow: auto; position: relative; }
|
||||
.wasm-source-content > output { display: block; padding: 8px; overflow-wrap: anywhere; color: #bbb; }
|
||||
.wasm-source-content > .viewport-placeholder { height: 100%; min-height: 0; }
|
||||
.wasm-viewport-binding { height: 100%; min-height: 0; display: flex; flex-direction: column; }
|
||||
.wasm-viewport-binding > .viewport-placeholder { flex: 1; min-height: 0; height: auto; }
|
||||
.wasm-view-state-controls { display: flex; align-items: center; gap: 6px; flex: none; min-height: 26px; padding: 2px 5px; background: #303030; color: #bbb; font-size: 11px; overflow-wrap: anywhere; }
|
||||
.wasm-view-state-controls button { width: 24px; height: 22px; padding: 0; flex: none; background: #424242; color: #ddd; border-radius: 3px; }
|
||||
.wasm-view-state-controls button:disabled { opacity: .45; }
|
||||
.wasm-python-console header select { max-width: 180px; min-width: 0; background: #292929; color: #ddd; border: 1px solid #555; font: 11px sans-serif; }
|
||||
212
web/app/src/engine-client/NativeAudioOutput.ts
Normal file
@@ -0,0 +1,212 @@
|
||||
import { NATIVE_AUDIO_CHANNELS, NATIVE_AUDIO_FRAMES, NATIVE_AUDIO_RATE, NATIVE_AUDIO_BUFFER_BLOCKS, NATIVE_AUDIO_RECOVERY_BLOCKS, NATIVE_AUDIO_BUSY_BLOCKS, type NativeAudioOutput as OutputMessage, type NativeAudioPull, type NativeAudioClock, type NativeAudioSegment, type NativeAudioPrepared } from "../../../protocol/native-audio";
|
||||
|
||||
/** Browser device only: no scene, playback, decoding or mixing emulation. */
|
||||
export class NativeAudioOutput {
|
||||
private context: AudioContext | null = null;
|
||||
private generation = 0;
|
||||
private sequence = 0;
|
||||
private pending: number | null = null;
|
||||
private preparation: { sequence: number; expiresAtMs: number } | null = null;
|
||||
private bufferBlocks = NATIVE_AUDIO_BUFFER_BLOCKS;
|
||||
private nextTime = 0;
|
||||
private disposed = false;
|
||||
private failed = false;
|
||||
private segments: NativeAudioSegment[] = [];
|
||||
private scheduledFrames = 0;
|
||||
private completedFrames = 0;
|
||||
private outputTime = 0;
|
||||
private clockSequence = 0;
|
||||
private pendingClock: number | null = null;
|
||||
private nodes = new Set<AudioBufferSourceNode>();
|
||||
private timer: ReturnType<typeof setInterval>;
|
||||
|
||||
constructor(private port: MessagePort, private onError: (message: string) => void) {
|
||||
port.onmessage = (event: MessageEvent<OutputMessage>) => this.receive(event.data);
|
||||
// resume() must execute within the same trusted gesture as Blender's input.
|
||||
window.addEventListener("pointerdown", this.unlock, true);
|
||||
window.addEventListener("keydown", this.unlock, true);
|
||||
this.timer = setInterval(() => { this.publishClock(); this.pull(); }, 10);
|
||||
}
|
||||
|
||||
private unlock = (): void => {
|
||||
if (this.disposed) return;
|
||||
try {
|
||||
if (!this.context) {
|
||||
this.context = new AudioContext({ latencyHint: "interactive" });
|
||||
this.context.onstatechange = () => { this.publishClock(); this.pull(); };
|
||||
}
|
||||
if (this.context.state !== "running") {
|
||||
void this.context.resume().then(() => this.pull()).catch(error => this.onError(String(error)));
|
||||
}
|
||||
}
|
||||
catch (error) { this.onError(String(error)); }
|
||||
};
|
||||
|
||||
private flush(resetClock = true): void {
|
||||
// Freeze the last presented position before removing queued nodes on error
|
||||
// or shutdown. Only a native generation reset may rewind the PCM counters.
|
||||
if (!resetClock) this.publishClock(false);
|
||||
for (const node of this.nodes) {
|
||||
node.onended = null;
|
||||
node.stop();
|
||||
node.disconnect();
|
||||
}
|
||||
this.nodes.clear();
|
||||
this.nextTime = 0;
|
||||
if (resetClock) {
|
||||
this.preparation = null;
|
||||
this.bufferBlocks = NATIVE_AUDIO_BUFFER_BLOCKS;
|
||||
this.segments = [];
|
||||
this.scheduledFrames = 0;
|
||||
this.completedFrames = 0;
|
||||
this.outputTime = 0;
|
||||
this.pendingClock = null;
|
||||
}
|
||||
}
|
||||
|
||||
private publishClock(allowAdvance = true, force = false): void {
|
||||
if (this.disposed) return;
|
||||
const context = this.context;
|
||||
const now = performance.now();
|
||||
const running = !!context && context.state === "running" && !this.failed && allowAdvance;
|
||||
if (context && !this.failed) {
|
||||
const stamp = context.getOutputTimestamp?.();
|
||||
// getOutputTimestamp already accounts for physical output delay; do not
|
||||
// subtract baseLatency again. Older devices use the explicit latency sum.
|
||||
const time = stamp && typeof stamp.performanceTime === 'number' && typeof stamp.contextTime === 'number' && stamp.performanceTime > 0 && Number.isFinite(stamp.contextTime)
|
||||
? stamp.contextTime + (running ? Math.max(0, now - stamp.performanceTime) / 1000 : 0)
|
||||
: context.currentTime - (context.baseLatency || 0) - (context.outputLatency || 0);
|
||||
this.outputTime = Math.max(this.outputTime, Math.min(context.currentTime, time));
|
||||
}
|
||||
// Retire by device presentation, not AudioBufferSourceNode.onended: that
|
||||
// event describes graph rendering and can precede the actual speaker output.
|
||||
while (this.segments.length && this.outputTime >=
|
||||
this.segments[0].start + this.segments[0].frames / NATIVE_AUDIO_RATE) {
|
||||
const segment = this.segments.shift()!;
|
||||
this.completedFrames = segment.firstFrame + segment.frames;
|
||||
}
|
||||
// Coalesce normal feedback while native code owns the Worker synchronously.
|
||||
// A final freeze bypasses this slot so shutdown cannot leave a running clock.
|
||||
if (allowAdvance && !force && this.pendingClock !== null) return;
|
||||
this.pendingClock = ++this.clockSequence;
|
||||
this.port.postMessage({
|
||||
type: "clock", generation: this.generation,
|
||||
sequence: this.pendingClock,
|
||||
sampledAtMs: performance.timeOrigin + now, outputTime: this.outputTime,
|
||||
running, completedFrames: this.completedFrames, segments: this.segments,
|
||||
} satisfies NativeAudioClock);
|
||||
}
|
||||
|
||||
private finishPreparation(allowAdvance = true): void {
|
||||
if (!this.preparation) return;
|
||||
const sequence = this.preparation.sequence;
|
||||
this.preparation = null;
|
||||
// Same port ordering makes this scheduled device clock visible to the
|
||||
// Worker before it resumes the native command after the acknowledgement.
|
||||
this.publishClock(allowAdvance, true);
|
||||
this.port.postMessage({ type: "prepared", generation: this.generation, sequence } satisfies NativeAudioPrepared);
|
||||
}
|
||||
|
||||
private pull(): void {
|
||||
const context = this.context;
|
||||
if (this.preparation && (this.failed || !context || context.state !== "running" ||
|
||||
performance.timeOrigin + performance.now() >= this.preparation.expiresAtMs)) {
|
||||
this.finishPreparation();
|
||||
}
|
||||
if (this.disposed || this.failed || !context || context.state !== "running" || this.pending !== null) return;
|
||||
const blockTime = NATIVE_AUDIO_FRAMES / NATIVE_AUDIO_RATE;
|
||||
const queued = Math.max(0, this.nextTime - context.currentTime);
|
||||
const target = (this.preparation ? NATIVE_AUDIO_BUSY_BLOCKS : this.bufferBlocks) * blockTime;
|
||||
if (this.preparation && queued >= target - blockTime) {
|
||||
this.finishPreparation();
|
||||
return;
|
||||
}
|
||||
// Refill below the low-water mark in one bounded native batch. During a
|
||||
// command preparation fill the entire reserve, then acknowledge scheduling.
|
||||
if (!this.preparation && queued > target / 2) return;
|
||||
const blocks = Math.min(NATIVE_AUDIO_BUSY_BLOCKS, Math.max(1, Math.ceil((target - queued) / blockTime)));
|
||||
this.pending = ++this.sequence;
|
||||
this.port.postMessage({ type: "pull", generation: this.generation, sequence: this.pending, blocks } satisfies NativeAudioPull);
|
||||
}
|
||||
|
||||
private receive(message: OutputMessage): void {
|
||||
if (this.disposed) return;
|
||||
if (message.type === "reset") {
|
||||
// An old pull can receive the same reset after the native notification.
|
||||
// Do not discard a newer in-flight block on that duplicate acknowledgement.
|
||||
if (message.generation <= this.generation) return;
|
||||
this.generation = message.generation;
|
||||
this.pending = null;
|
||||
this.failed = false;
|
||||
this.flush();
|
||||
this.publishClock();
|
||||
return;
|
||||
}
|
||||
if (message.generation !== this.generation) return;
|
||||
if (message.type === "prepare") {
|
||||
this.preparation = { sequence: message.sequence, expiresAtMs: message.expiresAtMs };
|
||||
this.pull();
|
||||
return;
|
||||
}
|
||||
if (message.type === "clockAck") {
|
||||
if (message.sequence === this.pendingClock) this.pendingClock = null;
|
||||
return;
|
||||
}
|
||||
if (message.type === "error") {
|
||||
this.pending = null;
|
||||
this.flush(false);
|
||||
this.failed = true;
|
||||
this.finishPreparation();
|
||||
this.onError(message.message);
|
||||
return;
|
||||
}
|
||||
if (message.sequence !== this.pending) return;
|
||||
this.pending = null;
|
||||
const context = this.context;
|
||||
if (!message.samples || !context) { this.finishPreparation(); return; }
|
||||
try {
|
||||
const samples = new Float32Array(message.samples);
|
||||
const frames = samples.length / NATIVE_AUDIO_CHANNELS;
|
||||
if (frames < NATIVE_AUDIO_FRAMES || frames > NATIVE_AUDIO_FRAMES * NATIVE_AUDIO_BUSY_BLOCKS ||
|
||||
frames % NATIVE_AUDIO_FRAMES !== 0) throw new Error("Invalid native audio block");
|
||||
const buffer = context.createBuffer(NATIVE_AUDIO_CHANNELS, frames, NATIVE_AUDIO_RATE);
|
||||
for (let channel = 0; channel < NATIVE_AUDIO_CHANNELS; channel++) {
|
||||
const output = buffer.getChannelData(channel);
|
||||
for (let frame = 0; frame < frames; frame++) output[frame] = samples[frame * NATIVE_AUDIO_CHANNELS + channel];
|
||||
}
|
||||
const node = context.createBufferSource();
|
||||
node.buffer = buffer;
|
||||
node.connect(context.destination);
|
||||
node.onended = () => { this.nodes.delete(node); node.disconnect(); };
|
||||
this.nodes.add(node);
|
||||
if (this.nextTime > 0 && this.nextTime <= context.currentTime) {
|
||||
// Never replay missed PCM or pretend the native timeline advanced during
|
||||
// silence. Start a new device-clock segment and increase bounded reserve.
|
||||
this.bufferBlocks = Math.min(NATIVE_AUDIO_RECOVERY_BLOCKS, this.bufferBlocks + 2);
|
||||
}
|
||||
this.nextTime = Math.max(this.nextTime, context.currentTime + 0.005);
|
||||
node.start(this.nextTime);
|
||||
this.segments.push({ start: this.nextTime, frames, firstFrame: this.scheduledFrames });
|
||||
this.scheduledFrames += frames;
|
||||
this.nextTime += buffer.duration;
|
||||
this.publishClock();
|
||||
this.pull();
|
||||
}
|
||||
catch (error) { this.flush(false); this.failed = true; this.finishPreparation(); this.onError(String(error)); }
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.flush(false);
|
||||
this.finishPreparation(false);
|
||||
this.disposed = true;
|
||||
clearInterval(this.timer);
|
||||
window.removeEventListener("pointerdown", this.unlock, true);
|
||||
window.removeEventListener("keydown", this.unlock, true);
|
||||
this.port.close();
|
||||
if (this.context) {
|
||||
this.context.onstatechange = null;
|
||||
void this.context.close().catch(() => {});
|
||||
}
|
||||
this.context = null;
|
||||
}
|
||||
}
|
||||
142
web/app/src/engine-client/NativeResourceClient.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import type {NativeWorkflowInput} from '../../../protocol/native-workflow';
|
||||
import {sha256Hex} from '../../../protocol/render-assets';
|
||||
|
||||
type Binding=NonNullable<NativeWorkflowInput['resources']>;
|
||||
type Stored={archive:Blob;sha256:string};
|
||||
const endpoint='/api/blender-resources';
|
||||
|
||||
async function stored(project:string,value?:Stored|null):Promise<Stored|undefined>{
|
||||
const db=await new Promise<IDBDatabase>((resolve,reject)=>{
|
||||
const request=indexedDB.open('blender-native-resources',1);
|
||||
request.onupgradeneeded=()=>request.result.createObjectStore('projects');
|
||||
request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error);
|
||||
});
|
||||
try{return await new Promise((resolve,reject)=>{
|
||||
const transaction=db.transaction('projects',value===undefined?'readonly':'readwrite');
|
||||
const store=transaction.objectStore('projects');
|
||||
const request=value===undefined?store.get(project):value===null?store.delete(project):store.put(value,project);
|
||||
transaction.oncomplete=()=>resolve(value===undefined?request.result:undefined);
|
||||
transaction.onabort=()=>reject(transaction.error??new Error('RESOURCE_STORAGE_ABORTED'));
|
||||
transaction.onerror=()=>reject(transaction.error);
|
||||
});}finally{db.close();}
|
||||
}
|
||||
|
||||
// Store the actual bytes, not a short-lived service token. Each project has its own archive.
|
||||
export class NativeResourceClient {
|
||||
static removeStoredProject(project:string):Promise<Stored|undefined>{return stored(project,null);}
|
||||
private project:string|null=null;
|
||||
private generation=0;
|
||||
private binding:Binding|undefined;
|
||||
private archive:Stored|undefined;
|
||||
private loaded=false;
|
||||
private pending:Promise<Binding|undefined>|undefined;
|
||||
constructor(){
|
||||
window.addEventListener('pagehide',()=>{
|
||||
const binding=this.binding;this.binding=undefined;
|
||||
if(binding)void fetch(endpoint,{method:'POST',keepalive:true,headers:{'X-Blender-Workflow':'1',
|
||||
'X-Blender-Resource-Action':'release','Content-Type':'application/json'},body:JSON.stringify(binding)}).catch(()=>undefined);
|
||||
});
|
||||
}
|
||||
setProject(project:string|null):void{
|
||||
if(project===this.project)return;
|
||||
const old=this.binding;this.project=project;this.generation++;this.binding=undefined;
|
||||
this.archive=undefined;this.loaded=false;this.pending=undefined;
|
||||
if(old)void this.release(old);
|
||||
}
|
||||
async copyToProject(project:string):Promise<void>{
|
||||
if(!project||project===this.project)throw new Error('RESOURCE_COPY_TARGET_INVALID');
|
||||
const generation=this.generation;
|
||||
await this.resolve();this.assertCurrent(generation);
|
||||
if(this.archive)await stored(project,this.archive);
|
||||
this.assertCurrent(generation);
|
||||
}
|
||||
private assertCurrent(generation:number):void{if(generation!==this.generation)throw new Error('RESOURCE_PROJECT_CHANGED');}
|
||||
private async request(action:string,body:Blob|Binding):Promise<Response>{
|
||||
return fetch(endpoint,{method:'POST',headers:{'X-Blender-Workflow':'1','X-Blender-Resource-Action':action,
|
||||
'Content-Type':body instanceof Blob?'application/octet-stream':'application/json'},
|
||||
body:body instanceof Blob?body:JSON.stringify(body),signal:AbortSignal.timeout(120000)});
|
||||
}
|
||||
private async release(binding:Binding):Promise<void>{await this.request('release',binding).catch(()=>undefined);}
|
||||
private async upload(archive:Blob):Promise<Binding&{files:unknown[]}>{
|
||||
const response=await this.request('upload',archive),result=await response.json();
|
||||
if(!response.ok)throw new Error(result.error??'RESOURCE_UPLOAD_FAILED');
|
||||
if(!/^[a-f0-9]{64}$/.test(result.token)||!/^[a-f0-9]{64}$/.test(result.sha256))throw new Error('RESOURCE_RESULT_BINDING');
|
||||
return result;
|
||||
}
|
||||
private async archiveFor(binding:Binding):Promise<Stored>{
|
||||
const response=await this.request('export',binding);
|
||||
if(!response.ok){const error=await response.json();throw new Error(error.error??'RESOURCE_EXPORT_FAILED');}
|
||||
const archive=await response.blob();
|
||||
if(archive.size>258*1024*1024)throw new Error('RESOURCE_ARCHIVE_BUDGET');
|
||||
const data=await archive.arrayBuffer(),length=new DataView(data).getUint32(4,true);
|
||||
if(new TextDecoder().decode(data.slice(0,4))!=='BAR1'||8+length>data.byteLength||
|
||||
await sha256Hex(data.slice(8,8+length))!==binding.sha256)throw new Error('RESOURCE_ARCHIVE_BINDING');
|
||||
return {archive,sha256:binding.sha256};
|
||||
}
|
||||
async adopt(binding:Binding|undefined):Promise<void>{
|
||||
if(!binding)return;
|
||||
const generation=this.generation,project=this.project;
|
||||
const archive=await this.archiveFor(binding);this.assertCurrent(generation);
|
||||
if(project)await stored(project,archive);this.assertCurrent(generation);
|
||||
const previous=this.binding;this.binding=binding;this.archive=archive;this.loaded=true;
|
||||
if(previous&&previous.token!==binding.token)void this.release(previous);
|
||||
}
|
||||
async sync(archive:Blob,merge=false):Promise<{files:unknown[]}>{
|
||||
const generation=this.generation;
|
||||
if(merge){
|
||||
await this.resolve();this.assertCurrent(generation);
|
||||
if(this.archive){
|
||||
const entries=new Map<string,{metadata:{path:string;bytes:number;sha256:string;sourcePath?:string};bytes:Blob}>();
|
||||
for(const source of [this.archive.archive,archive]){
|
||||
const head=await source.slice(0,8).arrayBuffer();
|
||||
if(new TextDecoder().decode(head.slice(0,4))!=='BAR1')throw new Error('RESOURCE_ENVELOPE_INVALID');
|
||||
const length=new DataView(head).getUint32(4,true),manifest=JSON.parse(await source.slice(8,8+length).text());let offset=8+length;
|
||||
for(const metadata of manifest.files){
|
||||
if(!Number.isSafeInteger(metadata.bytes)||metadata.bytes<0||offset+metadata.bytes>source.size)throw new Error('RESOURCE_MANIFEST_INVALID');
|
||||
const bytes=source.slice(offset,offset+metadata.bytes);offset+=metadata.bytes;
|
||||
if(await sha256Hex(await bytes.arrayBuffer())!==metadata.sha256)throw new Error('RESOURCE_HASH_MISMATCH');
|
||||
entries.set(metadata.path,{metadata,bytes});
|
||||
}
|
||||
if(offset!==source.size)throw new Error('RESOURCE_TRAILING_DATA');
|
||||
}
|
||||
const values=[...entries.values()];
|
||||
if(values.length>4096||values.reduce((total,item)=>total+item.bytes.size,0)>256*1024*1024)throw new Error('RESOURCE_UPLOAD_BUDGET');
|
||||
const metadata=new TextEncoder().encode(JSON.stringify({files:values.map(item=>item.metadata)})),header=new Uint8Array(8);
|
||||
header.set(new TextEncoder().encode('BAR1'));new DataView(header.buffer).setUint32(4,metadata.length,true);
|
||||
archive=new Blob([header,metadata,...values.map(item=>item.bytes)]);
|
||||
}
|
||||
}
|
||||
this.assertCurrent(generation);const result=await this.upload(archive);
|
||||
try{this.assertCurrent(generation);await this.adopt(result);return result;}
|
||||
catch(error){await this.release(result);throw error;}
|
||||
}
|
||||
async resolve():Promise<Binding|undefined>{
|
||||
if(this.pending)return this.pending;
|
||||
const generation=this.generation;
|
||||
const pending=this.restore(generation);this.pending=pending;
|
||||
try{return await pending;}finally{if(this.pending===pending)this.pending=undefined;}
|
||||
}
|
||||
private async restore(generation:number):Promise<Binding|undefined>{
|
||||
if(!this.loaded){
|
||||
const archive=this.project?await stored(this.project):undefined;this.assertCurrent(generation);
|
||||
this.archive=archive;this.loaded=true;
|
||||
}
|
||||
if(!this.archive)return undefined;
|
||||
if(this.binding){
|
||||
const response=await this.request('describe',this.binding);this.assertCurrent(generation);
|
||||
if(response.ok){await response.json();return this.binding;}
|
||||
const result=await response.json();
|
||||
if(result.error!=='RESOURCE_BUNDLE_EXPIRED_OR_CHANGED')throw new Error(result.error??'RESOURCE_RESTORE_FAILED');
|
||||
}
|
||||
const result=await this.upload(this.archive.archive);
|
||||
try{this.assertCurrent(generation);if(result.sha256!==this.archive.sha256)throw new Error('RESOURCE_RESTORE_HASH');}
|
||||
catch(error){await this.release(result);throw error;}
|
||||
this.binding={token:result.token,sha256:result.sha256};return this.binding;
|
||||
}
|
||||
async clear():Promise<void>{
|
||||
const generation=this.generation,project=this.project,old=this.binding;
|
||||
if(project)await stored(project,null);this.assertCurrent(generation);
|
||||
this.generation++;this.binding=undefined;this.archive=undefined;this.loaded=true;this.pending=undefined;
|
||||
if(old)await this.release(old);
|
||||
}
|
||||
}
|
||||