@hozo/three 0.1.0

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 (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +389 -0
  3. package/conformance.md +335 -0
  4. package/dist/accessible-controls.d.ts +55 -0
  5. package/dist/accessible-controls.d.ts.map +1 -0
  6. package/dist/accessible-controls.js +82 -0
  7. package/dist/accessible-controls.js.map +1 -0
  8. package/dist/conformance-scenes.d.ts +39 -0
  9. package/dist/conformance-scenes.d.ts.map +1 -0
  10. package/dist/conformance-scenes.js +443 -0
  11. package/dist/conformance-scenes.js.map +1 -0
  12. package/dist/index.d.ts +4 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +3 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/line-gradient.d.ts +13 -0
  17. package/dist/line-gradient.d.ts.map +1 -0
  18. package/dist/line-gradient.js +104 -0
  19. package/dist/line-gradient.js.map +1 -0
  20. package/dist/project.d.ts +23 -0
  21. package/dist/project.d.ts.map +1 -0
  22. package/dist/project.js +2298 -0
  23. package/dist/project.js.map +1 -0
  24. package/dist/r3f-accessibility.d.ts +30 -0
  25. package/dist/r3f-accessibility.d.ts.map +1 -0
  26. package/dist/r3f-accessibility.js +4 -0
  27. package/dist/r3f-accessibility.js.map +1 -0
  28. package/dist/r3f-native-unavailable.d.ts +5 -0
  29. package/dist/r3f-native-unavailable.d.ts.map +1 -0
  30. package/dist/r3f-native-unavailable.js +5 -0
  31. package/dist/r3f-native-unavailable.js.map +1 -0
  32. package/dist/r3f-native.d.ts +23 -0
  33. package/dist/r3f-native.d.ts.map +1 -0
  34. package/dist/r3f-native.js +66 -0
  35. package/dist/r3f-native.js.map +1 -0
  36. package/dist/r3f-react-native.d.ts +5 -0
  37. package/dist/r3f-react-native.d.ts.map +1 -0
  38. package/dist/r3f-react-native.js +5 -0
  39. package/dist/r3f-react-native.js.map +1 -0
  40. package/dist/r3f.d.ts +39 -0
  41. package/dist/r3f.d.ts.map +1 -0
  42. package/dist/r3f.js +41 -0
  43. package/dist/r3f.js.map +1 -0
  44. package/dist/surface.d.ts +81 -0
  45. package/dist/surface.d.ts.map +1 -0
  46. package/dist/surface.js +79 -0
  47. package/dist/surface.js.map +1 -0
  48. package/dist/three-canvas.d.ts +42 -0
  49. package/dist/three-canvas.d.ts.map +1 -0
  50. package/dist/three-canvas.js +91 -0
  51. package/dist/three-canvas.js.map +1 -0
  52. package/dist/web-surface.d.ts +55 -0
  53. package/dist/web-surface.d.ts.map +1 -0
  54. package/dist/web-surface.js +285 -0
  55. package/dist/web-surface.js.map +1 -0
  56. package/dist/webgl-react-native.d.ts +5 -0
  57. package/dist/webgl-react-native.d.ts.map +1 -0
  58. package/dist/webgl-react-native.js +5 -0
  59. package/dist/webgl-react-native.js.map +1 -0
  60. package/dist/webgl-renderer.d.ts +14 -0
  61. package/dist/webgl-renderer.d.ts.map +1 -0
  62. package/dist/webgl-renderer.js +13 -0
  63. package/dist/webgl-renderer.js.map +1 -0
  64. package/dist/webgpu-react-native.d.ts +5 -0
  65. package/dist/webgpu-react-native.d.ts.map +1 -0
  66. package/dist/webgpu-react-native.js +5 -0
  67. package/dist/webgpu-react-native.js.map +1 -0
  68. package/dist/webgpu.d.ts +18 -0
  69. package/dist/webgpu.d.ts.map +1 -0
  70. package/dist/webgpu.js +29 -0
  71. package/dist/webgpu.js.map +1 -0
  72. package/package.json +122 -0
  73. package/scene-conformance.json +244 -0
  74. package/scene-conformance.md +31 -0
  75. package/src/accessible-controls.ts +84 -0
  76. package/src/conformance-scenes.ts +529 -0
  77. package/src/index.ts +24 -0
  78. package/src/line-gradient.ts +134 -0
  79. package/src/project.ts +2742 -0
  80. package/src/r3f-accessibility.ts +37 -0
  81. package/src/r3f-native-unavailable.tsx +15 -0
  82. package/src/r3f-native.tsx +187 -0
  83. package/src/r3f-react-native.tsx +17 -0
  84. package/src/r3f.tsx +159 -0
  85. package/src/surface.ts +178 -0
  86. package/src/three-canvas.tsx +215 -0
  87. package/src/web-surface.tsx +475 -0
  88. package/src/webgl-react-native.tsx +17 -0
  89. package/src/webgl-renderer.tsx +56 -0
  90. package/src/webgpu-react-native.tsx +17 -0
  91. package/src/webgpu.tsx +71 -0
@@ -0,0 +1,2298 @@
1
+ import { BackSide, ClampToEdgeWrapping, Color, ColorManagement, DoubleSide, LessEqualDepth, LinearSRGBColorSpace, Matrix3, Matrix4, Mesh, MirroredRepeatWrapping, NearestFilter, NormalBlending, RepeatWrapping, SRGBColorSpace, UVMapping, Vector2, Vector3, Vector4, } from 'three';
2
+ import { portableLineColorStops } from './line-gradient.js';
3
+ function isColorBackground(background) {
4
+ return background !== null && background.isColor === true;
5
+ }
6
+ function isTextureBackground(background) {
7
+ return background !== null && background.isTexture === true;
8
+ }
9
+ function fogReason(fog) {
10
+ if (fog.isFogExp2 === true) {
11
+ const density = fog.density;
12
+ if (!Number.isFinite(density) || density < 0) {
13
+ return 'FogExp2 density must be finite and non-negative.';
14
+ }
15
+ return undefined;
16
+ }
17
+ const linear = fog;
18
+ if (![linear.near, linear.far].every(Number.isFinite) || linear.far <= linear.near) {
19
+ return 'Fog near and far must be finite, with far greater than near.';
20
+ }
21
+ return undefined;
22
+ }
23
+ function fogFactor(fog, viewDepth) {
24
+ if (fog.isFogExp2 === true) {
25
+ const density = fog.density;
26
+ return Math.max(0, Math.min(1, 1 - Math.exp(-(density * density * viewDepth * viewDepth))));
27
+ }
28
+ const { near, far } = fog;
29
+ const normalized = Math.max(0, Math.min(1, (viewDepth - near) / (far - near)));
30
+ return normalized * normalized * (3 - 2 * normalized);
31
+ }
32
+ function foggedColorAtDepth(color, fog, viewDepth) {
33
+ return fog ? color.clone().lerp(fog.color, fogFactor(fog, viewDepth)) : color.clone();
34
+ }
35
+ function foggedColorAtWorld(color, fog, world, viewMatrix) {
36
+ if (!fog)
37
+ return color.clone();
38
+ return foggedColorAtDepth(color, fog, -world.clone().applyMatrix4(viewMatrix).z);
39
+ }
40
+ const clipPlanes = [
41
+ (point) => point.w + point.x,
42
+ (point) => point.w - point.x,
43
+ (point) => point.w + point.y,
44
+ (point) => point.w - point.y,
45
+ (point) => point.w + point.z,
46
+ (point) => point.w - point.z,
47
+ ];
48
+ function clippedPolygon(triangle) {
49
+ let polygon = triangle.map((point) => point.clone());
50
+ for (const distance of clipPlanes) {
51
+ if (polygon.length === 0)
52
+ return polygon;
53
+ const clipped = [];
54
+ let previous = polygon.at(-1);
55
+ let previousDistance = distance(previous);
56
+ for (const current of polygon) {
57
+ const currentDistance = distance(current);
58
+ const previousInside = previousDistance >= 0;
59
+ const currentInside = currentDistance >= 0;
60
+ if (previousInside !== currentInside) {
61
+ const denominator = previousDistance - currentDistance;
62
+ if (denominator !== 0) {
63
+ clipped.push(previous.clone().lerp(current, previousDistance / denominator));
64
+ }
65
+ }
66
+ if (currentInside)
67
+ clipped.push(current.clone());
68
+ previous = current;
69
+ previousDistance = currentDistance;
70
+ }
71
+ polygon = clipped;
72
+ }
73
+ return polygon;
74
+ }
75
+ function interpolateColouredVertex(from, to, ratio) {
76
+ return {
77
+ alpha: from.alpha === undefined && to.alpha === undefined
78
+ ? undefined
79
+ : (from.alpha ?? 1) + ((to.alpha ?? 1) - (from.alpha ?? 1)) * ratio,
80
+ color: from.color.clone().lerp(to.color, ratio),
81
+ position: from.position.clone().lerp(to.position, ratio),
82
+ viewDepth: from.viewDepth === undefined || to.viewDepth === undefined
83
+ ? undefined
84
+ : from.viewDepth + (to.viewDepth - from.viewDepth) * ratio,
85
+ };
86
+ }
87
+ function clippedColouredPolygon(triangle) {
88
+ let polygon = triangle.map(({ alpha, color, position, viewDepth }) => ({
89
+ alpha,
90
+ color: color.clone(),
91
+ position: position.clone(),
92
+ viewDepth,
93
+ }));
94
+ for (const distance of clipPlanes) {
95
+ if (polygon.length === 0)
96
+ return polygon;
97
+ const clipped = [];
98
+ let previous = polygon.at(-1);
99
+ let previousDistance = distance(previous.position);
100
+ for (const current of polygon) {
101
+ const currentDistance = distance(current.position);
102
+ const previousInside = previousDistance >= 0;
103
+ const currentInside = currentDistance >= 0;
104
+ if (previousInside !== currentInside) {
105
+ const denominator = previousDistance - currentDistance;
106
+ if (denominator !== 0) {
107
+ clipped.push(interpolateColouredVertex(previous, current, previousDistance / denominator));
108
+ }
109
+ }
110
+ if (currentInside) {
111
+ clipped.push({
112
+ alpha: current.alpha,
113
+ color: current.color.clone(),
114
+ position: current.position.clone(),
115
+ viewDepth: current.viewDepth,
116
+ });
117
+ }
118
+ previous = current;
119
+ previousDistance = currentDistance;
120
+ }
121
+ polygon = clipped;
122
+ }
123
+ return polygon;
124
+ }
125
+ function cloneTexturedVertex(vertex) {
126
+ return { position: vertex.position.clone(), texture: vertex.texture.clone() };
127
+ }
128
+ function interpolateTexturedVertex(from, to, ratio) {
129
+ return {
130
+ position: from.position.clone().lerp(to.position, ratio),
131
+ texture: from.texture.clone().lerp(to.texture, ratio),
132
+ };
133
+ }
134
+ function clippedTexturedPolygon(triangle) {
135
+ let polygon = triangle.map(cloneTexturedVertex);
136
+ for (const distance of clipPlanes) {
137
+ if (polygon.length === 0)
138
+ return polygon;
139
+ const clipped = [];
140
+ let previous = polygon.at(-1);
141
+ let previousDistance = distance(previous.position);
142
+ for (const current of polygon) {
143
+ const currentDistance = distance(current.position);
144
+ const previousInside = previousDistance >= 0;
145
+ const currentInside = currentDistance >= 0;
146
+ if (previousInside !== currentInside) {
147
+ const denominator = previousDistance - currentDistance;
148
+ if (denominator !== 0) {
149
+ clipped.push(interpolateTexturedVertex(previous, current, previousDistance / denominator));
150
+ }
151
+ }
152
+ if (currentInside)
153
+ clipped.push(cloneTexturedVertex(current));
154
+ previous = current;
155
+ previousDistance = currentDistance;
156
+ }
157
+ polygon = clipped;
158
+ }
159
+ return polygon;
160
+ }
161
+ function clippedSegment(from, to) {
162
+ let start = from.clone();
163
+ let end = to.clone();
164
+ for (const distance of clipPlanes) {
165
+ const startDistance = distance(start);
166
+ const endDistance = distance(end);
167
+ if (startDistance < 0 && endDistance < 0)
168
+ return undefined;
169
+ if (startDistance >= 0 && endDistance >= 0)
170
+ continue;
171
+ const crossing = start.clone().lerp(end, startDistance / (startDistance - endDistance));
172
+ if (startDistance < 0)
173
+ start = crossing;
174
+ else
175
+ end = crossing;
176
+ }
177
+ return [start, end];
178
+ }
179
+ function planeDistance(plane, point) {
180
+ return (plane.normal.x * point.x + plane.normal.y * point.y + plane.normal.z * point.z + plane.constant);
181
+ }
182
+ function clippedMaterialPolygonSide(source, plane, keepInside) {
183
+ if (source.length === 0)
184
+ return [];
185
+ const clipped = [];
186
+ let previous = source.at(-1);
187
+ let previousDistance = planeDistance(plane, previous);
188
+ for (const current of source) {
189
+ const currentDistance = planeDistance(plane, current);
190
+ const previousInside = keepInside ? previousDistance >= 0 : previousDistance < 0;
191
+ const currentInside = keepInside ? currentDistance >= 0 : currentDistance < 0;
192
+ if (previousInside !== currentInside) {
193
+ const denominator = previousDistance - currentDistance;
194
+ if (denominator !== 0) {
195
+ clipped.push(previous.clone().lerp(current, previousDistance / denominator));
196
+ }
197
+ }
198
+ if (currentInside)
199
+ clipped.push(current.clone());
200
+ previous = current;
201
+ previousDistance = currentDistance;
202
+ }
203
+ return clipped;
204
+ }
205
+ function clippedMaterialPolygons(source, planes, clipIntersection) {
206
+ if (planes.length === 0)
207
+ return [source.map((point) => point.clone())];
208
+ if (!clipIntersection) {
209
+ let polygon = source.map((point) => point.clone());
210
+ for (const plane of planes)
211
+ polygon = clippedMaterialPolygonSide(polygon, plane, true);
212
+ return polygon.length >= 3 ? [polygon] : [];
213
+ }
214
+ let remaining = source.map((point) => point.clone());
215
+ const retained = [];
216
+ for (const plane of planes) {
217
+ const inside = clippedMaterialPolygonSide(remaining, plane, true);
218
+ if (inside.length >= 3)
219
+ retained.push(inside);
220
+ remaining = clippedMaterialPolygonSide(remaining, plane, false);
221
+ if (remaining.length < 3)
222
+ break;
223
+ }
224
+ return retained;
225
+ }
226
+ function clippedMaterialColouredPolygonSide(source, plane, keepInside) {
227
+ if (source.length === 0)
228
+ return [];
229
+ const clipped = [];
230
+ let previous = source.at(-1);
231
+ let previousDistance = planeDistance(plane, previous.position);
232
+ for (const current of source) {
233
+ const currentDistance = planeDistance(plane, current.position);
234
+ const previousInside = keepInside ? previousDistance >= 0 : previousDistance < 0;
235
+ const currentInside = keepInside ? currentDistance >= 0 : currentDistance < 0;
236
+ if (previousInside !== currentInside) {
237
+ const denominator = previousDistance - currentDistance;
238
+ if (denominator !== 0) {
239
+ clipped.push(interpolateColouredVertex(previous, current, previousDistance / denominator));
240
+ }
241
+ }
242
+ if (currentInside) {
243
+ clipped.push({
244
+ alpha: current.alpha,
245
+ color: current.color.clone(),
246
+ position: current.position.clone(),
247
+ viewDepth: current.viewDepth,
248
+ });
249
+ }
250
+ previous = current;
251
+ previousDistance = currentDistance;
252
+ }
253
+ return clipped;
254
+ }
255
+ function clippedMaterialColouredPolygons(source, planes, clipIntersection) {
256
+ const clone = (vertices) => vertices.map(({ alpha, color, position, viewDepth }) => ({
257
+ alpha,
258
+ color: color.clone(),
259
+ position: position.clone(),
260
+ viewDepth,
261
+ }));
262
+ if (planes.length === 0)
263
+ return [clone(source)];
264
+ if (!clipIntersection) {
265
+ let polygon = clone(source);
266
+ for (const plane of planes) {
267
+ polygon = clippedMaterialColouredPolygonSide(polygon, plane, true);
268
+ }
269
+ return polygon.length >= 3 ? [polygon] : [];
270
+ }
271
+ let remaining = clone(source);
272
+ const retained = [];
273
+ for (const plane of planes) {
274
+ const inside = clippedMaterialColouredPolygonSide(remaining, plane, true);
275
+ if (inside.length >= 3)
276
+ retained.push(inside);
277
+ remaining = clippedMaterialColouredPolygonSide(remaining, plane, false);
278
+ if (remaining.length < 3)
279
+ break;
280
+ }
281
+ return retained;
282
+ }
283
+ function clippedMaterialTexturedPolygonSide(source, plane, keepInside) {
284
+ if (source.length === 0)
285
+ return [];
286
+ const clipped = [];
287
+ let previous = source.at(-1);
288
+ let previousDistance = planeDistance(plane, previous.position);
289
+ for (const current of source) {
290
+ const currentDistance = planeDistance(plane, current.position);
291
+ const previousInside = keepInside ? previousDistance >= 0 : previousDistance < 0;
292
+ const currentInside = keepInside ? currentDistance >= 0 : currentDistance < 0;
293
+ if (previousInside !== currentInside) {
294
+ const denominator = previousDistance - currentDistance;
295
+ if (denominator !== 0) {
296
+ clipped.push(interpolateTexturedVertex(previous, current, previousDistance / denominator));
297
+ }
298
+ }
299
+ if (currentInside)
300
+ clipped.push(cloneTexturedVertex(current));
301
+ previous = current;
302
+ previousDistance = currentDistance;
303
+ }
304
+ return clipped;
305
+ }
306
+ function clippedMaterialTexturedPolygons(source, planes, clipIntersection) {
307
+ if (planes.length === 0)
308
+ return [source.map(cloneTexturedVertex)];
309
+ if (!clipIntersection) {
310
+ let polygon = source.map(cloneTexturedVertex);
311
+ for (const plane of planes) {
312
+ polygon = clippedMaterialTexturedPolygonSide(polygon, plane, true);
313
+ }
314
+ return polygon.length >= 3 ? [polygon] : [];
315
+ }
316
+ let remaining = source.map(cloneTexturedVertex);
317
+ const retained = [];
318
+ for (const plane of planes) {
319
+ const inside = clippedMaterialTexturedPolygonSide(remaining, plane, true);
320
+ if (inside.length >= 3)
321
+ retained.push(inside);
322
+ remaining = clippedMaterialTexturedPolygonSide(remaining, plane, false);
323
+ if (remaining.length < 3)
324
+ break;
325
+ }
326
+ return retained;
327
+ }
328
+ function clippedMaterialSegmentSide(from, to, plane, keepInside) {
329
+ const startDistance = planeDistance(plane, from);
330
+ const endDistance = planeDistance(plane, to);
331
+ const startInside = keepInside ? startDistance >= 0 : startDistance < 0;
332
+ const endInside = keepInside ? endDistance >= 0 : endDistance < 0;
333
+ if (!startInside && !endInside)
334
+ return undefined;
335
+ if (startInside && endInside)
336
+ return [from.clone(), to.clone()];
337
+ const crossing = from.clone().lerp(to, startDistance / (startDistance - endDistance));
338
+ return startInside ? [from.clone(), crossing] : [crossing, to.clone()];
339
+ }
340
+ function clippedMaterialSegments(from, to, planes, clipIntersection) {
341
+ if (planes.length === 0)
342
+ return [[from.clone(), to.clone()]];
343
+ if (!clipIntersection) {
344
+ let segment = [from.clone(), to.clone()];
345
+ for (const plane of planes) {
346
+ segment = clippedMaterialSegmentSide(segment[0], segment[1], plane, true);
347
+ if (!segment)
348
+ return [];
349
+ }
350
+ return [segment];
351
+ }
352
+ let remaining = [from.clone(), to.clone()];
353
+ const retained = [];
354
+ for (const plane of planes) {
355
+ if (!remaining)
356
+ break;
357
+ const inside = clippedMaterialSegmentSide(remaining[0], remaining[1], plane, true);
358
+ if (inside)
359
+ retained.push(inside);
360
+ remaining = clippedMaterialSegmentSide(remaining[0], remaining[1], plane, false);
361
+ }
362
+ return retained;
363
+ }
364
+ function segmentRatio(point, from, to) {
365
+ const dx = to.x - from.x;
366
+ const dy = to.y - from.y;
367
+ const dz = to.z - from.z;
368
+ const dw = to.w - from.w;
369
+ const denominator = dx * dx + dy * dy + dz * dz + dw * dw;
370
+ if (denominator === 0)
371
+ return 0;
372
+ return Math.max(0, Math.min(1, ((point.x - from.x) * dx +
373
+ (point.y - from.y) * dy +
374
+ (point.z - from.z) * dz +
375
+ (point.w - from.w) * dw) /
376
+ denominator));
377
+ }
378
+ function positiveModulo(value, divisor) {
379
+ return value - divisor * Math.floor(value / divisor);
380
+ }
381
+ function dashedSegments(from, to, fromDistance, toDistance, material) {
382
+ const dashSize = material.dashSize;
383
+ const gapSize = material.gapSize;
384
+ const period = dashSize + gapSize;
385
+ if (dashSize === 0)
386
+ return [];
387
+ if (gapSize === 0 || material.scale === 0 || fromDistance === toDistance) {
388
+ const phase = positiveModulo(material.scale * fromDistance, period);
389
+ return phase <= dashSize ? [[from, to]] : [];
390
+ }
391
+ const scaledFrom = material.scale * fromDistance;
392
+ const scaledTo = material.scale * toDistance;
393
+ if (!Number.isFinite(scaledFrom) || !Number.isFinite(scaledTo))
394
+ return undefined;
395
+ const low = Math.min(scaledFrom, scaledTo);
396
+ const high = Math.max(scaledFrom, scaledTo);
397
+ const boundaries = [0, 1];
398
+ const firstPeriod = Math.floor(low / period) - 1;
399
+ const lastPeriod = Math.ceil(high / period) + 1;
400
+ if (lastPeriod - firstPeriod > 10_000)
401
+ return undefined;
402
+ for (let cycle = firstPeriod; cycle <= lastPeriod; cycle += 1) {
403
+ for (const boundary of [cycle * period, cycle * period + dashSize]) {
404
+ const ratio = (boundary - scaledFrom) / (scaledTo - scaledFrom);
405
+ if (ratio > 0 && ratio < 1)
406
+ boundaries.push(ratio);
407
+ }
408
+ }
409
+ boundaries.sort((left, right) => left - right);
410
+ const segments = [];
411
+ for (let index = 0; index + 1 < boundaries.length; index += 1) {
412
+ const start = boundaries[index];
413
+ const end = boundaries[index + 1];
414
+ if (start === undefined || end === undefined || end <= start)
415
+ continue;
416
+ const midpoint = (start + end) / 2;
417
+ const distance = scaledFrom + (scaledTo - scaledFrom) * midpoint;
418
+ if (positiveModulo(distance, period) > dashSize)
419
+ continue;
420
+ segments.push([from.clone().lerp(to, start), from.clone().lerp(to, end)]);
421
+ }
422
+ return segments;
423
+ }
424
+ function printable(value) {
425
+ const rounded = Math.abs(value) < 0.0000005 ? 0 : Number(value.toFixed(6));
426
+ return String(rounded);
427
+ }
428
+ function projectedPoint(point, width, height) {
429
+ if (point.w === 0)
430
+ return undefined;
431
+ const x = point.x / point.w;
432
+ const y = point.y / point.w;
433
+ const z = point.z / point.w;
434
+ if (![x, y, z].every(Number.isFinite))
435
+ return undefined;
436
+ return {
437
+ x: ((x + 1) * width) / 2,
438
+ y: ((1 - y) * height) / 2,
439
+ z,
440
+ };
441
+ }
442
+ function positionMorphState(geometry, influences) {
443
+ const attributes = geometry.morphAttributes.position;
444
+ if (!influences || !attributes || attributes.length === 0)
445
+ return undefined;
446
+ return {
447
+ attributes,
448
+ baseInfluence: geometry.morphTargetsRelative
449
+ ? 1
450
+ : 1 - influences.reduce((sum, influence) => sum + influence, 0),
451
+ influences,
452
+ };
453
+ }
454
+ function normalMorphState(geometry, influences) {
455
+ const attributes = geometry.morphAttributes.normal;
456
+ if (!influences || !attributes || attributes.length === 0)
457
+ return undefined;
458
+ return {
459
+ attributes,
460
+ baseInfluence: geometry.morphTargetsRelative
461
+ ? 1
462
+ : 1 - influences.reduce((sum, influence) => sum + influence, 0),
463
+ influences,
464
+ };
465
+ }
466
+ function localPosition(position, vertexIndex, morph) {
467
+ const baseX = position.getX(vertexIndex);
468
+ const baseY = position.getY(vertexIndex);
469
+ const baseZ = position.getZ(vertexIndex);
470
+ if (!morph)
471
+ return new Vector4(baseX, baseY, baseZ, 1);
472
+ let x = baseX * morph.baseInfluence;
473
+ let y = baseY * morph.baseInfluence;
474
+ let z = baseZ * morph.baseInfluence;
475
+ for (let index = 0; index < morph.attributes.length; index += 1) {
476
+ const influence = morph.influences[index] ?? 0;
477
+ const attribute = morph.attributes[index];
478
+ if (influence === 0 || !attribute)
479
+ continue;
480
+ x += attribute.getX(vertexIndex) * influence;
481
+ y += attribute.getY(vertexIndex) * influence;
482
+ z += attribute.getZ(vertexIndex) * influence;
483
+ }
484
+ return new Vector4(x, y, z, 1);
485
+ }
486
+ function localNormal(normal, vertexIndex, morph) {
487
+ const baseX = normal.getX(vertexIndex);
488
+ const baseY = normal.getY(vertexIndex);
489
+ const baseZ = normal.getZ(vertexIndex);
490
+ if (!morph)
491
+ return new Vector3(baseX, baseY, baseZ);
492
+ let x = baseX * morph.baseInfluence;
493
+ let y = baseY * morph.baseInfluence;
494
+ let z = baseZ * morph.baseInfluence;
495
+ for (let index = 0; index < morph.attributes.length; index += 1) {
496
+ const influence = morph.influences[index] ?? 0;
497
+ const attribute = morph.attributes[index];
498
+ if (influence === 0 || !attribute)
499
+ continue;
500
+ x += attribute.getX(vertexIndex) * influence;
501
+ y += attribute.getY(vertexIndex) * influence;
502
+ z += attribute.getZ(vertexIndex) * influence;
503
+ }
504
+ return new Vector3(x, y, z);
505
+ }
506
+ function skinnedNormal(mesh, vertexIndex, normal, scratch) {
507
+ const skinIndex = mesh.geometry.getAttribute('skinIndex');
508
+ const skinWeight = mesh.geometry.getAttribute('skinWeight');
509
+ scratch.blended.elements.fill(0);
510
+ for (let index = 0; index < 4; index += 1) {
511
+ const weight = skinWeight.getComponent(vertexIndex, index);
512
+ if (weight === 0)
513
+ continue;
514
+ const boneIndex = skinIndex.getComponent(vertexIndex, index);
515
+ const bone = mesh.skeleton.bones[boneIndex];
516
+ const inverse = mesh.skeleton.boneInverses[boneIndex];
517
+ if (!bone || !inverse)
518
+ continue;
519
+ scratch.bone.multiplyMatrices(bone.matrixWorld, inverse);
520
+ for (let element = 0; element < 16; element += 1) {
521
+ scratch.blended.elements[element] =
522
+ (scratch.blended.elements[element] ?? 0) + (scratch.bone.elements[element] ?? 0) * weight;
523
+ }
524
+ }
525
+ scratch.blended.multiply(mesh.bindMatrix).premultiply(mesh.bindMatrixInverse);
526
+ return normal.applyMatrix3(scratch.direction.setFromMatrix4(scratch.blended));
527
+ }
528
+ function signedArea(points) {
529
+ const [a, b, c] = points;
530
+ if (!a || !b || !c)
531
+ return 0;
532
+ return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
533
+ }
534
+ function baseMaterialReason(material) {
535
+ if (material.blending !== NormalBlending)
536
+ return 'non-default blending is not projected';
537
+ if (!Number.isFinite(material.alphaTest))
538
+ return 'alphaTest must be finite';
539
+ if (material.alphaHash)
540
+ return 'alpha-hashed transparency needs per-fragment sampling';
541
+ if (material.alphaToCoverage)
542
+ return 'alpha-to-coverage needs an MSAA renderer';
543
+ if (material.depthTest !== true ||
544
+ material.depthWrite !== true ||
545
+ material.depthFunc !== LessEqualDepth) {
546
+ return 'non-default depth material state is not projected';
547
+ }
548
+ if (material.stencilWrite)
549
+ return 'stencil-writing materials are not projected';
550
+ if (!material.colorWrite)
551
+ return 'materials with colorWrite disabled are not projected';
552
+ if (material.polygonOffset)
553
+ return 'polygon-offset material state is not projected';
554
+ if (material.dithering)
555
+ return 'material dithering needs per-fragment sampling';
556
+ return undefined;
557
+ }
558
+ function passesUniformAlphaTest(material) {
559
+ return material.alphaTest <= 0 || material.opacity >= material.alphaTest;
560
+ }
561
+ function materialReason(material) {
562
+ const baseReason = baseMaterialReason(material);
563
+ if (baseReason)
564
+ return baseReason;
565
+ if (!Number.isFinite(material.opacity))
566
+ return 'material opacity must be finite';
567
+ if (material.alphaMap ||
568
+ material.aoMap ||
569
+ material.envMap ||
570
+ material.lightMap ||
571
+ material.specularMap) {
572
+ return 'only the primary MeshBasicMaterial map is projected';
573
+ }
574
+ if (material.map) {
575
+ if (material.vertexColors)
576
+ return 'texture and vertex-colour modulation is not projected yet';
577
+ if (material.wireframe)
578
+ return 'textured wireframes are not projected';
579
+ if (![material.color.r, material.color.g, material.color.b].every(Number.isFinite))
580
+ return 'texture material colour must be finite';
581
+ if (material.alphaTest > 0)
582
+ return 'textured alphaTest needs per-pixel sampling';
583
+ }
584
+ return undefined;
585
+ }
586
+ function normalMaterialReason(material) {
587
+ const baseReason = baseMaterialReason(material);
588
+ if (baseReason)
589
+ return baseReason;
590
+ if (!Number.isFinite(material.opacity))
591
+ return 'material opacity must be finite';
592
+ if (material.bumpMap || material.normalMap || material.displacementMap) {
593
+ return 'MeshNormalMaterial texture perturbation needs per-fragment sampling';
594
+ }
595
+ return undefined;
596
+ }
597
+ function textureSource(texture) {
598
+ const source = texture.source.data;
599
+ if (typeof source === 'string' || typeof source === 'number')
600
+ return source;
601
+ if (!source || typeof source !== 'object')
602
+ return undefined;
603
+ const candidate = source;
604
+ if (typeof candidate.uri === 'string')
605
+ return { uri: candidate.uri };
606
+ if (typeof candidate.src === 'string' && candidate.src.length > 0)
607
+ return candidate.src;
608
+ if (typeof candidate.default === 'string')
609
+ return { default: candidate.default };
610
+ return undefined;
611
+ }
612
+ function textureReason(texture, usesGeometryChannel = false) {
613
+ if (texture.mapping !== UVMapping)
614
+ return 'portable colour textures need UVMapping';
615
+ if (usesGeometryChannel &&
616
+ (!Number.isInteger(texture.channel) || texture.channel < 0 || texture.channel > 3)) {
617
+ return 'texture channel must select uv, uv1, uv2, or uv3';
618
+ }
619
+ if (!textureWrap(texture)) {
620
+ return 'texture wrapping must clamp, repeat, or mirror';
621
+ }
622
+ if (texture.colorSpace !== SRGBColorSpace) {
623
+ return 'colour textures need SRGBColorSpace for portable Canvas sampling';
624
+ }
625
+ if (texture.premultiplyAlpha)
626
+ return 'premultiplied texture alpha is not projected';
627
+ if (!textureSource(texture))
628
+ return 'texture source needs a URL, URI, or Native asset ID';
629
+ return undefined;
630
+ }
631
+ function textureWrapAxis(wrap) {
632
+ if (wrap === ClampToEdgeWrapping)
633
+ return 'clamp';
634
+ if (wrap === RepeatWrapping)
635
+ return 'repeat';
636
+ if (wrap === MirroredRepeatWrapping)
637
+ return 'mirror';
638
+ return undefined;
639
+ }
640
+ function textureWrap(texture) {
641
+ const wrapX = textureWrapAxis(texture.wrapS);
642
+ const wrapY = textureWrapAxis(texture.wrapT);
643
+ return wrapX && wrapY ? [wrapX, wrapY] : undefined;
644
+ }
645
+ function textureWrapProps(texture) {
646
+ const [wrapX, wrapY] = textureWrap(texture) ?? ['clamp', 'clamp'];
647
+ if (wrapX === wrapY)
648
+ return wrapX === 'clamp' ? {} : { wrap: wrapX };
649
+ return { wrapX, wrapY };
650
+ }
651
+ function textureTintProps(color) {
652
+ return color.r === 1 && color.g === 1 && color.b === 1
653
+ ? {}
654
+ : { tint: { r: color.r, g: color.g, b: color.b } };
655
+ }
656
+ function textureAttributeName(texture) {
657
+ return texture.channel === 0 ? 'uv' : `uv${texture.channel}`;
658
+ }
659
+ function portableTexturePoint(texture, x, y) {
660
+ const coordinate = new Vector2(x, y).applyMatrix3(texture.matrix);
661
+ const [wrapX, wrapY] = textureWrap(texture) ?? ['clamp', 'clamp'];
662
+ if (!Number.isFinite(coordinate.x) ||
663
+ !Number.isFinite(coordinate.y) ||
664
+ (wrapX === 'clamp' && (coordinate.x < 0 || coordinate.x > 1)) ||
665
+ (wrapY === 'clamp' && (coordinate.y < 0 || coordinate.y > 1))) {
666
+ return undefined;
667
+ }
668
+ if (texture.flipY)
669
+ coordinate.y = 1 - coordinate.y;
670
+ return coordinate;
671
+ }
672
+ function portablePointTexturePoint(texture, x, y) {
673
+ const coordinate = new Vector2(x, y).applyMatrix3(texture.matrix);
674
+ const [wrapX, wrapY] = textureWrap(texture) ?? ['clamp', 'clamp'];
675
+ if (!Number.isFinite(coordinate.x) ||
676
+ !Number.isFinite(coordinate.y) ||
677
+ (wrapX === 'clamp' && (coordinate.x < 0 || coordinate.x > 1)) ||
678
+ (wrapY === 'clamp' && (coordinate.y < 0 || coordinate.y > 1))) {
679
+ return undefined;
680
+ }
681
+ // Three's point shader already turns gl_PointCoord into top-left image space.
682
+ // Only an upload that opts out of Three's usual flip needs reversing here.
683
+ if (!texture.flipY)
684
+ coordinate.y = 1 - coordinate.y;
685
+ return coordinate;
686
+ }
687
+ function portableTextureCoordinate(texture, attribute, vertexIndex) {
688
+ return portableTexturePoint(texture, attribute.getX(vertexIndex), attribute.getY(vertexIndex));
689
+ }
690
+ function canvasVertexColor(color, alpha) {
691
+ const value = { r: 0, g: 0, b: 0 };
692
+ color.getRGB(value, SRGBColorSpace);
693
+ return alpha === undefined ? value : { ...value, a: alpha };
694
+ }
695
+ function packedNormalColor(normal, flipped = false) {
696
+ const direction = normal.clone().normalize();
697
+ if (flipped)
698
+ direction.negate();
699
+ return new Color().setRGB(direction.x * 0.5 + 0.5, direction.y * 0.5 + 0.5, direction.z * 0.5 + 0.5);
700
+ }
701
+ function flipPackedNormalColor(color) {
702
+ return new Color().setRGB(1 - color.r, 1 - color.g, 1 - color.b);
703
+ }
704
+ function canvasColorCss(color, alpha) {
705
+ if (alpha === undefined || alpha >= 1)
706
+ return `#${color.getHexString()}`;
707
+ const { r, g, b } = canvasVertexColor(color);
708
+ return `rgba(${Math.round(r * 255)}, ${Math.round(g * 255)}, ${Math.round(b * 255)}, ${Math.max(0, Math.min(1, alpha))})`;
709
+ }
710
+ function portableVertexAlpha(attribute, index) {
711
+ const alpha = attribute.getW(index);
712
+ return Number.isFinite(alpha) ? Math.max(0, Math.min(1, alpha)) : undefined;
713
+ }
714
+ function hasPortableVertexAlphas(attribute, count = attribute.count) {
715
+ for (let index = 0; index < count; index += 1) {
716
+ if (portableVertexAlpha(attribute, index) === undefined)
717
+ return false;
718
+ }
719
+ return true;
720
+ }
721
+ function lineMaterialReason(material) {
722
+ const baseReason = baseMaterialReason(material);
723
+ if (baseReason)
724
+ return baseReason;
725
+ if (material.isLineDashedMaterial) {
726
+ const dashed = material;
727
+ if (![dashed.scale, dashed.dashSize, dashed.gapSize].every(Number.isFinite) ||
728
+ dashed.dashSize < 0 ||
729
+ dashed.gapSize < 0 ||
730
+ dashed.dashSize + dashed.gapSize <= 0) {
731
+ return 'dashed line sizes and scale must be finite and non-negative';
732
+ }
733
+ }
734
+ if (!Number.isFinite(material.opacity))
735
+ return 'line opacity must be finite';
736
+ return undefined;
737
+ }
738
+ function pointsMaterialReason(material) {
739
+ const baseReason = baseMaterialReason(material);
740
+ if (baseReason)
741
+ return baseReason;
742
+ if (!Number.isFinite(material.opacity))
743
+ return 'point opacity must be finite';
744
+ if (material.alphaMap)
745
+ return 'PointsMaterial alphaMap needs per-pixel sampling';
746
+ if (material.map) {
747
+ const mapReason = textureReason(material.map);
748
+ if (mapReason)
749
+ return mapReason;
750
+ if (material.vertexColors)
751
+ return 'texture and per-point colour modulation is not projected yet';
752
+ if (![material.color.r, material.color.g, material.color.b].every(Number.isFinite))
753
+ return 'texture point colour must be finite';
754
+ if (material.alphaTest > 0)
755
+ return 'textured alphaTest needs per-pixel sampling';
756
+ }
757
+ return undefined;
758
+ }
759
+ function spriteMaterialReason(material) {
760
+ const baseReason = baseMaterialReason(material);
761
+ if (baseReason)
762
+ return baseReason;
763
+ if (!Number.isFinite(material.opacity))
764
+ return 'sprite opacity must be finite';
765
+ if (material.alphaMap)
766
+ return 'SpriteMaterial alphaMap needs per-pixel sampling';
767
+ if (material.map) {
768
+ const mapReason = textureReason(material.map);
769
+ if (mapReason)
770
+ return mapReason;
771
+ if (![material.color.r, material.color.g, material.color.b].every(Number.isFinite))
772
+ return 'texture sprite colour must be finite';
773
+ if (material.alphaTest > 0)
774
+ return 'textured alphaTest needs per-pixel sampling';
775
+ }
776
+ return undefined;
777
+ }
778
+ function projectedOpacity(material) {
779
+ if (!material.transparent)
780
+ return undefined;
781
+ const opacity = Math.max(0, Math.min(1, material.opacity));
782
+ return opacity === 1 ? undefined : opacity;
783
+ }
784
+ function projectedOpacityProps(material) {
785
+ const opacity = projectedOpacity(material);
786
+ return opacity === undefined ? {} : { opacity };
787
+ }
788
+ function effectiveMaterial(original, override) {
789
+ return override && original.allowOverride ? override : original;
790
+ }
791
+ function isSupportedCamera(object) {
792
+ const candidate = object;
793
+ return candidate.isPerspectiveCamera === true || candidate.isOrthographicCamera === true;
794
+ }
795
+ function inheritedGroupOrder(object, camera) {
796
+ let ancestor = object.parent;
797
+ while (ancestor) {
798
+ if (ancestor.isGroup === true &&
799
+ ancestor.layers.test(camera.layers)) {
800
+ return ancestor.renderOrder;
801
+ }
802
+ ancestor = ancestor.parent;
803
+ }
804
+ return 0;
805
+ }
806
+ function diagnostic(diagnostics, options, value) {
807
+ diagnostics.push(value);
808
+ options.onDiagnostic?.(value);
809
+ }
810
+ /**
811
+ * Projects the deliberately portable part of a Three.js scene into Hozo's
812
+ * retained 2D scene.
813
+ *
814
+ * This is not a software WebGL renderer. It accepts ordinary public Three.js
815
+ * scene objects and preserves their world transforms, camera projection,
816
+ * clip volume, face side and back-to-front order. Features whose correct
817
+ * answer needs a GPU -- general texture sampling, blending and shaders among
818
+ * them -- are omitted with a diagnostic rather than drawn approximately.
819
+ */
820
+ function projectThreeSceneInternal(scene, camera, options, includeSceneState) {
821
+ const diagnostics = [];
822
+ if (!(options.width > 0) || !(options.height > 0)) {
823
+ diagnostic(diagnostics, options, {
824
+ code: 'INVALID_VIEWPORT',
825
+ message: `Three projection needs a positive viewport; received ${options.width} x ${options.height}.`,
826
+ });
827
+ return { scene: [], objects: [], diagnostics };
828
+ }
829
+ const arrayCamera = camera.isArrayCamera === true
830
+ ? camera
831
+ : undefined;
832
+ if (!arrayCamera && !isSupportedCamera(camera)) {
833
+ diagnostic(diagnostics, options, {
834
+ code: 'UNSUPPORTED_CAMERA',
835
+ message: 'Only Three.js PerspectiveCamera and OrthographicCamera are portable.',
836
+ object: camera,
837
+ });
838
+ return { scene: [], objects: [], diagnostics };
839
+ }
840
+ const decoration = [];
841
+ const decorationObjects = [];
842
+ if (includeSceneState && isColorBackground(scene.background)) {
843
+ decoration.push({
844
+ kind: 'rect',
845
+ props: {
846
+ x: 0,
847
+ y: 0,
848
+ width: options.width,
849
+ height: options.height,
850
+ fill: `#${scene.background.getHexString()}`,
851
+ },
852
+ });
853
+ decorationObjects.push(undefined);
854
+ }
855
+ else if (includeSceneState && isTextureBackground(scene.background)) {
856
+ const background = scene.background;
857
+ let reason = textureReason(background);
858
+ if (!reason && !Number.isFinite(scene.backgroundIntensity)) {
859
+ reason = 'scene backgroundIntensity must be finite';
860
+ }
861
+ if (background.matrixAutoUpdate)
862
+ background.updateMatrix();
863
+ const coordinates = [
864
+ portableTexturePoint(background, 0, 1),
865
+ portableTexturePoint(background, 1, 1),
866
+ portableTexturePoint(background, 1, 0),
867
+ portableTexturePoint(background, 0, 0),
868
+ ];
869
+ if (!reason && coordinates.some((coordinate) => coordinate === undefined)) {
870
+ reason =
871
+ 'scene background texture coordinates must remain finite and inside 0..1 after the texture transform';
872
+ }
873
+ if (reason) {
874
+ diagnostic(diagnostics, options, {
875
+ code: 'UNSUPPORTED_SCENE',
876
+ message: reason,
877
+ object: scene,
878
+ });
879
+ }
880
+ else {
881
+ decoration.push({
882
+ kind: 'triangle-mesh',
883
+ props: {
884
+ indices: [0, 1, 2, 0, 2, 3],
885
+ texture: {
886
+ source: textureSource(background),
887
+ coordinates: coordinates.map((coordinate) => ({
888
+ x: coordinate.x,
889
+ y: coordinate.y,
890
+ })),
891
+ filter: background.magFilter === NearestFilter ? 'nearest' : 'linear',
892
+ ...(scene.backgroundIntensity === 1
893
+ ? {}
894
+ : { intensity: Math.max(0, scene.backgroundIntensity) }),
895
+ ...textureWrapProps(background),
896
+ },
897
+ vertices: [
898
+ { x: 0, y: 0 },
899
+ { x: options.width, y: 0 },
900
+ { x: options.width, y: options.height },
901
+ { x: 0, y: options.height },
902
+ ],
903
+ },
904
+ });
905
+ decorationObjects.push(undefined);
906
+ }
907
+ }
908
+ else if (includeSceneState && scene.background !== null) {
909
+ diagnostic(diagnostics, options, {
910
+ code: 'UNSUPPORTED_SCENE',
911
+ message: 'This scene background type is not projected yet.',
912
+ object: scene,
913
+ });
914
+ }
915
+ if (includeSceneState && scene.fog !== null) {
916
+ const reason = fogReason(scene.fog);
917
+ if (reason) {
918
+ diagnostic(diagnostics, options, {
919
+ code: 'UNSUPPORTED_SCENE',
920
+ message: reason,
921
+ object: scene,
922
+ });
923
+ return { scene: decoration, objects: decorationObjects, diagnostics };
924
+ }
925
+ }
926
+ if (arrayCamera) {
927
+ for (const subCamera of arrayCamera.cameras) {
928
+ const viewport = subCamera.viewport;
929
+ if (!viewport) {
930
+ diagnostic(diagnostics, options, {
931
+ code: 'UNSUPPORTED_CAMERA',
932
+ message: 'Every ArrayCamera sub-camera needs a viewport.',
933
+ object: subCamera,
934
+ });
935
+ continue;
936
+ }
937
+ const projected = projectThreeSceneInternal(scene, subCamera, {
938
+ width: viewport.z,
939
+ height: viewport.w,
940
+ lineColorInterpolation: options.lineColorInterpolation,
941
+ onDiagnostic: options.onDiagnostic,
942
+ }, false);
943
+ diagnostics.push(...projected.diagnostics);
944
+ const translateX = viewport.x;
945
+ const translateY = options.height - viewport.y - viewport.w;
946
+ for (let index = 0; index < projected.scene.length; index += 1) {
947
+ const node = projected.scene[index];
948
+ if (!node)
949
+ continue;
950
+ decoration.push({
951
+ kind: 'group',
952
+ props: { transform: { translateX, translateY } },
953
+ children: [node],
954
+ });
955
+ decorationObjects.push(projected.objects[index]);
956
+ }
957
+ }
958
+ return { scene: decoration, objects: decorationObjects, diagnostics };
959
+ }
960
+ if (!isSupportedCamera(camera))
961
+ return { scene: decoration, objects: decorationObjects, diagnostics };
962
+ scene.updateMatrixWorld(true);
963
+ camera.updateMatrixWorld(true);
964
+ const viewProjection = new Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
965
+ const primitives = [];
966
+ const boundedLineColors = options.lineColorInterpolation !== 'endpoints' &&
967
+ ColorManagement.enabled &&
968
+ ColorManagement.workingColorSpace === LinearSRGBColorSpace;
969
+ let order = 0;
970
+ scene.traverseVisible((object) => {
971
+ const candidate = object;
972
+ if (candidate.isLOD === true) {
973
+ const lod = object;
974
+ if (lod.layers.test(camera.layers) && lod.autoUpdate)
975
+ lod.update(camera);
976
+ return;
977
+ }
978
+ if (!object.layers.test(camera.layers))
979
+ return;
980
+ const groupOrder = inheritedGroupOrder(object, camera);
981
+ if (candidate.isSprite === true) {
982
+ const sprite = object;
983
+ if (sprite.count <= 0)
984
+ return;
985
+ if (sprite.material.visible === false)
986
+ return;
987
+ const material = effectiveMaterial(sprite.material, scene.overrideMaterial);
988
+ if (material.isSpriteMaterial !== true) {
989
+ diagnostic(diagnostics, options, {
990
+ code: 'UNSUPPORTED_MATERIAL',
991
+ message: 'The portable sprite subset currently accepts SpriteMaterial only.',
992
+ object,
993
+ });
994
+ return;
995
+ }
996
+ const reason = spriteMaterialReason(material);
997
+ if (reason) {
998
+ diagnostic(diagnostics, options, {
999
+ code: 'UNSUPPORTED_MATERIAL',
1000
+ message: reason,
1001
+ object,
1002
+ });
1003
+ return;
1004
+ }
1005
+ if (!passesUniformAlphaTest(material))
1006
+ return;
1007
+ const spriteMaterial = material;
1008
+ const spriteMap = spriteMaterial.map;
1009
+ if (spriteMap && spriteMaterial.fog && scene.fog) {
1010
+ diagnostic(diagnostics, options, {
1011
+ code: 'UNSUPPORTED_MATERIAL',
1012
+ message: 'texture and sprite fog modulation is not projected yet',
1013
+ object,
1014
+ });
1015
+ return;
1016
+ }
1017
+ if (spriteMap?.matrixAutoUpdate)
1018
+ spriteMap.updateMatrix();
1019
+ const modelView = new Matrix4().multiplyMatrices(camera.matrixWorldInverse, sprite.matrixWorld);
1020
+ const world = sprite.matrixWorld.elements;
1021
+ let scaleX = Math.hypot(world[0] ?? 0, world[1] ?? 0, world[2] ?? 0);
1022
+ let scaleY = Math.hypot(world[4] ?? 0, world[5] ?? 0, world[6] ?? 0);
1023
+ const viewX = modelView.elements[12] ?? 0;
1024
+ const viewY = modelView.elements[13] ?? 0;
1025
+ const viewZ = modelView.elements[14] ?? 0;
1026
+ const spriteColor = foggedColorAtDepth(spriteMaterial.color, spriteMaterial.fog ? scene.fog : null, -viewZ);
1027
+ if (camera.isPerspectiveCamera === true &&
1028
+ !spriteMaterial.sizeAttenuation) {
1029
+ scaleX *= -viewZ;
1030
+ scaleY *= -viewZ;
1031
+ }
1032
+ const cosine = Math.cos(spriteMaterial.rotation);
1033
+ const sine = Math.sin(spriteMaterial.rotation);
1034
+ const corners = [
1035
+ [-0.5, -0.5],
1036
+ [0.5, -0.5],
1037
+ [0.5, 0.5],
1038
+ [-0.5, 0.5],
1039
+ ];
1040
+ const spriteTexture = spriteMap
1041
+ ? [
1042
+ portableTexturePoint(spriteMap, 0, 0),
1043
+ portableTexturePoint(spriteMap, 1, 0),
1044
+ portableTexturePoint(spriteMap, 1, 1),
1045
+ portableTexturePoint(spriteMap, 0, 1),
1046
+ ]
1047
+ : undefined;
1048
+ if (spriteTexture?.some((coordinate) => coordinate === undefined)) {
1049
+ diagnostic(diagnostics, options, {
1050
+ code: 'UNSUPPORTED_MATERIAL',
1051
+ message: 'sprite texture coordinates must remain finite and inside 0..1 after the texture transform',
1052
+ object,
1053
+ });
1054
+ return;
1055
+ }
1056
+ const worldCorners = corners.map(([x, y]) => {
1057
+ const alignedX = (x - (sprite.center.x - 0.5)) * scaleX;
1058
+ const alignedY = (y - (sprite.center.y - 0.5)) * scaleY;
1059
+ return new Vector4(viewX + cosine * alignedX - sine * alignedY, viewY + sine * alignedX + cosine * alignedY, viewZ, 1).applyMatrix4(camera.matrixWorld);
1060
+ });
1061
+ const materialPolygons = spriteTexture
1062
+ ? clippedMaterialTexturedPolygons(worldCorners.map((position, index) => ({
1063
+ position,
1064
+ texture: spriteTexture[index],
1065
+ })), (spriteMaterial.clippingPlanes ?? []), spriteMaterial.clipIntersection)
1066
+ : clippedMaterialPolygons(worldCorners, (spriteMaterial.clippingPlanes ?? []), spriteMaterial.clipIntersection);
1067
+ for (const materialPolygon of materialPolygons) {
1068
+ const polygon = spriteTexture
1069
+ ? clippedTexturedPolygon(materialPolygon.map(({ position, texture }) => ({
1070
+ position: position.clone().applyMatrix4(viewProjection),
1071
+ texture,
1072
+ })))
1073
+ : clippedPolygon(materialPolygon.map((point) => point.applyMatrix4(viewProjection)));
1074
+ if (polygon.length < 3)
1075
+ continue;
1076
+ const projected = polygon.map((point) => projectedPoint(spriteTexture ? point.position : point, options.width, options.height));
1077
+ if (projected.some((point) => point === undefined))
1078
+ continue;
1079
+ const points = projected;
1080
+ const [first, ...rest] = points;
1081
+ if (!first)
1082
+ continue;
1083
+ const path = spriteTexture
1084
+ ? undefined
1085
+ : `M ${printable(first.x)} ${printable(first.y)} ${rest
1086
+ .map((point) => `L ${printable(point.x)} ${printable(point.y)}`)
1087
+ .join(' ')} Z`;
1088
+ const indices = [];
1089
+ for (let fan = 1; fan + 1 < points.length; fan += 1)
1090
+ indices.push(0, fan, fan + 1);
1091
+ primitives.push({
1092
+ depth: points.reduce((sum, point) => sum + point.z, 0) / points.length,
1093
+ groupOrder,
1094
+ object,
1095
+ order: order++,
1096
+ renderOrder: object.renderOrder,
1097
+ transparent: spriteMaterial.transparent,
1098
+ node: spriteTexture && spriteMap
1099
+ ? {
1100
+ kind: 'triangle-mesh',
1101
+ props: {
1102
+ indices,
1103
+ texture: {
1104
+ source: textureSource(spriteMap),
1105
+ coordinates: polygon.map(({ texture }) => ({
1106
+ x: texture.x,
1107
+ y: texture.y,
1108
+ })),
1109
+ filter: spriteMap.magFilter === NearestFilter ? 'nearest' : 'linear',
1110
+ ...textureWrapProps(spriteMap),
1111
+ ...textureTintProps(spriteMaterial.color),
1112
+ },
1113
+ vertices: points.map(({ x, y }) => ({ x, y })),
1114
+ ...projectedOpacityProps(spriteMaterial),
1115
+ },
1116
+ }
1117
+ : {
1118
+ kind: 'path',
1119
+ props: {
1120
+ path: path,
1121
+ fill: `#${spriteColor.getHexString()}`,
1122
+ ...projectedOpacityProps(spriteMaterial),
1123
+ },
1124
+ },
1125
+ });
1126
+ }
1127
+ return;
1128
+ }
1129
+ if (candidate.isLine === true) {
1130
+ const line = object;
1131
+ if (Array.isArray(line.material)) {
1132
+ diagnostic(diagnostics, options, {
1133
+ code: 'UNSUPPORTED_MATERIAL',
1134
+ message: 'Material arrays and geometry groups are not projected yet.',
1135
+ object,
1136
+ });
1137
+ return;
1138
+ }
1139
+ if (line.material.visible === false)
1140
+ return;
1141
+ const material = effectiveMaterial(line.material, scene.overrideMaterial);
1142
+ if (material.isLineBasicMaterial !== true) {
1143
+ diagnostic(diagnostics, options, {
1144
+ code: 'UNSUPPORTED_MATERIAL',
1145
+ message: 'The portable line subset currently accepts LineBasicMaterial only.',
1146
+ object,
1147
+ });
1148
+ return;
1149
+ }
1150
+ const reason = lineMaterialReason(material);
1151
+ if (reason) {
1152
+ diagnostic(diagnostics, options, {
1153
+ code: 'UNSUPPORTED_MATERIAL',
1154
+ message: reason,
1155
+ object,
1156
+ });
1157
+ return;
1158
+ }
1159
+ if (!material.isLineDashedMaterial &&
1160
+ !passesUniformAlphaTest(material)) {
1161
+ return;
1162
+ }
1163
+ const position = line.geometry.getAttribute('position');
1164
+ if (!position || position.itemSize < 3) {
1165
+ diagnostic(diagnostics, options, {
1166
+ code: 'UNSUPPORTED_GEOMETRY',
1167
+ message: 'BufferGeometry needs a position attribute with three components.',
1168
+ object,
1169
+ });
1170
+ return;
1171
+ }
1172
+ const index = line.geometry.getIndex();
1173
+ const available = index?.count ?? position.count;
1174
+ const start = Math.max(0, Math.floor(line.geometry.drawRange.start));
1175
+ const requested = line.geometry.drawRange.count;
1176
+ const end = Math.min(available, Number.isFinite(requested) ? start + requested : available);
1177
+ const morph = positionMorphState(line.geometry, line.morphTargetInfluences);
1178
+ const lineDistance = line.geometry.getAttribute('lineDistance');
1179
+ const dashedMaterial = material.isLineDashedMaterial
1180
+ ? material
1181
+ : undefined;
1182
+ const color = material.vertexColors ? line.geometry.getAttribute('color') : undefined;
1183
+ if (color && color.itemSize !== 3 && color.itemSize !== 4) {
1184
+ diagnostic(diagnostics, options, {
1185
+ code: 'UNSUPPORTED_GEOMETRY',
1186
+ message: 'Portable line colour attributes must be RGB or RGBA.',
1187
+ object,
1188
+ });
1189
+ return;
1190
+ }
1191
+ if (color?.itemSize === 4 && (!material.transparent || (material.alphaTest ?? 0) > 0)) {
1192
+ diagnostic(diagnostics, options, {
1193
+ code: 'UNSUPPORTED_MATERIAL',
1194
+ message: 'RGBA line colours need transparent: true and alphaTest: 0 for portable blending.',
1195
+ object,
1196
+ });
1197
+ return;
1198
+ }
1199
+ if (color?.itemSize === 4 && !hasPortableVertexAlphas(color)) {
1200
+ diagnostic(diagnostics, options, {
1201
+ code: 'UNSUPPORTED_GEOMETRY',
1202
+ message: 'RGBA line alpha values must be finite.',
1203
+ object,
1204
+ });
1205
+ return;
1206
+ }
1207
+ const vertex = (offset) => {
1208
+ const vertexIndex = index ? index.getX(offset) : offset;
1209
+ return localPosition(position, vertexIndex, morph).applyMatrix4(line.matrixWorld);
1210
+ };
1211
+ const distance = (offset) => {
1212
+ const vertexIndex = index ? index.getX(offset) : offset;
1213
+ return lineDistance?.getX(vertexIndex) ?? 0;
1214
+ };
1215
+ const stroke = `#${material.color.getHexString()}`;
1216
+ const strokeWidth = Math.max(0, material.linewidth);
1217
+ if (strokeWidth === 0)
1218
+ return;
1219
+ const segments = [];
1220
+ const primitiveStart = primitives.length;
1221
+ if (line.isLineSegments) {
1222
+ for (let offset = start; offset + 1 < end; offset += 2) {
1223
+ segments.push([offset, offset + 1]);
1224
+ }
1225
+ }
1226
+ else {
1227
+ for (let offset = start; offset + 1 < end; offset += 1) {
1228
+ segments.push([offset, offset + 1]);
1229
+ }
1230
+ if (line.isLineLoop && end - start > 1) {
1231
+ segments.push([end - 1, start]);
1232
+ }
1233
+ }
1234
+ for (const [fromOffset, toOffset] of segments) {
1235
+ const fromVertex = vertex(fromOffset);
1236
+ const toVertex = vertex(toOffset);
1237
+ const materialColor = material.color;
1238
+ const fromIndex = index ? index.getX(fromOffset) : fromOffset;
1239
+ const toIndex = index ? index.getX(toOffset) : toOffset;
1240
+ const fromColor = color
1241
+ ? new Color(color.getX(fromIndex), color.getY(fromIndex), color.getZ(fromIndex)).multiply(materialColor)
1242
+ : materialColor;
1243
+ const toColor = color
1244
+ ? new Color(color.getX(toIndex), color.getY(toIndex), color.getZ(toIndex)).multiply(materialColor)
1245
+ : materialColor;
1246
+ const fromAlpha = color?.itemSize === 4 ? portableVertexAlpha(color, fromIndex) : undefined;
1247
+ const toAlpha = color?.itemSize === 4 ? portableVertexAlpha(color, toIndex) : undefined;
1248
+ const colorAt = (world) => {
1249
+ const base = fromColor.clone().lerp(toColor, segmentRatio(world, fromVertex, toVertex));
1250
+ return foggedColorAtWorld(base, material.fog ? scene.fog : null, world, camera.matrixWorldInverse);
1251
+ };
1252
+ const alphaAt = (world) => fromAlpha === undefined || toAlpha === undefined
1253
+ ? undefined
1254
+ : fromAlpha + (toAlpha - fromAlpha) * segmentRatio(world, fromVertex, toVertex);
1255
+ const pieces = dashedMaterial
1256
+ ? dashedSegments(fromVertex, toVertex, distance(fromOffset), distance(toOffset), dashedMaterial)
1257
+ : [[fromVertex, toVertex]];
1258
+ if (!pieces) {
1259
+ primitives.splice(primitiveStart);
1260
+ diagnostic(diagnostics, options, {
1261
+ code: 'UNSUPPORTED_GEOMETRY',
1262
+ message: 'Dashed line expansion exceeds the portable 10,000-interval limit.',
1263
+ object,
1264
+ });
1265
+ return;
1266
+ }
1267
+ for (const piece of pieces) {
1268
+ const materialClippedSegments = clippedMaterialSegments(piece[0], piece[1], (material.clippingPlanes ?? []), material.clipIntersection ?? false);
1269
+ for (const materialClipped of materialClippedSegments) {
1270
+ const materialFromClip = materialClipped[0].clone().applyMatrix4(viewProjection);
1271
+ const materialToClip = materialClipped[1].clone().applyMatrix4(viewProjection);
1272
+ const clipped = clippedSegment(materialFromClip, materialToClip);
1273
+ if (!clipped)
1274
+ continue;
1275
+ const from = projectedPoint(clipped[0], options.width, options.height);
1276
+ const to = projectedPoint(clipped[1], options.width, options.height);
1277
+ if (!from || !to || (from.x === to.x && from.y === to.y))
1278
+ continue;
1279
+ let projectedStroke = stroke;
1280
+ if (color || (material.fog && scene.fog)) {
1281
+ const clippedFromWorld = materialClipped[0]
1282
+ .clone()
1283
+ .lerp(materialClipped[1], segmentRatio(clipped[0], materialFromClip, materialToClip));
1284
+ const clippedToWorld = materialClipped[0]
1285
+ .clone()
1286
+ .lerp(materialClipped[1], segmentRatio(clipped[1], materialFromClip, materialToClip));
1287
+ const clippedFromColor = colorAt(clippedFromWorld);
1288
+ const clippedToColor = colorAt(clippedToWorld);
1289
+ const clippedFromAlpha = alphaAt(clippedFromWorld);
1290
+ const clippedToAlpha = alphaAt(clippedToWorld);
1291
+ projectedStroke = {
1292
+ kind: 'linear',
1293
+ from: { x: from.x, y: from.y },
1294
+ to: { x: to.x, y: to.y },
1295
+ stops: boundedLineColors &&
1296
+ !material.transparent &&
1297
+ clippedFromAlpha === undefined &&
1298
+ !(material.fog && scene.fog)
1299
+ ? portableLineColorStops(clippedFromColor, clippedToColor, clipped[0].w, clipped[1].w, Math.hypot(to.x - from.x, to.y - from.y))
1300
+ : [
1301
+ { offset: 0, color: canvasColorCss(clippedFromColor, clippedFromAlpha) },
1302
+ { offset: 1, color: canvasColorCss(clippedToColor, clippedToAlpha) },
1303
+ ],
1304
+ };
1305
+ }
1306
+ primitives.push({
1307
+ depth: (from.z + to.z) / 2,
1308
+ groupOrder,
1309
+ object,
1310
+ order: order++,
1311
+ renderOrder: object.renderOrder,
1312
+ transparent: material.transparent ?? false,
1313
+ node: {
1314
+ kind: 'line',
1315
+ props: {
1316
+ x1: from.x,
1317
+ y1: from.y,
1318
+ x2: to.x,
1319
+ y2: to.y,
1320
+ stroke: projectedStroke,
1321
+ strokeWidth,
1322
+ ...projectedOpacityProps(material),
1323
+ },
1324
+ },
1325
+ });
1326
+ }
1327
+ }
1328
+ }
1329
+ return;
1330
+ }
1331
+ if (candidate.isPoints === true) {
1332
+ const points = object;
1333
+ if (Array.isArray(points.material)) {
1334
+ diagnostic(diagnostics, options, {
1335
+ code: 'UNSUPPORTED_MATERIAL',
1336
+ message: 'Material arrays and geometry groups are not projected yet.',
1337
+ object,
1338
+ });
1339
+ return;
1340
+ }
1341
+ if (points.material.visible === false)
1342
+ return;
1343
+ const material = effectiveMaterial(points.material, scene.overrideMaterial);
1344
+ if (material.isPointsMaterial !== true) {
1345
+ diagnostic(diagnostics, options, {
1346
+ code: 'UNSUPPORTED_MATERIAL',
1347
+ message: 'The portable point subset currently accepts PointsMaterial only.',
1348
+ object,
1349
+ });
1350
+ return;
1351
+ }
1352
+ const reason = pointsMaterialReason(material);
1353
+ if (reason) {
1354
+ diagnostic(diagnostics, options, {
1355
+ code: 'UNSUPPORTED_MATERIAL',
1356
+ message: reason,
1357
+ object,
1358
+ });
1359
+ return;
1360
+ }
1361
+ if (!passesUniformAlphaTest(material))
1362
+ return;
1363
+ const position = points.geometry.getAttribute('position');
1364
+ if (!position || position.itemSize < 3) {
1365
+ diagnostic(diagnostics, options, {
1366
+ code: 'UNSUPPORTED_GEOMETRY',
1367
+ message: 'BufferGeometry needs a position attribute with three components.',
1368
+ object,
1369
+ });
1370
+ return;
1371
+ }
1372
+ const index = points.geometry.getIndex();
1373
+ const available = index?.count ?? position.count;
1374
+ const start = Math.max(0, Math.floor(points.geometry.drawRange.start));
1375
+ const requested = points.geometry.drawRange.count;
1376
+ const end = Math.min(available, Number.isFinite(requested) ? start + requested : available);
1377
+ const pointMaterial = material;
1378
+ const pointMap = pointMaterial.map;
1379
+ if (pointMap && pointMaterial.fog && scene.fog) {
1380
+ diagnostic(diagnostics, options, {
1381
+ code: 'UNSUPPORTED_MATERIAL',
1382
+ message: 'texture and point fog modulation is not projected yet',
1383
+ object,
1384
+ });
1385
+ return;
1386
+ }
1387
+ if (pointMap && points.geometry.getAttribute('uv')) {
1388
+ diagnostic(diagnostics, options, {
1389
+ code: 'UNSUPPORTED_GEOMETRY',
1390
+ message: 'Points geometry UVs sample one texel per point; the portable backend supports point-sprite map coordinates only.',
1391
+ object,
1392
+ });
1393
+ return;
1394
+ }
1395
+ if (pointMap?.matrixAutoUpdate)
1396
+ pointMap.updateMatrix();
1397
+ const pointTexture = pointMap
1398
+ ? [
1399
+ portablePointTexturePoint(pointMap, 0, 0),
1400
+ portablePointTexturePoint(pointMap, 1, 0),
1401
+ portablePointTexturePoint(pointMap, 1, 1),
1402
+ portablePointTexturePoint(pointMap, 0, 1),
1403
+ ]
1404
+ : undefined;
1405
+ if (pointTexture?.some((coordinate) => coordinate === undefined)) {
1406
+ diagnostic(diagnostics, options, {
1407
+ code: 'UNSUPPORTED_MATERIAL',
1408
+ message: 'point texture coordinates must remain finite and inside 0..1 after the texture transform',
1409
+ object,
1410
+ });
1411
+ return;
1412
+ }
1413
+ const color = pointMaterial.vertexColors ? points.geometry.getAttribute('color') : undefined;
1414
+ if (color && color.itemSize !== 3 && color.itemSize !== 4) {
1415
+ diagnostic(diagnostics, options, {
1416
+ code: 'UNSUPPORTED_GEOMETRY',
1417
+ message: 'Portable point colour attributes must be RGB or RGBA.',
1418
+ object,
1419
+ });
1420
+ return;
1421
+ }
1422
+ if (color?.itemSize === 4 && (!pointMaterial.transparent || pointMaterial.alphaTest > 0)) {
1423
+ diagnostic(diagnostics, options, {
1424
+ code: 'UNSUPPORTED_MATERIAL',
1425
+ message: 'RGBA point colours need transparent: true and alphaTest: 0 for portable blending.',
1426
+ object,
1427
+ });
1428
+ return;
1429
+ }
1430
+ if (color?.itemSize === 4 && !hasPortableVertexAlphas(color)) {
1431
+ diagnostic(diagnostics, options, {
1432
+ code: 'UNSUPPORTED_GEOMETRY',
1433
+ message: 'RGBA point alpha values must be finite.',
1434
+ object,
1435
+ });
1436
+ return;
1437
+ }
1438
+ const morph = positionMorphState(points.geometry, points.morphTargetInfluences);
1439
+ const fillColor = new Color();
1440
+ const materialPlanes = (pointMaterial.clippingPlanes ?? []);
1441
+ for (let offset = start; offset < end; offset += 1) {
1442
+ const vertexIndex = index ? index.getX(offset) : offset;
1443
+ const world = localPosition(position, vertexIndex, morph).applyMatrix4(points.matrixWorld);
1444
+ const insideMaterialPlanes = pointMaterial.clipIntersection
1445
+ ? materialPlanes.length === 0 ||
1446
+ materialPlanes.some((plane) => planeDistance(plane, world) >= 0)
1447
+ : materialPlanes.every((plane) => planeDistance(plane, world) >= 0);
1448
+ if (!insideMaterialPlanes) {
1449
+ continue;
1450
+ }
1451
+ const view = world.clone().applyMatrix4(camera.matrixWorldInverse);
1452
+ const clip = view.clone().applyMatrix4(camera.projectionMatrix);
1453
+ if (!clipPlanes.every((distance) => distance(clip) >= 0))
1454
+ continue;
1455
+ const projected = projectedPoint(clip, options.width, options.height);
1456
+ if (!projected)
1457
+ continue;
1458
+ const diameter = camera.isPerspectiveCamera === true &&
1459
+ pointMaterial.sizeAttenuation
1460
+ ? (pointMaterial.size * options.height) / 2 / -view.z
1461
+ : pointMaterial.size;
1462
+ const radius = diameter / 2;
1463
+ if (!(radius > 0) || !Number.isFinite(radius))
1464
+ continue;
1465
+ fillColor.copy(pointMaterial.color);
1466
+ if (color) {
1467
+ fillColor.r *= color.getX(vertexIndex);
1468
+ fillColor.g *= color.getY(vertexIndex);
1469
+ fillColor.b *= color.getZ(vertexIndex);
1470
+ }
1471
+ const projectedFill = foggedColorAtDepth(fillColor, pointMaterial.fog ? scene.fog : null, -view.z);
1472
+ const vertexAlpha = color?.itemSize === 4 ? portableVertexAlpha(color, vertexIndex) : undefined;
1473
+ primitives.push({
1474
+ depth: projected.z,
1475
+ groupOrder,
1476
+ object,
1477
+ order: order++,
1478
+ renderOrder: object.renderOrder,
1479
+ transparent: pointMaterial.transparent,
1480
+ node: pointTexture && pointMap
1481
+ ? {
1482
+ kind: 'triangle-mesh',
1483
+ props: {
1484
+ indices: [0, 1, 2, 0, 2, 3],
1485
+ texture: {
1486
+ source: textureSource(pointMap),
1487
+ coordinates: pointTexture.map((coordinate) => ({
1488
+ x: coordinate.x,
1489
+ y: coordinate.y,
1490
+ })),
1491
+ filter: pointMap.magFilter === NearestFilter ? 'nearest' : 'linear',
1492
+ ...textureWrapProps(pointMap),
1493
+ ...textureTintProps(pointMaterial.color),
1494
+ },
1495
+ vertices: [
1496
+ { x: projected.x - radius, y: projected.y - radius },
1497
+ { x: projected.x + radius, y: projected.y - radius },
1498
+ { x: projected.x + radius, y: projected.y + radius },
1499
+ { x: projected.x - radius, y: projected.y + radius },
1500
+ ],
1501
+ ...projectedOpacityProps(pointMaterial),
1502
+ },
1503
+ }
1504
+ : {
1505
+ kind: 'circle',
1506
+ props: {
1507
+ cx: projected.x,
1508
+ cy: projected.y,
1509
+ radius,
1510
+ fill: canvasColorCss(projectedFill, vertexAlpha),
1511
+ ...projectedOpacityProps(pointMaterial),
1512
+ },
1513
+ },
1514
+ });
1515
+ }
1516
+ return;
1517
+ }
1518
+ if (candidate.isMesh !== true)
1519
+ return;
1520
+ const mesh = object;
1521
+ const batchedMesh = candidate.isBatchedMesh === true ? mesh : undefined;
1522
+ const instancedMesh = mesh.isInstancedMesh
1523
+ ? mesh
1524
+ : undefined;
1525
+ const skinnedMesh = mesh.isSkinnedMesh
1526
+ ? mesh
1527
+ : undefined;
1528
+ const position = mesh.geometry.getAttribute('position');
1529
+ if (!position || position.itemSize < 3) {
1530
+ diagnostic(diagnostics, options, {
1531
+ code: 'UNSUPPORTED_GEOMETRY',
1532
+ message: 'BufferGeometry needs a position attribute with three components.',
1533
+ object,
1534
+ });
1535
+ return;
1536
+ }
1537
+ const directMaterial = Array.isArray(mesh.material)
1538
+ ? undefined
1539
+ : effectiveMaterial(mesh.material, scene.overrideMaterial);
1540
+ if (directMaterial?.isMeshNormalMaterial === true) {
1541
+ const material = directMaterial;
1542
+ const reason = normalMaterialReason(material);
1543
+ if (reason) {
1544
+ diagnostic(diagnostics, options, {
1545
+ code: 'UNSUPPORTED_MATERIAL',
1546
+ message: reason,
1547
+ object,
1548
+ });
1549
+ return;
1550
+ }
1551
+ if (!passesUniformAlphaTest(material))
1552
+ return;
1553
+ if (batchedMesh || instancedMesh?.morphTexture) {
1554
+ diagnostic(diagnostics, options, {
1555
+ code: 'UNSUPPORTED_MESH',
1556
+ message: 'Portable MeshNormalMaterial currently rejects batched meshes and instanced morph textures.',
1557
+ object,
1558
+ });
1559
+ return;
1560
+ }
1561
+ const normal = mesh.geometry.getAttribute('normal');
1562
+ if (!material.flatShading &&
1563
+ (!normal || normal.itemSize < 3 || normal.count < position.count)) {
1564
+ diagnostic(diagnostics, options, {
1565
+ code: 'UNSUPPORTED_GEOMETRY',
1566
+ message: 'Smooth MeshNormalMaterial needs one three-component normal per vertex.',
1567
+ object,
1568
+ });
1569
+ return;
1570
+ }
1571
+ if (skinnedMesh) {
1572
+ const skinIndex = mesh.geometry.getAttribute('skinIndex');
1573
+ const skinWeight = mesh.geometry.getAttribute('skinWeight');
1574
+ if (!skinnedMesh.skeleton ||
1575
+ !skinIndex ||
1576
+ skinIndex.itemSize < 4 ||
1577
+ skinIndex.count < position.count ||
1578
+ !skinWeight ||
1579
+ skinWeight.itemSize < 4 ||
1580
+ skinWeight.count < position.count) {
1581
+ diagnostic(diagnostics, options, {
1582
+ code: 'UNSUPPORTED_GEOMETRY',
1583
+ message: 'Skinned MeshNormalMaterial needs a bound skeleton and four skin indices and weights per vertex.',
1584
+ object,
1585
+ });
1586
+ return;
1587
+ }
1588
+ }
1589
+ const morph = positionMorphState(mesh.geometry, mesh.morphTargetInfluences);
1590
+ const normalMorph = normalMorphState(mesh.geometry, mesh.morphTargetInfluences);
1591
+ if (!material.flatShading &&
1592
+ normalMorph?.attributes.some((attribute) => attribute.itemSize < 3 || attribute.count < position.count)) {
1593
+ diagnostic(diagnostics, options, {
1594
+ code: 'UNSUPPORTED_GEOMETRY',
1595
+ message: 'Smooth MeshNormalMaterial morph normals must provide three components per vertex.',
1596
+ object,
1597
+ });
1598
+ return;
1599
+ }
1600
+ const index = mesh.geometry.getIndex();
1601
+ const available = index?.count ?? position.count;
1602
+ const start = Math.max(0, Math.floor(mesh.geometry.drawRange.start));
1603
+ const requested = mesh.geometry.drawRange.count;
1604
+ const end = Math.min(available, Number.isFinite(requested) ? Math.floor(start + requested) : available);
1605
+ const worldMatrices = [];
1606
+ if (instancedMesh) {
1607
+ const instanceMatrix = new Matrix4();
1608
+ for (let instance = 0; instance < instancedMesh.count; instance += 1) {
1609
+ instancedMesh.getMatrixAt(instance, instanceMatrix);
1610
+ worldMatrices.push(new Matrix4().multiplyMatrices(mesh.matrixWorld, instanceMatrix));
1611
+ }
1612
+ }
1613
+ else {
1614
+ worldMatrices.push(mesh.matrixWorld);
1615
+ }
1616
+ const materialPlanes = (material.clippingPlanes ?? []);
1617
+ const skinNormalScratch = skinnedMesh
1618
+ ? { blended: new Matrix4(), bone: new Matrix4(), direction: new Matrix3() }
1619
+ : undefined;
1620
+ for (const worldMatrix of worldMatrices) {
1621
+ const modelView = new Matrix4().multiplyMatrices(camera.matrixWorldInverse, worldMatrix);
1622
+ const normalMatrix = new Matrix3().getNormalMatrix(modelView);
1623
+ for (let offset = start; offset + 2 < end; offset += 3) {
1624
+ const vertexIndices = [
1625
+ index ? index.getX(offset) : offset,
1626
+ index ? index.getX(offset + 1) : offset + 1,
1627
+ index ? index.getX(offset + 2) : offset + 2,
1628
+ ];
1629
+ const worldPositions = vertexIndices.map((vertexIndex) => {
1630
+ if (skinnedMesh) {
1631
+ const local = skinnedMesh.getVertexPosition(vertexIndex, new Vector3());
1632
+ return new Vector4(local.x, local.y, local.z, 1).applyMatrix4(worldMatrix);
1633
+ }
1634
+ return localPosition(position, vertexIndex, morph).applyMatrix4(worldMatrix);
1635
+ });
1636
+ let sourceColors;
1637
+ if (material.flatShading) {
1638
+ const viewPositions = worldPositions.map((point) => new Vector3(point.x, point.y, point.z).applyMatrix4(camera.matrixWorldInverse));
1639
+ const edgeA = viewPositions[1].clone().sub(viewPositions[0]);
1640
+ const edgeB = viewPositions[2].clone().sub(viewPositions[0]);
1641
+ const faceNormal = edgeA.cross(edgeB);
1642
+ if (faceNormal.lengthSq() === 0)
1643
+ continue;
1644
+ const color = packedNormalColor(faceNormal, material.side === BackSide);
1645
+ sourceColors = [color, color, color];
1646
+ }
1647
+ else {
1648
+ sourceColors = vertexIndices.map((vertexIndex) => {
1649
+ let transformed = localNormal(normal, vertexIndex, normalMorph);
1650
+ if (skinnedMesh && skinNormalScratch) {
1651
+ transformed = skinnedNormal(skinnedMesh, vertexIndex, transformed, skinNormalScratch);
1652
+ }
1653
+ transformed.applyMatrix3(normalMatrix);
1654
+ return packedNormalColor(transformed, material.side === BackSide);
1655
+ });
1656
+ }
1657
+ if (material.wireframe) {
1658
+ const strokeWidth = Math.max(0, material.wireframeLinewidth);
1659
+ if (strokeWidth === 0)
1660
+ continue;
1661
+ for (const [fromIndex, toIndex] of [
1662
+ [0, 1],
1663
+ [1, 2],
1664
+ [2, 0],
1665
+ ]) {
1666
+ const wireFrom = worldPositions[fromIndex];
1667
+ const wireTo = worldPositions[toIndex];
1668
+ const fromColor = sourceColors[fromIndex];
1669
+ const toColor = sourceColors[toIndex];
1670
+ const materialClippedSegments = clippedMaterialSegments(wireFrom, wireTo, materialPlanes, material.clipIntersection);
1671
+ for (const materialClipped of materialClippedSegments) {
1672
+ const materialFromClip = materialClipped[0].clone().applyMatrix4(viewProjection);
1673
+ const materialToClip = materialClipped[1].clone().applyMatrix4(viewProjection);
1674
+ const clipped = clippedSegment(materialFromClip, materialToClip);
1675
+ if (!clipped)
1676
+ continue;
1677
+ const from = projectedPoint(clipped[0], options.width, options.height);
1678
+ const to = projectedPoint(clipped[1], options.width, options.height);
1679
+ if (!from || !to || (from.x === to.x && from.y === to.y))
1680
+ continue;
1681
+ const clippedFromWorld = materialClipped[0]
1682
+ .clone()
1683
+ .lerp(materialClipped[1], segmentRatio(clipped[0], materialFromClip, materialToClip));
1684
+ const clippedToWorld = materialClipped[0]
1685
+ .clone()
1686
+ .lerp(materialClipped[1], segmentRatio(clipped[1], materialFromClip, materialToClip));
1687
+ const clippedFromColor = fromColor
1688
+ .clone()
1689
+ .lerp(toColor, segmentRatio(clippedFromWorld, wireFrom, wireTo));
1690
+ const clippedToColor = fromColor
1691
+ .clone()
1692
+ .lerp(toColor, segmentRatio(clippedToWorld, wireFrom, wireTo));
1693
+ primitives.push({
1694
+ depth: (from.z + to.z) / 2,
1695
+ groupOrder,
1696
+ object,
1697
+ order: order++,
1698
+ renderOrder: object.renderOrder,
1699
+ transparent: material.transparent,
1700
+ node: {
1701
+ kind: 'line',
1702
+ props: {
1703
+ x1: from.x,
1704
+ y1: from.y,
1705
+ x2: to.x,
1706
+ y2: to.y,
1707
+ stroke: {
1708
+ kind: 'linear',
1709
+ from: { x: from.x, y: from.y },
1710
+ to: { x: to.x, y: to.y },
1711
+ stops: [
1712
+ { offset: 0, color: canvasColorCss(clippedFromColor) },
1713
+ { offset: 1, color: canvasColorCss(clippedToColor) },
1714
+ ],
1715
+ },
1716
+ strokeWidth,
1717
+ ...projectedOpacityProps(material),
1718
+ },
1719
+ },
1720
+ });
1721
+ }
1722
+ }
1723
+ continue;
1724
+ }
1725
+ const materialPolygons = clippedMaterialColouredPolygons(worldPositions.map((position, indexInTriangle) => ({
1726
+ color: sourceColors[indexInTriangle].clone(),
1727
+ position,
1728
+ })), materialPlanes, material.clipIntersection);
1729
+ for (const materialPolygon of materialPolygons) {
1730
+ const polygon = clippedColouredPolygon(materialPolygon.map(({ color, position }) => ({
1731
+ color,
1732
+ position: position.clone().applyMatrix4(viewProjection),
1733
+ })));
1734
+ if (polygon.length < 3)
1735
+ continue;
1736
+ for (let fan = 1; fan + 1 < polygon.length; fan += 1) {
1737
+ const first = polygon[0];
1738
+ const second = polygon[fan];
1739
+ const third = polygon[fan + 1];
1740
+ if (!first || !second || !third)
1741
+ continue;
1742
+ const clipTriangle = [first, second, third];
1743
+ const points = clipTriangle.map(({ position }) => projectedPoint(position, options.width, options.height));
1744
+ if (points.some((point) => point === undefined))
1745
+ continue;
1746
+ const projected = points;
1747
+ const area = signedArea(projected) * (worldMatrix.determinant() < 0 ? -1 : 1);
1748
+ if (area === 0)
1749
+ continue;
1750
+ if (material.side !== DoubleSide &&
1751
+ (material.side === BackSide ? area < 0 : area > 0)) {
1752
+ continue;
1753
+ }
1754
+ const flipDoubleSidedBackFace = material.side === DoubleSide && area > 0;
1755
+ primitives.push({
1756
+ depth: projected.reduce((sum, point) => sum + point.z, 0) / 3,
1757
+ groupOrder,
1758
+ object,
1759
+ order: order++,
1760
+ renderOrder: object.renderOrder,
1761
+ transparent: material.transparent,
1762
+ node: {
1763
+ kind: 'triangle-mesh',
1764
+ props: {
1765
+ colors: clipTriangle.map(({ color }) => canvasVertexColor(flipDoubleSidedBackFace ? flipPackedNormalColor(color) : color)),
1766
+ vertices: projected.map(({ x, y }) => ({ x, y })),
1767
+ ...projectedOpacityProps(material),
1768
+ },
1769
+ },
1770
+ });
1771
+ }
1772
+ }
1773
+ }
1774
+ }
1775
+ return;
1776
+ }
1777
+ const vertexColor = mesh.geometry.getAttribute('color');
1778
+ const index = mesh.geometry.getIndex();
1779
+ const available = index?.count ?? position.count;
1780
+ const drawStart = Math.max(0, Math.floor(mesh.geometry.drawRange.start));
1781
+ const requested = mesh.geometry.drawRange.count;
1782
+ const drawEnd = Math.min(available, Number.isFinite(requested) ? Math.floor(drawStart + requested) : available);
1783
+ const reportedMaterials = new Set();
1784
+ const appendRange = (ranges, source, start, end, groupStart = start, groupCount = end - start) => {
1785
+ if (!source || typeof source !== 'object')
1786
+ return;
1787
+ const material = source;
1788
+ if (material.isMeshBasicMaterial !== true) {
1789
+ if (!reportedMaterials.has(source)) {
1790
+ reportedMaterials.add(source);
1791
+ diagnostic(diagnostics, options, {
1792
+ code: 'UNSUPPORTED_MATERIAL',
1793
+ message: 'The portable subset currently accepts MeshBasicMaterial only.',
1794
+ object,
1795
+ });
1796
+ }
1797
+ return;
1798
+ }
1799
+ const reason = materialReason(material);
1800
+ if (reason) {
1801
+ if (!reportedMaterials.has(source)) {
1802
+ reportedMaterials.add(source);
1803
+ diagnostic(diagnostics, options, {
1804
+ code: 'UNSUPPORTED_MATERIAL',
1805
+ message: reason,
1806
+ object,
1807
+ });
1808
+ }
1809
+ return;
1810
+ }
1811
+ const map = material.map;
1812
+ if (map) {
1813
+ const mapReason = textureReason(map, true);
1814
+ if (mapReason) {
1815
+ if (!reportedMaterials.has(source)) {
1816
+ reportedMaterials.add(source);
1817
+ diagnostic(diagnostics, options, {
1818
+ code: 'UNSUPPORTED_MATERIAL',
1819
+ message: mapReason,
1820
+ object,
1821
+ });
1822
+ }
1823
+ return;
1824
+ }
1825
+ if (material.fog && scene.fog) {
1826
+ if (!reportedMaterials.has(source)) {
1827
+ reportedMaterials.add(source);
1828
+ diagnostic(diagnostics, options, {
1829
+ code: 'UNSUPPORTED_MATERIAL',
1830
+ message: 'texture and fog modulation is not projected yet',
1831
+ object,
1832
+ });
1833
+ }
1834
+ return;
1835
+ }
1836
+ const textureCoordinate = mesh.geometry.getAttribute(textureAttributeName(map));
1837
+ if (textureCoordinate?.itemSize !== 2 || textureCoordinate.count < position.count) {
1838
+ if (!reportedMaterials.has(source)) {
1839
+ reportedMaterials.add(source);
1840
+ diagnostic(diagnostics, options, {
1841
+ code: 'UNSUPPORTED_GEOMETRY',
1842
+ message: `MeshBasicMaterial.map needs one two-component ${textureAttributeName(map)} value per vertex.`,
1843
+ object,
1844
+ });
1845
+ }
1846
+ return;
1847
+ }
1848
+ if (map.matrixAutoUpdate)
1849
+ map.updateMatrix();
1850
+ for (let vertexIndex = 0; vertexIndex < position.count; vertexIndex += 1) {
1851
+ if (portableTextureCoordinate(map, textureCoordinate, vertexIndex))
1852
+ continue;
1853
+ if (!reportedMaterials.has(source)) {
1854
+ reportedMaterials.add(source);
1855
+ diagnostic(diagnostics, options, {
1856
+ code: 'UNSUPPORTED_GEOMETRY',
1857
+ message: 'texture coordinates must remain finite and inside 0..1 after the texture transform',
1858
+ object,
1859
+ });
1860
+ }
1861
+ return;
1862
+ }
1863
+ }
1864
+ if (!passesUniformAlphaTest(material))
1865
+ return;
1866
+ if (material.vertexColors &&
1867
+ ((vertexColor?.itemSize !== 3 && vertexColor?.itemSize !== 4) ||
1868
+ vertexColor.count < position.count)) {
1869
+ if (!reportedMaterials.has(source)) {
1870
+ reportedMaterials.add(source);
1871
+ diagnostic(diagnostics, options, {
1872
+ code: 'UNSUPPORTED_GEOMETRY',
1873
+ message: 'MeshBasicMaterial.vertexColors needs one RGB or RGBA value per vertex.',
1874
+ object,
1875
+ });
1876
+ }
1877
+ return;
1878
+ }
1879
+ if (material.vertexColors &&
1880
+ vertexColor?.itemSize === 4 &&
1881
+ !hasPortableVertexAlphas(vertexColor, position.count)) {
1882
+ if (!reportedMaterials.has(source)) {
1883
+ reportedMaterials.add(source);
1884
+ diagnostic(diagnostics, options, {
1885
+ code: 'UNSUPPORTED_GEOMETRY',
1886
+ message: 'RGBA mesh alpha values must be finite.',
1887
+ object,
1888
+ });
1889
+ }
1890
+ return;
1891
+ }
1892
+ if (material.vertexColors &&
1893
+ vertexColor?.itemSize === 4 &&
1894
+ (!material.transparent || (material.alphaTest ?? 0) > 0)) {
1895
+ if (!reportedMaterials.has(source)) {
1896
+ reportedMaterials.add(source);
1897
+ diagnostic(diagnostics, options, {
1898
+ code: 'UNSUPPORTED_MATERIAL',
1899
+ message: 'RGBA mesh colours need transparent: true and alphaTest: 0 for portable blending.',
1900
+ object,
1901
+ });
1902
+ }
1903
+ return;
1904
+ }
1905
+ const groupEnd = Number.isFinite(groupCount) ? Math.floor(groupStart + groupCount) : available;
1906
+ const rangeStart = Math.max(start, 0, Math.floor(groupStart));
1907
+ const rangeEnd = Math.min(end, available, groupEnd);
1908
+ if (rangeEnd <= rangeStart)
1909
+ return;
1910
+ ranges.push({ start: rangeStart, end: rangeEnd, material: material });
1911
+ };
1912
+ const rangesFor = (start, end) => {
1913
+ const ranges = [];
1914
+ if (Array.isArray(mesh.material)) {
1915
+ for (const group of mesh.geometry.groups) {
1916
+ const original = mesh.material[group.materialIndex ?? 0];
1917
+ if (!original || original.visible === false)
1918
+ continue;
1919
+ appendRange(ranges, effectiveMaterial(original, scene.overrideMaterial), start, end, group.start, group.count);
1920
+ }
1921
+ }
1922
+ else {
1923
+ if (mesh.material.visible !== false) {
1924
+ appendRange(ranges, effectiveMaterial(mesh.material, scene.overrideMaterial), start, end);
1925
+ }
1926
+ }
1927
+ return ranges;
1928
+ };
1929
+ const projectionInstances = [];
1930
+ if (batchedMesh) {
1931
+ if (Array.isArray(mesh.material)) {
1932
+ diagnostic(diagnostics, options, {
1933
+ code: 'UNSUPPORTED_MATERIAL',
1934
+ message: 'BatchedMesh material arrays cannot be matched to source geometry groups.',
1935
+ object,
1936
+ });
1937
+ return;
1938
+ }
1939
+ const instanceMatrix = new Matrix4();
1940
+ let colorsAvailable;
1941
+ let found = 0;
1942
+ for (let instance = 0; instance < batchedMesh.maxInstanceCount && found < batchedMesh.instanceCount; instance += 1) {
1943
+ let visible;
1944
+ try {
1945
+ visible = batchedMesh.getVisibleAt(instance);
1946
+ }
1947
+ catch {
1948
+ continue;
1949
+ }
1950
+ found += 1;
1951
+ if (!visible)
1952
+ continue;
1953
+ const geometryId = batchedMesh.getGeometryIdAt(instance);
1954
+ const range = batchedMesh.getGeometryRangeAt(geometryId);
1955
+ if (!range)
1956
+ continue;
1957
+ const rangeStart = Math.max(0, Math.floor(range.start));
1958
+ const rangeEnd = Math.min(available, Math.floor(range.start + range.count));
1959
+ const ranges = rangesFor(rangeStart, rangeEnd);
1960
+ if (ranges.length === 0)
1961
+ continue;
1962
+ batchedMesh.getMatrixAt(instance, instanceMatrix);
1963
+ let color;
1964
+ if (colorsAvailable !== false) {
1965
+ try {
1966
+ const instanceColor = new Color();
1967
+ batchedMesh.getColorAt(instance, instanceColor);
1968
+ colorsAvailable = true;
1969
+ color = instanceColor;
1970
+ }
1971
+ catch {
1972
+ // Three does not allocate the optional colour texture until setColorAt is used.
1973
+ colorsAvailable = false;
1974
+ }
1975
+ }
1976
+ projectionInstances.push({
1977
+ color,
1978
+ ranges,
1979
+ worldMatrix: new Matrix4().multiplyMatrices(mesh.matrixWorld, instanceMatrix),
1980
+ });
1981
+ }
1982
+ }
1983
+ else if (instancedMesh) {
1984
+ const ranges = rangesFor(drawStart, drawEnd);
1985
+ if (ranges.length === 0)
1986
+ return;
1987
+ const instanceMatrix = new Matrix4();
1988
+ const morphTarget = instancedMesh.morphTexture ? new Mesh(mesh.geometry) : undefined;
1989
+ for (let instance = 0; instance < instancedMesh.count; instance += 1) {
1990
+ instancedMesh.getMatrixAt(instance, instanceMatrix);
1991
+ let color;
1992
+ if (instancedMesh.instanceColor) {
1993
+ color = new Color();
1994
+ instancedMesh.getColorAt(instance, color);
1995
+ }
1996
+ let morph;
1997
+ if (morphTarget?.morphTargetInfluences) {
1998
+ instancedMesh.getMorphAt(instance, morphTarget);
1999
+ morph = positionMorphState(mesh.geometry, [...morphTarget.morphTargetInfluences]);
2000
+ }
2001
+ projectionInstances.push({
2002
+ color,
2003
+ morph,
2004
+ ranges,
2005
+ worldMatrix: new Matrix4().multiplyMatrices(mesh.matrixWorld, instanceMatrix),
2006
+ });
2007
+ }
2008
+ }
2009
+ else {
2010
+ const ranges = rangesFor(drawStart, drawEnd);
2011
+ if (ranges.length === 0)
2012
+ return;
2013
+ projectionInstances.push({
2014
+ morph: skinnedMesh
2015
+ ? undefined
2016
+ : positionMorphState(mesh.geometry, mesh.morphTargetInfluences),
2017
+ ranges,
2018
+ worldMatrix: mesh.matrixWorld,
2019
+ });
2020
+ }
2021
+ let wireframeIndices;
2022
+ const fillColor = new Color();
2023
+ const skinnedPosition = new Vector3();
2024
+ for (const { color, morph, ranges, worldMatrix } of projectionInstances) {
2025
+ const mirrored = worldMatrix.determinant() < 0;
2026
+ const vertexAt = (vertexIndex) => {
2027
+ if (skinnedMesh) {
2028
+ skinnedMesh.getVertexPosition(vertexIndex, skinnedPosition);
2029
+ return new Vector4(skinnedPosition.x, skinnedPosition.y, skinnedPosition.z, 1).applyMatrix4(worldMatrix);
2030
+ }
2031
+ return localPosition(position, vertexIndex, morph).applyMatrix4(worldMatrix);
2032
+ };
2033
+ const vertex = (offset) => {
2034
+ const vertexIndex = index ? index.getX(offset) : offset;
2035
+ return vertexAt(vertexIndex);
2036
+ };
2037
+ for (const range of ranges) {
2038
+ const map = range.material.map;
2039
+ if (map?.matrixAutoUpdate)
2040
+ map.updateMatrix();
2041
+ const textureCoordinate = map
2042
+ ? mesh.geometry.getAttribute(textureAttributeName(map))
2043
+ : undefined;
2044
+ if (map && color && color.getHex() !== 0xffffff) {
2045
+ if (!reportedMaterials.has(range.material)) {
2046
+ reportedMaterials.add(range.material);
2047
+ diagnostic(diagnostics, options, {
2048
+ code: 'UNSUPPORTED_MATERIAL',
2049
+ message: 'texture and instance-colour modulation is not projected yet',
2050
+ object,
2051
+ });
2052
+ }
2053
+ continue;
2054
+ }
2055
+ fillColor.copy(range.material.color);
2056
+ if (color)
2057
+ fillColor.multiply(color);
2058
+ const fill = `#${fillColor.getHexString()}`;
2059
+ const rangeFog = range.material.fog ? scene.fog : null;
2060
+ if (range.material.wireframe) {
2061
+ const strokeWidth = Math.max(0, range.material.wireframeLinewidth);
2062
+ if (strokeWidth === 0)
2063
+ continue;
2064
+ if (!wireframeIndices) {
2065
+ wireframeIndices = [];
2066
+ for (let offset = 0; offset + 2 < available; offset += 3) {
2067
+ const a = index ? index.getX(offset) : offset;
2068
+ const b = index ? index.getX(offset + 1) : offset + 1;
2069
+ const c = index ? index.getX(offset + 2) : offset + 2;
2070
+ wireframeIndices.push(a, b, b, c, c, a);
2071
+ }
2072
+ }
2073
+ const wireStart = range.start * 2;
2074
+ const wireEnd = Math.min(wireframeIndices.length, range.end * 2);
2075
+ for (let offset = wireStart; offset + 1 < wireEnd; offset += 2) {
2076
+ const fromIndex = wireframeIndices[offset];
2077
+ const toIndex = wireframeIndices[offset + 1];
2078
+ if (fromIndex === undefined || toIndex === undefined)
2079
+ continue;
2080
+ const wireFrom = vertexAt(fromIndex);
2081
+ const wireTo = vertexAt(toIndex);
2082
+ const fromColor = range.material.vertexColors
2083
+ ? new Color(vertexColor?.getX(fromIndex) ?? 0, vertexColor?.getY(fromIndex) ?? 0, vertexColor?.getZ(fromIndex) ?? 0).multiply(fillColor)
2084
+ : fillColor;
2085
+ const toColor = range.material.vertexColors
2086
+ ? new Color(vertexColor?.getX(toIndex) ?? 0, vertexColor?.getY(toIndex) ?? 0, vertexColor?.getZ(toIndex) ?? 0).multiply(fillColor)
2087
+ : fillColor;
2088
+ const fromAlpha = range.material.vertexColors && vertexColor?.itemSize === 4
2089
+ ? portableVertexAlpha(vertexColor, fromIndex)
2090
+ : undefined;
2091
+ const toAlpha = range.material.vertexColors && vertexColor?.itemSize === 4
2092
+ ? portableVertexAlpha(vertexColor, toIndex)
2093
+ : undefined;
2094
+ const colorAt = (world) => {
2095
+ const base = fromColor.clone().lerp(toColor, segmentRatio(world, wireFrom, wireTo));
2096
+ return foggedColorAtWorld(base, rangeFog, world, camera.matrixWorldInverse);
2097
+ };
2098
+ const alphaAt = (world) => fromAlpha === undefined || toAlpha === undefined
2099
+ ? undefined
2100
+ : fromAlpha + (toAlpha - fromAlpha) * segmentRatio(world, wireFrom, wireTo);
2101
+ const materialClippedSegments = clippedMaterialSegments(wireFrom, wireTo, (range.material.clippingPlanes ?? []), range.material.clipIntersection);
2102
+ for (const materialClipped of materialClippedSegments) {
2103
+ const materialFromClip = materialClipped[0].clone().applyMatrix4(viewProjection);
2104
+ const materialToClip = materialClipped[1].clone().applyMatrix4(viewProjection);
2105
+ const clipped = clippedSegment(materialFromClip, materialToClip);
2106
+ if (!clipped)
2107
+ continue;
2108
+ const from = projectedPoint(clipped[0], options.width, options.height);
2109
+ const to = projectedPoint(clipped[1], options.width, options.height);
2110
+ if (!from || !to || (from.x === to.x && from.y === to.y))
2111
+ continue;
2112
+ let projectedStroke = fill;
2113
+ if (range.material.vertexColors || rangeFog) {
2114
+ const clippedFromWorld = materialClipped[0]
2115
+ .clone()
2116
+ .lerp(materialClipped[1], segmentRatio(clipped[0], materialFromClip, materialToClip));
2117
+ const clippedToWorld = materialClipped[0]
2118
+ .clone()
2119
+ .lerp(materialClipped[1], segmentRatio(clipped[1], materialFromClip, materialToClip));
2120
+ const clippedFromColor = colorAt(clippedFromWorld);
2121
+ const clippedToColor = colorAt(clippedToWorld);
2122
+ const clippedFromAlpha = alphaAt(clippedFromWorld);
2123
+ const clippedToAlpha = alphaAt(clippedToWorld);
2124
+ projectedStroke = {
2125
+ kind: 'linear',
2126
+ from: { x: from.x, y: from.y },
2127
+ to: { x: to.x, y: to.y },
2128
+ stops: boundedLineColors &&
2129
+ !range.material.transparent &&
2130
+ clippedFromAlpha === undefined &&
2131
+ !rangeFog
2132
+ ? portableLineColorStops(clippedFromColor, clippedToColor, clipped[0].w, clipped[1].w, Math.hypot(to.x - from.x, to.y - from.y))
2133
+ : [
2134
+ {
2135
+ offset: 0,
2136
+ color: canvasColorCss(clippedFromColor, clippedFromAlpha),
2137
+ },
2138
+ {
2139
+ offset: 1,
2140
+ color: canvasColorCss(clippedToColor, clippedToAlpha),
2141
+ },
2142
+ ],
2143
+ };
2144
+ }
2145
+ primitives.push({
2146
+ depth: (from.z + to.z) / 2,
2147
+ groupOrder,
2148
+ object,
2149
+ order: order++,
2150
+ renderOrder: object.renderOrder,
2151
+ transparent: range.material.transparent,
2152
+ node: {
2153
+ kind: 'line',
2154
+ props: {
2155
+ x1: from.x,
2156
+ y1: from.y,
2157
+ x2: to.x,
2158
+ y2: to.y,
2159
+ stroke: projectedStroke,
2160
+ strokeWidth,
2161
+ ...projectedOpacityProps(range.material),
2162
+ },
2163
+ },
2164
+ });
2165
+ }
2166
+ }
2167
+ continue;
2168
+ }
2169
+ for (let offset = range.start; offset + 2 < range.end; offset += 3) {
2170
+ const sourceVertices = [vertex(offset), vertex(offset + 1), vertex(offset + 2)];
2171
+ const coloured = (range.material.vertexColors && vertexColor) || rangeFog;
2172
+ const textured = map && textureCoordinate;
2173
+ const materialPolygons = textured
2174
+ ? clippedMaterialTexturedPolygons(sourceVertices.map((position, indexInTriangle) => {
2175
+ const sourceOffset = offset + indexInTriangle;
2176
+ const vertexIndex = index ? index.getX(sourceOffset) : sourceOffset;
2177
+ return {
2178
+ position,
2179
+ texture: portableTextureCoordinate(map, textureCoordinate, vertexIndex),
2180
+ };
2181
+ }), (range.material.clippingPlanes ?? []), range.material.clipIntersection)
2182
+ : coloured
2183
+ ? clippedMaterialColouredPolygons(sourceVertices.map((position, indexInTriangle) => {
2184
+ const sourceOffset = offset + indexInTriangle;
2185
+ const vertexIndex = index ? index.getX(sourceOffset) : sourceOffset;
2186
+ const vertexFill = range.material.vertexColors
2187
+ ? new Color()
2188
+ .setRGB(vertexColor?.getX(vertexIndex) ?? 0, vertexColor?.getY(vertexIndex) ?? 0, vertexColor?.getZ(vertexIndex) ?? 0)
2189
+ .multiply(fillColor)
2190
+ : fillColor;
2191
+ return {
2192
+ alpha: range.material.vertexColors && vertexColor?.itemSize === 4
2193
+ ? portableVertexAlpha(vertexColor, vertexIndex)
2194
+ : undefined,
2195
+ color: vertexFill.clone(),
2196
+ position,
2197
+ };
2198
+ }), (range.material.clippingPlanes ?? []), range.material.clipIntersection)
2199
+ : clippedMaterialPolygons(sourceVertices, (range.material.clippingPlanes ?? []), range.material.clipIntersection);
2200
+ for (const materialPolygon of materialPolygons) {
2201
+ const polygon = textured
2202
+ ? clippedTexturedPolygon(materialPolygon.map(({ position, texture }) => ({
2203
+ position: position.clone().applyMatrix4(viewProjection),
2204
+ texture,
2205
+ })))
2206
+ : coloured
2207
+ ? clippedColouredPolygon(materialPolygon.map(({ alpha, color, position }) => {
2208
+ const viewDepth = -position.clone().applyMatrix4(camera.matrixWorldInverse).z;
2209
+ return {
2210
+ alpha,
2211
+ color,
2212
+ position: position.clone().applyMatrix4(viewProjection),
2213
+ viewDepth,
2214
+ };
2215
+ }))
2216
+ : clippedPolygon(materialPolygon.map((point) => point.applyMatrix4(viewProjection)));
2217
+ if (polygon.length < 3)
2218
+ continue;
2219
+ for (let fan = 1; fan + 1 < polygon.length; fan += 1) {
2220
+ const first = polygon[0];
2221
+ const second = polygon[fan];
2222
+ const third = polygon[fan + 1];
2223
+ if (!first || !second || !third)
2224
+ continue;
2225
+ const clipTriangle = [first, second, third];
2226
+ const points = clipTriangle.map((point) => projectedPoint(textured || coloured
2227
+ ? point.position
2228
+ : point, options.width, options.height));
2229
+ if (points.some((point) => point === undefined))
2230
+ continue;
2231
+ const projected = points;
2232
+ const area = signedArea(projected) * (mirrored ? -1 : 1);
2233
+ if (area === 0)
2234
+ continue;
2235
+ const side = range.material.side;
2236
+ if (side !== DoubleSide && (side === BackSide ? area < 0 : area > 0))
2237
+ continue;
2238
+ const path = `M ${printable(projected[0]?.x ?? 0)} ${printable(projected[0]?.y ?? 0)} L ${printable(projected[1]?.x ?? 0)} ${printable(projected[1]?.y ?? 0)} L ${printable(projected[2]?.x ?? 0)} ${printable(projected[2]?.y ?? 0)} Z`;
2239
+ primitives.push({
2240
+ depth: projected.reduce((sum, point) => sum + point.z, 0) / 3,
2241
+ groupOrder,
2242
+ object,
2243
+ order: order++,
2244
+ renderOrder: object.renderOrder,
2245
+ transparent: range.material.transparent,
2246
+ node: textured
2247
+ ? {
2248
+ kind: 'triangle-mesh',
2249
+ props: {
2250
+ texture: {
2251
+ source: textureSource(map),
2252
+ coordinates: clipTriangle.map((point) => {
2253
+ const coordinate = point.texture;
2254
+ return { x: coordinate.x, y: coordinate.y };
2255
+ }),
2256
+ filter: map.magFilter === NearestFilter ? 'nearest' : 'linear',
2257
+ ...textureWrapProps(map),
2258
+ ...textureTintProps(range.material.color),
2259
+ },
2260
+ vertices: projected.map(({ x, y }) => ({ x, y })),
2261
+ ...projectedOpacityProps(range.material),
2262
+ },
2263
+ }
2264
+ : coloured
2265
+ ? {
2266
+ kind: 'triangle-mesh',
2267
+ props: {
2268
+ colors: clipTriangle.map((point) => canvasVertexColor(foggedColorAtDepth(point.color, rangeFog, point.viewDepth ?? 0), point.alpha)),
2269
+ vertices: projected.map(({ x, y }) => ({ x, y })),
2270
+ ...projectedOpacityProps(range.material),
2271
+ },
2272
+ }
2273
+ : {
2274
+ kind: 'path',
2275
+ props: { path, fill, ...projectedOpacityProps(range.material) },
2276
+ },
2277
+ });
2278
+ }
2279
+ }
2280
+ }
2281
+ }
2282
+ }
2283
+ });
2284
+ primitives.sort((left, right) => Number(left.transparent) - Number(right.transparent) ||
2285
+ left.groupOrder - right.groupOrder ||
2286
+ left.renderOrder - right.renderOrder ||
2287
+ right.depth - left.depth ||
2288
+ left.order - right.order);
2289
+ return {
2290
+ scene: [...decoration, ...primitives.map((primitive) => primitive.node)],
2291
+ objects: [...decorationObjects, ...primitives.map((primitive) => primitive.object)],
2292
+ diagnostics,
2293
+ };
2294
+ }
2295
+ export function projectThreeScene(scene, camera, options) {
2296
+ return projectThreeSceneInternal(scene, camera, options, true);
2297
+ }
2298
+ //# sourceMappingURL=project.js.map