three-base 2.0.142 → 2.0.166

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (231) hide show
  1. package/DirectionalLight.d.ts +6 -6
  2. package/DirectionalLight.js +68 -68
  3. package/EventMap.d.ts +103 -103
  4. package/EventMap.js +17 -17
  5. package/EventMesh.d.ts +18 -18
  6. package/EventMesh.js +59 -59
  7. package/ExtrudeMesh.d.ts +112 -112
  8. package/ExtrudeMesh.js +342 -342
  9. package/FPScontrol.d.ts +531 -511
  10. package/FPScontrol.js +1866 -1799
  11. package/FPScontrol.ts +1922 -1855
  12. package/Fire/Fire.d.ts +28 -28
  13. package/Fire/Fire.js +80 -80
  14. package/Fire/FireGeometry.d.ts +9 -9
  15. package/Fire/FireGeometry.js +40 -40
  16. package/Fire/FireMaterial.d.ts +28 -28
  17. package/Fire/FireMaterial.js +32 -32
  18. package/Fire/index.d.ts +2 -2
  19. package/Fire/index.js +2 -2
  20. package/GLTFDracoLoader.d.ts +71 -71
  21. package/GLTFDracoLoader.js +266 -266
  22. package/GLTFDracoLoader.ts +1 -1
  23. package/Grass/Grass.d.ts +8 -8
  24. package/Grass/Grass.js +38 -38
  25. package/Grass/index.d.ts +2 -2
  26. package/Grass/index.js +2 -2
  27. package/Ground1/Ground1.d.ts +10 -10
  28. package/Ground1/Ground1.js +71 -71
  29. package/Ground1/index.d.ts +1 -1
  30. package/Ground1/index.js +1 -1
  31. package/MeshBase.d.ts +36 -36
  32. package/MeshBase.js +251 -247
  33. package/MeshBase.ts +6 -2
  34. package/Mirror.d.ts +25 -25
  35. package/Mirror.js +143 -143
  36. package/MktMesh/MktMesh.d.ts +301 -291
  37. package/MktMesh/MktMesh.js +1064 -1045
  38. package/MktMesh/MktMesh.ts +32 -11
  39. package/MktMesh/assetUrl.d.ts +59 -35
  40. package/MktMesh/assetUrl.js +165 -69
  41. package/MktMesh/assetUrl.ts +164 -69
  42. package/MktMesh/mktMappingShader.d.ts +12 -12
  43. package/MktMesh/mktMappingShader.js +138 -138
  44. package/MktMesh/mktMappingShader.ts +139 -139
  45. package/MktMesh/mktShader.d.ts +263 -263
  46. package/MktMesh/mktShader.js +1236 -1236
  47. package/MktMesh/mktShader.ts +1344 -1344
  48. package/MktMesh/panoBitmapTexture.d.ts +25 -25
  49. package/MktMesh/panoBitmapTexture.js +52 -52
  50. package/MktMesh/panoBitmapTexture.ts +54 -54
  51. package/MktMesh/panoSlotBind.d.ts +29 -29
  52. package/MktMesh/panoSlotBind.js +106 -106
  53. package/MktMesh/panoSlotBind.ts +153 -153
  54. package/MktMesh/panoSlotRoster.d.ts +22 -22
  55. package/MktMesh/panoSlotRoster.js +169 -169
  56. package/MktMesh/panoSlotRoster.ts +168 -168
  57. package/MktMesh/panoTileStitcher.d.ts +119 -119
  58. package/MktMesh/panoTileStitcher.js +529 -529
  59. package/MktMesh/panoTileStitcher.ts +616 -616
  60. package/MktMesh/types.d.ts +75 -75
  61. package/MktMesh/types.js +1 -1
  62. package/MktMesh/wallCapTessellate.d.ts +33 -33
  63. package/MktMesh/wallCapTessellate.js +97 -97
  64. package/MktMesh/wallCapTessellate.ts +68 -68
  65. package/PipeMesh/PathGeometry.d.ts +44 -44
  66. package/PipeMesh/PathGeometry.js +307 -307
  67. package/PipeMesh/PathPoint.d.ts +17 -17
  68. package/PipeMesh/PathPoint.js +31 -31
  69. package/PipeMesh/PathPointList.d.ts +31 -31
  70. package/PipeMesh/PathPointList.js +209 -209
  71. package/PipeMesh/PathTubeGeometry.d.ts +25 -25
  72. package/PipeMesh/PathTubeGeometry.js +130 -130
  73. package/PipeMesh/PipeMesh.d.ts +25 -25
  74. package/PipeMesh/PipeMesh.js +63 -63
  75. package/PipeMesh/index.d.ts +1 -1
  76. package/PipeMesh/index.js +1 -1
  77. package/PlaneModal1/PlaneModal1.d.ts +34 -34
  78. package/PlaneModal1/PlaneModal1.js +109 -109
  79. package/PlaneModal1/index.d.ts +1 -1
  80. package/PlaneModal1/index.js +1 -1
  81. package/PlaneText.d.ts +27 -27
  82. package/PlaneText.js +35 -35
  83. package/PlaneWithHtml.d.ts +13 -13
  84. package/PlaneWithHtml.js +66 -64
  85. package/PlaneWithHtml.ts +3 -1
  86. package/PointLight/PointLight.d.ts +13 -13
  87. package/PointLight/PointLight.js +64 -64
  88. package/PointLight/index.d.ts +1 -1
  89. package/PointLight/index.js +1 -1
  90. package/Sky/Sky.d.ts +9 -9
  91. package/Sky/Sky.js +22 -22
  92. package/Sky/index.d.ts +1 -1
  93. package/Sky/index.js +1 -1
  94. package/SpotLight.d.ts +6 -6
  95. package/SpotLight.js +72 -72
  96. package/SpriteModal1/SpriteModal1.d.ts +33 -33
  97. package/SpriteModal1/SpriteModal1.js +116 -116
  98. package/SpriteModal1/index.d.ts +1 -1
  99. package/SpriteModal1/index.js +1 -1
  100. package/SpriteText.d.ts +46 -46
  101. package/SpriteText.js +176 -176
  102. package/SpriteText2.d.ts +48 -48
  103. package/SpriteText2.js +223 -223
  104. package/SpriteText3.d.ts +86 -86
  105. package/SpriteText3.js +517 -517
  106. package/SpriteText3.ts +599 -599
  107. package/SpriteWithHtml.d.ts +9 -9
  108. package/SpriteWithHtml.js +46 -44
  109. package/SpriteWithHtml.ts +3 -1
  110. package/Text3D/Text3D.d.ts +20 -20
  111. package/Text3D/Text3D.js +58 -58
  112. package/Text3D/fontController.d.ts +60 -60
  113. package/Text3D/fontController.js +166 -166
  114. package/Text3D/index.d.ts +1 -1
  115. package/Text3D/index.js +1 -1
  116. package/ThreeBase.d.ts +248 -248
  117. package/ThreeBase.js +1202 -1202
  118. package/ThreeBase.ts +1314 -1314
  119. package/ThreeMouse.d.ts +53 -54
  120. package/ThreeMouse.js +453 -453
  121. package/Transition.d.ts +45 -45
  122. package/Transition.js +209 -209
  123. package/Water/Water.d.ts +5 -5
  124. package/Water/Water.js +44 -44
  125. package/Water/index.d.ts +2 -2
  126. package/Water/index.js +2 -2
  127. package/WaterFlow/FloatingDuck.d.ts +88 -88
  128. package/WaterFlow/FloatingDuck.js +307 -307
  129. package/WaterFlow/FloatingDuck.ts +445 -445
  130. package/WaterFlow/GPUFluidSimulation.d.ts +56 -56
  131. package/WaterFlow/GPUFluidSimulation.js +781 -781
  132. package/WaterFlow/GPUFluidSimulation.ts +827 -827
  133. package/WaterFlow/ReservoirSystem.d.ts +106 -106
  134. package/WaterFlow/ReservoirSystem.js +611 -611
  135. package/WaterFlow/ReservoirSystem.ts +754 -754
  136. package/WaterFlow/SPHField.d.ts +35 -35
  137. package/WaterFlow/SPHField.js +203 -203
  138. package/WaterFlow/SPHField.ts +228 -228
  139. package/WaterFlow/ScreenSpaceFluidPass.d.ts +69 -69
  140. package/WaterFlow/ScreenSpaceFluidPass.js +728 -728
  141. package/WaterFlow/ScreenSpaceFluidPass.ts +789 -789
  142. package/WaterFlow/ShallowWaterSurface.d.ts +45 -45
  143. package/WaterFlow/ShallowWaterSurface.js +438 -438
  144. package/WaterFlow/ShallowWaterSurface.ts +510 -510
  145. package/WaterFlow/WaterFlow.d.ts +87 -87
  146. package/WaterFlow/WaterFlow.js +171 -171
  147. package/WaterFlow/WaterFlow.ts +219 -219
  148. package/WaterFlow/types.d.ts +161 -161
  149. package/WaterFlow/types.js +1 -1
  150. package/WaterFlow/types.ts +189 -189
  151. package/WaterFlow/waterFlowPass.d.ts +3 -3
  152. package/WaterFlow/waterFlowPass.js +20 -20
  153. package/WaterFlow/waterFlowPass.ts +40 -40
  154. package/collisionOBB.d.ts +42 -42
  155. package/collisionOBB.js +112 -112
  156. package/collisionOBB.ts +108 -108
  157. package/declare.d.ts +25 -25
  158. package/index.d.ts +1 -1
  159. package/index.js +1 -1
  160. package/instanced/InstancedBatch.d.ts +57 -57
  161. package/instanced/InstancedBatch.js +348 -348
  162. package/instanced/InstancedBatch.ts +406 -406
  163. package/instanced/InstancedChild.d.ts +174 -174
  164. package/instanced/InstancedChild.js +264 -264
  165. package/instanced/InstancedChild.ts +327 -327
  166. package/instanced/InstancedGroup.d.ts +43 -43
  167. package/instanced/InstancedGroup.js +126 -126
  168. package/instanced/InstancedGroup.ts +137 -137
  169. package/instanced/InstancedMeshBase.d.ts +38 -38
  170. package/instanced/InstancedMeshBase.js +282 -282
  171. package/instanced/InstancedTemplate.d.ts +46 -46
  172. package/instanced/InstancedTemplate.js +125 -125
  173. package/keyControls.d.ts +29 -30
  174. package/keyControls.js +101 -101
  175. package/lensflare/LensFlare.d.ts +39 -39
  176. package/lensflare/LensFlare.js +284 -284
  177. package/package.json +6 -1
  178. package/pass/bloom_pass.d.ts +2 -2
  179. package/pass/bloom_pass.js +174 -174
  180. package/pass/cover_pass.d.ts +2 -2
  181. package/pass/cover_pass.js +108 -108
  182. package/pass/debugDepthState.d.ts +20 -20
  183. package/pass/debugDepthState.js +9 -9
  184. package/pass/debugDepthState.ts +22 -22
  185. package/pass/depthTestBias.d.ts +12 -12
  186. package/pass/depthTestBias.js +12 -12
  187. package/pass/depthTestBias.ts +12 -12
  188. package/pass/effectUserData.d.ts +27 -27
  189. package/pass/effectUserData.js +1 -1
  190. package/pass/effectUserData.ts +46 -46
  191. package/pass/frosted_glass_pass.d.ts +2 -2
  192. package/pass/frosted_glass_pass.js +150 -150
  193. package/pass/fsQuad.d.ts +9 -9
  194. package/pass/fsQuad.js +28 -28
  195. package/pass/glow_pass.d.ts +2 -2
  196. package/pass/glow_pass.js +350 -350
  197. package/pass/screen_bloom_pass.d.ts +11 -11
  198. package/pass/screen_bloom_pass.js +136 -136
  199. package/pass/ssao_pass.d.ts +88 -88
  200. package/pass/ssao_pass.js +799 -799
  201. package/pass/ssao_pass.ts +918 -918
  202. package/pass/stroke_pass.d.ts +2 -2
  203. package/pass/stroke_pass.js +267 -267
  204. package/shaders/FXAAShaderMaterial.d.ts +3 -3
  205. package/shaders/FXAAShaderMaterial.js +20 -20
  206. package/shaders/baseDepthVisShader.d.ts +11 -11
  207. package/shaders/baseDepthVisShader.js +36 -36
  208. package/shaders/baseDepthVisShader.ts +36 -36
  209. package/shaders/baseTextureToRenderShader.d.ts +2 -2
  210. package/shaders/baseTextureToRenderShader.js +19 -19
  211. package/shaders/copyShader.d.ts +3 -3
  212. package/shaders/copyShader.js +13 -13
  213. package/shaders/debugDepthCompareShader.d.ts +14 -14
  214. package/shaders/debugDepthCompareShader.js +49 -49
  215. package/shaders/debugDepthCompareShader.ts +50 -50
  216. package/shaders/debugDepthJudgeShader.d.ts +18 -18
  217. package/shaders/debugDepthJudgeShader.js +52 -52
  218. package/shaders/debugDepthJudgeShader.ts +54 -54
  219. package/shaders/debugExcludedShader.d.ts +13 -13
  220. package/shaders/debugExcludedShader.js +46 -46
  221. package/shaders/debugExcludedShader.ts +48 -48
  222. package/spriteTextBg.d.ts +1 -1
  223. package/spriteTextBg.js +20 -20
  224. package/spriteTextBg.ts +20 -20
  225. package/threeLoader.d.ts +35 -35
  226. package/threeLoader.js +518 -518
  227. package/threeUtils.d.ts +71 -53
  228. package/threeUtils.js +363 -329
  229. package/threeUtils.ts +35 -0
  230. package/types.d.ts +2 -2
  231. package/types.js +6 -6
package/threeUtils.js CHANGED
@@ -1,329 +1,363 @@
1
- /*
2
- * @Author: xiaosihan
3
- * @Date: 2022-02-24 22:49:42
4
- * @Last Modified by: xiaosihan
5
- * @Last Modified time: 2023-05-03 00:36:18
6
- */
7
- import { Box3, BufferGeometry, Clock, EventDispatcher, Material, Mesh, MeshBasicMaterial, MeshLambertMaterial, Object3D, Vector3 } from "three";
8
- import { MathUtils } from "three";
9
- const { generateUUID } = MathUtils;
10
- import { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter";
11
- class ThreeUtils extends EventDispatcher {
12
- constructor() {
13
- super();
14
- this.requestAnimationFrame();
15
- }
16
- isProd = typeof process !== 'undefined' && process.env?.NODE_ENV === "production";
17
- isDev = typeof process !== 'undefined' && process.env?.NODE_ENV === "development";
18
- _timeTemp = performance.now();
19
- _accumulate = 0; // 事件分发次数
20
- _box3 = new Box3();
21
- _size = new Vector3();
22
- _center = new Vector3();
23
- _clock = new Clock();
24
- requestAnimationFrame() {
25
- this._accumulate += 1;
26
- const timeTemp = (this._timeTemp = performance.now());
27
- this.dispatchEvent({
28
- type: "requestAnimationFrame",
29
- timeTemp,
30
- accumulate: this._accumulate,
31
- });
32
- this._computerDomZoom();
33
- //执行一个计划任务
34
- let work = this.workList.splice(0, 1)[0];
35
- work && work();
36
- setTimeout(() => {
37
- this.requestAnimationFrame();
38
- }, 30 - this._clock.getDelta());
39
- }
40
- // 需要保持宽高比的元素列表
41
- _keepZoomDoms = [];
42
- /**
43
- *计算需要保持比例的元素
44
- */
45
- _computerDomZoom() {
46
- //1. 踢除没有出现在页面上的 dom 元素
47
- this._keepZoomDoms = this._keepZoomDoms.filter((l) => this.inDocument(l.dom));
48
- //2.设置dom的缩放值样式
49
- this._keepZoomDoms.map((item, i) => {
50
- let parentDom = item.dom.parentNode;
51
- let scale = Math.min(parentDom.clientWidth / item.width, parentDom.clientHeight / item.height);
52
- Object.assign(item.dom.style, {
53
- position: "absolute",
54
- top: "50%",
55
- left: "50%",
56
- transform: `translate(-50%, -50%) scale(${scale})`,
57
- width: `${item.width}px`,
58
- height: `${item.height}px`,
59
- });
60
- });
61
- }
62
- /**
63
- * dom元素保持比例
64
- */
65
- keepZoom(dom, width = 1920, height = 1080) {
66
- if (dom) {
67
- // 去掉相同的dom存储的信息
68
- this._keepZoomDoms = this._keepZoomDoms.filter((l) => l.dom !== dom);
69
- // 把配置加入到列表中
70
- this._keepZoomDoms.push({ dom, width, height });
71
- dom.dataset.a = "这个元素缩放比例由 threeUtils.keepZoom 方法设置";
72
- this._computerDomZoom();
73
- }
74
- }
75
- workList = [];
76
- // 时钟对象
77
- clock = new Clock();
78
- // 按照任务队列依次执行计划任务 性能优化
79
- /**
80
- * @param {() => void} [callback]
81
- * @param {boolean} [first=true] 需要优先执行
82
- */
83
- addWork(work, first = false) {
84
- // 加入任务队列
85
- if (work && !this.workList.includes(work)) {
86
- if (first) {
87
- this.workList.splice(1, 0, work); // 优先执行的任务回调
88
- }
89
- else {
90
- this.workList.push(work);
91
- }
92
- }
93
- }
94
- /**
95
- *判断一个元素是否在页面上
96
- */
97
- inDocument(dom) {
98
- if (dom === null) {
99
- return false;
100
- }
101
- else if (dom.parentNode === null) {
102
- return false;
103
- }
104
- else if (dom.parentNode === document) {
105
- return true;
106
- }
107
- else {
108
- return this.inDocument(dom.parentNode);
109
- }
110
- }
111
- // 获取中心点
112
- getCenter(object3d) {
113
- if (object3d instanceof Object3D) {
114
- this._box3.setFromObject(object3d);
115
- this._box3.getCenter(this._center);
116
- }
117
- else if (object3d instanceof BufferGeometry) {
118
- object3d.computeBoundingBox();
119
- object3d.boundingBox.getCenter(this._center);
120
- }
121
- return this._center.clone();
122
- }
123
- // 获取模型大小
124
- getSize(object3d) {
125
- if (object3d instanceof Object3D) {
126
- this._box3.setFromObject(object3d);
127
- this._box3.getSize(this._size);
128
- }
129
- else if (object3d instanceof BufferGeometry) {
130
- object3d.computeBoundingBox();
131
- object3d.boundingBox.getSize(this._size);
132
- }
133
- return this._size.clone();
134
- }
135
- // 模型对齐底面
136
- alignBottom(object3d, y = 0) {
137
- if (object3d instanceof Object3D) {
138
- this._box3.setFromObject(object3d);
139
- this._box3.getCenter(this._center);
140
- this._box3.getSize(this._size);
141
- object3d.position.y -= this._center.y - this._size.y * 0.5;
142
- object3d.position.y += y;
143
- object3d.updateMatrixWorld(true);
144
- }
145
- else if (object3d instanceof BufferGeometry) {
146
- object3d.computeBoundingBox();
147
- object3d.translate(0, -object3d.boundingBox.min.y + y, 0);
148
- }
149
- }
150
- // 居中对象
151
- centerObject3D(object3d) {
152
- if (object3d instanceof Object3D) {
153
- this._box3.setFromObject(object3d);
154
- this._box3.getCenter(this._center);
155
- object3d.position.sub(this._center);
156
- object3d.updateMatrixWorld(true);
157
- }
158
- else if (object3d instanceof BufferGeometry) {
159
- object3d.center();
160
- }
161
- }
162
- //居中对象
163
- center(object3d) {
164
- this.centerObject3D(object3d);
165
- }
166
- // 使用指定的维度(xyz)计算, 缩放至指定大小;
167
- scaleTo(object3d, size = 1, key = ["x", "y", "z"]) {
168
- const originSize = this.getSize(object3d);
169
- const scale = size / Math.max(...key.map((k) => originSize[k]));
170
- if (object3d.isObject3D) {
171
- object3d.scale.multiplyScalar(scale);
172
- object3d.updateMatrixWorld(true);
173
- }
174
- else if (object3d.isBufferGeometry) {
175
- object3d.scale(scale, scale, scale);
176
- }
177
- }
178
- // 应用全部变化
179
- applyAllTranstion(object3d) {
180
- object3d.updateMatrixWorld(true);
181
- // 应用全部变换
182
- object3d.traverse((obj) => {
183
- obj.position.set(0, 0, 0);
184
- obj.rotation.set(0, 0, 0);
185
- obj.scale.set(1, 1, 1);
186
- if (obj instanceof Mesh) {
187
- obj.geometry.applyMatrix4(obj.matrixWorld);
188
- }
189
- });
190
- }
191
- // 导出 glb
192
- exportGLB(input, fileName = "threeUtils.exportGLB", maxTextureSize = 4096) {
193
- const gltfExporter = new GLTFExporter();
194
- gltfExporter.parse(input, (result) => {
195
- if (result instanceof ArrayBuffer) {
196
- const link = document.createElement("a");
197
- link.style.display = "none";
198
- document.body.appendChild(link); // Firefox workaround, see #6594
199
- link.href = URL.createObjectURL(new Blob([result], { type: "application/octet-stream" }));
200
- link.download = `${fileName}.glb`;
201
- link.click();
202
- }
203
- }, (error) => { }, {
204
- trs: true,
205
- onlyVisible: true,
206
- binary: true,
207
- maxTextureSize: maxTextureSize,
208
- });
209
- }
210
- //导出usdz
211
- exportUsdz() { }
212
- // 计算网格的体积
213
- getVolume(geometry) {
214
- if (!geometry.index)
215
- return 0;
216
- if (!geometry.isBufferGeometry) {
217
- console.warn("'geometry' must be an indexed or non-indexed buffer geometry");
218
- return 0;
219
- }
220
- const isIndexed = geometry.index !== null;
221
- const position = geometry.attributes.position;
222
- let sum = 0;
223
- const p1 = new Vector3(), p2 = new Vector3(), p3 = new Vector3();
224
- if (!isIndexed) {
225
- const faces = position.count / 3;
226
- for (let i = 0; i < faces; i++) {
227
- p1.fromBufferAttribute(position, i * 3 + 0);
228
- p2.fromBufferAttribute(position, i * 3 + 1);
229
- p3.fromBufferAttribute(position, i * 3 + 2);
230
- sum += this.signedVolumeOfTriangle(p1, p2, p3);
231
- }
232
- }
233
- else {
234
- const index = geometry.index;
235
- const faces = index.count / 3;
236
- for (let i = 0; i < faces; i++) {
237
- p1.fromBufferAttribute(position, index.array[i * 3 + 0]);
238
- p2.fromBufferAttribute(position, index.array[i * 3 + 1]);
239
- p3.fromBufferAttribute(position, index.array[i * 3 + 2]);
240
- sum += this.signedVolumeOfTriangle(p1, p2, p3);
241
- }
242
- }
243
- return sum > 0 ? sum : 0;
244
- }
245
- signedVolumeOfTriangle(p1, p2, p3) {
246
- return p1.dot(p2.cross(p3)) / 6.0;
247
- }
248
- //清理对象的网格和材质的缓存
249
- dipose(object3d) {
250
- object3d.traverse((obj) => {
251
- if (obj instanceof Mesh) {
252
- obj.geometry.dispose();
253
- if (obj.material instanceof Material) {
254
- obj.material.dispose();
255
- }
256
- else if (obj.material instanceof Array) {
257
- obj.material.map((m) => {
258
- m.dispose();
259
- });
260
- }
261
- }
262
- });
263
- }
264
- // 获取文件名的后缀
265
- getSuffix(filename) {
266
- const match = filename.match(/([^\.]+)$/);
267
- return match ? match[1].toLowerCase() : "";
268
- }
269
- // 从url 中提取文件名
270
- getFilename(url) {
271
- // 移除URL的查询字符串和哈希部分
272
- const path = url.split("?")[0].split("#")[0];
273
- // 使用lastIndexOf和substring从路径中提取文件名
274
- const filename = path.substring(path.lastIndexOf("/") + 1);
275
- return filename;
276
- }
277
- //文件转blob
278
- fileToBloburl(file) {
279
- return new Promise((resolve, reject) => {
280
- const reader = new FileReader();
281
- reader.onload = function (event) {
282
- const arrayBuffer = event.target.result;
283
- const blob = new Blob([arrayBuffer]);
284
- const bloburl = URL.createObjectURL(blob);
285
- resolve(bloburl);
286
- };
287
- reader.onerror = function (error) {
288
- throw new Error(`文件转blbo 失败,${file.name}`);
289
- };
290
- reader.readAsArrayBuffer(file);
291
- });
292
- }
293
- //材质转为基础材质
294
- toMeshBasicMaterial(material) {
295
- if (material instanceof Array) {
296
- return material.map((m) => this.toMeshBasicMaterial(m));
297
- }
298
- else {
299
- const meshBasicMaterial = new MeshBasicMaterial();
300
- for (let i in meshBasicMaterial) {
301
- if (!["type"].includes(i) &&
302
- meshBasicMaterial.hasOwnProperty(i) &&
303
- material.hasOwnProperty(i)) {
304
- meshBasicMaterial[i] = material[i];
305
- }
306
- }
307
- return meshBasicMaterial;
308
- }
309
- }
310
- toMeshLambertMaterial(material) {
311
- if (material instanceof Array) {
312
- return material.map((m) => this.toMeshLambertMaterial(m));
313
- }
314
- else {
315
- const meshLambertMaterial = new MeshLambertMaterial();
316
- for (let i in meshLambertMaterial) {
317
- if (!["type"].includes(i) &&
318
- meshLambertMaterial.hasOwnProperty(i) &&
319
- material.hasOwnProperty(i)) {
320
- meshLambertMaterial[i] = material[i];
321
- }
322
- }
323
- return meshLambertMaterial;
324
- }
325
- }
326
- }
327
- const threeUtils = new ThreeUtils();
328
- window.threeUtils = threeUtils;
329
- export default threeUtils;
1
+ /*
2
+ * @Author: xiaosihan
3
+ * @Date: 2022-02-24 22:49:42
4
+ * @Last Modified by: xiaosihan
5
+ * @Last Modified time: 2023-05-03 00:36:18
6
+ */
7
+ import { Box3, BufferGeometry, Clock, EventDispatcher, Material, Mesh, MeshBasicMaterial, MeshLambertMaterial, Object3D, Vector3 } from "three";
8
+ import { MathUtils } from "three";
9
+ const { generateUUID } = MathUtils;
10
+ import { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter";
11
+ class ThreeUtils extends EventDispatcher {
12
+ constructor() {
13
+ super();
14
+ this.requestAnimationFrame();
15
+ }
16
+ isProd = typeof process !== 'undefined' && process.env?.NODE_ENV === "production";
17
+ isDev = typeof process !== 'undefined' && process.env?.NODE_ENV === "development";
18
+ _timeTemp = performance.now();
19
+ _accumulate = 0; // 事件分发次数
20
+ _box3 = new Box3();
21
+ _size = new Vector3();
22
+ _center = new Vector3();
23
+ _clock = new Clock();
24
+ requestAnimationFrame() {
25
+ this._accumulate += 1;
26
+ const timeTemp = (this._timeTemp = performance.now());
27
+ this.dispatchEvent({
28
+ type: "requestAnimationFrame",
29
+ timeTemp,
30
+ accumulate: this._accumulate,
31
+ });
32
+ this._computerDomZoom();
33
+ //执行一个计划任务
34
+ let work = this.workList.splice(0, 1)[0];
35
+ work && work();
36
+ // ⭐ 2026-10-09 皇上旨「整条 rAF 链只走 threeUtils 一条」:先结算本帧挂起的「等下一帧」,
37
+ // 再排下一拍 ⇒ 与 dispatchEvent 同拍派发,语义 =「下一帧的此刻」,与原生 rAF 同口径。
38
+ // ⚠️ 必须在 dispatchEvent **之后**结算:挂在事件上的 resolve 期望的就是下一帧,别在同一帧里被清掉。
39
+ this._flushNextFrameWaiters();
40
+ setTimeout(() => {
41
+ this.requestAnimationFrame();
42
+ }, 30 - this._clock.getDelta());
43
+ }
44
+ /**
45
+ * 等下一帧(**本库唯一的「等一帧」入口**,皇上 2026-10-09 旨)。
46
+ *
47
+ * ⛔ 为什么不再用原生 `await new Promise(r => requestAnimationFrame(r))`:
48
+ * 那是**独立于本类主循环的另一个 rAF 回调**,同一帧里与主循环并行跑 ⇒ 每帧多一次调度,
49
+ * 模型多时(如同时加载十几个 GLB,每个都 `awaitLoaded`)会积成每帧几十个回调 ⇒ 卡顿。
50
+ * 走本方法则**全部挂在本类这一条链上**(本类已把节流控到 30ms/帧),零额外调度。
51
+ *
52
+ * 典型用法(原三处`await new Promise(r => requestAnimationFrame(r))` 逐字替换即可):
53
+ * ```ts
54
+ * import threeUtils from "three-base/threeUtils";
55
+ * await threeUtils.waitNextFrame();
56
+ * ```
57
+ */
58
+ waitNextFrame() {
59
+ return new Promise((resolve) => {
60
+ this._nextFrameWaiters.push(resolve);
61
+ });
62
+ }
63
+ /** 结算所有 `waitNextFrame` 的挂起项(每帧由 `requestAnimationFrame` 调一次) */
64
+ _nextFrameWaiters = [];
65
+ _flushNextFrameWaiters() {
66
+ if (this._nextFrameWaiters.length === 0)
67
+ return;
68
+ // 先摘出来再逐个调:回调里可能又挂新的(新挂的要等下一帧,不在本拍结算)
69
+ const waiters = this._nextFrameWaiters;
70
+ this._nextFrameWaiters = [];
71
+ for (const resolve of waiters)
72
+ resolve();
73
+ }
74
+ // 需要保持宽高比的元素列表
75
+ _keepZoomDoms = [];
76
+ /**
77
+ *计算需要保持比例的元素
78
+ */
79
+ _computerDomZoom() {
80
+ //1. 踢除没有出现在页面上的 dom 元素
81
+ this._keepZoomDoms = this._keepZoomDoms.filter((l) => this.inDocument(l.dom));
82
+ //2.设置dom的缩放值样式
83
+ this._keepZoomDoms.map((item, i) => {
84
+ let parentDom = item.dom.parentNode;
85
+ let scale = Math.min(parentDom.clientWidth / item.width, parentDom.clientHeight / item.height);
86
+ Object.assign(item.dom.style, {
87
+ position: "absolute",
88
+ top: "50%",
89
+ left: "50%",
90
+ transform: `translate(-50%, -50%) scale(${scale})`,
91
+ width: `${item.width}px`,
92
+ height: `${item.height}px`,
93
+ });
94
+ });
95
+ }
96
+ /**
97
+ * dom元素保持比例
98
+ */
99
+ keepZoom(dom, width = 1920, height = 1080) {
100
+ if (dom) {
101
+ // 去掉相同的dom存储的信息
102
+ this._keepZoomDoms = this._keepZoomDoms.filter((l) => l.dom !== dom);
103
+ // 把配置加入到列表中
104
+ this._keepZoomDoms.push({ dom, width, height });
105
+ dom.dataset.a = "这个元素缩放比例由 threeUtils.keepZoom 方法设置";
106
+ this._computerDomZoom();
107
+ }
108
+ }
109
+ workList = [];
110
+ // 时钟对象
111
+ clock = new Clock();
112
+ // 按照任务队列依次执行计划任务 性能优化
113
+ /**
114
+ * @param {() => void} [callback]
115
+ * @param {boolean} [first=true] 需要优先执行
116
+ */
117
+ addWork(work, first = false) {
118
+ // 加入任务队列
119
+ if (work && !this.workList.includes(work)) {
120
+ if (first) {
121
+ this.workList.splice(1, 0, work); // 优先执行的任务回调
122
+ }
123
+ else {
124
+ this.workList.push(work);
125
+ }
126
+ }
127
+ }
128
+ /**
129
+ *判断一个元素是否在页面上
130
+ */
131
+ inDocument(dom) {
132
+ if (dom === null) {
133
+ return false;
134
+ }
135
+ else if (dom.parentNode === null) {
136
+ return false;
137
+ }
138
+ else if (dom.parentNode === document) {
139
+ return true;
140
+ }
141
+ else {
142
+ return this.inDocument(dom.parentNode);
143
+ }
144
+ }
145
+ // 获取中心点
146
+ getCenter(object3d) {
147
+ if (object3d instanceof Object3D) {
148
+ this._box3.setFromObject(object3d);
149
+ this._box3.getCenter(this._center);
150
+ }
151
+ else if (object3d instanceof BufferGeometry) {
152
+ object3d.computeBoundingBox();
153
+ object3d.boundingBox.getCenter(this._center);
154
+ }
155
+ return this._center.clone();
156
+ }
157
+ // 获取模型大小
158
+ getSize(object3d) {
159
+ if (object3d instanceof Object3D) {
160
+ this._box3.setFromObject(object3d);
161
+ this._box3.getSize(this._size);
162
+ }
163
+ else if (object3d instanceof BufferGeometry) {
164
+ object3d.computeBoundingBox();
165
+ object3d.boundingBox.getSize(this._size);
166
+ }
167
+ return this._size.clone();
168
+ }
169
+ // 模型对齐底面
170
+ alignBottom(object3d, y = 0) {
171
+ if (object3d instanceof Object3D) {
172
+ this._box3.setFromObject(object3d);
173
+ this._box3.getCenter(this._center);
174
+ this._box3.getSize(this._size);
175
+ object3d.position.y -= this._center.y - this._size.y * 0.5;
176
+ object3d.position.y += y;
177
+ object3d.updateMatrixWorld(true);
178
+ }
179
+ else if (object3d instanceof BufferGeometry) {
180
+ object3d.computeBoundingBox();
181
+ object3d.translate(0, -object3d.boundingBox.min.y + y, 0);
182
+ }
183
+ }
184
+ // 居中对象
185
+ centerObject3D(object3d) {
186
+ if (object3d instanceof Object3D) {
187
+ this._box3.setFromObject(object3d);
188
+ this._box3.getCenter(this._center);
189
+ object3d.position.sub(this._center);
190
+ object3d.updateMatrixWorld(true);
191
+ }
192
+ else if (object3d instanceof BufferGeometry) {
193
+ object3d.center();
194
+ }
195
+ }
196
+ //居中对象
197
+ center(object3d) {
198
+ this.centerObject3D(object3d);
199
+ }
200
+ // 使用指定的维度(xyz)计算, 缩放至指定大小;
201
+ scaleTo(object3d, size = 1, key = ["x", "y", "z"]) {
202
+ const originSize = this.getSize(object3d);
203
+ const scale = size / Math.max(...key.map((k) => originSize[k]));
204
+ if (object3d.isObject3D) {
205
+ object3d.scale.multiplyScalar(scale);
206
+ object3d.updateMatrixWorld(true);
207
+ }
208
+ else if (object3d.isBufferGeometry) {
209
+ object3d.scale(scale, scale, scale);
210
+ }
211
+ }
212
+ // 应用全部变化
213
+ applyAllTranstion(object3d) {
214
+ object3d.updateMatrixWorld(true);
215
+ // 应用全部变换
216
+ object3d.traverse((obj) => {
217
+ obj.position.set(0, 0, 0);
218
+ obj.rotation.set(0, 0, 0);
219
+ obj.scale.set(1, 1, 1);
220
+ if (obj instanceof Mesh) {
221
+ obj.geometry.applyMatrix4(obj.matrixWorld);
222
+ }
223
+ });
224
+ }
225
+ // 导出 glb
226
+ exportGLB(input, fileName = "threeUtils.exportGLB", maxTextureSize = 4096) {
227
+ const gltfExporter = new GLTFExporter();
228
+ gltfExporter.parse(input, (result) => {
229
+ if (result instanceof ArrayBuffer) {
230
+ const link = document.createElement("a");
231
+ link.style.display = "none";
232
+ document.body.appendChild(link); // Firefox workaround, see #6594
233
+ link.href = URL.createObjectURL(new Blob([result], { type: "application/octet-stream" }));
234
+ link.download = `${fileName}.glb`;
235
+ link.click();
236
+ }
237
+ }, (error) => { }, {
238
+ trs: true,
239
+ onlyVisible: true, // 只导出可见的
240
+ binary: true, // glb
241
+ maxTextureSize: maxTextureSize,
242
+ });
243
+ }
244
+ //导出usdz
245
+ exportUsdz() { }
246
+ // 计算网格的体积
247
+ getVolume(geometry) {
248
+ if (!geometry.index)
249
+ return 0;
250
+ if (!geometry.isBufferGeometry) {
251
+ console.warn("'geometry' must be an indexed or non-indexed buffer geometry");
252
+ return 0;
253
+ }
254
+ const isIndexed = geometry.index !== null;
255
+ const position = geometry.attributes.position;
256
+ let sum = 0;
257
+ const p1 = new Vector3(), p2 = new Vector3(), p3 = new Vector3();
258
+ if (!isIndexed) {
259
+ const faces = position.count / 3;
260
+ for (let i = 0; i < faces; i++) {
261
+ p1.fromBufferAttribute(position, i * 3 + 0);
262
+ p2.fromBufferAttribute(position, i * 3 + 1);
263
+ p3.fromBufferAttribute(position, i * 3 + 2);
264
+ sum += this.signedVolumeOfTriangle(p1, p2, p3);
265
+ }
266
+ }
267
+ else {
268
+ const index = geometry.index;
269
+ const faces = index.count / 3;
270
+ for (let i = 0; i < faces; i++) {
271
+ p1.fromBufferAttribute(position, index.array[i * 3 + 0]);
272
+ p2.fromBufferAttribute(position, index.array[i * 3 + 1]);
273
+ p3.fromBufferAttribute(position, index.array[i * 3 + 2]);
274
+ sum += this.signedVolumeOfTriangle(p1, p2, p3);
275
+ }
276
+ }
277
+ return sum > 0 ? sum : 0;
278
+ }
279
+ signedVolumeOfTriangle(p1, p2, p3) {
280
+ return p1.dot(p2.cross(p3)) / 6.0;
281
+ }
282
+ //清理对象的网格和材质的缓存
283
+ dipose(object3d) {
284
+ object3d.traverse((obj) => {
285
+ if (obj instanceof Mesh) {
286
+ obj.geometry.dispose();
287
+ if (obj.material instanceof Material) {
288
+ obj.material.dispose();
289
+ }
290
+ else if (obj.material instanceof Array) {
291
+ obj.material.map((m) => {
292
+ m.dispose();
293
+ });
294
+ }
295
+ }
296
+ });
297
+ }
298
+ // 获取文件名的后缀
299
+ getSuffix(filename) {
300
+ const match = filename.match(/([^\.]+)$/);
301
+ return match ? match[1].toLowerCase() : "";
302
+ }
303
+ // 从url 中提取文件名
304
+ getFilename(url) {
305
+ // 移除URL的查询字符串和哈希部分
306
+ const path = url.split("?")[0].split("#")[0];
307
+ // 使用lastIndexOf和substring从路径中提取文件名
308
+ const filename = path.substring(path.lastIndexOf("/") + 1);
309
+ return filename;
310
+ }
311
+ //文件转blob
312
+ fileToBloburl(file) {
313
+ return new Promise((resolve, reject) => {
314
+ const reader = new FileReader();
315
+ reader.onload = function (event) {
316
+ const arrayBuffer = event.target.result;
317
+ const blob = new Blob([arrayBuffer]);
318
+ const bloburl = URL.createObjectURL(blob);
319
+ resolve(bloburl);
320
+ };
321
+ reader.onerror = function (error) {
322
+ throw new Error(`文件转blbo 失败,${file.name}`);
323
+ };
324
+ reader.readAsArrayBuffer(file);
325
+ });
326
+ }
327
+ //材质转为基础材质
328
+ toMeshBasicMaterial(material) {
329
+ if (material instanceof Array) {
330
+ return material.map((m) => this.toMeshBasicMaterial(m));
331
+ }
332
+ else {
333
+ const meshBasicMaterial = new MeshBasicMaterial();
334
+ for (let i in meshBasicMaterial) {
335
+ if (!["type"].includes(i) &&
336
+ meshBasicMaterial.hasOwnProperty(i) &&
337
+ material.hasOwnProperty(i)) {
338
+ meshBasicMaterial[i] = material[i];
339
+ }
340
+ }
341
+ return meshBasicMaterial;
342
+ }
343
+ }
344
+ toMeshLambertMaterial(material) {
345
+ if (material instanceof Array) {
346
+ return material.map((m) => this.toMeshLambertMaterial(m));
347
+ }
348
+ else {
349
+ const meshLambertMaterial = new MeshLambertMaterial();
350
+ for (let i in meshLambertMaterial) {
351
+ if (!["type"].includes(i) &&
352
+ meshLambertMaterial.hasOwnProperty(i) &&
353
+ material.hasOwnProperty(i)) {
354
+ meshLambertMaterial[i] = material[i];
355
+ }
356
+ }
357
+ return meshLambertMaterial;
358
+ }
359
+ }
360
+ }
361
+ const threeUtils = new ThreeUtils();
362
+ window.threeUtils = threeUtils;
363
+ export default threeUtils;