@aardworx/wombat.rendering 0.8.0 → 0.9.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.
- package/dist/core/command.d.ts +7 -9
- package/dist/core/command.d.ts.map +1 -1
- package/dist/core/renderTask.d.ts +64 -1
- package/dist/core/renderTask.d.ts.map +1 -1
- package/dist/core/renderTask.js +3 -1
- package/dist/core/renderTask.js.map +1 -1
- package/dist/resources/preparedRenderObject.js +3 -3
- package/dist/resources/preparedRenderObject.js.map +1 -1
- package/dist/resources/uniformBuffer.d.ts.map +1 -1
- package/dist/resources/uniformBuffer.js +17 -0
- package/dist/resources/uniformBuffer.js.map +1 -1
- package/dist/runtime/derivedUniforms/dispatch.d.ts +105 -0
- package/dist/runtime/derivedUniforms/dispatch.d.ts.map +1 -0
- package/dist/runtime/derivedUniforms/dispatch.js +355 -0
- package/dist/runtime/derivedUniforms/dispatch.js.map +1 -0
- package/dist/runtime/derivedUniforms/index.d.ts +6 -0
- package/dist/runtime/derivedUniforms/index.d.ts.map +1 -0
- package/dist/runtime/derivedUniforms/index.js +26 -0
- package/dist/runtime/derivedUniforms/index.js.map +1 -0
- package/dist/runtime/derivedUniforms/recipes.d.ts +42 -0
- package/dist/runtime/derivedUniforms/recipes.d.ts.map +1 -0
- package/dist/runtime/derivedUniforms/recipes.js +134 -0
- package/dist/runtime/derivedUniforms/recipes.js.map +1 -0
- package/dist/runtime/derivedUniforms/sceneIntegration.d.ts +56 -0
- package/dist/runtime/derivedUniforms/sceneIntegration.d.ts.map +1 -0
- package/dist/runtime/derivedUniforms/sceneIntegration.js +171 -0
- package/dist/runtime/derivedUniforms/sceneIntegration.js.map +1 -0
- package/dist/runtime/derivedUniforms/slotId.d.ts +15 -0
- package/dist/runtime/derivedUniforms/slotId.d.ts.map +1 -0
- package/dist/runtime/derivedUniforms/slotId.js +30 -0
- package/dist/runtime/derivedUniforms/slotId.js.map +1 -0
- package/dist/runtime/derivedUniforms/slots.d.ts +49 -0
- package/dist/runtime/derivedUniforms/slots.d.ts.map +1 -0
- package/dist/runtime/derivedUniforms/slots.js +123 -0
- package/dist/runtime/derivedUniforms/slots.js.map +1 -0
- package/dist/runtime/derivedUniforms/uberKernel.wgsl.d.ts +13 -0
- package/dist/runtime/derivedUniforms/uberKernel.wgsl.d.ts.map +1 -0
- package/dist/runtime/derivedUniforms/uberKernel.wgsl.js +218 -0
- package/dist/runtime/derivedUniforms/uberKernel.wgsl.js.map +1 -0
- package/dist/runtime/flattenTree.d.ts +5 -0
- package/dist/runtime/flattenTree.d.ts.map +1 -0
- package/dist/runtime/flattenTree.js +45 -0
- package/dist/runtime/flattenTree.js.map +1 -0
- package/dist/runtime/heapAdapter.d.ts +16 -0
- package/dist/runtime/heapAdapter.d.ts.map +1 -0
- package/dist/runtime/heapAdapter.js +263 -0
- package/dist/runtime/heapAdapter.js.map +1 -0
- package/dist/runtime/heapEffect.d.ts +235 -0
- package/dist/runtime/heapEffect.d.ts.map +1 -0
- package/dist/runtime/heapEffect.js +518 -0
- package/dist/runtime/heapEffect.js.map +1 -0
- package/dist/runtime/heapEffectIR.d.ts +34 -0
- package/dist/runtime/heapEffectIR.d.ts.map +1 -0
- package/dist/runtime/heapEffectIR.js +1161 -0
- package/dist/runtime/heapEffectIR.js.map +1 -0
- package/dist/runtime/heapEligibility.d.ts +9 -0
- package/dist/runtime/heapEligibility.d.ts.map +1 -0
- package/dist/runtime/heapEligibility.js +195 -0
- package/dist/runtime/heapEligibility.js.map +1 -0
- package/dist/runtime/heapScene.d.ts +240 -31
- package/dist/runtime/heapScene.d.ts.map +1 -1
- package/dist/runtime/heapScene.js +3334 -265
- package/dist/runtime/heapScene.js.map +1 -1
- package/dist/runtime/heapShaderFamily.d.ts +132 -0
- package/dist/runtime/heapShaderFamily.d.ts.map +1 -0
- package/dist/runtime/heapShaderFamily.js +866 -0
- package/dist/runtime/heapShaderFamily.js.map +1 -0
- package/dist/runtime/hybridScene.d.ts +133 -0
- package/dist/runtime/hybridScene.d.ts.map +1 -0
- package/dist/runtime/hybridScene.js +159 -0
- package/dist/runtime/hybridScene.js.map +1 -0
- package/dist/runtime/index.d.ts +8 -0
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/index.js +9 -0
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/renderTask.d.ts +21 -4
- package/dist/runtime/renderTask.d.ts.map +1 -1
- package/dist/runtime/renderTask.js +127 -32
- package/dist/runtime/renderTask.js.map +1 -1
- package/dist/runtime/runtime.d.ts +33 -3
- package/dist/runtime/runtime.d.ts.map +1 -1
- package/dist/runtime/runtime.js +12 -3
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/scenePass.d.ts +28 -3
- package/dist/runtime/scenePass.d.ts.map +1 -1
- package/dist/runtime/scenePass.js +37 -4
- package/dist/runtime/scenePass.js.map +1 -1
- package/dist/runtime/textureAtlas/atlasMipGutterKernel.d.ts +35 -0
- package/dist/runtime/textureAtlas/atlasMipGutterKernel.d.ts.map +1 -0
- package/dist/runtime/textureAtlas/atlasMipGutterKernel.js +247 -0
- package/dist/runtime/textureAtlas/atlasMipGutterKernel.js.map +1 -0
- package/dist/runtime/textureAtlas/atlasPool.d.ts +240 -0
- package/dist/runtime/textureAtlas/atlasPool.d.ts.map +1 -0
- package/dist/runtime/textureAtlas/atlasPool.js +798 -0
- package/dist/runtime/textureAtlas/atlasPool.js.map +1 -0
- package/dist/runtime/textureAtlas/bvhTree2d.d.ts +33 -0
- package/dist/runtime/textureAtlas/bvhTree2d.d.ts.map +1 -0
- package/dist/runtime/textureAtlas/bvhTree2d.js +501 -0
- package/dist/runtime/textureAtlas/bvhTree2d.js.map +1 -0
- package/dist/runtime/textureAtlas/packer.d.ts +50 -0
- package/dist/runtime/textureAtlas/packer.d.ts.map +1 -0
- package/dist/runtime/textureAtlas/packer.js +390 -0
- package/dist/runtime/textureAtlas/packer.js.map +1 -0
- package/dist/window/loop.d.ts +14 -0
- package/dist/window/loop.d.ts.map +1 -1
- package/dist/window/loop.js +18 -5
- package/dist/window/loop.js.map +1 -1
- package/package.json +5 -4
- package/src/core/command.ts +9 -9
- package/src/core/renderTask.ts +55 -2
- package/src/resources/preparedRenderObject.ts +3 -3
- package/src/resources/uniformBuffer.ts +15 -0
- package/src/runtime/derivedUniforms/dispatch.ts +407 -0
- package/src/runtime/derivedUniforms/index.ts +52 -0
- package/src/runtime/derivedUniforms/recipes.ts +159 -0
- package/src/runtime/derivedUniforms/sceneIntegration.ts +239 -0
- package/src/runtime/derivedUniforms/slotId.ts +35 -0
- package/src/runtime/derivedUniforms/slots.ts +155 -0
- package/src/runtime/derivedUniforms/uberKernel.wgsl.ts +220 -0
- package/src/runtime/flattenTree.ts +46 -0
- package/src/runtime/heapAdapter.ts +314 -0
- package/src/runtime/heapEffect.ts +719 -0
- package/src/runtime/heapEffectIR.ts +1211 -0
- package/src/runtime/heapEligibility.ts +189 -0
- package/src/runtime/heapScene.ts +3981 -349
- package/src/runtime/heapShaderFamily.ts +1102 -0
- package/src/runtime/hybridScene.ts +310 -0
- package/src/runtime/index.ts +46 -0
- package/src/runtime/renderTask.ts +167 -32
- package/src/runtime/runtime.ts +37 -4
- package/src/runtime/scenePass.ts +39 -4
- package/src/runtime/textureAtlas/atlasMipGutterKernel.ts +291 -0
- package/src/runtime/textureAtlas/atlasPool.ts +991 -0
- package/src/runtime/textureAtlas/bvhTree2d.ts +530 -0
- package/src/runtime/textureAtlas/packer.ts +429 -0
- package/src/window/loop.ts +32 -6
|
@@ -0,0 +1,719 @@
|
|
|
1
|
+
// heapEffect — effect introspection + bucket-layout generation.
|
|
2
|
+
//
|
|
3
|
+
// Two stages:
|
|
4
|
+
//
|
|
5
|
+
// 1. `compileHeapEffect(effect)` — runs `effect.compile({target:"wgsl"})`
|
|
6
|
+
// and returns the raw stage WGSL (untouched) plus a `schema`
|
|
7
|
+
// describing the effect's surviving inputs / uniforms / outputs
|
|
8
|
+
// (post link + DCE). No name hardcoding; everything is read off
|
|
9
|
+
// `CompiledEffect.interface`.
|
|
10
|
+
//
|
|
11
|
+
// 2. `buildBucketLayout(schema, hasTextures, opts)` — turns a schema
|
|
12
|
+
// into a concrete per-bucket WGSL prelude + a JS-side layout
|
|
13
|
+
// object that knows where each named uniform / attribute lives
|
|
14
|
+
// (struct field offset for packing). The IR rewriter in
|
|
15
|
+
// `heapEffectIR.ts` consumes this layout to substitute uniform /
|
|
16
|
+
// attribute reads with heap loads at the IR level.
|
|
17
|
+
|
|
18
|
+
import type { Effect } from "@aardworx/wombat.shader";
|
|
19
|
+
|
|
20
|
+
// ─── Schema (extracted from CompiledEffect.interface) ───────────────
|
|
21
|
+
|
|
22
|
+
export interface HeapEffectInput {
|
|
23
|
+
readonly name: string;
|
|
24
|
+
readonly wgslType: string;
|
|
25
|
+
readonly byteSize: number; // tightly-packed (vec3<f32> = 12, mat4 = 64)
|
|
26
|
+
readonly location?: number; // present on vertex-stage attributes
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* One field of the VS-output / FS-input inter-stage struct ("VsOut"
|
|
31
|
+
* conventionally). Drives the per-effect VsOut struct generated into
|
|
32
|
+
* the prelude — no hardcoded clipPos/worldPos/etc. The runtime stays
|
|
33
|
+
* agnostic to varying names, just like uniforms.
|
|
34
|
+
*/
|
|
35
|
+
export interface HeapVarying {
|
|
36
|
+
readonly name: string;
|
|
37
|
+
readonly wgslType: string;
|
|
38
|
+
readonly location?: number;
|
|
39
|
+
readonly builtin?: string;
|
|
40
|
+
readonly interpolation?: "smooth" | "flat" | "centroid" | "sample" | "no-perspective";
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** One texture binding the effect declares (post link + DCE). */
|
|
44
|
+
export interface HeapTextureBinding {
|
|
45
|
+
readonly name: string;
|
|
46
|
+
/** WGSL type expression, e.g. "texture_2d<f32>", "texture_cube<f32>". */
|
|
47
|
+
readonly wgslType: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One sampler binding the effect declares (post link + DCE). */
|
|
51
|
+
export interface HeapSamplerBinding {
|
|
52
|
+
readonly name: string;
|
|
53
|
+
/** WGSL type — "sampler" or "sampler_comparison". */
|
|
54
|
+
readonly wgslType: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface HeapEffectSchema {
|
|
58
|
+
readonly attributes: readonly HeapEffectInput[];
|
|
59
|
+
readonly uniforms: readonly HeapEffectInput[];
|
|
60
|
+
readonly varyings: readonly HeapVarying[];
|
|
61
|
+
readonly fragmentOutputs: readonly { readonly name: string; readonly location: number; readonly wgslType: string }[];
|
|
62
|
+
readonly textures: readonly HeapTextureBinding[];
|
|
63
|
+
readonly samplers: readonly HeapSamplerBinding[];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface CompiledHeapEffect {
|
|
67
|
+
readonly rawVs: string;
|
|
68
|
+
readonly rawFs: string;
|
|
69
|
+
readonly schema: HeapEffectSchema;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Maps fragment-output names to framebuffer locations. Outputs not
|
|
74
|
+
* in the map are pruned by `linkFragmentOutputs`, which cascades
|
|
75
|
+
* through `pruneCrossStage` / `reduceUniforms` — uniforms that only
|
|
76
|
+
* fed the dropped outputs vanish from the schema entirely.
|
|
77
|
+
*/
|
|
78
|
+
export interface FragmentOutputLayout {
|
|
79
|
+
readonly locations: ReadonlyMap<string, number>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function compileHeapEffect(effect: Effect, fragmentOutputLayout?: FragmentOutputLayout): CompiledHeapEffect {
|
|
83
|
+
const compiled = effect.compile(
|
|
84
|
+
fragmentOutputLayout !== undefined
|
|
85
|
+
? { target: "wgsl", fragmentOutputLayout }
|
|
86
|
+
: { target: "wgsl" },
|
|
87
|
+
);
|
|
88
|
+
const vsStage = compiled.stages.find(s => s.stage === "vertex");
|
|
89
|
+
const fsStage = compiled.stages.find(s => s.stage === "fragment");
|
|
90
|
+
return {
|
|
91
|
+
rawVs: vsStage?.source ?? "",
|
|
92
|
+
rawFs: fsStage?.source ?? "",
|
|
93
|
+
schema: buildSchema(compiled.interface),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ─── IR-Type → WGSL-string + packed-size helpers ────────────────────
|
|
98
|
+
|
|
99
|
+
type ProgramInterface = ReturnType<Effect["compile"]>["interface"];
|
|
100
|
+
type IrType = ProgramInterface["uniformBlocks"][number]["fields"][number]["type"];
|
|
101
|
+
|
|
102
|
+
function buildSchema(iface: ProgramInterface): HeapEffectSchema {
|
|
103
|
+
const attributes: HeapEffectInput[] = iface.attributes.map(a => ({
|
|
104
|
+
name: a.name,
|
|
105
|
+
wgslType: irTypeToWgsl(a.type),
|
|
106
|
+
byteSize: a.byteSize,
|
|
107
|
+
location: a.location,
|
|
108
|
+
}));
|
|
109
|
+
const uniforms: HeapEffectInput[] = [];
|
|
110
|
+
for (const block of iface.uniformBlocks) {
|
|
111
|
+
for (const f of block.fields) {
|
|
112
|
+
uniforms.push({
|
|
113
|
+
name: f.name,
|
|
114
|
+
wgslType: irTypeToWgsl(f.type),
|
|
115
|
+
byteSize: irTypePackedSize(f.type),
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
// GLSL-style "loose" uniforms (no enclosing buffer name). On WGSL these
|
|
120
|
+
// emit as individual `var<uniform>` decls; the heap IR rewrite substitutes
|
|
121
|
+
// each `ReadInput("Uniform", name, ...)` with a per-draw heap load before
|
|
122
|
+
// WGSL emit, so the loose decls never reach the final shader.
|
|
123
|
+
for (const u of iface.uniforms) {
|
|
124
|
+
uniforms.push({
|
|
125
|
+
name: u.name,
|
|
126
|
+
wgslType: irTypeToWgsl(u.type),
|
|
127
|
+
byteSize: irTypePackedSize(u.type),
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
// Inter-stage varyings: VS outputs (post link + DCE). The FS inputs
|
|
131
|
+
// mirror these — `linkCrossStage` aligns them by semantic, so we
|
|
132
|
+
// can use VS outputs as the single source of truth for VsOut.
|
|
133
|
+
const vsStage = iface.stages.find(s => s.stage === "vertex");
|
|
134
|
+
const varyings: HeapVarying[] = vsStage === undefined
|
|
135
|
+
? []
|
|
136
|
+
: vsStage.outputs.map(o => {
|
|
137
|
+
const v: {
|
|
138
|
+
name: string; wgslType: string;
|
|
139
|
+
location?: number; builtin?: string;
|
|
140
|
+
interpolation?: "smooth" | "flat" | "centroid" | "sample" | "no-perspective";
|
|
141
|
+
} = { name: o.name, wgslType: irTypeToWgsl(o.type) };
|
|
142
|
+
if (o.location !== undefined) v.location = o.location;
|
|
143
|
+
if (o.builtin !== undefined) v.builtin = o.builtin;
|
|
144
|
+
if (o.interpolation !== undefined) v.interpolation = o.interpolation;
|
|
145
|
+
return v as HeapVarying;
|
|
146
|
+
});
|
|
147
|
+
const fragmentOutputs = iface.fragmentOutputs.map(o => ({
|
|
148
|
+
name: o.name, location: o.location, wgslType: irTypeToWgsl(o.type),
|
|
149
|
+
}));
|
|
150
|
+
// Texture/sampler bindings post-DCE. The IR Type for textures is a
|
|
151
|
+
// structured kind we don't fully model here yet — for v1 every
|
|
152
|
+
// texture maps to "texture_2d<f32>" and every sampler to plain
|
|
153
|
+
// "sampler". Specialise as multi-kind support lands in the DSL.
|
|
154
|
+
const textures: HeapTextureBinding[] = iface.textures.map(t => ({
|
|
155
|
+
name: t.name, wgslType: "texture_2d<f32>",
|
|
156
|
+
}));
|
|
157
|
+
const samplers: HeapSamplerBinding[] = iface.samplers.map(s => ({
|
|
158
|
+
name: s.name, wgslType: "sampler",
|
|
159
|
+
}));
|
|
160
|
+
return { attributes, uniforms, varyings, fragmentOutputs, textures, samplers };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function irTypeToWgsl(t: IrType): string {
|
|
164
|
+
switch (t.kind) {
|
|
165
|
+
case "Float": return "f32";
|
|
166
|
+
case "Int": return t.signed ? "i32" : "u32";
|
|
167
|
+
case "Bool": return "bool";
|
|
168
|
+
case "Vector": return `vec${t.dim}<${irTypeToWgsl(t.element)}>`;
|
|
169
|
+
case "Matrix": return `mat${t.cols}x${t.rows}<${irTypeToWgsl(t.element)}>`;
|
|
170
|
+
case "Array": {
|
|
171
|
+
const inner = irTypeToWgsl(t.element);
|
|
172
|
+
return t.length === "runtime" ? `array<${inner}>` : `array<${inner}, ${t.length}>`;
|
|
173
|
+
}
|
|
174
|
+
default:
|
|
175
|
+
throw new Error(`compileHeapEffect: cannot map IR Type kind '${t.kind}' to WGSL`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function irTypePackedSize(t: IrType): number {
|
|
180
|
+
switch (t.kind) {
|
|
181
|
+
case "Float": return 4;
|
|
182
|
+
case "Int": return 4;
|
|
183
|
+
case "Bool": return 4;
|
|
184
|
+
case "Vector": return t.dim * irTypePackedSize(t.element);
|
|
185
|
+
case "Matrix": return t.cols * t.rows * irTypePackedSize(t.element);
|
|
186
|
+
case "Array": {
|
|
187
|
+
if (t.length === "runtime") {
|
|
188
|
+
throw new Error("compileHeapEffect: runtime-sized arrays have no fixed packed size");
|
|
189
|
+
}
|
|
190
|
+
return t.length * irTypePackedSize(t.element);
|
|
191
|
+
}
|
|
192
|
+
default:
|
|
193
|
+
throw new Error(`compileHeapEffect: cannot size IR Type kind '${t.kind}'`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ─── Bucket layout ──────────────────────────────────────────────────
|
|
198
|
+
|
|
199
|
+
export interface DrawHeaderField {
|
|
200
|
+
readonly name: string; // schema name (e.g. "ModelTrafo")
|
|
201
|
+
readonly wgslName: string; // WGSL field name (e.g. "modelTrafoRef")
|
|
202
|
+
readonly wgslType: string; // "u32" for refs; "scalar"-packed for atlas texture-ref entries
|
|
203
|
+
readonly byteOffset: number;
|
|
204
|
+
readonly byteSize: number;
|
|
205
|
+
readonly kind: "uniform-ref" | "attribute-ref" | "texture-ref";
|
|
206
|
+
/**
|
|
207
|
+
* For `uniform-ref`: the uniform's underlying WGSL type. The
|
|
208
|
+
* rewriter uses this to pick the right inline read expression
|
|
209
|
+
* (mat4x4 → 4 vec4 reads, vec3 → 3 f32 reads, etc.).
|
|
210
|
+
*/
|
|
211
|
+
readonly uniformWgslType?: string;
|
|
212
|
+
/**
|
|
213
|
+
* For `attribute-ref`: the attribute's declared WGSL type. Drives
|
|
214
|
+
* the inline `attributeLoadExpr` when generating preamble lets.
|
|
215
|
+
*/
|
|
216
|
+
readonly attributeWgslType?: string;
|
|
217
|
+
/**
|
|
218
|
+
* For `texture-ref`: which sub-entry this is. Atlas-variant texture
|
|
219
|
+
* bindings expand into four contiguous drawHeader entries —
|
|
220
|
+
* `pageRef` (u32 slot index), `formatBits` (u32 packed sampler
|
|
221
|
+
* state + mip + format), `origin` (vec2<f32>, mip-0 top-left in
|
|
222
|
+
* normalized atlas coords), `size` (vec2<f32>, mip-0 size). The
|
|
223
|
+
* runtime packs these as inline values (not pool refs); the
|
|
224
|
+
* shader pass that consumes them lands in a follow-up PR.
|
|
225
|
+
*/
|
|
226
|
+
readonly textureSub?: "pageRef" | "formatBits" | "origin" | "size";
|
|
227
|
+
/** For `texture-ref`: the schema's logical texture binding name (shared by all four sub-entries). */
|
|
228
|
+
readonly textureBindingName?: string;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export interface BucketLayout {
|
|
232
|
+
readonly drawHeaderFields: readonly DrawHeaderField[];
|
|
233
|
+
readonly drawHeaderBytes: number;
|
|
234
|
+
/** Generated WGSL prelude — bindings + per-effect VsOut struct. No helper fns, no DrawHeader struct. */
|
|
235
|
+
readonly preludeWgsl: string;
|
|
236
|
+
/** DrawHeader stride in u32 elements (drawHeaderBytes / 4). */
|
|
237
|
+
readonly strideU32: number;
|
|
238
|
+
/**
|
|
239
|
+
* Names (schema-side) of uniforms that vary per instance. Populated
|
|
240
|
+
* from `spec.instances.values` at addDraw time; the rewriter pulls
|
|
241
|
+
* these via `instanceLoadExpr` instead of `uniformLoadExpr`.
|
|
242
|
+
*/
|
|
243
|
+
readonly perInstanceUniforms: ReadonlySet<string>;
|
|
244
|
+
/**
|
|
245
|
+
* Names (schema-side) of attributes that vary per instance. Populated
|
|
246
|
+
* from `spec.instanceAttributes` at addDraw time. The rewriter
|
|
247
|
+
* indexes per-instance attribute reads by `iidx` (= `instance_index`
|
|
248
|
+
* the megacall path) instead of `vid`.
|
|
249
|
+
*/
|
|
250
|
+
readonly perInstanceAttributes: ReadonlySet<string>;
|
|
251
|
+
/**
|
|
252
|
+
* Texture bindings: name + WGSL type + bind-group binding number
|
|
253
|
+
* (allocated starting at TEX_BINDING_START, after the four heap-
|
|
254
|
+
* data bindings 0–3 and the three megacall bindings 4–6).
|
|
255
|
+
*/
|
|
256
|
+
readonly textureBindings: readonly { readonly name: string; readonly wgslType: string; readonly binding: number }[];
|
|
257
|
+
/** Sampler bindings, allocated after textures. */
|
|
258
|
+
readonly samplerBindings: readonly { readonly name: string; readonly wgslType: string; readonly binding: number }[];
|
|
259
|
+
/**
|
|
260
|
+
* Atlas-routed texture binding names, exposed for the FS rewriter so
|
|
261
|
+
* it can substitute `textureSample(name, smp, uv)` with the heap
|
|
262
|
+
* `atlasSample(...)` helper for these names only.
|
|
263
|
+
*/
|
|
264
|
+
readonly atlasTextureBindings: ReadonlySet<string>;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* First texture binding number; samplers come after the textures.
|
|
269
|
+
* Bindings 0–3 are the four heap arena views, 4–6 are megacall
|
|
270
|
+
* (drawTable, indexStorage, firstDrawInTile).
|
|
271
|
+
*/
|
|
272
|
+
export const HEAP_TEX_BINDING_START = 7;
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Number of independent pages per format. Drives both the BGL slot
|
|
276
|
+
* count (N consecutive linear bindings + N consecutive srgb bindings
|
|
277
|
+
* + 1 sampler) and the shader's `switch pageRef` ladder. Must match
|
|
278
|
+
* `ATLAS_MAX_PAGES_PER_FORMAT` in `textureAtlas/atlasPool.ts`.
|
|
279
|
+
*/
|
|
280
|
+
export const ATLAS_ARRAY_SIZE = 8;
|
|
281
|
+
|
|
282
|
+
/** First atlas binding (linear texture for page 0). */
|
|
283
|
+
export const ATLAS_LINEAR_BINDING_BASE = 11;
|
|
284
|
+
/** First srgb atlas binding (= linear base + N). */
|
|
285
|
+
export const ATLAS_SRGB_BINDING_BASE = ATLAS_LINEAR_BINDING_BASE + ATLAS_ARRAY_SIZE;
|
|
286
|
+
/** Atlas sampler binding (= linear base + 2N). */
|
|
287
|
+
export const ATLAS_SAMPLER_BINDING = ATLAS_LINEAR_BINDING_BASE + 2 * ATLAS_ARRAY_SIZE;
|
|
288
|
+
|
|
289
|
+
export function buildBucketLayout(
|
|
290
|
+
schema: HeapEffectSchema,
|
|
291
|
+
_hasTextures: boolean,
|
|
292
|
+
opts: {
|
|
293
|
+
perInstanceUniforms?: ReadonlySet<string>;
|
|
294
|
+
perInstanceAttributes?: ReadonlySet<string>;
|
|
295
|
+
/**
|
|
296
|
+
* Names of schema texture bindings routed via the atlas binding-array
|
|
297
|
+
* path. Each such binding is dropped from `textureBindings` /
|
|
298
|
+
* `samplerBindings` and replaced with four `texture-ref` drawHeader
|
|
299
|
+
* fields (pageRef / formatBits / origin / size). Pass an empty set
|
|
300
|
+
* (default) for the standalone texture path.
|
|
301
|
+
*/
|
|
302
|
+
atlasTextureBindings?: ReadonlySet<string>;
|
|
303
|
+
} = {},
|
|
304
|
+
): BucketLayout {
|
|
305
|
+
const perInstanceUniforms = opts.perInstanceUniforms ?? new Set<string>();
|
|
306
|
+
const perInstanceAttributes = opts.perInstanceAttributes ?? new Set<string>();
|
|
307
|
+
const atlasTextureBindings = opts.atlasTextureBindings ?? new Set<string>();
|
|
308
|
+
const drawHeaderFields: DrawHeaderField[] = [];
|
|
309
|
+
|
|
310
|
+
// Per-draw uniforms → u32 ref slots in the DrawHeader. The runtime
|
|
311
|
+
// (UniformPool) keeps one arena allocation per unique aval; sharing
|
|
312
|
+
// across draws → shared ref → shared upload.
|
|
313
|
+
let dhOff = 0;
|
|
314
|
+
for (const u of schema.uniforms) {
|
|
315
|
+
dhOff = roundUp(dhOff, 4);
|
|
316
|
+
drawHeaderFields.push({
|
|
317
|
+
name: u.name, wgslName: lowerFirst(u.name) + "Ref", wgslType: "u32",
|
|
318
|
+
byteOffset: dhOff, byteSize: 4, kind: "uniform-ref",
|
|
319
|
+
uniformWgslType: u.wgslType,
|
|
320
|
+
});
|
|
321
|
+
dhOff += 4;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// Attribute refs — same shape as uniform refs, also routed through the pool.
|
|
325
|
+
for (const a of schema.attributes) {
|
|
326
|
+
dhOff = roundUp(dhOff, 4);
|
|
327
|
+
drawHeaderFields.push({
|
|
328
|
+
name: a.name, wgslName: lowerFirst(a.name) + "Ref", wgslType: "u32",
|
|
329
|
+
byteOffset: dhOff, byteSize: 4, kind: "attribute-ref",
|
|
330
|
+
attributeWgslType: a.wgslType,
|
|
331
|
+
});
|
|
332
|
+
dhOff += 4;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Atlas-routed texture bindings: 24 bytes / binding split into
|
|
336
|
+
// pageRef (u32) + formatBits (u32) + origin (vec2<f32>) + size
|
|
337
|
+
// (vec2<f32>). Inline values, not pool refs — the runtime packs
|
|
338
|
+
// them at addDraw time from the atlas acquisition + ISampler.
|
|
339
|
+
for (const t of schema.textures) {
|
|
340
|
+
if (!atlasTextureBindings.has(t.name)) continue;
|
|
341
|
+
const base = lowerFirst(t.name);
|
|
342
|
+
dhOff = roundUp(dhOff, 4);
|
|
343
|
+
drawHeaderFields.push({
|
|
344
|
+
name: `${t.name}.pageRef`, wgslName: `${base}PageRef`, wgslType: "u32",
|
|
345
|
+
byteOffset: dhOff, byteSize: 4, kind: "texture-ref",
|
|
346
|
+
textureSub: "pageRef", textureBindingName: t.name,
|
|
347
|
+
});
|
|
348
|
+
dhOff += 4;
|
|
349
|
+
drawHeaderFields.push({
|
|
350
|
+
name: `${t.name}.formatBits`, wgslName: `${base}FormatBits`, wgslType: "u32",
|
|
351
|
+
byteOffset: dhOff, byteSize: 4, kind: "texture-ref",
|
|
352
|
+
textureSub: "formatBits", textureBindingName: t.name,
|
|
353
|
+
});
|
|
354
|
+
dhOff += 4;
|
|
355
|
+
dhOff = roundUp(dhOff, 8);
|
|
356
|
+
drawHeaderFields.push({
|
|
357
|
+
name: `${t.name}.origin`, wgslName: `${base}Origin`, wgslType: "vec2<f32>",
|
|
358
|
+
byteOffset: dhOff, byteSize: 8, kind: "texture-ref",
|
|
359
|
+
textureSub: "origin", textureBindingName: t.name,
|
|
360
|
+
});
|
|
361
|
+
dhOff += 8;
|
|
362
|
+
drawHeaderFields.push({
|
|
363
|
+
name: `${t.name}.size`, wgslName: `${base}Size`, wgslType: "vec2<f32>",
|
|
364
|
+
byteOffset: dhOff, byteSize: 8, kind: "texture-ref",
|
|
365
|
+
textureSub: "size", textureBindingName: t.name,
|
|
366
|
+
});
|
|
367
|
+
dhOff += 8;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const drawHeaderBytes = roundUp(dhOff, 16);
|
|
371
|
+
const strideU32 = drawHeaderBytes / 4;
|
|
372
|
+
|
|
373
|
+
// Allocate texture + sampler bindings starting at HEAP_TEX_BINDING_START.
|
|
374
|
+
// Order: all textures, then all samplers — matches the prelude
|
|
375
|
+
// layout below and the runtime's BGL/bind-group construction.
|
|
376
|
+
// Atlas-routed bindings drop out — their data flows through the
|
|
377
|
+
// drawHeader instead of through individual texture/sampler slots.
|
|
378
|
+
let nextBinding = HEAP_TEX_BINDING_START;
|
|
379
|
+
const textureBindings = schema.textures
|
|
380
|
+
.filter(t => !atlasTextureBindings.has(t.name))
|
|
381
|
+
.map(t => ({ name: t.name, wgslType: t.wgslType, binding: nextBinding++ }));
|
|
382
|
+
// Samplers: drop the matching one when its texture is atlas-routed.
|
|
383
|
+
// Heuristic: assume position-aligned (nth sampler pairs with nth
|
|
384
|
+
// texture). Heap path's v1 surface only ever has 0..1 of each, so
|
|
385
|
+
// this collapses to "if the lone texture is atlas, drop the lone
|
|
386
|
+
// sampler too".
|
|
387
|
+
const atlasSamplerNames = new Set<string>();
|
|
388
|
+
for (let i = 0; i < schema.textures.length; i++) {
|
|
389
|
+
const t = schema.textures[i]!;
|
|
390
|
+
if (atlasTextureBindings.has(t.name)) {
|
|
391
|
+
const s = schema.samplers[i];
|
|
392
|
+
if (s !== undefined) atlasSamplerNames.add(s.name);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
const samplerBindings = schema.samplers
|
|
396
|
+
.filter(s => !atlasSamplerNames.has(s.name))
|
|
397
|
+
.map(s => ({ name: s.name, wgslType: s.wgslType, binding: nextBinding++ }));
|
|
398
|
+
|
|
399
|
+
const isAtlasBucket = atlasTextureBindings.size > 0;
|
|
400
|
+
// Extend the schema's varyings with flat-interpolated atlas threading
|
|
401
|
+
// slots when atlas is in use — the prelude generator emits these into
|
|
402
|
+
// VsOut so user VS code can write them and FS can read them. The
|
|
403
|
+
// location numbers are picked after the existing varyings.
|
|
404
|
+
const schemaForPrelude = isAtlasBucket
|
|
405
|
+
? extendSchemaWithAtlasVaryings(schema, atlasTextureBindings)
|
|
406
|
+
: schema;
|
|
407
|
+
const preludeWgsl = generatePrelude(
|
|
408
|
+
schemaForPrelude, textureBindings, samplerBindings,
|
|
409
|
+
isAtlasBucket,
|
|
410
|
+
);
|
|
411
|
+
|
|
412
|
+
return {
|
|
413
|
+
drawHeaderFields, drawHeaderBytes, preludeWgsl, strideU32,
|
|
414
|
+
perInstanceUniforms,
|
|
415
|
+
perInstanceAttributes,
|
|
416
|
+
textureBindings, samplerBindings,
|
|
417
|
+
atlasTextureBindings,
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Append flat-interpolated atlas threading varyings to a schema.
|
|
423
|
+
* Locations follow the highest existing `@location(N)` so we don't
|
|
424
|
+
* collide with effect-declared varyings.
|
|
425
|
+
*/
|
|
426
|
+
function extendSchemaWithAtlasVaryings(
|
|
427
|
+
schema: HeapEffectSchema,
|
|
428
|
+
atlasNames: ReadonlySet<string>,
|
|
429
|
+
): HeapEffectSchema {
|
|
430
|
+
let nextLoc = 0;
|
|
431
|
+
for (const v of schema.varyings) {
|
|
432
|
+
if (v.location !== undefined) nextLoc = Math.max(nextLoc, v.location + 1);
|
|
433
|
+
}
|
|
434
|
+
const extras: HeapVarying[] = [];
|
|
435
|
+
for (const name of atlasNames) {
|
|
436
|
+
const v = atlasVaryingNames(name);
|
|
437
|
+
extras.push({ name: v.pageRef, wgslType: "u32", location: nextLoc++, interpolation: "flat" });
|
|
438
|
+
extras.push({ name: v.formatBits, wgslType: "u32", location: nextLoc++, interpolation: "flat" });
|
|
439
|
+
extras.push({ name: v.origin, wgslType: "vec2<f32>", location: nextLoc++, interpolation: "flat" });
|
|
440
|
+
extras.push({ name: v.size, wgslType: "vec2<f32>", location: nextLoc++, interpolation: "flat" });
|
|
441
|
+
}
|
|
442
|
+
return { ...schema, varyings: [...schema.varyings, ...extras] };
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function lowerFirst(s: string): string {
|
|
446
|
+
return s.length === 0 ? s : s[0]!.toLowerCase() + s.slice(1);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function roundUp(value: number, mult: number): number {
|
|
450
|
+
return Math.ceil(value / mult) * mult;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// ─── Prelude generation ─────────────────────────────────────────────
|
|
454
|
+
|
|
455
|
+
function generatePrelude(
|
|
456
|
+
schema: HeapEffectSchema,
|
|
457
|
+
textureBindings: readonly { name: string; wgslType: string; binding: number }[],
|
|
458
|
+
samplerBindings: readonly { name: string; wgslType: string; binding: number }[],
|
|
459
|
+
isAtlasBucket: boolean,
|
|
460
|
+
): string {
|
|
461
|
+
// VsOut is generated from the schema's surviving VS outputs (post
|
|
462
|
+
// link + DCE). No hardcoded fields — what the effect declared is
|
|
463
|
+
// what ends up here.
|
|
464
|
+
const vsOutBody = schema.varyings.map(v => ` ${vsOutFieldDecl(v)}: ${v.wgslType},`).join("\n");
|
|
465
|
+
|
|
466
|
+
// Textures + samplers — one binding per surviving entry, starting
|
|
467
|
+
// at HEAP_TEX_BINDING_START. The user's WGSL must reference them
|
|
468
|
+
// by their schema name; the rewriter drops any DSL-emitted decls
|
|
469
|
+
// that conflict.
|
|
470
|
+
const texDecls = textureBindings.map(t =>
|
|
471
|
+
`@group(0) @binding(${t.binding}) var ${t.name}: ${t.wgslType};`,
|
|
472
|
+
).join("\n");
|
|
473
|
+
const smpDecls = samplerBindings.map(s =>
|
|
474
|
+
`@group(0) @binding(${s.binding}) var ${s.name}: ${s.wgslType};`,
|
|
475
|
+
).join("\n");
|
|
476
|
+
const samplingBlock = (texDecls.length > 0 || smpDecls.length > 0)
|
|
477
|
+
? `\n${texDecls}${texDecls && smpDecls ? "\n" : ""}${smpDecls}\n`
|
|
478
|
+
: "";
|
|
479
|
+
|
|
480
|
+
const megacallDecls = `\n@group(0) @binding(4) var<storage, read> drawTable: array<u32>;\n@group(0) @binding(5) var<storage, read> indexStorage: array<u32>;\n@group(0) @binding(6) var<storage, read> firstDrawInTile: array<u32>;`;
|
|
481
|
+
|
|
482
|
+
const atlasBlock = isAtlasBucket ? generateAtlasPrelude() : "";
|
|
483
|
+
|
|
484
|
+
return /* wgsl */`
|
|
485
|
+
@group(0) @binding(0) var<storage, read> heapU32: array<u32>;
|
|
486
|
+
@group(0) @binding(1) var<storage, read> headersU32: array<u32>;
|
|
487
|
+
@group(0) @binding(2) var<storage, read> heapF32: array<f32>;
|
|
488
|
+
@group(0) @binding(3) var<storage, read> heapV4f: array<vec4<f32>>;${megacallDecls}
|
|
489
|
+
${samplingBlock}${atlasBlock}
|
|
490
|
+
struct VsOut {
|
|
491
|
+
${vsOutBody}
|
|
492
|
+
};
|
|
493
|
+
`;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Atlas prelude: declares N independent `texture_2d<f32>` bindings
|
|
498
|
+
* per format (linear + srgb), plus a shared atlas sampler. The N-way
|
|
499
|
+
* `switch pageRef` ladder picks the matching texture pair for each
|
|
500
|
+
* draw. Each atlas page is its own `GPUTexture` — adding pages to a
|
|
501
|
+
* format is just a fresh allocation slotted into the next BGL entry,
|
|
502
|
+
* no GPU-side `copyTextureToTexture` required.
|
|
503
|
+
*
|
|
504
|
+
* `binding_array<texture_2d<f32>, N>` would collapse the switch into
|
|
505
|
+
* a runtime index but requires Chrome's experimental bindless
|
|
506
|
+
* feature; the N-consecutive-bindings + switch pattern is native
|
|
507
|
+
* WebGPU 1.0.
|
|
508
|
+
*
|
|
509
|
+
* Mip filtering is software (the GPU's mip walk would walk the
|
|
510
|
+
* texture's mip chain, not our embedded Iliffe pyramid). LOD is
|
|
511
|
+
* computed from screen-space derivatives of `uv * size_px` in mip-0
|
|
512
|
+
* texels-per-screen-pixel.
|
|
513
|
+
*
|
|
514
|
+
* Sample math (verified by `tests-browser/atlas-sampling-conformance.test.ts`
|
|
515
|
+
* to match native hardware bilinear within 1 LSB across clamp/repeat/
|
|
516
|
+
* mirror at any uv):
|
|
517
|
+
* - Clamp: atlas_p = origin_px + clamp(uv, 0, 1) * size_px
|
|
518
|
+
* - Mirror: atlas_p = origin_px + mirrorUv(uv) * size_px
|
|
519
|
+
* - Repeat: atlas_p = origin_px + fract(uv) * size_px, then shift ∓1
|
|
520
|
+
* if within 0.5 atlas-pixel of the sub-rect edge, so
|
|
521
|
+
* hardware bilinear straddles the outer wrap-gutter ring.
|
|
522
|
+
* `origin_px` / `size_px` are atlas-pixel coordinates of mip-0, NOT
|
|
523
|
+
* normalized. Mip-k rect is computed by walking the integer floor-
|
|
524
|
+
* halving sequence that matches the CPU packer's pyramid layout.
|
|
525
|
+
* Each sub-rect (incl. every mip slot) carries a 2-px gutter (inner
|
|
526
|
+
* ring = clamp-replicate edge, outer ring = wrap = opposite edge)
|
|
527
|
+
* filled by the upload kernel; without it bilinear at the edges
|
|
528
|
+
* bleeds across sub-rect boundaries.
|
|
529
|
+
*/
|
|
530
|
+
export function generateAtlasPrelude(): string {
|
|
531
|
+
return /* wgsl */`
|
|
532
|
+
${generateAtlasBindings()}
|
|
533
|
+
|
|
534
|
+
fn mirrorAtlasUv(u: f32) -> f32 {
|
|
535
|
+
let t = u - floor(u * 0.5) * 2.0;
|
|
536
|
+
return 1.0 - abs(t - 1.0);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// One axis: produce atlas-pixel coord from logical uv per wrap mode.
|
|
540
|
+
// mip_origin / mip_size are in atlas pixels for the target mip slot.
|
|
541
|
+
fn atlasAxisAt(uv: f32, mip_origin: f32, mip_size: f32, mode: u32) -> f32 {
|
|
542
|
+
if (mode == 0u) { // clamp
|
|
543
|
+
let c = clamp(uv, 0.0, 1.0);
|
|
544
|
+
return mip_origin + c * mip_size;
|
|
545
|
+
}
|
|
546
|
+
if (mode == 2u) { // mirror
|
|
547
|
+
let m = mirrorAtlasUv(uv);
|
|
548
|
+
return mip_origin + m * mip_size;
|
|
549
|
+
}
|
|
550
|
+
// repeat
|
|
551
|
+
let f = uv - floor(uv);
|
|
552
|
+
var p = mip_origin + f * mip_size;
|
|
553
|
+
let dL = p - mip_origin;
|
|
554
|
+
let dR = (mip_origin + mip_size) - p;
|
|
555
|
+
if (dL < 0.5) { p = p - 1.0; }
|
|
556
|
+
else if (dR < 0.5) { p = p + 1.0; }
|
|
557
|
+
return p;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// Mip-k rect within the Iliffe pyramid, in atlas pixels. Matches the
|
|
561
|
+
// CPU packer's integer floor-halving (so non-pow2 sources still hit
|
|
562
|
+
// the right texels). 2-px gutter between adjacent mip slots.
|
|
563
|
+
const ATLAS_MIP_GAP: f32 = 4.0;
|
|
564
|
+
|
|
565
|
+
fn atlasMipOriginPx(origin: vec2<f32>, size: vec2<f32>, k: u32) -> vec2<f32> {
|
|
566
|
+
if (k == 0u) { return origin; }
|
|
567
|
+
let x = origin.x + size.x + ATLAS_MIP_GAP;
|
|
568
|
+
var y = origin.y;
|
|
569
|
+
var j: u32 = 1u;
|
|
570
|
+
loop {
|
|
571
|
+
if (j >= k) { break; }
|
|
572
|
+
let mh = max(1.0, floor(size.y * exp2(-f32(j))));
|
|
573
|
+
y = y + mh + ATLAS_MIP_GAP;
|
|
574
|
+
j = j + 1u;
|
|
575
|
+
}
|
|
576
|
+
return vec2<f32>(x, y);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
fn atlasMipSizePx(size: vec2<f32>, k: u32) -> vec2<f32> {
|
|
580
|
+
return vec2<f32>(
|
|
581
|
+
max(1.0, floor(size.x * exp2(-f32(k)))),
|
|
582
|
+
max(1.0, floor(size.y * exp2(-f32(k)))),
|
|
583
|
+
);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
fn atlasSampleAtMip(
|
|
587
|
+
pageRef: u32, format: u32,
|
|
588
|
+
origin_px: vec2<f32>, size_px: vec2<f32>,
|
|
589
|
+
k: u32,
|
|
590
|
+
uv: vec2<f32>,
|
|
591
|
+
addrU: u32, addrV: u32,
|
|
592
|
+
) -> vec4<f32> {
|
|
593
|
+
let mip_o = atlasMipOriginPx(origin_px, size_px, k);
|
|
594
|
+
let mip_s = atlasMipSizePx(size_px, k);
|
|
595
|
+
let px = atlasAxisAt(uv.x, mip_o.x, mip_s.x, addrU);
|
|
596
|
+
let py = atlasAxisAt(uv.y, mip_o.y, mip_s.y, addrV);
|
|
597
|
+
let atlasUv = vec2<f32>(px, py) / ${atlasPageSizeConst()}.0;
|
|
598
|
+
${generateAtlasSwitch()}
|
|
599
|
+
return vec4<f32>(0.0);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
fn atlasSample(
|
|
603
|
+
pageRef: u32, formatBits: u32,
|
|
604
|
+
origin_px: vec2<f32>, size_px: vec2<f32>,
|
|
605
|
+
uv: vec2<f32>,
|
|
606
|
+
) -> vec4<f32> {
|
|
607
|
+
let format = formatBits & 0x1u;
|
|
608
|
+
let numMips = (formatBits >> 1u) & 0x7u;
|
|
609
|
+
let addrU = (formatBits >> 4u) & 0x3u;
|
|
610
|
+
let addrV = (formatBits >> 6u) & 0x3u;
|
|
611
|
+
// LOD on pre-wrap UV. dpdx/dpdy on the wrapped value spikes at the
|
|
612
|
+
// fract/mirror seam (discontinuity → bogus huge derivative → tiny
|
|
613
|
+
// mip selected → blurred band). Multiply by size_px to get
|
|
614
|
+
// texels-per-screen-pixel.
|
|
615
|
+
let dx = dpdx(uv) * size_px;
|
|
616
|
+
let dy = dpdy(uv) * size_px;
|
|
617
|
+
let rho = max(length(dx), length(dy));
|
|
618
|
+
let maxLod = f32(max(numMips, 1u) - 1u);
|
|
619
|
+
let lod = clamp(log2(max(rho, 1e-6)), 0.0, maxLod);
|
|
620
|
+
let lo = u32(floor(lod));
|
|
621
|
+
let hi = min(lo + 1u, max(numMips, 1u) - 1u);
|
|
622
|
+
let t = lod - f32(lo);
|
|
623
|
+
let a = atlasSampleAtMip(pageRef, format, origin_px, size_px, lo, uv, addrU, addrV);
|
|
624
|
+
if (numMips <= 1u) { return a; }
|
|
625
|
+
let b = atlasSampleAtMip(pageRef, format, origin_px, size_px, hi, uv, addrU, addrV);
|
|
626
|
+
return mix(a, b, t);
|
|
627
|
+
}
|
|
628
|
+
`;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
function atlasPageSizeConst(): string {
|
|
632
|
+
// Embedded literal — divisor matches ATLAS_PAGE_SIZE in atlasPool.ts.
|
|
633
|
+
return "4096";
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* Emit `2 * ATLAS_ARRAY_SIZE + 1` binding declarations: N linear
|
|
638
|
+
* `texture_2d<f32>`, N srgb `texture_2d<f32>`, then the shared
|
|
639
|
+
* atlas sampler.
|
|
640
|
+
*/
|
|
641
|
+
export function generateAtlasBindings(): string {
|
|
642
|
+
const lines: string[] = [];
|
|
643
|
+
for (let i = 0; i < ATLAS_ARRAY_SIZE; i++) {
|
|
644
|
+
lines.push(`@group(0) @binding(${ATLAS_LINEAR_BINDING_BASE + i}) var atlasLinear${i}: texture_2d<f32>;`);
|
|
645
|
+
}
|
|
646
|
+
for (let i = 0; i < ATLAS_ARRAY_SIZE; i++) {
|
|
647
|
+
lines.push(`@group(0) @binding(${ATLAS_SRGB_BINDING_BASE + i}) var atlasSrgb${i}: texture_2d<f32>;`);
|
|
648
|
+
}
|
|
649
|
+
lines.push(`@group(0) @binding(${ATLAS_SAMPLER_BINDING}) var atlasSampler: sampler;`);
|
|
650
|
+
return lines.join("\n");
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* Emit the `switch pageRef` ladder body for `atlasSampleAtMip`. Each
|
|
655
|
+
* case picks the matching `atlasLinear<i>` / `atlasSrgb<i>` decl and
|
|
656
|
+
* blends on `format == 1u`. The fallback (page out of range) is the
|
|
657
|
+
* function-level `vec4<f32>(0.0)` after the switch.
|
|
658
|
+
*/
|
|
659
|
+
export function generateAtlasSwitch(): string {
|
|
660
|
+
const lines: string[] = [" switch pageRef {"];
|
|
661
|
+
for (let i = 0; i < ATLAS_ARRAY_SIZE; i++) {
|
|
662
|
+
lines.push(` case ${i}u: {`);
|
|
663
|
+
lines.push(` let lin = textureSampleLevel(atlasLinear${i}, atlasSampler, atlasUv, 0.0);`);
|
|
664
|
+
lines.push(` let sr = textureSampleLevel(atlasSrgb${i}, atlasSampler, atlasUv, 0.0);`);
|
|
665
|
+
lines.push(` return select(lin, sr, format == 1u);`);
|
|
666
|
+
lines.push(` }`);
|
|
667
|
+
}
|
|
668
|
+
lines.push(" default: {}");
|
|
669
|
+
lines.push(" }");
|
|
670
|
+
return lines.join("\n");
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** Render one varying as the WGSL field declaration: `[@builtin(...) | @location(N)] [@interpolate(...)] name`. */
|
|
674
|
+
function vsOutFieldDecl(v: HeapVarying): string {
|
|
675
|
+
if (v.builtin !== undefined) return `@builtin(${v.builtin}) ${v.name}`;
|
|
676
|
+
const interp = v.interpolation !== undefined ? ` @interpolate(${v.interpolation})` : "";
|
|
677
|
+
if (v.location === undefined) {
|
|
678
|
+
throw new Error(`heapEffect: varying '${v.name}' has neither @builtin nor @location`);
|
|
679
|
+
}
|
|
680
|
+
return `@location(${v.location})${interp} ${v.name}`;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/** Atlas-texture varying names used by the VS→FS threading + FS preamble. */
|
|
684
|
+
export function atlasVaryingNames(name: string): {
|
|
685
|
+
pageRef: string; formatBits: string; origin: string; size: string;
|
|
686
|
+
} {
|
|
687
|
+
return {
|
|
688
|
+
pageRef: `_h_${name}PageRef`,
|
|
689
|
+
formatBits: `_h_${name}FormatBits`,
|
|
690
|
+
origin: `_h_${name}Origin`,
|
|
691
|
+
size: `_h_${name}Size`,
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
/**
|
|
697
|
+
* Megacall VS prelude: binary-search `drawTable` (one record per slot,
|
|
698
|
+
* 5 u32s: firstEmit, drawIdx, indexStart, indexCount, instanceCount)
|
|
699
|
+
* for the slot owning the given `emitIdx`, then split the in-record
|
|
700
|
+
* offset into `(instId, vid)` so per-RO instancing collapses to one
|
|
701
|
+
* record + one drawIndirect. Defines:
|
|
702
|
+
* - `heap_drawIdx` — per-RO selector for header reads.
|
|
703
|
+
* - `instId` — instance index in [0, instanceCount-1].
|
|
704
|
+
* - `vid` — vertex index pulled from indexStorage.
|
|
705
|
+
*
|
|
706
|
+
* Layout: each record emits `indexCount * instanceCount` vertices.
|
|
707
|
+
* `local = emitIdx - firstEmit`, `instId = local / indexCount`,
|
|
708
|
+
* `vid = indices[indexStart + local % indexCount]`.
|
|
709
|
+
*/
|
|
710
|
+
export function megacallSearchPrelude(): string {
|
|
711
|
+
// The shared megacall values (`heap_drawIdx`, `instId`, `vid`) are
|
|
712
|
+
// declared as `let` locals inside the @vertex fn body. Wombat.shader's
|
|
713
|
+
// composed-stage helper functions (extractFusedEntry) that reference
|
|
714
|
+
// these identifiers are post-processed in `applyMegacallToEmittedVs`
|
|
715
|
+
// to receive them as `u32` parameters — module-scope `var<private>`
|
|
716
|
+
// is rejected by some WGSL parsers (Safari/WebKit), so we thread the
|
|
717
|
+
// values through helper signatures instead.
|
|
718
|
+
return ` let _tileIdx = emitIdx >> 6u;\n var lo: u32 = firstDrawInTile[_tileIdx];\n var hi: u32 = firstDrawInTile[_tileIdx + 1u];\n loop {\n if (lo >= hi) { break; }\n let _mid = (lo + hi + 1u) >> 1u;\n if (drawTable[_mid * 5u] <= emitIdx) { lo = _mid; } else { hi = _mid - 1u; }\n }\n let _slot = lo;\n let _firstEmit = drawTable[_slot * 5u + 0u];\n let heap_drawIdx: u32 = drawTable[_slot * 5u + 1u];\n let _indexStart = drawTable[_slot * 5u + 2u];\n let _indexCount = drawTable[_slot * 5u + 3u];\n let _local = emitIdx - _firstEmit;\n let instId: u32 = _local / _indexCount;\n let vid: u32 = indexStorage[_indexStart + (_local % _indexCount)];\n`;
|
|
719
|
+
}
|