@hozo/three 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +389 -0
  3. package/conformance.md +335 -0
  4. package/dist/accessible-controls.d.ts +55 -0
  5. package/dist/accessible-controls.d.ts.map +1 -0
  6. package/dist/accessible-controls.js +82 -0
  7. package/dist/accessible-controls.js.map +1 -0
  8. package/dist/conformance-scenes.d.ts +39 -0
  9. package/dist/conformance-scenes.d.ts.map +1 -0
  10. package/dist/conformance-scenes.js +443 -0
  11. package/dist/conformance-scenes.js.map +1 -0
  12. package/dist/index.d.ts +4 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +3 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/line-gradient.d.ts +13 -0
  17. package/dist/line-gradient.d.ts.map +1 -0
  18. package/dist/line-gradient.js +104 -0
  19. package/dist/line-gradient.js.map +1 -0
  20. package/dist/project.d.ts +23 -0
  21. package/dist/project.d.ts.map +1 -0
  22. package/dist/project.js +2298 -0
  23. package/dist/project.js.map +1 -0
  24. package/dist/r3f-accessibility.d.ts +30 -0
  25. package/dist/r3f-accessibility.d.ts.map +1 -0
  26. package/dist/r3f-accessibility.js +4 -0
  27. package/dist/r3f-accessibility.js.map +1 -0
  28. package/dist/r3f-native-unavailable.d.ts +5 -0
  29. package/dist/r3f-native-unavailable.d.ts.map +1 -0
  30. package/dist/r3f-native-unavailable.js +5 -0
  31. package/dist/r3f-native-unavailable.js.map +1 -0
  32. package/dist/r3f-native.d.ts +23 -0
  33. package/dist/r3f-native.d.ts.map +1 -0
  34. package/dist/r3f-native.js +66 -0
  35. package/dist/r3f-native.js.map +1 -0
  36. package/dist/r3f-react-native.d.ts +5 -0
  37. package/dist/r3f-react-native.d.ts.map +1 -0
  38. package/dist/r3f-react-native.js +5 -0
  39. package/dist/r3f-react-native.js.map +1 -0
  40. package/dist/r3f.d.ts +39 -0
  41. package/dist/r3f.d.ts.map +1 -0
  42. package/dist/r3f.js +41 -0
  43. package/dist/r3f.js.map +1 -0
  44. package/dist/surface.d.ts +81 -0
  45. package/dist/surface.d.ts.map +1 -0
  46. package/dist/surface.js +79 -0
  47. package/dist/surface.js.map +1 -0
  48. package/dist/three-canvas.d.ts +42 -0
  49. package/dist/three-canvas.d.ts.map +1 -0
  50. package/dist/three-canvas.js +91 -0
  51. package/dist/three-canvas.js.map +1 -0
  52. package/dist/web-surface.d.ts +55 -0
  53. package/dist/web-surface.d.ts.map +1 -0
  54. package/dist/web-surface.js +285 -0
  55. package/dist/web-surface.js.map +1 -0
  56. package/dist/webgl-react-native.d.ts +5 -0
  57. package/dist/webgl-react-native.d.ts.map +1 -0
  58. package/dist/webgl-react-native.js +5 -0
  59. package/dist/webgl-react-native.js.map +1 -0
  60. package/dist/webgl-renderer.d.ts +14 -0
  61. package/dist/webgl-renderer.d.ts.map +1 -0
  62. package/dist/webgl-renderer.js +13 -0
  63. package/dist/webgl-renderer.js.map +1 -0
  64. package/dist/webgpu-react-native.d.ts +5 -0
  65. package/dist/webgpu-react-native.d.ts.map +1 -0
  66. package/dist/webgpu-react-native.js +5 -0
  67. package/dist/webgpu-react-native.js.map +1 -0
  68. package/dist/webgpu.d.ts +18 -0
  69. package/dist/webgpu.d.ts.map +1 -0
  70. package/dist/webgpu.js +29 -0
  71. package/dist/webgpu.js.map +1 -0
  72. package/package.json +122 -0
  73. package/scene-conformance.json +244 -0
  74. package/scene-conformance.md +31 -0
  75. package/src/accessible-controls.ts +84 -0
  76. package/src/conformance-scenes.ts +529 -0
  77. package/src/index.ts +24 -0
  78. package/src/line-gradient.ts +134 -0
  79. package/src/project.ts +2742 -0
  80. package/src/r3f-accessibility.ts +37 -0
  81. package/src/r3f-native-unavailable.tsx +15 -0
  82. package/src/r3f-native.tsx +187 -0
  83. package/src/r3f-react-native.tsx +17 -0
  84. package/src/r3f.tsx +159 -0
  85. package/src/surface.ts +178 -0
  86. package/src/three-canvas.tsx +215 -0
  87. package/src/web-surface.tsx +475 -0
  88. package/src/webgl-react-native.tsx +17 -0
  89. package/src/webgl-renderer.tsx +56 -0
  90. package/src/webgpu-react-native.tsx +17 -0
  91. package/src/webgpu.tsx +71 -0
@@ -0,0 +1,529 @@
1
+ import {
2
+ AmbientLight,
3
+ AnimationMixer,
4
+ BoxGeometry,
5
+ BufferGeometry,
6
+ Cache,
7
+ Color,
8
+ DataTexture,
9
+ Float32BufferAttribute,
10
+ InstancedMesh,
11
+ LineBasicMaterial,
12
+ LineSegments,
13
+ LoadingManager,
14
+ Matrix4,
15
+ Mesh,
16
+ MeshBasicMaterial,
17
+ MeshStandardMaterial,
18
+ NearestFilter,
19
+ type Object3D,
20
+ OrthographicCamera,
21
+ PerspectiveCamera,
22
+ Points,
23
+ PointsMaterial,
24
+ RGBAFormat,
25
+ Scene,
26
+ Sprite,
27
+ SpriteMaterial,
28
+ SRGBColorSpace,
29
+ type Texture,
30
+ TextureLoader,
31
+ UnsignedByteType,
32
+ } from 'three'
33
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
34
+
35
+ export interface SceneCorpusScene {
36
+ animation?: { object: Object3D; update: (delta: number) => void }
37
+ camera: OrthographicCamera | PerspectiveCamera
38
+ scene: Scene
39
+ textureImage?: { decoding: 'fixture' | 'host'; width: number; height: number }
40
+ }
41
+
42
+ export interface SceneCorpusHostOptions {
43
+ /** GPU hosts supply their image loader; Node's deterministic report uses pinned pixels. */
44
+ textureLoader?: TextureLoader
45
+ }
46
+
47
+ export interface SceneCorpusSceneDefinition {
48
+ create: (
49
+ loadGltfSource: () => Promise<string>,
50
+ options?: SceneCorpusHostOptions,
51
+ ) => Promise<SceneCorpusScene>
52
+ id: string
53
+ }
54
+
55
+ /**
56
+ * The tiny pinned glTF asset used by every conformance host.
57
+ *
58
+ * Keeping the source beside the scene builders lets browser, Node and React
59
+ * Native execute the same asset without teaching Metro how to import `.gltf`
60
+ * files. `fixtures/minimal-pbr.gltf` remains the human-readable copy used by
61
+ * the report and is checked against this value by the corpus test.
62
+ */
63
+ export const MINIMAL_PBR_GLTF_SOURCE = JSON.stringify({
64
+ asset: { generator: '@hozo/three real-scene corpus', version: '2.0' },
65
+ scene: 0,
66
+ scenes: [{ nodes: [0] }],
67
+ nodes: [{ mesh: 0, name: 'Pinned PBR triangle' }],
68
+ meshes: [{ primitives: [{ attributes: { POSITION: 0 }, material: 0 }] }],
69
+ materials: [
70
+ {
71
+ name: 'Ordinary PBR material',
72
+ pbrMetallicRoughness: {
73
+ baseColorFactor: [0.125, 0.45, 0.85, 1],
74
+ metallicFactor: 0.25,
75
+ roughnessFactor: 0.65,
76
+ },
77
+ },
78
+ ],
79
+ accessors: [
80
+ {
81
+ bufferView: 0,
82
+ componentType: 5126,
83
+ count: 3,
84
+ max: [1, 1, 0],
85
+ min: [-1, -1, 0],
86
+ type: 'VEC3',
87
+ },
88
+ ],
89
+ bufferViews: [{ buffer: 0, byteLength: 36 }],
90
+ buffers: [
91
+ {
92
+ byteLength: 36,
93
+ uri: 'data:application/octet-stream;base64,AACAvwAAgL8AAAAAAAAAPwAAgL8AAAAAAAAAAAAAAD8AAAAA',
94
+ },
95
+ ],
96
+ })
97
+
98
+ /**
99
+ * A self-contained product-viewer asset with a node hierarchy, UVs, two PBR
100
+ * materials, a punctual light, and a rotation animation. Its small embedded
101
+ * buffer makes the same glTF loadable by the browser and Hermes probes.
102
+ */
103
+ export const PRODUCT_VIEWER_GLTF_SOURCE = JSON.stringify({
104
+ asset: { generator: '@hozo/three product-viewer corpus', version: '2.0' },
105
+ extensionsUsed: ['KHR_lights_punctual'],
106
+ extensions: {
107
+ KHR_lights_punctual: {
108
+ lights: [{ type: 'point', color: [1, 0.94, 0.85], intensity: 30 }],
109
+ },
110
+ },
111
+ scene: 0,
112
+ scenes: [{ nodes: [0, 2] }],
113
+ nodes: [
114
+ { mesh: 0, name: 'Product housing', children: [1] },
115
+ { mesh: 1, name: 'Product display' },
116
+ {
117
+ name: 'Product key light',
118
+ translation: [1, 2, 2],
119
+ extensions: { KHR_lights_punctual: { light: 0 } },
120
+ },
121
+ ],
122
+ meshes: [
123
+ {
124
+ primitives: [
125
+ { attributes: { POSITION: 0, NORMAL: 1, TEXCOORD_0: 2 }, indices: 3, material: 0 },
126
+ ],
127
+ },
128
+ {
129
+ primitives: [
130
+ { attributes: { POSITION: 4, NORMAL: 5, TEXCOORD_0: 6 }, indices: 7, material: 1 },
131
+ ],
132
+ },
133
+ ],
134
+ materials: [
135
+ {
136
+ name: 'Brushed housing',
137
+ pbrMetallicRoughness: {
138
+ baseColorFactor: [0.3, 0.4, 0.55, 1],
139
+ metallicFactor: 0.4,
140
+ roughnessFactor: 0.55,
141
+ },
142
+ },
143
+ {
144
+ name: 'Display surface',
145
+ pbrMetallicRoughness: {
146
+ baseColorTexture: { index: 0 },
147
+ metallicFactor: 0,
148
+ roughnessFactor: 0.8,
149
+ },
150
+ },
151
+ ],
152
+ textures: [{ source: 0 }],
153
+ images: [
154
+ {
155
+ uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAFklEQVR4nGOQDur9D8Jf5xmCMQPpAgDkoCXhxs9CRAAAAABJRU5ErkJggg==',
156
+ },
157
+ ],
158
+ animations: [
159
+ {
160
+ name: 'Turntable',
161
+ samplers: [{ input: 8, output: 9, interpolation: 'LINEAR' }],
162
+ channels: [{ sampler: 0, target: { node: 0, path: 'rotation' } }],
163
+ },
164
+ ],
165
+ accessors: [
166
+ {
167
+ bufferView: 0,
168
+ componentType: 5126,
169
+ count: 8,
170
+ min: [-0.7, -0.8, -0.15],
171
+ max: [0.7, 0.8, 0.15],
172
+ type: 'VEC3',
173
+ },
174
+ { bufferView: 1, componentType: 5126, count: 8, type: 'VEC3' },
175
+ { bufferView: 2, componentType: 5126, count: 8, type: 'VEC2' },
176
+ { bufferView: 3, componentType: 5123, count: 36, type: 'SCALAR' },
177
+ {
178
+ bufferView: 4,
179
+ componentType: 5126,
180
+ count: 4,
181
+ min: [-0.55, -0.65, 0.16],
182
+ max: [0.55, 0.65, 0.16],
183
+ type: 'VEC3',
184
+ },
185
+ { bufferView: 5, componentType: 5126, count: 4, type: 'VEC3' },
186
+ { bufferView: 6, componentType: 5126, count: 4, type: 'VEC2' },
187
+ { bufferView: 7, componentType: 5123, count: 6, type: 'SCALAR' },
188
+ { bufferView: 8, componentType: 5126, count: 3, min: [0], max: [1], type: 'SCALAR' },
189
+ { bufferView: 9, componentType: 5126, count: 3, type: 'VEC4' },
190
+ ],
191
+ bufferViews: [
192
+ { buffer: 0, byteOffset: 0, byteLength: 96 },
193
+ { buffer: 0, byteOffset: 96, byteLength: 96 },
194
+ { buffer: 0, byteOffset: 192, byteLength: 64 },
195
+ { buffer: 0, byteOffset: 256, byteLength: 72 },
196
+ { buffer: 0, byteOffset: 328, byteLength: 48 },
197
+ { buffer: 0, byteOffset: 376, byteLength: 48 },
198
+ { buffer: 0, byteOffset: 424, byteLength: 32 },
199
+ { buffer: 0, byteOffset: 456, byteLength: 12 },
200
+ { buffer: 0, byteOffset: 468, byteLength: 12 },
201
+ { buffer: 0, byteOffset: 480, byteLength: 48 },
202
+ ],
203
+ buffers: [
204
+ {
205
+ byteLength: 528,
206
+ uri: 'data:application/octet-stream;base64,MzMzv83MTL+amRm+MzMzP83MTL+amRm+MzMzP83MTD+amRm+MzMzv83MTD+amRm+MzMzv83MTL+amRk+MzMzP83MTL+amRk+MzMzP83MTD+amRk+MzMzv83MTD+amRk+AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAgD8AAIA/AAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAACAPwAAgD8AAAAAAACAPwAAAgABAAAAAwACAAQABQAGAAQABgAHAAAAAQAFAAAABQAEAAMABwAGAAMABgACAAEAAgAGAAEABgAFAAAABAAHAAAABwADAM3MDL9mZia/CtcjPs3MDD9mZia/CtcjPs3MDD9mZiY/CtcjPs3MDL9mZiY/CtcjPgAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAIA/AACAPwAAAAAAAIA/AAABAAIAAAACAAMAAAAAAAAAAD8AAIA/AAAAAAAAAAAAAAAAAACAPwAAAAB3V30+AAAAAKUKeD8AAAAAAAAAAAAAAAAAAIA/',
207
+ },
208
+ ],
209
+ })
210
+
211
+ function perspective(): PerspectiveCamera {
212
+ const camera = new PerspectiveCamera(90, 1, 0.1, 100)
213
+ camera.position.z = 5
214
+ camera.updateProjectionMatrix()
215
+ return camera
216
+ }
217
+
218
+ function decodeUtf8(input: AllowSharedBufferSource | undefined): string {
219
+ if (!input) return ''
220
+ const bytes = ArrayBuffer.isView(input)
221
+ ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength)
222
+ : new Uint8Array(input)
223
+ let result = ''
224
+ for (let index = 0; index < bytes.length; ) {
225
+ const first = bytes[index++] ?? 0
226
+ if (first < 0x80) {
227
+ result += String.fromCharCode(first)
228
+ continue
229
+ }
230
+ const width = first < 0xe0 ? 2 : first < 0xf0 ? 3 : 4
231
+ let codePoint = first & (0x7f >> width)
232
+ for (let offset = 1; offset < width; offset += 1) {
233
+ const next = bytes[index++]
234
+ if (next === undefined || (next & 0xc0) !== 0x80) {
235
+ result += '\uFFFD'
236
+ codePoint = -1
237
+ break
238
+ }
239
+ codePoint = (codePoint << 6) | (next & 0x3f)
240
+ }
241
+ if (codePoint < 0) continue
242
+ if (codePoint <= 0xffff) result += String.fromCharCode(codePoint)
243
+ else {
244
+ const astral = codePoint - 0x10000
245
+ result += String.fromCharCode(0xd800 + (astral >> 10), 0xdc00 + (astral & 0x3ff))
246
+ }
247
+ }
248
+ return result
249
+ }
250
+
251
+ function decodeBase64(value: string): ArrayBuffer {
252
+ const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
253
+ const clean = value.replace(/\s/g, '')
254
+ const bytes: number[] = []
255
+ for (let index = 0; index < clean.length; index += 4) {
256
+ const a = alphabet.indexOf(clean[index] ?? '')
257
+ const b = alphabet.indexOf(clean[index + 1] ?? '')
258
+ const c = alphabet.indexOf(clean[index + 2] ?? '')
259
+ const d = alphabet.indexOf(clean[index + 3] ?? '')
260
+ if (a < 0 || b < 0) throw new Error('Invalid embedded glTF base64 buffer')
261
+ bytes.push((a << 2) | (b >> 4))
262
+ if (clean[index + 2] !== '=') {
263
+ if (c < 0) throw new Error('Invalid embedded glTF base64 buffer')
264
+ bytes.push(((b & 0x0f) << 4) | (c >> 2))
265
+ }
266
+ if (clean[index + 3] !== '=') {
267
+ if (c < 0 || d < 0) throw new Error('Invalid embedded glTF base64 buffer')
268
+ bytes.push(((c & 0x03) << 6) | d)
269
+ }
270
+ }
271
+ return Uint8Array.from(bytes).buffer
272
+ }
273
+
274
+ function cacheEmbeddedGltfBuffers(source: string): () => void {
275
+ const document = JSON.parse(source) as { buffers?: { uri?: string }[] }
276
+ const previousEnabled = Cache.enabled
277
+ Cache.enabled = true
278
+ const entries = (document.buffers ?? []).flatMap(({ uri }) => {
279
+ if (!uri?.startsWith('data:') || !uri.includes(';base64,')) return []
280
+ const key = `file:${uri}`
281
+ const previous = Cache.get(key)
282
+ Cache.add(key, decodeBase64(uri.slice(uri.indexOf(',') + 1)))
283
+ return [{ key, previous }]
284
+ })
285
+ return () => {
286
+ for (const { key, previous } of entries) {
287
+ if (previous === undefined) Cache.remove(key)
288
+ else Cache.add(key, previous)
289
+ }
290
+ Cache.enabled = previousEnabled
291
+ }
292
+ }
293
+
294
+ function installGltfHostPolyfills(): void {
295
+ // GLTFLoader's image-source path reads self.URL even for a data: URI
296
+ // handled by the fixture's own TextureLoader. Hermes does not expose self.
297
+ if (typeof globalThis.self === 'undefined') {
298
+ Object.defineProperty(globalThis, 'self', { configurable: true, value: globalThis })
299
+ }
300
+ // Hermes does not expose TextDecoder. GLTFLoader uses it while parsing even
301
+ // an embedded JSON fixture, so keep this conformance-only host shim beside
302
+ // the fixture instead of adding a runtime dependency to @hozo/three.
303
+ if (typeof globalThis.TextDecoder === 'undefined') {
304
+ Object.defineProperty(globalThis, 'TextDecoder', {
305
+ configurable: true,
306
+ value: class ConformanceTextDecoder {
307
+ readonly encoding = 'utf-8'
308
+
309
+ decode(input?: AllowSharedBufferSource): string {
310
+ return decodeUtf8(input)
311
+ }
312
+ },
313
+ })
314
+ }
315
+
316
+ // React Native defines navigator, but unlike browsers it may omit
317
+ // userAgent. GLTFLoader currently probes it unconditionally when choosing a
318
+ // texture loader, including for this texture-free fixture.
319
+ if (typeof globalThis.navigator === 'undefined') {
320
+ Object.defineProperty(globalThis, 'navigator', {
321
+ configurable: true,
322
+ value: { userAgent: 'React Native' },
323
+ })
324
+ } else if (typeof globalThis.navigator.userAgent !== 'string') {
325
+ Object.defineProperty(globalThis.navigator, 'userAgent', {
326
+ configurable: true,
327
+ value: 'React Native',
328
+ })
329
+ }
330
+
331
+ if (typeof globalThis.ProgressEvent !== 'undefined') return
332
+ Object.defineProperty(globalThis, 'ProgressEvent', {
333
+ configurable: true,
334
+ value: class ConformanceProgressEvent extends Event {
335
+ readonly lengthComputable: boolean
336
+ readonly loaded: number
337
+ readonly total: number
338
+
339
+ constructor(type: string, init: ProgressEventInit = {}) {
340
+ super(type)
341
+ this.lengthComputable = init.lengthComputable ?? false
342
+ this.loaded = init.loaded ?? 0
343
+ this.total = init.total ?? 0
344
+ }
345
+ },
346
+ })
347
+ }
348
+
349
+ function triangleGeometry(): BufferGeometry {
350
+ return new BufferGeometry().setAttribute(
351
+ 'position',
352
+ new Float32BufferAttribute([-1, -1, 0, 1, -1, 0, 0, 1, 0], 3),
353
+ )
354
+ }
355
+
356
+ async function flatDiagram(): Promise<SceneCorpusScene> {
357
+ const camera = new OrthographicCamera(-4, 4, 3, -3, 0.1, 20)
358
+ camera.position.z = 5
359
+ camera.updateProjectionMatrix()
360
+ const scene = new Scene()
361
+ scene.background = new Color('#f8fafc')
362
+ const left = new Mesh(triangleGeometry(), new MeshBasicMaterial({ color: '#2563eb' }))
363
+ left.name = 'Input node'
364
+ left.position.x = -1.5
365
+ const right = new Mesh(triangleGeometry(), new MeshBasicMaterial({ color: '#16a34a' }))
366
+ right.name = 'Output node'
367
+ right.position.x = 1.5
368
+ const edge = new BufferGeometry().setAttribute(
369
+ 'position',
370
+ new Float32BufferAttribute([-0.5, 0, 0, 0.5, 0, 0], 3),
371
+ )
372
+ const connector = new LineSegments(edge, new LineBasicMaterial({ color: '#475569' }))
373
+ connector.name = 'Connection'
374
+ scene.add(left, connector, right)
375
+ return { camera, scene }
376
+ }
377
+
378
+ async function wireframeCad(): Promise<SceneCorpusScene> {
379
+ const scene = new Scene()
380
+ const model = new Mesh(
381
+ new BoxGeometry(2, 2, 2),
382
+ new MeshBasicMaterial({ color: '#0f766e', wireframe: true }),
383
+ )
384
+ model.name = 'Wireframe assembly'
385
+ model.rotation.set(0.4, 0.6, 0.1)
386
+ scene.add(model)
387
+ return { camera: perspective(), scene }
388
+ }
389
+
390
+ async function pointsAndSprite(): Promise<SceneCorpusScene> {
391
+ const scene = new Scene()
392
+ const geometry = new BufferGeometry().setAttribute(
393
+ 'position',
394
+ new Float32BufferAttribute([-1.5, 0, 0, 0, 1, 0, 1.5, 0, 0], 3),
395
+ )
396
+ const cloud = new Points(
397
+ geometry,
398
+ new PointsMaterial({ color: '#7c3aed', size: 8, sizeAttenuation: false }),
399
+ )
400
+ cloud.name = 'Point cloud'
401
+ const marker = new Sprite(new SpriteMaterial({ color: '#f97316' }))
402
+ marker.name = 'Selected point'
403
+ marker.position.set(0, -1, 0)
404
+ scene.add(cloud, marker)
405
+ return { camera: perspective(), scene }
406
+ }
407
+
408
+ async function instancingAndMorph(): Promise<SceneCorpusScene> {
409
+ const geometry = triangleGeometry()
410
+ geometry.morphTargetsRelative = true
411
+ geometry.morphAttributes.position = [new Float32BufferAttribute([-1, 0, 0, 1, 0, 0, 0, 2, 0], 3)]
412
+ const instances = new InstancedMesh(geometry, new MeshBasicMaterial({ color: '#0284c7' }), 2)
413
+ instances.name = 'Morphed instances'
414
+ instances.setMatrixAt(0, new Matrix4().makeTranslation(-1.25, 0, 0))
415
+ instances.setMatrixAt(1, new Matrix4().makeTranslation(1.25, 0, 0))
416
+ const morphTarget = new Mesh(geometry)
417
+ if (!morphTarget.morphTargetInfluences) throw new Error('morph target did not initialise')
418
+ morphTarget.morphTargetInfluences[0] = 0
419
+ instances.setMorphAt(0, morphTarget)
420
+ morphTarget.morphTargetInfluences[0] = 1
421
+ instances.setMorphAt(1, morphTarget)
422
+ const scene = new Scene()
423
+ scene.add(instances)
424
+ return { camera: perspective(), scene }
425
+ }
426
+
427
+ async function pinnedGltfPbr(loadGltfSource: () => Promise<string>): Promise<SceneCorpusScene> {
428
+ const source = await loadGltfSource()
429
+ const gltf = await parseEmbeddedGltf(source)
430
+ const scene = new Scene()
431
+ scene.add(new AmbientLight('#ffffff', 2), gltf.scene)
432
+ return { camera: perspective(), scene }
433
+ }
434
+
435
+ async function parseEmbeddedGltf(source: string, manager?: LoadingManager) {
436
+ installGltfHostPolyfills()
437
+ // React Native's fetch does not load data: buffers. Seed Three's public
438
+ // FileLoader cache with the exact embedded bytes, which also avoids adding
439
+ // a global fetch shim merely to execute this conformance fixture.
440
+ const restoreCache = cacheEmbeddedGltfBuffers(source)
441
+ return new GLTFLoader(manager).parseAsync(source, '').finally(restoreCache)
442
+ }
443
+
444
+ async function productViewer(
445
+ _loadGltfSource: () => Promise<string>,
446
+ options: SceneCorpusHostOptions = {},
447
+ ): Promise<SceneCorpusScene> {
448
+ const pixels = new Uint8Array([
449
+ 27, 82, 141, 255, 27, 82, 141, 255, 245, 158, 49, 255, 245, 158, 49, 255, 27, 82, 141, 255, 27,
450
+ 82, 141, 255, 245, 158, 49, 255, 245, 158, 49, 255, 27, 82, 141, 255, 27, 82, 141, 255, 245,
451
+ 158, 49, 255, 245, 158, 49, 255, 27, 82, 141, 255, 27, 82, 141, 255, 245, 158, 49, 255, 245,
452
+ 158, 49, 255,
453
+ ])
454
+ // Node reports use pinned pixels. GPU probes supply the host's TextureLoader
455
+ // to decode the embedded PNG through the browser or R3F Native/Expo GL.
456
+ const manager = new LoadingManager()
457
+ class CorpusTextureLoader extends TextureLoader {
458
+ override load(_url: string, onLoad?: (texture: Texture) => void): Texture {
459
+ const texture = new DataTexture(pixels, 4, 4, RGBAFormat, UnsignedByteType)
460
+ texture.colorSpace = SRGBColorSpace
461
+ texture.magFilter = NearestFilter
462
+ texture.minFilter = NearestFilter
463
+ texture.needsUpdate = true
464
+ onLoad?.(texture)
465
+ return texture
466
+ }
467
+ }
468
+ const imageLoader = options.textureLoader ?? new CorpusTextureLoader(manager)
469
+ let imageError: unknown
470
+ class CheckedTextureLoader extends TextureLoader {
471
+ override load(
472
+ url: string,
473
+ onLoad?: (texture: Texture) => void,
474
+ onProgress?: (event: ProgressEvent) => void,
475
+ onError?: (error: unknown) => void,
476
+ ): Texture {
477
+ return imageLoader.load(url, onLoad, onProgress, (error) => {
478
+ imageError = error
479
+ onError?.(error)
480
+ })
481
+ }
482
+ }
483
+ manager.addHandler(/^data:image\/png/, new CheckedTextureLoader(manager))
484
+ const gltf = await parseEmbeddedGltf(PRODUCT_VIEWER_GLTF_SOURCE, manager)
485
+ const housing = gltf.scene.getObjectByName('Product_housing')
486
+ const display = gltf.scene.getObjectByName('Product_display')
487
+ if (
488
+ !(housing instanceof Mesh) ||
489
+ !(display instanceof Mesh) ||
490
+ !(display.material instanceof MeshStandardMaterial)
491
+ ) {
492
+ throw new Error('Product viewer glTF did not load its PBR display mesh')
493
+ }
494
+ const image = display.material.map?.image as { width?: number; height?: number } | undefined
495
+ if (image?.width !== 4 || image.height !== 4) {
496
+ throw new Error(
497
+ `Product viewer glTF did not decode and bind its 4x4 base colour texture${imageError ? `: ${imageError instanceof Error ? imageError.message : String(imageError)}` : ''}`,
498
+ )
499
+ }
500
+
501
+ const turntable = gltf.animations.find((clip) => clip.name === 'Turntable')
502
+ if (!turntable) throw new Error('Product viewer glTF did not load its animation')
503
+ const mixer = new AnimationMixer(gltf.scene)
504
+ mixer.clipAction(turntable).play()
505
+ mixer.setTime(0.5)
506
+
507
+ const scene = new Scene()
508
+ scene.add(new AmbientLight('#ffffff', 0.6), gltf.scene)
509
+ scene.updateMatrixWorld(true)
510
+ return {
511
+ animation: { object: housing, update: (delta) => mixer.update(delta) },
512
+ camera: perspective(),
513
+ scene,
514
+ textureImage: {
515
+ decoding: options.textureLoader ? 'host' : 'fixture',
516
+ width: image.width,
517
+ height: image.height,
518
+ },
519
+ }
520
+ }
521
+
522
+ export const SCENE_CORPUS_SCENES: readonly SceneCorpusSceneDefinition[] = [
523
+ { create: flatDiagram, id: 'flat-labelled-diagram' },
524
+ { create: wireframeCad, id: 'wireframe-cad' },
525
+ { create: pointsAndSprite, id: 'points-and-sprite' },
526
+ { create: instancingAndMorph, id: 'instancing-and-morph' },
527
+ { create: productViewer, id: 'product-viewer-gltf' },
528
+ { create: pinnedGltfPbr, id: 'gltf-pbr' },
529
+ ]
package/src/index.ts ADDED
@@ -0,0 +1,24 @@
1
+ export {
2
+ projectThreeScene,
3
+ type ThreeProjection,
4
+ type ThreeProjectionDiagnostic,
5
+ type ThreeProjectionDiagnosticCode,
6
+ type ThreeProjectionOptions,
7
+ } from './project.ts'
8
+ export type {
9
+ ThreeSurfaceCameraResize,
10
+ ThreeSurfaceFrame,
11
+ ThreeSurfaceFrameloop,
12
+ ThreeSurfaceHandle,
13
+ ThreeSurfaceProps,
14
+ ThreeSurfaceSize,
15
+ } from './surface.ts'
16
+ export {
17
+ ThreeCanvas,
18
+ type ThreeCanvasCamera,
19
+ type ThreeCanvasFrame,
20
+ type ThreeCanvasFrameloop,
21
+ type ThreeCanvasHandle,
22
+ type ThreeCanvasObjectEvent,
23
+ type ThreeCanvasProps,
24
+ } from './three-canvas.tsx'
@@ -0,0 +1,134 @@
1
+ interface LinearRGB {
2
+ r: number
3
+ g: number
4
+ b: number
5
+ }
6
+
7
+ interface Stop {
8
+ readonly offset: number
9
+ readonly color: string
10
+ }
11
+
12
+ const maximumStops = 32
13
+ const cache = new Map<string, readonly Stop[]>()
14
+ // A small table avoids three pow calls per refinement sample. Interpolation
15
+ // preserves sub-byte precision, including the steep dark end of the curve.
16
+ const encoded = Float32Array.from({ length: 4097 }, (_, index) => {
17
+ const value = index / 4096
18
+ return 255 * (value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055)
19
+ })
20
+
21
+ function channel(value: number): number {
22
+ const position = Math.max(0, Math.min(1, value)) * 4096
23
+ const index = Math.floor(position)
24
+ return index === 4096
25
+ ? 255
26
+ : encoded[index]! + (encoded[index + 1]! - encoded[index]!) * (position - index)
27
+ }
28
+
29
+ function css(r: number, g: number, b: number): string {
30
+ return `#${((Math.round(r) << 16) | (Math.round(g) << 8) | Math.round(b)).toString(16).padStart(6, '0')}`
31
+ }
32
+
33
+ /** Bounded approximation of opaque linear-RGB, perspective-correct line colour. */
34
+ export function portableLineColorStops(
35
+ from: LinearRGB,
36
+ to: LinearRGB,
37
+ fromW: number,
38
+ toW: number,
39
+ projectedLength: number,
40
+ ): readonly Stop[] {
41
+ const budget = Math.max(2, Math.min(maximumStops, 1 + Math.ceil(projectedLength / 2)))
42
+ const depthRatio = toW / fromW
43
+ // Position is deliberately absent: translating an edge can reuse its stops.
44
+ // The bounded cache cannot grow with the number of animation frames.
45
+ const key = `${from.r},${from.g},${from.b},${to.r},${to.g},${to.b},${depthRatio},${budget}`
46
+ const previous = cache.get(key)
47
+ if (previous) return previous
48
+
49
+ if (budget === 2 || (from.r === to.r && from.g === to.g && from.b === to.b)) {
50
+ const stops = Object.freeze([
51
+ Object.freeze({ offset: 0, color: css(channel(from.r), channel(from.g), channel(from.b)) }),
52
+ Object.freeze({ offset: 1, color: css(channel(to.r), channel(to.g), channel(to.b)) }),
53
+ ])
54
+ if (cache.size >= 256) cache.delete(cache.keys().next().value!)
55
+ cache.set(key, stops)
56
+ return stops
57
+ }
58
+
59
+ const positions = new Float64Array(maximumStops)
60
+ const colors = new Float64Array(maximumStops * 3)
61
+ const errors = new Float64Array(maximumStops)
62
+ const splits = new Float64Array(maximumStops)
63
+ const dr = to.r - from.r
64
+ const dg = to.g - from.g
65
+ const db = to.b - from.b
66
+ const sourceRatio = (s: number) => s / ((1 - s) * depthRatio + s)
67
+ const evaluate = (index: number, position: number) => {
68
+ positions[index] = position
69
+ const t = sourceRatio(position)
70
+ colors[index * 3] = channel(from.r + dr * t)
71
+ colors[index * 3 + 1] = channel(from.g + dg * t)
72
+ colors[index * 3 + 2] = channel(from.b + db * t)
73
+ }
74
+ const intervalError = (index: number) => {
75
+ let error = 0
76
+ let split = 0
77
+ for (let fraction = 0.25; fraction < 1; fraction += 0.25) {
78
+ const position = positions[index]! + (positions[index + 1]! - positions[index]!) * fraction
79
+ const t = sourceRatio(position)
80
+ const at = index * 3
81
+ const largest = Math.max(
82
+ Math.abs(
83
+ channel(from.r + dr * t) - (colors[at]! + (colors[at + 3]! - colors[at]!) * fraction),
84
+ ),
85
+ Math.abs(
86
+ channel(from.g + dg * t) -
87
+ (colors[at + 1]! + (colors[at + 4]! - colors[at + 1]!) * fraction),
88
+ ),
89
+ Math.abs(
90
+ channel(from.b + db * t) -
91
+ (colors[at + 2]! + (colors[at + 5]! - colors[at + 2]!) * fraction),
92
+ ),
93
+ )
94
+ if (largest > error) {
95
+ error = largest
96
+ split = position
97
+ }
98
+ }
99
+ errors[index] = error
100
+ splits[index] = split
101
+ }
102
+ evaluate(0, 0)
103
+ evaluate(1, 1)
104
+ let count = 2
105
+ intervalError(0)
106
+ while (count < budget) {
107
+ let index = 0
108
+ for (let candidate = 1; candidate < count - 1; candidate += 1)
109
+ if (errors[candidate]! > errors[index]!) index = candidate
110
+ // Sub-byte accuracy is not a host-pixel guarantee: CSS stops are quantized
111
+ // and short edges can exhaust their screen-length budget first.
112
+ if (errors[index]! <= 1) break
113
+ const position = splits[index]!
114
+ positions.copyWithin(index + 2, index + 1, count)
115
+ colors.copyWithin((index + 2) * 3, (index + 1) * 3, count * 3)
116
+ errors.copyWithin(index + 2, index + 1, count - 1)
117
+ splits.copyWithin(index + 2, index + 1, count - 1)
118
+ evaluate(index + 1, position)
119
+ count += 1
120
+ intervalError(index)
121
+ intervalError(index + 1)
122
+ }
123
+ const stops = Object.freeze(
124
+ Array.from({ length: count }, (_, index) =>
125
+ Object.freeze({
126
+ offset: positions[index]!,
127
+ color: css(colors[index * 3]!, colors[index * 3 + 1]!, colors[index * 3 + 2]!),
128
+ }),
129
+ ),
130
+ )
131
+ if (cache.size >= 256) cache.delete(cache.keys().next().value!)
132
+ cache.set(key, stops)
133
+ return stops
134
+ }