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