@threenative/three-native 0.0.0-stage → 0.3.5
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.
- package/LICENSE +21 -0
- package/README.md +24 -2
- package/package.json +42 -3
- package/src/addons/buffer-geometry-utils.ts +14 -0
- package/src/addons/data-utils.ts +63 -0
- package/src/addons/decal-geometry.ts +25 -0
- package/src/addons/decal.ts +218 -0
- package/src/addons/gltf-loader-web.ts +323 -0
- package/src/addons/hdr-loader.ts +71 -0
- package/src/addons/hdr.ts +139 -0
- package/src/addons/lut-cube-loader-web.ts +17 -0
- package/src/addons/lut-cube-loader.ts +149 -0
- package/src/addons/merge-geometries.ts +374 -0
- package/src/addons/mesh-bvh-webgpu.ts +13 -0
- package/src/addons/mesh-bvh.ts +50 -0
- package/src/addons/post-effects-web.ts +22 -0
- package/src/addons/post-effects.ts +173 -0
- package/src/audio.ts +564 -0
- package/src/blend-mode.ts +33 -0
- package/src/browser-backend.ts +2156 -0
- package/src/browser-entry.ts +305 -0
- package/src/browser-math.ts +448 -0
- package/src/browser-renderer.ts +527 -0
- package/src/browser-tsl.ts +650 -0
- package/src/catalog.ts +497 -0
- package/src/fixture-format.ts +721 -0
- package/src/fixture-native.ts +426 -0
- package/src/fixture-protocol.ts +315 -0
- package/src/math-utils.ts +65 -0
- package/src/object-surface.ts +250 -0
- package/src/pass-node.ts +286 -0
- package/src/property-binding.ts +93 -0
- package/src/quad-mesh.ts +54 -0
- package/src/reflector.ts +89 -0
- package/src/refused.ts +27 -0
- package/src/render-target.ts +107 -0
- package/src/rtt.ts +158 -0
- package/src/shadow-map.ts +21 -0
- package/src/storage.ts +206 -0
- package/src/texture-sources.ts +252 -0
- package/src/tsl-extras.ts +51 -0
- package/src/tsl-struct.ts +20 -0
- package/src/tsl-uniforms.ts +234 -0
- package/src/update-ranges.ts +109 -0
- package/src/wgsl-fn.ts +55 -0
package/src/rtt.ts
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/** RTTNode's mutable target and quad over the engine's scheduled fullscreen pass. */
|
|
2
|
+
interface IRttNode {
|
|
3
|
+
__effect(name: string, value?: number): number;
|
|
4
|
+
__rtt(target: unknown, quad: unknown): unknown;
|
|
5
|
+
}
|
|
6
|
+
interface IRttQuad {
|
|
7
|
+
material: unknown;
|
|
8
|
+
name: string;
|
|
9
|
+
render(renderer: unknown): void;
|
|
10
|
+
}
|
|
11
|
+
export interface IRttClasses {
|
|
12
|
+
// quality-allow: three's class name, so a back end passes its class map.
|
|
13
|
+
// biome-ignore lint/style/useNamingConvention: three's class name, so a back end passes its class map.
|
|
14
|
+
NodeMaterial: new () => { name: string; needsUpdate: boolean; fragmentNode: unknown };
|
|
15
|
+
// quality-allow: three's class name, so a back end passes its class map.
|
|
16
|
+
// biome-ignore lint/style/useNamingConvention: three's class name, so a back end passes its class map.
|
|
17
|
+
QuadMesh: new (
|
|
18
|
+
...args: never[]
|
|
19
|
+
) => object;
|
|
20
|
+
// quality-allow: three's class name, so a back end passes its class map.
|
|
21
|
+
// biome-ignore lint/style/useNamingConvention: three's class name, so a back end passes its class map.
|
|
22
|
+
RenderTarget: new (
|
|
23
|
+
width: number,
|
|
24
|
+
height: number,
|
|
25
|
+
options: Record<string, unknown>,
|
|
26
|
+
) => {
|
|
27
|
+
texture: unknown;
|
|
28
|
+
width: number;
|
|
29
|
+
height: number;
|
|
30
|
+
setSize(w: number, h: number): void;
|
|
31
|
+
dispose(): void;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
function validateOptions(options: Record<string, unknown>): void {
|
|
35
|
+
for (const [key, value] of Object.entries(options)) {
|
|
36
|
+
if (key === "type" && value === 1016) continue;
|
|
37
|
+
if (key === "depthBuffer" && value === false) continue;
|
|
38
|
+
if ((key === "minFilter" || key === "magFilter") && (value === 1003 || value === 1006))
|
|
39
|
+
continue;
|
|
40
|
+
throw new TypeError(`TN_TSL_RTT_OPTION: unsupported ${key}=${value}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export function defineRtt(make: (...args: unknown[]) => IRttNode, classes?: IRttClasses) {
|
|
44
|
+
return (
|
|
45
|
+
source: unknown,
|
|
46
|
+
width: number | null = null,
|
|
47
|
+
height: number | null = null,
|
|
48
|
+
options: Record<string, unknown> = { type: 1016 },
|
|
49
|
+
) => {
|
|
50
|
+
validateOptions(options);
|
|
51
|
+
if (!classes)
|
|
52
|
+
throw new TypeError("TN_RTT_CLASSES: engine material, quad and target classes are required");
|
|
53
|
+
const node = make(
|
|
54
|
+
source,
|
|
55
|
+
width ?? 0,
|
|
56
|
+
height ?? 0,
|
|
57
|
+
options.minFilter ?? 1006,
|
|
58
|
+
options.magFilter ?? 1006,
|
|
59
|
+
);
|
|
60
|
+
const material = new classes.NodeMaterial();
|
|
61
|
+
material.fragmentNode = source;
|
|
62
|
+
const quad = new classes.QuadMesh(material as never) as IRttQuad;
|
|
63
|
+
const { minFilter = 1006, magFilter = 1006, ...targetOptions } = options;
|
|
64
|
+
const target = new classes.RenderTarget(width ?? 1, height ?? 1, targetOptions);
|
|
65
|
+
Object.assign(target.texture as object, { minFilter, magFilter });
|
|
66
|
+
node.__rtt(target, quad);
|
|
67
|
+
let version = 0;
|
|
68
|
+
const parameter = (name: string) => ({
|
|
69
|
+
get: () => node.__effect(name),
|
|
70
|
+
set: (value: number) => node.__effect(name, value),
|
|
71
|
+
});
|
|
72
|
+
const setSize = (w: number, h: number) => {
|
|
73
|
+
const scale = node.__effect("resolutionScale");
|
|
74
|
+
if (![w, h].every((v) => Number.isFinite(v) && v >= 0 && v <= 16384))
|
|
75
|
+
throw new TypeError("TN_RTT_SIZE: expected finite dimensions in [0, 16384]");
|
|
76
|
+
target.setSize(Math.floor(w * scale), Math.floor(h * scale));
|
|
77
|
+
node.__effect("textureNeedsUpdate", 1);
|
|
78
|
+
};
|
|
79
|
+
return Object.defineProperties(node, {
|
|
80
|
+
version: { get: () => version },
|
|
81
|
+
needsUpdate: {
|
|
82
|
+
set: (value: boolean) => {
|
|
83
|
+
if (value === true) ++version;
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
_quadMesh: { value: quad },
|
|
87
|
+
setup: {
|
|
88
|
+
value: () => {
|
|
89
|
+
const current = quad.material as InstanceType<IRttClasses["NodeMaterial"]>;
|
|
90
|
+
current.name = "RTT";
|
|
91
|
+
current.needsUpdate = true;
|
|
92
|
+
return node;
|
|
93
|
+
},
|
|
94
|
+
},
|
|
95
|
+
updateBefore: {
|
|
96
|
+
value: ({
|
|
97
|
+
renderer,
|
|
98
|
+
}: {
|
|
99
|
+
renderer: {
|
|
100
|
+
getRenderTarget(): unknown;
|
|
101
|
+
setRenderTarget(target: unknown): void;
|
|
102
|
+
getDrawingBufferSize(target: unknown): { width: number; height: number };
|
|
103
|
+
};
|
|
104
|
+
}) => {
|
|
105
|
+
if (!node.__effect("textureNeedsUpdate") && !node.__effect("autoUpdate")) return;
|
|
106
|
+
node.__effect("textureNeedsUpdate", 0);
|
|
107
|
+
if (node.__effect("width") === 0) {
|
|
108
|
+
const size = renderer.getDrawingBufferSize({
|
|
109
|
+
set(w: number, h: number) {
|
|
110
|
+
return { width: w, height: h };
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
const scale = node.__effect("resolutionScale");
|
|
114
|
+
if (
|
|
115
|
+
Math.floor(size.width * scale) !== target.width ||
|
|
116
|
+
Math.floor(size.height * scale) !== target.height
|
|
117
|
+
)
|
|
118
|
+
setSize(size.width, size.height);
|
|
119
|
+
}
|
|
120
|
+
const current = quad.material as InstanceType<IRttClasses["NodeMaterial"]>;
|
|
121
|
+
if (current.fragmentNode !== source) current.fragmentNode = source;
|
|
122
|
+
node.__rtt(target, quad);
|
|
123
|
+
quad.name = "RTT";
|
|
124
|
+
const previous = renderer.getRenderTarget();
|
|
125
|
+
renderer.setRenderTarget(target);
|
|
126
|
+
try {
|
|
127
|
+
quad.render(renderer);
|
|
128
|
+
} finally {
|
|
129
|
+
renderer.setRenderTarget(previous);
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
isRTTNode: { value: true },
|
|
134
|
+
autoResize: { get: () => node.__effect("width") === 0 },
|
|
135
|
+
renderTarget: { value: target },
|
|
136
|
+
value: { value: target.texture },
|
|
137
|
+
width: parameter("width"),
|
|
138
|
+
height: parameter("height"),
|
|
139
|
+
autoUpdate: {
|
|
140
|
+
get: () => !!node.__effect("autoUpdate"),
|
|
141
|
+
set: (v: boolean) => node.__effect("autoUpdate", Number(v)),
|
|
142
|
+
},
|
|
143
|
+
textureNeedsUpdate: {
|
|
144
|
+
get: () => !!node.__effect("textureNeedsUpdate"),
|
|
145
|
+
set: (v: boolean) => node.__effect("textureNeedsUpdate", Number(v)),
|
|
146
|
+
},
|
|
147
|
+
setResolutionScale: {
|
|
148
|
+
value: (scale: number) => {
|
|
149
|
+
node.__effect("resolutionScale", scale);
|
|
150
|
+
if (width !== null) setSize(node.__effect("width"), node.__effect("height"));
|
|
151
|
+
return node;
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
getResolutionScale: { value: () => node.__effect("resolutionScale") },
|
|
155
|
+
setSize: { value: setSize },
|
|
156
|
+
});
|
|
157
|
+
};
|
|
158
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* three's `renderer.shadowMap`, shared by both engine back ends (PRD-540; moved from the V8 player's
|
|
3
|
+
* core-webgpu.mjs). The renderer hands `enabled` and `type` to the engine with its other settings
|
|
4
|
+
* before each frame. A type the engine has no filter for is refused when it is set, as well as there.
|
|
5
|
+
*/
|
|
6
|
+
export class ShadowMap {
|
|
7
|
+
enabled = false;
|
|
8
|
+
#type = 1; // PCFShadowMap, three's default
|
|
9
|
+
|
|
10
|
+
get type(): number {
|
|
11
|
+
return this.#type;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
set type(value: number) {
|
|
15
|
+
if (value !== 1 && value !== 2)
|
|
16
|
+
throw new Error(
|
|
17
|
+
"TN_NATIVE_SHADOWMAP_TYPE_UNSUPPORTED: renderer.shadowMap.type must be PCFShadowMap or PCFSoftShadowMap",
|
|
18
|
+
);
|
|
19
|
+
this.#type = value;
|
|
20
|
+
}
|
|
21
|
+
}
|
package/src/storage.ts
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* three's storage buffers over engine BufferAttributes, for both back ends (PRD-620): the
|
|
3
|
+
* StorageBufferAttribute classes, `storage(attribute, type, count)`, `instancedArray` and
|
|
4
|
+
* `attributeArray` over the engine's `storage` node, and `renderer.getArrayBufferAsync`'s result forms.
|
|
5
|
+
* An attribute holds the buffer's initial contents; the engine owns the GPU copy a kernel writes.
|
|
6
|
+
*/
|
|
7
|
+
interface IStorageNode {
|
|
8
|
+
[key: string]: unknown;
|
|
9
|
+
}
|
|
10
|
+
type TypedArrayClass = new (length: number) => ArrayBufferView & { length: number };
|
|
11
|
+
type StorageArray = ArrayBufferView & {
|
|
12
|
+
length: number;
|
|
13
|
+
subarray(a: number, b: number): StorageArray;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const lengths: Readonly<Record<string, number>> = {
|
|
17
|
+
float: 1,
|
|
18
|
+
int: 1,
|
|
19
|
+
uint: 1,
|
|
20
|
+
bool: 1,
|
|
21
|
+
vec2: 2,
|
|
22
|
+
ivec2: 2,
|
|
23
|
+
uvec2: 2,
|
|
24
|
+
vec3: 3,
|
|
25
|
+
ivec3: 3,
|
|
26
|
+
uvec3: 3,
|
|
27
|
+
vec4: 4,
|
|
28
|
+
ivec4: 4,
|
|
29
|
+
uvec4: 4,
|
|
30
|
+
mat3: 9,
|
|
31
|
+
mat4: 16,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
function lengthOf(type: unknown): number {
|
|
35
|
+
const length = typeof type === "string" ? lengths[type] : undefined;
|
|
36
|
+
if (length === undefined)
|
|
37
|
+
throw new TypeError(
|
|
38
|
+
`TN_TSL storage: the native engine holds ${Object.keys(lengths).join(", ")} elements, not ${String(type)}`,
|
|
39
|
+
);
|
|
40
|
+
return length;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function arrayClassOf(type: string): TypedArrayClass {
|
|
44
|
+
if (type === "uint" || type.startsWith("uvec")) return Uint32Array;
|
|
45
|
+
if (type === "int" || type.startsWith("ivec")) return Int32Array;
|
|
46
|
+
return Float32Array;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** WGSL lays a vec3 array out at 16 bytes an element, so three pads a packed itemSize 3 array to 4. */
|
|
50
|
+
function padded(array: StorageArray, itemSize: number): [StorageArray, number] {
|
|
51
|
+
if (itemSize !== 3) return [array, itemSize];
|
|
52
|
+
const count = array.length / 3;
|
|
53
|
+
const out = new (array.constructor as new (length: number) => StorageArray)(count * 4);
|
|
54
|
+
// quality-allow: the typed array's set() is called on a view the constructor cast cannot name.
|
|
55
|
+
const target = out as unknown as { set(source: ArrayLike<number>, offset: number): void };
|
|
56
|
+
for (let i = 0; i < count; i += 1) target.set(array.subarray(i * 3, i * 3 + 3) as never, i * 4);
|
|
57
|
+
return [out, 4];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* three's ReadbackBuffer (renderers/common/ReadbackBuffer.js): the caller-owned target of
|
|
62
|
+
* `renderer.getArrayBufferAsync(attribute, target)`, which assigns `target.buffer` the bytes.
|
|
63
|
+
*/
|
|
64
|
+
export class ReadbackBuffer {
|
|
65
|
+
isReadbackBuffer = true;
|
|
66
|
+
name = "";
|
|
67
|
+
buffer: ArrayBuffer | null = null;
|
|
68
|
+
readonly maxByteLength: number;
|
|
69
|
+
#listeners = new Map<string, Set<(event: object) => void>>();
|
|
70
|
+
constructor(maxByteLength: number) {
|
|
71
|
+
this.maxByteLength = maxByteLength;
|
|
72
|
+
}
|
|
73
|
+
addEventListener(type: string, listener: (event: object) => void): void {
|
|
74
|
+
if (!this.#listeners.has(type)) this.#listeners.set(type, new Set());
|
|
75
|
+
this.#listeners.get(type)?.add(listener);
|
|
76
|
+
}
|
|
77
|
+
removeEventListener(type: string, listener: (event: object) => void): void {
|
|
78
|
+
this.#listeners.get(type)?.delete(listener);
|
|
79
|
+
}
|
|
80
|
+
dispatchEvent(event: { type: string }): void {
|
|
81
|
+
for (const listener of [...(this.#listeners.get(event.type) ?? [])])
|
|
82
|
+
listener.call(this, { ...event, target: this });
|
|
83
|
+
}
|
|
84
|
+
release(): void {
|
|
85
|
+
this.dispatchEvent({ type: "release" });
|
|
86
|
+
}
|
|
87
|
+
dispose(): void {
|
|
88
|
+
this.dispatchEvent({ type: "dispose" });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function defineStorage(
|
|
93
|
+
tsl: {
|
|
94
|
+
storage(attribute: unknown, type: string, count: number): IStorageNode;
|
|
95
|
+
readonly instanceIndex: unknown;
|
|
96
|
+
readonly vertexIndex: unknown;
|
|
97
|
+
varying(value: unknown): unknown;
|
|
98
|
+
},
|
|
99
|
+
BufferAttribute: new (
|
|
100
|
+
array: ArrayBufferView,
|
|
101
|
+
itemSize: number,
|
|
102
|
+
) => { count: number; itemSize: number; needsUpdate: boolean },
|
|
103
|
+
) {
|
|
104
|
+
const make = (flag: string) => {
|
|
105
|
+
const Attribute = class extends BufferAttribute {
|
|
106
|
+
constructor(
|
|
107
|
+
count: number | StorageArray,
|
|
108
|
+
itemSize: number,
|
|
109
|
+
typeClass: TypedArrayClass = Float32Array,
|
|
110
|
+
) {
|
|
111
|
+
const array = ArrayBuffer.isView(count)
|
|
112
|
+
? (count as StorageArray)
|
|
113
|
+
: (new typeClass(count * itemSize) as StorageArray);
|
|
114
|
+
const [stored, stride] = padded(array, itemSize);
|
|
115
|
+
super(stored, stride);
|
|
116
|
+
// The contents reach the engine now (the Wasm facade holds a handed array until its next engine call),
|
|
117
|
+
// so no later write-back lands over what a kernel has written.
|
|
118
|
+
this.needsUpdate = true;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
Object.defineProperty(Attribute.prototype, flag, { value: true });
|
|
122
|
+
return Attribute;
|
|
123
|
+
};
|
|
124
|
+
const StorageBufferAttribute = make("isStorageBufferAttribute");
|
|
125
|
+
const StorageInstancedBufferAttribute = make("isStorageInstancedBufferAttribute");
|
|
126
|
+
|
|
127
|
+
const storage = (
|
|
128
|
+
value: {
|
|
129
|
+
count: number;
|
|
130
|
+
itemSize: number;
|
|
131
|
+
isStorageInstancedBufferAttribute?: boolean;
|
|
132
|
+
isInstancedBufferAttribute?: boolean;
|
|
133
|
+
},
|
|
134
|
+
type: unknown = null,
|
|
135
|
+
count = 0,
|
|
136
|
+
) => {
|
|
137
|
+
if (type !== null && typeof type !== "string")
|
|
138
|
+
throw new TypeError(
|
|
139
|
+
"TN_TSL storage: a struct element type is not supported on the native engine",
|
|
140
|
+
);
|
|
141
|
+
const elementType = type ?? ["float", "vec2", "vec3", "vec4"][value.itemSize - 1];
|
|
142
|
+
if (elementType === undefined) throw new TypeError("TN_TSL storage: name the element type");
|
|
143
|
+
const node = tsl.storage(value, elementType, count || value.count);
|
|
144
|
+
Object.defineProperty(node, "value", { value, enumerable: true });
|
|
145
|
+
Object.defineProperty(node, "isStorageBufferNode", { value: true });
|
|
146
|
+
// A vertex attribute is interpolated to fragments; only instanced storage uses the instance index.
|
|
147
|
+
Object.defineProperty(node, "toAttribute", {
|
|
148
|
+
value: () =>
|
|
149
|
+
tsl.varying(
|
|
150
|
+
(node.element as (index: unknown) => unknown)(
|
|
151
|
+
value.isStorageInstancedBufferAttribute || value.isInstancedBufferAttribute
|
|
152
|
+
? tsl.instanceIndex
|
|
153
|
+
: tsl.vertexIndex,
|
|
154
|
+
),
|
|
155
|
+
),
|
|
156
|
+
});
|
|
157
|
+
return node;
|
|
158
|
+
};
|
|
159
|
+
const array =
|
|
160
|
+
(Attribute: typeof StorageBufferAttribute) =>
|
|
161
|
+
(count: number | StorageArray, type = "float") => {
|
|
162
|
+
const itemSize = lengthOf(type);
|
|
163
|
+
const attribute = new Attribute(count, itemSize, arrayClassOf(type));
|
|
164
|
+
if (attribute.count === 0)
|
|
165
|
+
throw new TypeError("TN_TSL instancedArray: storage count must be positive");
|
|
166
|
+
return storage(attribute, type, attribute.count);
|
|
167
|
+
};
|
|
168
|
+
return {
|
|
169
|
+
StorageBufferAttribute,
|
|
170
|
+
StorageInstancedBufferAttribute,
|
|
171
|
+
storage,
|
|
172
|
+
attributeArray: array(StorageBufferAttribute),
|
|
173
|
+
instancedArray: array(StorageInstancedBufferAttribute),
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
interface IReadbackBuffer {
|
|
178
|
+
isReadbackBuffer?: boolean;
|
|
179
|
+
buffer: unknown;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* `renderer.getArrayBufferAsync(attribute, target, offset, count)`: the buffer's bytes as a new
|
|
184
|
+
* ArrayBuffer, or written into a ReadbackBuffer (`target.buffer`) or an ArrayBuffer target.
|
|
185
|
+
*/
|
|
186
|
+
export async function readStorageBytes(
|
|
187
|
+
read: (attribute: unknown) => Promise<ArrayBuffer>,
|
|
188
|
+
attribute: unknown,
|
|
189
|
+
target: ArrayBuffer | IReadbackBuffer | null = null,
|
|
190
|
+
offset = 0,
|
|
191
|
+
count = -1,
|
|
192
|
+
): Promise<ArrayBuffer | IReadbackBuffer> {
|
|
193
|
+
if (offset % 4 !== 0 || (count > 0 && count % 4 !== 0))
|
|
194
|
+
throw new Error(
|
|
195
|
+
'THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.',
|
|
196
|
+
);
|
|
197
|
+
const all = await read(attribute);
|
|
198
|
+
const bytes = all.slice(offset, count === -1 ? all.byteLength : offset + count);
|
|
199
|
+
if (target === null) return bytes;
|
|
200
|
+
if ((target as IReadbackBuffer).isReadbackBuffer === true) {
|
|
201
|
+
(target as IReadbackBuffer).buffer = bytes;
|
|
202
|
+
return target;
|
|
203
|
+
}
|
|
204
|
+
new Uint8Array(target as ArrayBuffer).set(new Uint8Array(bytes));
|
|
205
|
+
return target;
|
|
206
|
+
}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* three's texture sources on the browser back end: the typed array a `DataTexture` was built
|
|
3
|
+
* from, a 2D canvas, and an image (`ImageBitmap`, `<img>`, `ImageData`). The engine holds a copy of
|
|
4
|
+
* the texels, so the JS-side source is re-sent on `needsUpdate`, as three re-reads `texture.image`
|
|
5
|
+
* before an upload. The V8 player's equivalent is `runtime-native/src/engine/player/core-textures.mjs`;
|
|
6
|
+
* the browser decodes images itself, so no bitmap needs the engine decoder here.
|
|
7
|
+
*/
|
|
8
|
+
import { type IBrowserRuntime, type IEngineRef, engineRef } from "./browser-backend.js";
|
|
9
|
+
|
|
10
|
+
type EngineClass = new (...args: unknown[]) => object;
|
|
11
|
+
|
|
12
|
+
interface IPixels {
|
|
13
|
+
readonly data: ArrayLike<number>;
|
|
14
|
+
readonly width: number;
|
|
15
|
+
readonly height: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface ICanvasLike {
|
|
19
|
+
readonly width: number;
|
|
20
|
+
readonly height: number;
|
|
21
|
+
getContext(
|
|
22
|
+
kind: "2d",
|
|
23
|
+
): { getImageData(x: number, y: number, w: number, h: number): IPixels } | null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** three's Texture defaults: an image is flipped, linear-filtered and mipmapped, unlike DataTexture's. */
|
|
27
|
+
const IMAGE_DEFAULTS = { flipY: true, generateMipmaps: true, magFilter: 1006, minFilter: 1008 };
|
|
28
|
+
|
|
29
|
+
function isCanvas(image: unknown): image is ICanvasLike {
|
|
30
|
+
return typeof (image as Partial<ICanvasLike>)?.getContext === "function";
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function isPixels(image: unknown): image is IPixels {
|
|
34
|
+
const candidate = image as Partial<IPixels> | null;
|
|
35
|
+
return ArrayBuffer.isView(candidate?.data) && typeof candidate?.width === "number";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** An image's RGBA pixels: its own `data`, a canvas's 2D readback, or a drawable drawn once. */
|
|
39
|
+
function pixelsOf(image: unknown): IPixels {
|
|
40
|
+
if (isPixels(image)) return image;
|
|
41
|
+
const source = isCanvas(image) ? image : undefined;
|
|
42
|
+
if (source !== undefined) {
|
|
43
|
+
const pixels = source.getContext("2d")?.getImageData(0, 0, source.width, source.height);
|
|
44
|
+
if (pixels !== undefined) return pixels;
|
|
45
|
+
}
|
|
46
|
+
const drawable = image as { width?: number; height?: number } | null;
|
|
47
|
+
if (
|
|
48
|
+
typeof OffscreenCanvas !== "undefined" &&
|
|
49
|
+
drawable?.width &&
|
|
50
|
+
drawable.height &&
|
|
51
|
+
!isCanvas(image)
|
|
52
|
+
) {
|
|
53
|
+
const context = new OffscreenCanvas(drawable.width, drawable.height).getContext("2d");
|
|
54
|
+
context?.drawImage(image as CanvasImageSource, 0, 0);
|
|
55
|
+
const pixels = context?.getImageData(0, 0, drawable.width, drawable.height);
|
|
56
|
+
if (pixels !== undefined) return pixels;
|
|
57
|
+
}
|
|
58
|
+
throw new TypeError(
|
|
59
|
+
"TN_BROWSER_TEXTURE_SOURCE: expected ImageData, a canvas with a 2D context, or an image OffscreenCanvas can draw",
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** `DataTexture`, `CanvasTexture`, `Texture` and `ImageBitmapLoader` over the engine's classes. */
|
|
64
|
+
export function defineTextureSources(
|
|
65
|
+
classes: Readonly<Record<string, unknown>>,
|
|
66
|
+
runtime: IBrowserRuntime,
|
|
67
|
+
): Record<string, unknown> {
|
|
68
|
+
const BaseTexture = classes.Texture as EngineClass;
|
|
69
|
+
const BaseVolume = classes.Data3DTexture as EngineClass | undefined;
|
|
70
|
+
const BaseData = classes.DataTexture as EngineClass;
|
|
71
|
+
const BaseCanvas = classes.CanvasTexture as EngineClass | undefined;
|
|
72
|
+
if (BaseCanvas === undefined) throw new TypeError("TN_BROWSER_UNBOUND: CanvasTexture");
|
|
73
|
+
const sources = new WeakMap<object, unknown>();
|
|
74
|
+
const prototype = BaseData.prototype as object;
|
|
75
|
+
/** `image` is the JS source; `needsUpdate` re-sends its pixels, as three re-reads `texture.image`. */
|
|
76
|
+
const followSource = (target: object, name: string): void => {
|
|
77
|
+
const needsUpdate = Object.getOwnPropertyDescriptor(target, "needsUpdate")?.set;
|
|
78
|
+
if (needsUpdate === undefined) throw new TypeError(`TN_BROWSER_UNBOUND: ${name}.needsUpdate`);
|
|
79
|
+
Object.defineProperties(target, {
|
|
80
|
+
image: {
|
|
81
|
+
configurable: true,
|
|
82
|
+
get(this: object) {
|
|
83
|
+
return sources.get(this);
|
|
84
|
+
},
|
|
85
|
+
set(this: object, image: unknown) {
|
|
86
|
+
sources.set(this, image);
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
needsUpdate: {
|
|
90
|
+
configurable: true,
|
|
91
|
+
set(this: object, value: unknown) {
|
|
92
|
+
const image = value ? sources.get(this) : undefined;
|
|
93
|
+
if (image !== undefined)
|
|
94
|
+
runtime.set(
|
|
95
|
+
engineRef(this) as IEngineRef,
|
|
96
|
+
"image.data",
|
|
97
|
+
Array.from(pixelsOf(image).data),
|
|
98
|
+
);
|
|
99
|
+
needsUpdate.call(this, value);
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
};
|
|
104
|
+
followSource(prototype, "DataTexture");
|
|
105
|
+
if (BaseVolume !== undefined) followSource(BaseVolume.prototype as object, "Data3DTexture");
|
|
106
|
+
followSource(BaseCanvas.prototype as object, "CanvasTexture");
|
|
107
|
+
|
|
108
|
+
/** An engine DataTexture holding `pixels`, re-read from `image` on every needsUpdate. */
|
|
109
|
+
const fromImage = (image: unknown, target: object): object => {
|
|
110
|
+
const pixels = pixelsOf(image);
|
|
111
|
+
const texture = new BaseData(pixels.data, pixels.width, pixels.height);
|
|
112
|
+
Object.setPrototypeOf(texture, target);
|
|
113
|
+
Object.assign(texture, IMAGE_DEFAULTS);
|
|
114
|
+
sources.set(texture, image);
|
|
115
|
+
return texture;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
function DataTexture(
|
|
119
|
+
this: unknown,
|
|
120
|
+
data?: ArrayLike<number> | null,
|
|
121
|
+
width = 1,
|
|
122
|
+
height = 1,
|
|
123
|
+
...rest: unknown[]
|
|
124
|
+
) {
|
|
125
|
+
const texture = Reflect.construct(
|
|
126
|
+
BaseData,
|
|
127
|
+
[data ?? undefined, width, height, ...rest],
|
|
128
|
+
new.target ?? DataTexture,
|
|
129
|
+
);
|
|
130
|
+
if (data) sources.set(texture, { data, width, height });
|
|
131
|
+
return texture;
|
|
132
|
+
}
|
|
133
|
+
DataTexture.prototype = prototype;
|
|
134
|
+
|
|
135
|
+
function Data3DTexture(
|
|
136
|
+
this: unknown,
|
|
137
|
+
data?: ArrayLike<number> | null,
|
|
138
|
+
width = 1,
|
|
139
|
+
height = 1,
|
|
140
|
+
depth = 1,
|
|
141
|
+
) {
|
|
142
|
+
if (BaseVolume === undefined) throw new TypeError("TN_BROWSER_UNBOUND: Data3DTexture");
|
|
143
|
+
const texture = Reflect.construct(
|
|
144
|
+
BaseVolume,
|
|
145
|
+
[data ?? undefined, width, height, depth],
|
|
146
|
+
new.target ?? Data3DTexture,
|
|
147
|
+
);
|
|
148
|
+
sources.set(texture, { data: data ?? null, width, height, depth });
|
|
149
|
+
return texture;
|
|
150
|
+
}
|
|
151
|
+
if (BaseVolume !== undefined) Data3DTexture.prototype = BaseVolume.prototype;
|
|
152
|
+
|
|
153
|
+
/** three's CanvasTexture: the engine's own class over the canvas's pixels, with a full mip chain. */
|
|
154
|
+
function CanvasTexture(this: unknown, canvas: unknown, ...rest: unknown[]) {
|
|
155
|
+
const pixels = pixelsOf(canvas);
|
|
156
|
+
const texture = Reflect.construct(
|
|
157
|
+
BaseCanvas as EngineClass,
|
|
158
|
+
[pixels.data, pixels.width, pixels.height, ...rest],
|
|
159
|
+
new.target ?? CanvasTexture,
|
|
160
|
+
) as object;
|
|
161
|
+
sources.set(texture, canvas);
|
|
162
|
+
return texture;
|
|
163
|
+
}
|
|
164
|
+
CanvasTexture.prototype = BaseCanvas.prototype;
|
|
165
|
+
if (!Object.hasOwn(BaseCanvas.prototype, "isCanvasTexture"))
|
|
166
|
+
Object.defineProperty(BaseCanvas.prototype, "isCanvasTexture", { value: true });
|
|
167
|
+
|
|
168
|
+
/** `new Texture(image)` uploads the image's pixels; with no image it is the engine's Texture. */
|
|
169
|
+
function Texture(this: unknown, image?: unknown, ...rest: unknown[]) {
|
|
170
|
+
if (image === undefined || image === null)
|
|
171
|
+
return Reflect.construct(BaseTexture, rest, new.target ?? Texture);
|
|
172
|
+
return fromImage(image, prototype);
|
|
173
|
+
}
|
|
174
|
+
Texture.prototype = BaseTexture.prototype;
|
|
175
|
+
|
|
176
|
+
/** three's ImageBitmapLoader: fetch, then the browser's own createImageBitmap. */
|
|
177
|
+
class ImageBitmapLoader {
|
|
178
|
+
options: ImageBitmapOptions = { premultiplyAlpha: "none" };
|
|
179
|
+
path = "";
|
|
180
|
+
setOptions(options: ImageBitmapOptions): this {
|
|
181
|
+
this.options = options;
|
|
182
|
+
return this;
|
|
183
|
+
}
|
|
184
|
+
setPath(path: string): this {
|
|
185
|
+
this.path = path;
|
|
186
|
+
return this;
|
|
187
|
+
}
|
|
188
|
+
load(
|
|
189
|
+
url: string,
|
|
190
|
+
onLoad?: (bitmap: ImageBitmap) => void,
|
|
191
|
+
_onProgress?: unknown,
|
|
192
|
+
onError?: (error: unknown) => void,
|
|
193
|
+
) {
|
|
194
|
+
this.loadAsync(url).then(onLoad, (error) => {
|
|
195
|
+
if (onError === undefined) throw error;
|
|
196
|
+
onError(error);
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
async loadAsync(url: string): Promise<ImageBitmap> {
|
|
200
|
+
const response = await fetch(this.path + url);
|
|
201
|
+
if (!response.ok)
|
|
202
|
+
throw new Error(
|
|
203
|
+
`TN_BROWSER_IMAGE_FETCH: ${this.path + url} answered ${String(response.status)}`,
|
|
204
|
+
);
|
|
205
|
+
return createImageBitmap(await response.blob(), {
|
|
206
|
+
...this.options,
|
|
207
|
+
colorSpaceConversion: "none",
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* three's TextureLoader: the browser decodes the file, and the texture is a Texture over its
|
|
214
|
+
* pixels with three's image defaults (flipY true), as an `<img>` upload would be.
|
|
215
|
+
* ponytail: `load()` hands the texture to `onLoad` and returns nothing, since the engine texture
|
|
216
|
+
* exists only once the pixels do; add a resizable placeholder if a game uses the return value.
|
|
217
|
+
*/
|
|
218
|
+
class TextureLoader {
|
|
219
|
+
path = "";
|
|
220
|
+
setPath(path: string): this {
|
|
221
|
+
this.path = path;
|
|
222
|
+
return this;
|
|
223
|
+
}
|
|
224
|
+
setCrossOrigin(): this {
|
|
225
|
+
return this;
|
|
226
|
+
}
|
|
227
|
+
load(
|
|
228
|
+
url: string,
|
|
229
|
+
onLoad?: (texture: object) => void,
|
|
230
|
+
_onProgress?: unknown,
|
|
231
|
+
onError?: (error: unknown) => void,
|
|
232
|
+
): void {
|
|
233
|
+
this.loadAsync(url).then(onLoad, (error) => {
|
|
234
|
+
if (onError === undefined) throw error;
|
|
235
|
+
onError(error);
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
async loadAsync(url: string): Promise<object> {
|
|
239
|
+
const bitmap = await new ImageBitmapLoader().setPath(this.path).loadAsync(url);
|
|
240
|
+
return Reflect.construct(Texture, [bitmap]) as object;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return {
|
|
245
|
+
CanvasTexture,
|
|
246
|
+
DataTexture,
|
|
247
|
+
...(BaseVolume === undefined ? {} : { Data3DTexture }),
|
|
248
|
+
ImageBitmapLoader,
|
|
249
|
+
Texture,
|
|
250
|
+
TextureLoader,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { unsupportedExport } from "./refused.js";
|
|
2
|
+
|
|
3
|
+
/** The engine TSL functions and inputs the extras compose, read at call time (some are lazy getters). */
|
|
4
|
+
interface IExtrasTsl {
|
|
5
|
+
readonly cameraFar: IFogNode;
|
|
6
|
+
readonly cameraNear: IFogNode;
|
|
7
|
+
readonly clamp: (value: unknown, low: number, high: number) => unknown;
|
|
8
|
+
readonly float: (value: number) => IFogNode;
|
|
9
|
+
readonly linearDepth: () => IFogNode;
|
|
10
|
+
readonly vec4: (color: unknown, factor: unknown) => IFogNode;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface IFogNode {
|
|
14
|
+
add(value: unknown): IFogNode;
|
|
15
|
+
exp(): IFogNode;
|
|
16
|
+
mul(value: unknown): IFogNode;
|
|
17
|
+
negate(): IFogNode;
|
|
18
|
+
oneMinus(): IFogNode;
|
|
19
|
+
sub(value: unknown): IFogNode;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The r185 `three/tsl` exports that are plain JS over the engine's TSL functions, for both back ends
|
|
24
|
+
* (the V8 player's core-tsl.mjs and the Wasm web module): `saturate`, `densityFogFactor`, `fog`, and
|
|
25
|
+
* the two exports the engine refuses by name.
|
|
26
|
+
*/
|
|
27
|
+
export function defineTslExtras(tsl: IExtrasTsl) {
|
|
28
|
+
return {
|
|
29
|
+
// r185's saturate(x) is clamp(x, 0, 1).
|
|
30
|
+
saturate: (value: unknown) => tsl.clamp(value, 0, 1),
|
|
31
|
+
// r185's densityFogFactor (nodes/fog/Fog.js): 1 - exp(-density^2 * viewZ^2). The fragment's view-space
|
|
32
|
+
// depth is the one linearDepth() encodes, so -positionView.z = near + linearDepth() * (far - near).
|
|
33
|
+
densityFogFactor: (density: number | IFogNode) => {
|
|
34
|
+
const viewZ = tsl.cameraNear.add(tsl.linearDepth().mul(tsl.cameraFar.sub(tsl.cameraNear)));
|
|
35
|
+
const d = typeof density === "number" ? tsl.float(density) : density;
|
|
36
|
+
return d.mul(d).mul(viewZ).mul(viewZ).negate().exp().oneMinus();
|
|
37
|
+
},
|
|
38
|
+
// r185's fog(color, factor) composes the finished fragment (`output.rgb`), which a native material graph
|
|
39
|
+
// cannot read. The engine mixes it in itself: fog() is the engine node vec4(color, factor) that
|
|
40
|
+
// `scene.fogNode` holds, and the engine's setupFog mixes the colour by the factor in place of `scene.fog`.
|
|
41
|
+
fog: (color: unknown, factor: unknown) => {
|
|
42
|
+
const node = tsl.vec4(color, typeof factor === "number" ? tsl.float(factor) : factor);
|
|
43
|
+
Object.defineProperty(node, "isFogNode", { value: true });
|
|
44
|
+
return node;
|
|
45
|
+
},
|
|
46
|
+
// context() and velocity: the context that carries the previous-frame velocity, and that accessor.
|
|
47
|
+
// The native engine has neither, so they refuse at use, by name.
|
|
48
|
+
context: unsupportedExport("context"),
|
|
49
|
+
velocity: unsupportedExport("velocity"),
|
|
50
|
+
};
|
|
51
|
+
}
|