Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
ShaderParser.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
13
14#include "WaterSunShader.hpp"
15#include "ShaderParser.hpp"
16#include "../core/Log.hpp"
22
23#include <string_view>
24#include <algorithm>
25#include <cctype>
26#include <cstdlib>
27#include <cstring>
28#include <mutex>
29#include <unordered_map>
30#include <unordered_set>
31
32namespace esengine::resource {
33
34// =============================================================================
35// Include Expansion
36// =============================================================================
37
38namespace {
39
40// The pieces of a stream this file used, without the stream: libc++'s iostream pulls its locale machinery into the module for the sake of
41// splitting lines and appending text, and these do both.
42
44class LineReader {
45public:
46 explicit LineReader(const std::string& text) : text_(text) {}
47 bool next(std::string& line) {
48 if (pos_ >= text_.size()) return false;
49 const usize end = text_.find('\n', pos_);
50 if (end == std::string::npos) {
51 line.assign(text_, pos_, std::string::npos);
52 pos_ = text_.size();
53 } else {
54 line.assign(text_, pos_, end - pos_);
55 pos_ = end + 1;
56 }
57 return true;
58 }
59
60private:
61 const std::string& text_;
62 usize pos_ = 0;
63};
64
66std::string nextToken(const std::string& text, usize& pos) {
67 while (pos < text.size() && std::isspace(static_cast<unsigned char>(text[pos]))) ++pos;
68 const usize start = pos;
69 while (pos < text.size() && !std::isspace(static_cast<unsigned char>(text[pos]))) ++pos;
70 return text.substr(start, pos - start);
71}
72
74class TextBuilder {
75public:
76 TextBuilder& operator<<(const std::string& s) { text_ += s; return *this; }
77 TextBuilder& operator<<(std::string_view s) { text_ += s; return *this; }
78 TextBuilder& operator<<(const char* s) { text_ += s; return *this; }
79 TextBuilder& operator<<(char c) { text_ += c; return *this; }
80 const std::string& str() const { return text_; }
81 void str(const char*) { text_.clear(); }
82 void clear() {}
83
84private:
85 std::string text_;
86};
87
104bool namesRecords(const std::string& stageText) {
105 return stageText.find("esInstance") != std::string::npos || stageText.find("esApplyMorph") != std::string::npos;
106}
107
109std::string instanceRecordWGSL() {
110 const std::string texels = std::to_string(MESH_INSTANCE_TEXELS);
111 const std::string width = std::to_string(MESH_INSTANCE_TEXTURE_WIDTH);
112 const std::string unit = std::to_string(MESH_INSTANCE_TEXTURE_UNIT);
113 return
114 "struct InstanceConstants { base : vec4u };\n"
115 "@group(0) @binding(" + std::to_string(INSTANCE_CONSTANTS_BINDING)
116 + ") var<uniform> inst : InstanceConstants;\n"
117 // vs_main's instance_index, put where the helpers can reach it — WGSL has
118 // no global for it the way GLSL has gl_InstanceID.
119 "var<private> g_instanceId : i32 = 0;\n"
120 "fn esFrameTexel(texel : i32) -> vec4f {\n"
121 " return textureLoad(t" + unit + ", vec2i(texel % " + width + ", texel / " + width + "), 0);\n"
122 "}\n"
123 // WebGPU draws one draw a call, so its entry is the block's own.
124 "fn esDrawEntry() -> vec4f { return esFrameTexel(i32(inst.base.x)); }\n"
125 "fn esInstanceTexel(texel : i32) -> vec4f {\n"
126 " return esFrameTexel((i32(esDrawEntry().x) + g_instanceId) * " + texels + " + texel);\n"
127 "}\n"
128 "fn esInstanceModel() -> mat4x4f {\n"
129 " let r0 = esInstanceTexel(" + std::to_string(MESH_INSTANCE_TEXEL_MODEL) + ");\n"
130 " let r1 = esInstanceTexel(" + std::to_string(MESH_INSTANCE_TEXEL_MODEL + 1) + ");\n"
131 " let r2 = esInstanceTexel(" + std::to_string(MESH_INSTANCE_TEXEL_MODEL + 2) + ");\n"
132 " return mat4x4f(vec4f(r0.x, r1.x, r2.x, 0.0), vec4f(r0.y, r1.y, r2.y, 0.0),\n"
133 " vec4f(r0.z, r1.z, r2.z, 0.0), vec4f(r0.w, r1.w, r2.w, 1.0));\n"
134 "}\n"
135 "fn esInstanceNormalMatrix() -> mat3x3f {\n"
136 " return mat3x3f(esInstanceTexel(" + std::to_string(MESH_INSTANCE_TEXEL_NORMAL) + ").xyz,\n"
137 " esInstanceTexel(" + std::to_string(MESH_INSTANCE_TEXEL_NORMAL + 1) + ").xyz,\n"
138 " esInstanceTexel(" + std::to_string(MESH_INSTANCE_TEXEL_NORMAL + 2) + ").xyz);\n"
139 "}\n"
140 "fn esInstanceTint() -> vec4f { return esInstanceTexel("
141 + std::to_string(MESH_INSTANCE_TEXEL_TINT) + "); }\n"
142 "fn esInstanceLightmapRect() -> vec4f { return esInstanceTexel("
143 + std::to_string(MESH_INSTANCE_TEXEL_LIGHTMAP) + "); }\n";
144}
145
155std::string instanceRecordGLSLDecls() {
156 return
157 "layout(std140) uniform InstanceConstants {\n"
158 " highp uvec4 u_instanceBase;\n"
159 "};\n"
160 + std::string(glslMultiDraw() ? "#ifndef VULKAN\n"
161 "#define ES_DRAW_ID gl_DrawID\n"
162 "#else\n"
163 "#define ES_DRAW_ID 0\n"
164 "#endif\n"
165 : "#define ES_DRAW_ID 0\n") +
166 "#ifdef VULKAN\n"
167 "#define ES_RECORD_ID gl_InstanceIndex\n"
168 "#else\n"
169 "#define ES_RECORD_ID gl_InstanceID\n"
170 "#endif\n"
171 "#define ES_DRAW_RECORD int(esDrawEntry().x)\n"
172 // The instance's place in its run's probe block, which the probe slot counts from.
173 "#undef ES_INSTANCE_ID\n"
174 "#define ES_INSTANCE_ID (ES_RECORD_ID + int(esDrawEntry().y))\n"
175 "uniform highp sampler2D u_instanceData;\n"
176 "highp vec4 esFrameTexel(int texel);\n"
177 "highp vec4 esDrawEntry();\n"
178 "highp vec4 esInstanceTexel(int texel);\n"
179 "highp mat4 esInstanceModel();\n"
180 "highp mat3 esInstanceNormalMatrix();\n"
181 "highp vec4 esInstanceTint();\n"
182 "highp vec4 esInstanceLightmapRect();\n";
183}
184
185std::string instanceRecordGLSLBodies() {
186 const std::string texels = std::to_string(MESH_INSTANCE_TEXELS);
187 const std::string width = std::to_string(MESH_INSTANCE_TEXTURE_WIDTH);
188 return
189 "highp vec4 esFrameTexel(int texel) {\n"
190 " return texelFetch(u_instanceData, ivec2(texel % " + width + ", texel / " + width + "), 0);\n"
191 "}\n"
192 "highp vec4 esDrawEntry() { return esFrameTexel(int(u_instanceBase.x) + ES_DRAW_ID); }\n"
193 "highp vec4 esInstanceTexel(int texel) {\n"
194 " return esFrameTexel((ES_DRAW_RECORD + ES_RECORD_ID) * " + texels + " + texel);\n"
195 "}\n"
196 "highp mat4 esInstanceModel() {\n"
197 " highp vec4 r0 = esInstanceTexel(" + std::to_string(MESH_INSTANCE_TEXEL_MODEL) + ");\n"
198 " highp vec4 r1 = esInstanceTexel(" + std::to_string(MESH_INSTANCE_TEXEL_MODEL + 1) + ");\n"
199 " highp vec4 r2 = esInstanceTexel(" + std::to_string(MESH_INSTANCE_TEXEL_MODEL + 2) + ");\n"
200 " return mat4(vec4(r0.x, r1.x, r2.x, 0.0), vec4(r0.y, r1.y, r2.y, 0.0),\n"
201 " vec4(r0.z, r1.z, r2.z, 0.0), vec4(r0.w, r1.w, r2.w, 1.0));\n"
202 "}\n"
203 "highp mat3 esInstanceNormalMatrix() {\n"
204 " return mat3(esInstanceTexel(" + std::to_string(MESH_INSTANCE_TEXEL_NORMAL) + ").xyz,\n"
205 " esInstanceTexel(" + std::to_string(MESH_INSTANCE_TEXEL_NORMAL + 1) + ").xyz,\n"
206 " esInstanceTexel(" + std::to_string(MESH_INSTANCE_TEXEL_NORMAL + 2) + ").xyz);\n"
207 "}\n"
208 "highp vec4 esInstanceTint() { return esInstanceTexel("
209 + std::to_string(MESH_INSTANCE_TEXEL_TINT) + "); }\n"
210 "highp vec4 esInstanceLightmapRect() { return esInstanceTexel("
211 + std::to_string(MESH_INSTANCE_TEXEL_LIGHTMAP) + "); }\n";
212}
213
222std::string morphHelpersGLSL() {
223 return
224 "uniform highp sampler2D u_morphDeltas;\n"
225 "vec3 esMorphDelta(highp float index, highp float width) {\n"
226 " return texelFetch(u_morphDeltas, ivec2(int(mod(index, width)), int(index / width)), 0).xyz;\n"
227 "}\n"
228 "void esApplyMorph(inout vec3 position, inout vec3 normal) {\n"
229 " int head = int(esDrawEntry().z);\n"
230 " if (head == 0) return;\n"
231 " highp vec4 info = esFrameTexel(head);\n"
232 " int live = int(info.x);\n"
233 " for (int i = 0; i < " + std::to_string(MESH_MAX_ACTIVE_MORPHS) + "; i++) {\n"
234 " if (i >= live) break;\n"
235 " highp vec4 shape = esFrameTexel(head + 1 + i);\n"
236 " highp float at = (shape.x * info.y + float(gl_VertexID)) * info.z;\n"
237 " position += shape.y * esMorphDelta(at, info.w);\n"
238 " if (info.z > 1.5) normal += shape.y * esMorphDelta(at + 1.0, info.w);\n"
239 " }\n"
240 "}\n";
241}
242
248std::string morphHelpersWGSL() {
249 return
250 "@group(1) @binding(" + std::to_string(MORPH_DELTA_TEXTURE_UNIT) + ") var t" + std::to_string(MORPH_DELTA_TEXTURE_UNIT)
251 + " : texture_2d<f32>;\n"
252 "fn esMorphDelta(index : f32, width : f32) -> vec3f {\n"
253 " return textureLoad(t" + std::to_string(MORPH_DELTA_TEXTURE_UNIT)
254 + ", vec2i(i32(index % width), i32(index / width)), 0).xyz;\n"
255 "}\n"
256 "fn esApplyMorph(position : ptr<function, vec3f>, normal : ptr<function, vec3f>, vertexIndex : u32) {\n"
257 " let head = i32(esDrawEntry().z);\n"
258 " if (head == 0) { return; }\n"
259 " let info = esFrameTexel(head);\n"
260 " let live = i32(info.x);\n"
261 " for (var i = 0; i < " + std::to_string(MESH_MAX_ACTIVE_MORPHS) + "; i = i + 1) {\n"
262 " if (i >= live) { break; }\n"
263 " let shape = esFrameTexel(head + 1 + i);\n"
264 " let at = (shape.x * info.y + f32(vertexIndex)) * info.z;\n"
265 " *position = *position + shape.y * esMorphDelta(at, info.w);\n"
266 " if (info.z > 1.5) { *normal = *normal + shape.y * esMorphDelta(at + 1.0, info.w); }\n"
267 " }\n"
268 "}\n";
269}
270
271
272constexpr u32 kMaxIncludeDepth = 16;
273
274std::string ltrim(const std::string& s) {
275 usize start = s.find_first_not_of(" \t");
276 return start == std::string::npos ? std::string() : s.substr(start);
277}
278
279bool expandIncludes(const std::string& source,
280 const std::string& currentFile,
281 const ShaderIncludeResolver& resolver,
282 std::unordered_set<std::string>& active,
283 u32 depth,
284 std::string& out,
285 std::vector<SourceLine>& outMap,
286 std::string& errorMessage) {
287 if (depth > kMaxIncludeDepth) {
288 errorMessage = "Shader include depth exceeded " + std::to_string(kMaxIncludeDepth);
289 return false;
290 }
291
292 LineReader stream(source);
293 std::string line;
294 u32 lineNumber = 0;
295 while (stream.next(line)) {
296 ++lineNumber;
297 const std::string lead = ltrim(line);
298 if (lead.rfind("#include", 0) != 0) {
299 out += line;
300 out += '\n';
301 outMap.push_back(SourceLine{currentFile, lineNumber});
302 continue;
303 }
304
305 const usize q1 = lead.find('"');
306 const usize q2 = (q1 == std::string::npos) ? std::string::npos : lead.find('"', q1 + 1);
307 if (q1 == std::string::npos || q2 == std::string::npos || q2 <= q1 + 1) {
308 errorMessage = "Malformed #include directive: " + line;
309 return false;
310 }
311 const std::string path = lead.substr(q1 + 1, q2 - q1 - 1);
312
313 if (!resolver) {
314 errorMessage = "#include \"" + path + "\" used but no include resolver was provided";
315 return false;
316 }
317 if (active.count(path) != 0) {
318 errorMessage = "Circular #include of \"" + path + "\"";
319 return false;
320 }
321 std::optional<std::string> contents = resolver(path);
322 if (!contents) {
323 errorMessage = "Could not resolve #include \"" + path + "\"";
324 return false;
325 }
326
327 active.insert(path);
328 if (!expandIncludes(*contents, path, resolver, active, depth + 1, out, outMap, errorMessage)) {
329 return false;
330 }
331 active.erase(path);
332 }
333 return true;
334}
335
336// Swap a placeholder that a canonical stage's literal text carries for the material's hook (or
337// nothing, which is what keeps a stage without one byte-for-byte what it was).
338void fillHook(std::string& src, const std::string& token, const std::string& text) {
339 for (usize at = src.find(token); at != std::string::npos; at = src.find(token, at + text.size())) {
340 src.replace(at, token.size(), text);
341 }
342}
343
344// The WGSL varying interface of the canonical 2D vertex stage. Injected into
345// BOTH canonical stages (vertex emits it, fragment consumes it), so
346// fragment-only twins write `fs_main(v : VSOut)` against an engine-owned
347// struct — WGSL has no module-scope varyings to match by name.
348std::string wgslCanonicalVSOut(bool lit) {
349 std::string src =
350 "struct VSOut {\n"
351 // Invariant as mesh.esshader's: a material's depth prepass draws with that stage and its colour pass with this one.
352 " @builtin(position) @invariant pos : vec4f,\n"
353 " @location(0) v_color : vec4f,\n"
354 " @location(1) v_texCoord : vec2f,\n";
355 if (lit) {
356 src += " @location(2) v_worldPos : vec2f,\n";
357 // The layer the sprite is on (plus 129), or 0 where the draw has none to give.
358 src += " @location(8) @interpolate(flat) v_lightLayer : f32,\n";
359 }
360 // A mesh that HAS normals hands them on, with the full world position a
361 // tangent frame needs. v_worldPos stays vec2 so one fragment stage serves
362 // both vertex sources.
363 src +=
364 "#ifdef MESH_NORMALS\n"
365 " @location(3) v_worldNormal : vec3f,\n"
366 " @location(4) v_worldXYZ : vec3f,\n"
367 "#endif\n"
368 "#ifdef PARTICLE\n"
369 " @location(11) v_particle : vec4f,\n"
370 "#endif\n"
371 // The geometry's own tangent frame (xyz along +u, w the bitangent's handedness), when the mesh carries one.
372 "#ifdef MESH_TANGENTS\n"
373 " @location(7) v_worldTangent : vec4f,\n"
374 "#endif\n"
375 // mesh.esshader's twin of the same varying, carried through a material's
376 // variant so the LAYOUT matches. What a material's fragment makes of it
377 // is the material's, as all of its shading is.
378 "#ifdef MESH_LIGHTMAP\n"
379 " @location(5) v_lightmap : vec3f,\n"
380 // The mesh's own second uv set, as authored: what a material that is not a bake reads it for (a mask, a dissolve map). The vertices carry it
381 // whenever MESH_LIGHTMAP is on, which is what that feature says.
382 " @location(9) v_texCoord1 : vec2f,\n"
383 "#endif\n"
384 // The mesh's own position, before it is placed: what an effect authored against model space reads (a terrain tiles its detail by it).
385 // Only a shader that declares the feature gets it.
386 "#ifdef MESH_LOCAL_POSITION\n"
387 " @location(10) v_localPos : vec3f,\n"
388 "#endif\n";
389 if (lit) {
390 // Which run of coefficients this instance reads. Flat: an index, not a
391 // gradient — and the fragment stage has no instance number of its own.
392 src += " @location(6) @interpolate(flat) v_probeSlot : f32,\n";
393 }
394 src += "};\n";
395 return src;
396}
397
398// WGSL twin of canonicalVertexStage: same attribute locations, GLSL names
399// kept behind struct fields (a_position -> v.a_position) so the two stages diff
400// cleanly. FrameConstants arrives with the injected headers.
401std::string canonicalVertexStageWGSL(bool lit, const std::string& hook = {}) {
402 std::string src = wgslCanonicalVSOut(lit);
403 src +=
404 "\n"
405 "#ifdef SKINNED\n"
406 // As many bones as the renderer poses (SkinConstants.hpp). This said 64 while the block holds MESH_MAX_BONES,
407 // so a skin of more joints than 64 (a Tripo rig has 78) read past the array and drew as a white smear.
408 "struct SkinConstants { bones : array<mat4x4f, " + std::to_string(MESH_MAX_BONES) + "> };\n"
409 "@group(0) @binding(5) var<uniform> skin : SkinConstants;\n"
410 "#endif\n"
411 "#ifdef MESH\n"
412 // The shapes, as mesh.esshader's vertex stage reads them: one author for both (morphHelpersWGSL).
413 + morphHelpersWGSL() +
414 "#endif\n"
415 "\n"
416 "struct VSIn {\n"
417 // A particle's quad corner is the vertex; where that corner lands is on the
418 // instance, so this layout replaces the block rather than adding to it.
419 "#ifdef PARTICLE\n"
420 " @location(0) a_position : vec2f,\n"
421 " @location(1) a_texCoord : vec2f,\n"
422 " @location(2) a_inst_position : vec3f,\n"
423 " @location(3) a_inst_size : vec2f,\n"
424 " @location(4) a_inst_rotation : f32,\n"
425 " @location(5) a_inst_color : vec4f,\n"
426 " @location(6) a_inst_uv : vec4f,\n"
427 " @location(7) a_inst_extra : vec4f,\n"
428 "#else\n"
429 " @location(0) a_position : vec3f,\n"
430 " @location(1) a_color : vec4f,\n"
431 " @location(2) a_texCoord : vec2f,\n"
432 "#ifdef MESH_NORMALS\n"
433 " @location(3) a_normal : vec3f,\n"
434 "#endif\n"
435 "#ifdef MESH_LIGHTMAP\n"
436 " @location(7) a_texCoord1 : vec2f,\n"
437 "#endif\n"
438 "#ifdef MESH_TANGENTS\n"
439 " @location(4) a_tangent : vec4f,\n"
440 "#endif\n"
441 + std::string(lit ? "#if !defined(MESH) && !defined(SKINNED)\n"
442 " @location(4) a_lightLayer : f32,\n"
443 "#endif\n" : "") +
444 "#ifdef SKINNED\n"
445 " @location(5) a_joints : vec4u,\n"
446 " @location(6) a_weights : vec4f,\n"
447 "#endif\n"
448 "#ifdef MESH\n"
449 // What the GLSL twin reads as gl_VertexID.
450 " @builtin(vertex_index) vertexIndex : u32,\n"
451 "#endif\n"
452 "#endif\n"
453 "};\n"
454 "\n"
455 "\n"
456 "@@WGSL_HOOK@@"
457 "@vertex fn vs_main(v : VSIn, @builtin(instance_index) instanceId : u32) -> VSOut {\n"
458 " var out : VSOut;\n"
459 " g_instanceId = i32(instanceId);\n"
460 "#ifdef MESH\n"
461 " var local = v.a_position;\n"
462 "#ifdef MESH_NORMALS\n"
463 " var localNormal = v.a_normal;\n"
464 "#else\n"
465 " var localNormal = vec3f(0.0, 0.0, 1.0);\n"
466 "#endif\n"
467 // Before the pose: a target was authored against the mesh at rest.
468 " esApplyMorph(&local, &localNormal, v.vertexIndex);\n"
469 "@@WGSL_CALL@@"
470 "#endif\n"
471 // A particle faces the viewer wherever it is seen from; head-on and
472 // orthographic the axes come out (1,0,0) and (0,1,0), the flat quad a 2D
473 // scene has always drawn.
474 "#ifdef PARTICLE\n"
475 " let scaled = v.a_position * v.a_inst_size;\n"
476 " let cosR = cos(v.a_inst_rotation);\n"
477 " let sinR = sin(v.a_inst_rotation);\n"
478 " let rotated = vec2f(scaled.x * cosR - scaled.y * sinR,\n"
479 " scaled.x * sinR + scaled.y * cosR);\n"
480 " let fwd = viewDirection(v.a_inst_position);\n"
481 // Looking straight down the world up, that axis cannot orient the quad.
482 " var refUp = vec3f(0.0, 1.0, 0.0);\n"
483 " if (abs(fwd.y) > 0.999) { refUp = vec3f(0.0, 0.0, 1.0); }\n"
484 " let right = normalize(cross(refUp, fwd));\n"
485 " let up = cross(fwd, right);\n"
486 " let world = vec4f(v.a_inst_position + right * rotated.x + up * rotated.y, 1.0);\n"
487 " out.v_color = vec4f(v.a_inst_color.rgb * v.a_inst_extra.z, v.a_inst_color.a);\n"
488 " out.v_particle = vec4f(v.a_inst_extra.x, v.a_inst_extra.y, v.a_inst_extra.w, v.a_inst_extra.z);\n"
489 // Bones are already world-space, so a skinned mesh's own transform is not
490 // read — which is what glTF requires of one.
491 "#elif defined(SKINNED)\n"
492 " let pose = v.a_weights.x * skin.bones[v.a_joints.x]\n"
493 " + v.a_weights.y * skin.bones[v.a_joints.y]\n"
494 " + v.a_weights.z * skin.bones[v.a_joints.z]\n"
495 " + v.a_weights.w * skin.bones[v.a_joints.w];\n"
496 " let world = pose * vec4f(local, 1.0);\n"
497 " out.v_color = v.a_color * esInstanceTint();\n"
498 "#elif defined(MESH)\n"
499 " let world = esInstanceModel() * vec4f(local, 1.0);\n"
500 " out.v_color = @@WGSL_MESH_COLOR@@ * esInstanceTint();\n"
501 "#else\n"
502 " let world = vec4f(v.a_position, 1.0);\n"
503 " out.v_color = v.a_color;\n"
504 "#endif\n"
505 " out.pos = frame.projection * world;\n"
506 "#ifdef PARTICLE\n"
507 // A sheet animation moves the frame under the same quad.
508 " out.v_texCoord = v.a_texCoord * v.a_inst_uv.zw + v.a_inst_uv.xy;\n"
509 "#else\n"
510 " out.v_texCoord = v.a_texCoord;\n"
511 "#endif\n"
512 "#ifdef MESH_NORMALS\n"
513 // A particle in the world (a shader that declares PARTICLE_WORLD): its quad faces the eye, so that is its normal.
514 "#if defined(PARTICLE)\n"
515 " out.v_worldNormal = fwd;\n"
516 "#elif defined(SKINNED)\n"
517 " out.v_worldNormal = mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * localNormal;\n"
518 "#else\n"
519 " out.v_worldNormal = esInstanceNormalMatrix() * localNormal;\n"
520 "#endif\n"
521 " out.v_worldXYZ = world.xyz;\n"
522 "#ifdef MESH_TANGENTS\n"
523 "#ifdef SKINNED\n"
524 " out.v_worldTangent = vec4f(mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * v.a_tangent.xyz, v.a_tangent.w);\n"
525 "#else\n"
526 " let tangentModel = mat3x3f(esInstanceModel()[0].xyz, esInstanceModel()[1].xyz, esInstanceModel()[2].xyz);\n"
527 " out.v_worldTangent = vec4f(tangentModel * v.a_tangent.xyz,\n"
528 " select(v.a_tangent.w, -v.a_tangent.w, determinant(tangentModel) < 0.0));\n"
529 "#endif\n"
530 "#endif\n"
531 "#endif\n"
532 "#ifdef MESH_LIGHTMAP\n"
533 " let lmRect = esInstanceLightmapRect();\n"
534 " out.v_lightmap = vec3f(v.a_texCoord1 * lmRect.xy + lmRect.zw,\n"
535 " select(0.0, 1.0, lmRect.x > 0.0));\n"
536 " out.v_texCoord1 = v.a_texCoord1;\n"
537 "#endif\n"
538 "#if defined(MESH_LOCAL_POSITION) && defined(MESH)\n"
539 " out.v_localPos = v.a_position;\n"
540 "#endif\n";
541 if (lit) {
542 src += " out.v_worldPos = world.xy;\n";
543 src += "#if !defined(MESH) && !defined(SKINNED) && !defined(PARTICLE)\n out.v_lightLayer = v.a_lightLayer;\n#else\n out.v_lightLayer = 0.0;\n#endif\n";
544 // Declared by wgslVSOut under the same condition, so filled here —
545 // a slot left at zero makes every instance read the first probe.
546 // A particle's instances are particles, not objects with a run of their own: all of them read the first.
547 src += "#ifdef PARTICLE\n out.v_probeSlot = 0.0;\n#else\n out.v_probeSlot = f32(instanceId);\n#endif\n";
548 }
549 // Clip y turned over, last, so a target's rows land bottom-up as GL lays them: every WebGPU vertex stage does this, and
550 // the fragment sees the screen as GL shows it (uv, @builtin(position), derivatives). See WebGPUDevice::ensurePipeline.
551 src +=
552 " out.pos.y = -out.pos.y;\n"
553 " return out;\n"
554 "}\n";
555 // A hook's own per-vertex channels: `es_vertexColor` (a painted weight; what the hook leaves there is the colour the fragment gets,
556 // untouched if it leaves it) and `es_vertexUv1`, the mesh's second uv (where a vertex sits from its plant's pivot), zero on a mesh
557 // with none.
558 fillHook(src, "@@WGSL_MESH_COLOR@@", hook.empty() ? std::string("v.a_color") : std::string("es_vertexColor"));
559 fillHook(src, "@@WGSL_HOOK@@", hook.empty() ? std::string() :
560 "#ifdef MESH\nvar<private> es_vertexColor : vec4f;\nvar<private> es_vertexUv1 : vec2f;\n" + hook + "\n#endif\n");
561 fillHook(src, "@@WGSL_CALL@@", hook.empty() ? std::string() :
562 " es_vertexColor = v.a_color;\n#ifdef MESH_LIGHTMAP\n es_vertexUv1 = v.a_texCoord1;\n#else\n es_vertexUv1 = vec2f(0.0);\n#endif\n"
563 " esMaterialVertex(&local, &localNormal, v.a_texCoord);\n");
564 return src;
565}
566
567// The PostProcess domain's varying interface: a fullscreen pass carries only
568// the uv (plus the position builtin, which doubles as the pixel coordinate).
569std::string wgslPPVSOut() {
570 return
571 "struct VSOut {\n"
572 " @builtin(position) pos : vec4f,\n"
573 " @location(0) v_texCoord : vec2f,\n"
574 "};\n";
575}
576
577// WGSL twin of canonicalPPVertexStage. Clip y is turned over, as every WebGPU vertex
578// stage turns it: the pass lands with its rows bottom-up, as GL lays them, so the
579// uv is the screen's y-up uv on both backends and is passed on as it came.
580std::string canonicalPPVertexStageWGSL() {
581 std::string src = wgslPPVSOut();
582 src +=
583 "\n"
584 "struct VSIn {\n"
585 " @location(0) a_position : vec2f,\n"
586 " @location(1) a_texCoord : vec2f,\n"
587 "};\n"
588 "\n"
589 "@vertex fn vs_main(v : VSIn) -> VSOut {\n"
590 " var out : VSOut;\n"
591 " out.pos = vec4f(v.a_position.x, -v.a_position.y, 0.0, 1.0);\n"
592 " out.v_texCoord = v.a_texCoord;\n"
593 " return out;\n"
594 "}\n";
595 return src;
596}
597
598// Canonical PostProcess vertex stage for fragment-only .esshaders: fullscreen
599// passes all share the clip-space pass-through (the engine draws one
600// fullscreen triangle; no projection, no color).
601std::string canonicalPPVertexStage() {
602 return
603 "layout(location = 0) in vec2 a_position;\n"
604 "layout(location = 1) in vec2 a_texCoord;\n"
605 "\n"
606 "out vec2 v_texCoord;\n"
607 "\n"
608 "void main() {\n"
609 " v_texCoord = a_texCoord;\n"
610 " gl_Position = vec4(a_position, 0.0, 1.0);\n"
611 "}\n";
612}
613
614// Canonical 2D vertex stage for fragment-only .esshaders, in its three VERTEX
615// SOURCES: batch (already world space), resident mesh (local + a per-object
616// transform), skinned (posed by bones). One material serves all three.
617std::string canonicalVertexStage(bool lit, const std::string& hook = {}) {
618 std::string src =
619 // A particle's quad corner is the vertex; where that corner lands is on the
620 // instance. The layout differs from every other source, so it replaces the
621 // block rather than adding to it.
622 "#ifdef PARTICLE\n"
623 "layout(location = 0) in vec2 a_position;\n"
624 "layout(location = 1) in vec2 a_texCoord;\n"
625 "layout(location = 2) in vec3 a_inst_position;\n"
626 "layout(location = 3) in vec2 a_inst_size;\n"
627 "layout(location = 4) in float a_inst_rotation;\n"
628 "layout(location = 5) in vec4 a_inst_color;\n"
629 "layout(location = 6) in vec4 a_inst_uv;\n"
630 "layout(location = 7) in vec4 a_inst_extra;\n"
631 "#else\n"
632 "layout(location = 0) in vec3 a_position;\n"
633 "layout(location = 1) in vec4 a_color;\n"
634 "layout(location = 2) in vec2 a_texCoord;\n"
635 "#ifdef MESH_NORMALS\n"
636 "layout(location = 3) in vec3 a_normal;\n"
637 "#endif\n"
638 "#ifdef MESH_LIGHTMAP\n"
639 "layout(location = 7) in vec2 a_texCoord1;\n"
640 "#endif\n"
641 "#ifdef MESH_TANGENTS\n"
642 "layout(location = 4) in vec4 a_tangent;\n"
643 "#endif\n"
644 // The batch layout carries a sprite's layer in the lane text spends on its outline (see SPRITE_LAYER_BIAS); a lit batch draw reads it.
645 + std::string(lit ? "#if !defined(MESH) && !defined(SKINNED)\n"
646 "layout(location = 4) in float a_lightLayer;\n"
647 "#endif\n" : "") +
648 "#ifdef SKINNED\n"
649 "layout(location = 5) in uvec4 a_joints;\n"
650 "layout(location = 6) in vec4 a_weights;\n"
651 // This draw's pose, rewritten immediately before it (SkinConstants, binding 5).
652 "layout(std140) uniform SkinConstants {\n"
653 // MESH_MAX_BONES, the size of the block the renderer fills; see the WGSL twin.
654 " mat4 u_bones[" + std::to_string(MESH_MAX_BONES) + "];\n"
655 "};\n"
656 "#endif\n"
657 "#endif\n"
658 "#ifdef MESH\n"
659 // The shapes a resident mesh is blended towards, as mesh.esshader's vertex stage reads them: one author for both
660 // (morphHelpersGLSL), so a material's mesh variant deforms the same geometry the same way.
661 + morphHelpersGLSL() +
662 "#endif\n"
663 "\n"
664 // A material's depth prepass draws with mesh.esshader's vertex stage and its colour pass with this one, landing on that depth by an
665 // equal test: both declare the position invariant, or a compiler (Metal's) may order the arithmetic differently and miss by a bit.
666 "invariant gl_Position;\n"
667 "out vec4 v_color;\n"
668 "out vec2 v_texCoord;\n"
669 "#ifdef MESH_NORMALS\n"
670 "out highp vec3 v_worldNormal;\n"
671 "out highp vec3 v_worldXYZ;\n"
672 "#ifdef MESH_TANGENTS\n"
673 "out highp vec4 v_worldTangent;\n"
674 "#endif\n"
675 "#endif\n"
676 "#ifdef PARTICLE\n"
677 "out highp vec4 v_particle;\n"
678 "#endif\n"
679 "#ifdef MESH_LIGHTMAP\n"
680 "out highp vec3 v_lightmap;\n"
681 "out highp vec2 v_texCoord1;\n"
682 "#endif\n"
683 // The mesh's own position, before it is placed, for a shader that declares MESH_LOCAL_POSITION (see the WGSL twin's v_localPos).
684 "#ifdef MESH_LOCAL_POSITION\n"
685 "out highp vec3 v_localPos;\n"
686 "#endif\n";
687 if (lit) {
688 src += "out highp vec2 v_worldPos;\n";
689 // The layer the sprite is on (plus 129), or 0 where the draw has none to give. Flat: it is a label, not a gradient.
690 src += "flat out highp float v_lightLayer;\n";
691 // Which run of coefficients THIS instance reads. The fragment stage has
692 // no instance index, and the draw's own base is the same for every
693 // instance in a merged run — so the one stage that can say it, says it.
694
695 }
696 src +=
697 "\n"
698 "@@GLSL_HOOK@@"
699 "void main() {\n"
700 "#ifdef MESH\n"
701 " vec3 local = a_position;\n"
702 "#ifdef MESH_NORMALS\n"
703 " vec3 localNormal = a_normal;\n"
704 "#else\n"
705 " vec3 localNormal = vec3(0.0, 0.0, 1.0);\n"
706 "#endif\n"
707 // Before the pose: a target was authored against the mesh at rest.
708 " esApplyMorph(local, localNormal);\n"
709 "@@GLSL_CALL@@"
710 "#endif\n"
711 // A particle faces the viewer wherever it is seen from; head-on and
712 // orthographic the axes come out (1,0,0) and (0,1,0), the flat quad a 2D
713 // scene has always drawn.
714 "#ifdef PARTICLE\n"
715 " vec2 scaled = a_position * a_inst_size;\n"
716 " float cosR = cos(a_inst_rotation);\n"
717 " float sinR = sin(a_inst_rotation);\n"
718 " vec2 rotated = vec2(scaled.x * cosR - scaled.y * sinR,\n"
719 " scaled.x * sinR + scaled.y * cosR);\n"
720 " highp vec3 fwd = viewDirection(a_inst_position);\n"
721 // Looking straight down the world up, that axis cannot orient the quad.
722 " highp vec3 refUp = abs(fwd.y) > 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);\n"
723 " highp vec3 right = normalize(cross(refUp, fwd));\n"
724 " highp vec3 up = cross(fwd, right);\n"
725 " vec4 world = vec4(a_inst_position + right * rotated.x + up * rotated.y, 1.0);\n"
726 " v_color = vec4(a_inst_color.rgb * a_inst_extra.z, a_inst_color.a);\n"
727 " v_particle = vec4(a_inst_extra.x, a_inst_extra.y, a_inst_extra.w, a_inst_extra.z);\n"
728 // Bones are already world-space, so a skinned mesh's own transform is not
729 // read — which is what glTF requires of one.
730 "#elif defined(SKINNED)\n"
731 " mat4 skin = a_weights.x * u_bones[a_joints.x]\n"
732 " + a_weights.y * u_bones[a_joints.y]\n"
733 " + a_weights.z * u_bones[a_joints.z]\n"
734 " + a_weights.w * u_bones[a_joints.w];\n"
735 " vec4 world = skin * vec4(local, 1.0);\n"
736 " v_color = a_color * esInstanceTint();\n"
737 "#elif defined(MESH)\n"
738 " vec4 world = esInstanceModel() * vec4(local, 1.0);\n"
739 " v_color = @@GLSL_MESH_COLOR@@ * esInstanceTint();\n"
740 "#else\n"
741 " vec4 world = vec4(a_position, 1.0);\n"
742 " v_color = a_color;\n"
743 "#endif\n"
744 " gl_Position = u_projection * world;\n"
745 "#ifdef PARTICLE\n"
746 // A sheet animation moves the frame under the same quad.
747 " v_texCoord = a_texCoord * a_inst_uv.zw + a_inst_uv.xy;\n"
748 "#else\n"
749 " v_texCoord = a_texCoord;\n"
750 "#endif\n"
751 "#ifdef MESH_NORMALS\n"
752 // A particle in the world (a shader that declares PARTICLE_WORLD): its quad faces the eye, so that is its normal.
753 "#if defined(PARTICLE)\n"
754 " v_worldNormal = fwd;\n"
755 "#elif defined(SKINNED)\n"
756 " v_worldNormal = mat3(skin) * localNormal;\n"
757 "#else\n"
758 " v_worldNormal = esInstanceNormalMatrix() * localNormal;\n"
759 "#endif\n"
760 " v_worldXYZ = world.xyz;\n"
761 "#ifdef MESH_TANGENTS\n"
762 "#ifdef SKINNED\n"
763 " v_worldTangent = vec4(mat3(skin) * a_tangent.xyz, a_tangent.w);\n"
764 "#else\n"
765 " mat3 tangentModel = mat3(esInstanceModel());\n"
766 // A mirrored placement turns the bitangent the other way round.
767 " v_worldTangent = vec4(tangentModel * a_tangent.xyz, determinant(tangentModel) < 0.0 ? -a_tangent.w : a_tangent.w);\n"
768 "#endif\n"
769 "#endif\n"
770 "#endif\n"
771 "#ifdef MESH_LIGHTMAP\n"
772 " highp vec4 lmRect = esInstanceLightmapRect();\n"
773 " v_lightmap = vec3(a_texCoord1 * lmRect.xy + lmRect.zw,\n"
774 " lmRect.x > 0.0 ? 1.0 : 0.0);\n"
775 " v_texCoord1 = a_texCoord1;\n"
776 "#endif\n"
777 "#if defined(MESH_LOCAL_POSITION) && defined(MESH)\n"
778 " v_localPos = a_position;\n"
779 "#endif\n";
780 if (lit) {
781 src += " v_worldPos = world.xy;\n";
782 src += "#if !defined(MESH) && !defined(SKINNED) && !defined(PARTICLE)\n v_lightLayer = a_lightLayer;\n#else\n v_lightLayer = 0.0;\n#endif\n";
783 // The instance's own run of probe coefficients — declared by the Lit
784 // vertex header, so filled under the same condition.
785 src += "#ifdef PARTICLE\n v_probeSlot = 0.0;\n#else\n v_probeSlot = float(ES_INSTANCE_ID);\n#endif\n";
786 }
787 src += "}\n";
788 fillHook(src, "@@GLSL_MESH_COLOR@@", hook.empty() ? std::string("a_color") : std::string("es_vertexColor"));
789 fillHook(src, "@@GLSL_HOOK@@", hook.empty() ? std::string() :
790 "#ifdef MESH\nhighp vec4 es_vertexColor;\nhighp vec2 es_vertexUv1;\n" + hook + "\n#endif\n");
791 fillHook(src, "@@GLSL_CALL@@", hook.empty() ? std::string() :
792 " es_vertexColor = a_color;\n#ifdef MESH_LIGHTMAP\n es_vertexUv1 = a_texCoord1;\n#else\n es_vertexUv1 = vec2(0.0);\n#endif\n"
793 " esMaterialVertex(local, localNormal, a_texCoord);\n");
794 return src;
795}
796
803std::string normalizeDomain(const std::string& authored) {
804 if (authored == "Lit2D") return "Lit";
805 if (authored == "Unlit2D") return "Unlit";
806 return authored;
807}
808
809} // namespace
810
811// =============================================================================
812// Parser State
813// =============================================================================
814
823
824namespace {
825
826bool identChar(char c) { return std::isalnum(static_cast<unsigned char>(c)) || c == '_'; }
827
828std::string declaredName(std::string_view decl) {
829 const size_t bracket = decl.find('[');
830 if (bracket != std::string_view::npos) decl = decl.substr(0, bracket);
831 while (!decl.empty() && !identChar(decl.back())) decl.remove_suffix(1);
832 size_t start = decl.size();
833 while (start > 0 && identChar(decl[start - 1])) --start;
834 return std::string(decl.substr(start));
835}
836
837void collectUniformNames(const std::string& glsl, std::unordered_map<std::string, std::string>& out) {
838 size_t at = 0;
839 while ((at = glsl.find("uniform ", at)) != std::string::npos) {
840 if (at > 0 && identChar(glsl[at - 1])) { at += 8; continue; }
841 const size_t end = glsl.find_first_of("{;", at);
842 if (end == std::string::npos) break;
843 if (glsl[end] == ';') {
844 const std::string name = declaredName(std::string_view(glsl).substr(at, end - at));
845 if (!name.empty()) out.emplace(name, "a uniform");
846 at = end + 1;
847 continue;
848 }
849 const std::string block = declaredName(std::string_view(glsl).substr(at, end - at));
850 const size_t close = glsl.find('}', end);
851 if (close == std::string::npos) break;
852 size_t member = end + 1;
853 while (member < close) {
854 const size_t semi = glsl.find(';', member);
855 if (semi == std::string::npos || semi > close) break;
856 std::string_view line = std::string_view(glsl).substr(member, semi - member);
857 const size_t hash = line.rfind('\n');
858 if (hash != std::string_view::npos) line = line.substr(hash + 1);
859 const std::string name = declaredName(line);
860 if (!name.empty() && line.find('#') == std::string_view::npos) out.emplace(name, block);
861 member = semi + 1;
862 }
863 at = close + 1;
864 }
865}
866
867const std::unordered_map<std::string, std::string>& engineUniformNames(const ParsedShader& parsed) {
868 static std::mutex lock;
869 static std::unordered_map<std::string, std::unordered_map<std::string, std::string>> byDomain;
870 std::lock_guard<std::mutex> guard(lock);
871 const std::string key = parsed.domain + (parsed.vertexIsCanonical ? "|canonical" : "|own");
872 auto found = byDomain.find(key);
873 if (found != byDomain.end()) return found->second;
874
875 ParsedShader probe;
876 probe.valid = true;
877 probe.version = parsed.version;
878 probe.domain = parsed.domain;
879 probe.vertexIsCanonical = parsed.vertexIsCanonical;
880 probe.stages[ShaderStage::Vertex] = parsed.vertexIsCanonical ? parsed.stages.at(ShaderStage::Vertex) : "void main() {}\n";
881 probe.stages[ShaderStage::Fragment] = "void main() {}\n";
882 const std::vector<std::string> everything{
883 "MESH", "MESH_NORMALS", "MESH_TANGENTS", "MESH_LIGHTMAP", "SKINNED", "ES_RECEIVE_SHADOW",
884 "ES_ENV_MAP", "ES_SURFACE_3D", "ES_GBUFFER", "ES_VELOCITY", "ES_OPAQUE"};
885 auto& names = byDomain[key];
887 collectUniformNames(ShaderParser::assembleStage(probe, stage, "", everything, ShaderTargetLanguage::GLSL_ES300), names);
888 }
889 return names;
890}
891
892} // namespace
893
894// =============================================================================
895// Public Methods
896// =============================================================================
897
898ParsedShader ShaderParser::parse(const std::string& source) {
899 return parse(source, ShaderIncludeResolver{});
900}
901
902ParsedShader ShaderParser::parse(const std::string& source, const ShaderIncludeResolver& resolver) {
903 ParsedShader result;
904 result.valid = false;
905
906 if (source.empty()) {
907 result.errorMessage = "Empty shader source";
908 return result;
909 }
910
911 std::string expanded;
912 {
913 std::unordered_set<std::string> active;
914 std::string includeError;
915 if (!expandIncludes(source, std::string{}, resolver, active, 0,
916 expanded, result.expandedLineMap, includeError)) {
917 result.errorMessage = includeError;
918 return result;
919 }
920 }
921
922 LineReader stream(expanded);
923 std::string line;
925 std::string currentVariantName;
926 TextBuilder currentSection;
927 std::vector<SourceLine> currentSectionMap;
928 bool currentSectionIsWGSL = false;
929 bool currentSectionIsFullWGSL = false;
930 u32 lineNumber = 0;
931
932 while (stream.next(line)) {
933 lineNumber++;
934 std::string directive, argument;
935 parseDirective(line, directive, argument);
936
937 if (directive == "shader") {
938 if (argument.size() >= 2 && argument.front() == '"' && argument.back() == '"') {
939 result.name = argument.substr(1, argument.size() - 2);
940 } else {
941 result.name = argument;
942 }
943 continue;
944 }
945
946 if (directive == "version") {
947 result.version = argument;
948 continue;
949 }
950
951 if (directive == "feature") {
952 // Declares a compile-time variant keyword. Self-documenting; the consumer
953 // chooses which features to enable and assembleStage injects their #defines.
954 if (!argument.empty()) result.features.push_back(argument);
955 continue;
956 }
957
958 if (directive == "param") {
959 // Declarative material parameter: ShaderParser owns its std140 slot in the
960 // generated MaterialConstants block (or a sampler unit for textures).
961 ShaderProperty prop = parseParamDirective(argument);
962 if (!prop.name.empty()) result.properties.push_back(prop);
963 continue;
964 }
965
966 if (directive == "coverage") {
967 result.coverageParam = argument;
968 continue;
969 }
970
971 if (directive == "tips") {
972 result.tipParam = argument;
973 continue;
974 }
975
976 if (directive == "hairshadow") {
977 result.hairShadowParam = argument;
978 continue;
979 }
980
981 if (directive == "gbuffer") {
982 result.usesGBuffer = true;
983 continue;
984 }
985
986 if (directive == "lights") {
987 result.usesLights = true;
988 continue;
989 }
990
991 if (directive == "highprecision") {
992 result.highPrecision = true;
993 continue;
994 }
995
996 if (directive == "depthinput") {
997 result.depthInput = trim(argument);
998 continue;
999 }
1000
1001 if (directive == "vertexbounds") {
1002 // How far the vertex hook may move a vertex, in the mesh's local units.
1003 result.vertexBounds = std::strtof(argument.c_str(), nullptr);
1004 if (!(result.vertexBounds >= 0.0f)) result.vertexBounds = 0.0f;
1005 continue;
1006 }
1007
1008 if (directive == "vertexoffset") {
1009 if (state != ParseState::Global) {
1010 result.errorMessage = "Unexpected #pragma vertexoffset at line " + std::to_string(lineNumber);
1011 return result;
1012 }
1013 if (!argument.empty() && argument != "wgsl") {
1014 result.errorMessage = "Unknown vertexoffset language '" + argument + "' at line " +
1015 std::to_string(lineNumber) + " (expected no tag for GLSL, or 'wgsl')";
1016 return result;
1017 }
1018 state = ParseState::VertexHook;
1019 currentSectionIsWGSL = !argument.empty();
1020 currentSectionIsFullWGSL = false;
1021 currentSection.str("");
1022 currentSection.clear();
1023 currentSectionMap.clear();
1024 continue;
1025 }
1026
1027 if (directive == "domain") {
1028 if (!argument.empty()) result.domain = normalizeDomain(argument);
1029 continue;
1030 }
1031
1032 if (directive == "lighting") {
1033 // `#pragma lighting direct`: this surface is lit by the lights of the block and hard shadows only (see ES_LIGHT_DIRECT).
1034 if (trim(argument) == "direct") result.lightingDirect = true;
1035 continue;
1036 }
1037
1038 if (directive == "switch") {
1039 // Material-controlled compile-time toggle: `#pragma switch NAME [default(on|off)]`.
1040 usize swPos = 0;
1041 ShaderSwitch decl;
1042 decl.name = nextToken(argument, swPos);
1043 if (!decl.name.empty()) {
1044 const usize p = argument.find("default(");
1045 if (p != std::string::npos) {
1046 const usize open = p + 8;
1047 const usize close = argument.find(')', open);
1048 if (close != std::string::npos) {
1049 const std::string v = trim(argument.substr(open, close - open));
1050 decl.defaultOn = (v == "on" || v == "true" || v == "1");
1051 }
1052 }
1053 result.switches.push_back(decl);
1054 }
1055 continue;
1056 }
1057
1058 if (directive == "properties") {
1059 if (state != ParseState::Global) {
1060 result.errorMessage = "Unexpected #pragma properties at line " + std::to_string(lineNumber);
1061 return result;
1062 }
1063 state = ParseState::Properties;
1064 continue;
1065 }
1066
1067 if (directive == "vertex" || directive == "fragment") {
1068 if (state != ParseState::Global) {
1069 result.errorMessage = "Unexpected #pragma " + directive +
1070 " at line " + std::to_string(lineNumber);
1071 return result;
1072 }
1073 // Optional language tag: `#pragma fragment wgsl` opens the stage's
1074 // WGSL twin section; `wgsl full` marks a SELF-CONTAINED twin whose
1075 // assembly skips every injected header (the cook-generated shape);
1076 // no tag is the GLSL stage.
1077 if (!argument.empty() && argument != "wgsl" && argument != "wgsl full") {
1078 result.errorMessage = "Unknown stage language '" + argument +
1079 "' at line " + std::to_string(lineNumber) +
1080 " (expected no tag for GLSL, 'wgsl', or 'wgsl full')";
1081 return result;
1082 }
1083 state = (directive == "vertex") ? ParseState::Vertex : ParseState::Fragment;
1084 currentSectionIsWGSL = !argument.empty();
1085 currentSectionIsFullWGSL = (argument == "wgsl full");
1086 currentSection.str("");
1087 currentSection.clear();
1088 currentSectionMap.clear();
1089 continue;
1090 }
1091
1092 if (directive == "variant") {
1093 if (state != ParseState::Global) {
1094 result.errorMessage = "Unexpected #pragma variant at line " + std::to_string(lineNumber);
1095 return result;
1096 }
1097 state = ParseState::Variant;
1098 currentVariantName = argument;
1099 currentSection.str("");
1100 currentSection.clear();
1101 currentSectionMap.clear();
1102 continue;
1103 }
1104
1105 if (directive == "end") {
1106 switch (state) {
1108 break;
1109 case ParseState::Vertex:
1110 case ParseState::Fragment: {
1113 auto& stages = currentSectionIsWGSL ? result.wgslStages : result.stages;
1114 auto& maps = currentSectionIsWGSL ? result.wgslStageLineMaps : result.stageLineMaps;
1115 stages[s] = currentSection.str();
1116 maps[s] = std::move(currentSectionMap);
1117 if (currentSectionIsWGSL && currentSectionIsFullWGSL) {
1118 result.wgslStageFull[s] = true;
1119 }
1120 currentSectionMap.clear();
1121 currentSectionIsWGSL = false;
1122 currentSectionIsFullWGSL = false;
1123 break;
1124 }
1126 (currentSectionIsWGSL ? result.wgslVertexHook : result.vertexHook) = currentSection.str();
1127 currentSectionMap.clear();
1128 currentSectionIsWGSL = false;
1129 break;
1131 result.variants[currentVariantName] = currentSection.str();
1132 currentVariantName.clear();
1133 currentSectionMap.clear();
1134 break;
1135 default:
1136 break;
1137 }
1138 state = ParseState::Global;
1139 continue;
1140 }
1141
1142 switch (state) {
1143 case ParseState::Global:
1144 if (!trim(line).empty() && line[0] != '/' && trim(line).substr(0, 2) != "//") {
1145 result.sharedCode += line + "\n";
1146 }
1147 break;
1148
1150 std::string trimmedLine = trim(line);
1151 if (!trimmedLine.empty() && trimmedLine.find("uniform") != std::string::npos) {
1152 ShaderProperty prop = parsePropertyAnnotation(line);
1153 if (!prop.name.empty()) {
1154 result.properties.push_back(prop);
1155 }
1156 }
1157 break;
1158 }
1159
1160 case ParseState::Vertex:
1163 case ParseState::Variant: {
1164 currentSection << line << "\n";
1165 const SourceLine src = (lineNumber >= 1 && lineNumber <= result.expandedLineMap.size())
1166 ? result.expandedLineMap[lineNumber - 1]
1167 : SourceLine{};
1168 currentSectionMap.push_back(src);
1169 break;
1170 }
1171 }
1172 }
1173
1174 if (state != ParseState::Global) {
1175 result.errorMessage = "Unexpected end of file - missing #pragma end";
1176 return result;
1177 }
1178
1179 if (result.stages.find(ShaderStage::Vertex) == result.stages.end()) {
1180 // Fragment-only authoring: 2D domains get the canonical batch-space
1181 // pass-through, PostProcess the canonical fullscreen pass-through.
1182 if (result.domain == "Unlit" || result.domain == "Lit") {
1183 result.stages[ShaderStage::Vertex] = canonicalVertexStage(result.domain == "Lit", result.vertexHook);
1184 result.vertexIsCanonical = true;
1185 } else if (result.domain == "PostProcess") {
1186 result.stages[ShaderStage::Vertex] = canonicalPPVertexStage();
1187 } else {
1188 result.errorMessage = "Missing vertex shader stage";
1189 return result;
1190 }
1191 }
1192
1193 if (result.stages.find(ShaderStage::Fragment) == result.stages.end()) {
1194 result.errorMessage = "Missing fragment shader stage";
1195 return result;
1196 }
1197
1198 // Same for the WGSL twin: a fragment-only twin gets the domain's canonical
1199 // WGSL vertex, and the flag makes the fragment assembly inject the matching
1200 // VSOut interface. A file with no wgsl sections simply has no twin.
1201 if (result.wgslStages.count(ShaderStage::Fragment) != 0 &&
1202 result.wgslStages.count(ShaderStage::Vertex) == 0) {
1203 if (result.domain == "Unlit" || result.domain == "Lit") {
1204 result.wgslStages[ShaderStage::Vertex] = canonicalVertexStageWGSL(result.domain == "Lit", result.wgslVertexHook);
1205 result.wgslVertexIsCanonical = true;
1206 } else if (result.domain == "PostProcess") {
1207 result.wgslStages[ShaderStage::Vertex] = canonicalPPVertexStageWGSL();
1208 result.wgslVertexIsCanonical = true;
1209 }
1210 }
1211
1212 if (!result.properties.empty()) {
1213 const auto& engine = engineUniformNames(result);
1214 for (const auto& prop : result.properties) {
1215 const auto clash = engine.find(prop.name);
1216 if (clash == engine.end()) continue;
1217 result.errorMessage = "#pragma param '" + prop.name + "' is reserved: the engine declares it in " +
1218 (clash->second == "a uniform" ? std::string("a uniform") : "the " + clash->second + " block") +
1219 " of every " + result.domain + " shader, and on WebGL two declarations of one name do not compile. " +
1220 (clash->second == "TimeConstants"
1221 ? "Read it directly instead (GLSL: u_time.x = seconds, u_time.y = frame delta, u_viewport.xy = canvas pixels; "
1222 "WGSL: tc.u_time / tc.u_viewport). "
1223 : "") +
1224 "Give a parameter of your own a different name.";
1225 return result;
1226 }
1227 }
1228
1229 computeMaterialLayout(result);
1230
1231 result.valid = true;
1232 return result;
1233}
1234
1236 ShaderStage stage,
1237 const std::string& platform,
1238 const std::vector<std::string>& features,
1239 ShaderTargetLanguage target) {
1240 return assembleStageEx(parsed, stage, platform, features, target).source;
1241}
1242
1243std::string ShaderParser::variantKey(const std::vector<std::string>& features) {
1244 std::vector<std::string> sorted(features);
1245 std::sort(sorted.begin(), sorted.end());
1246 std::string key;
1247 for (const auto& f : sorted) {
1248 if (!key.empty()) key += '|';
1249 key += f;
1250 }
1251 return key;
1252}
1253
1254std::vector<std::string> ShaderParser::splitFeatures(const std::string& csv) {
1255 std::vector<std::string> features;
1256 for (usize start = 0; start <= csv.size();) {
1257 const usize comma = csv.find(',', start);
1258 const usize end = comma == std::string::npos ? csv.size() : comma;
1259 const std::string f = trim(csv.substr(start, end - start));
1260 if (!f.empty()) features.push_back(f);
1261 if (comma == std::string::npos) break;
1262 start = comma + 1;
1263 }
1264 return features;
1265}
1266
1267namespace {
1268
1269usize wordCount(const std::string& text, const std::string& word) {
1270 usize n = 0;
1271 for (usize at = text.find(word); at != std::string::npos; at = text.find(word, at + word.size())) {
1272 const bool before = at > 0 && (std::isalnum(static_cast<unsigned char>(text[at - 1])) || text[at - 1] == '_');
1273 const usize end = at + word.size();
1274 const bool after = end < text.size() && (std::isalnum(static_cast<unsigned char>(text[end])) || text[end] == '_');
1275 if (!before && !after) ++n;
1276 }
1277 return n;
1278}
1279
1280std::string withoutDefines(std::string text, const std::vector<std::string>& names) {
1281 for (const auto& name : names) {
1282 const std::string line = "#define " + name + " 1\n";
1283 if (const usize at = text.find(line); at != std::string::npos) text.erase(at, line.size());
1284 }
1285 return text;
1286}
1287
1288} // namespace
1289
1290std::vector<std::string> ShaderParser::featuresRead(const ParsedShader& parsed,
1291 const std::vector<std::string>& features,
1292 ShaderTargetLanguage target) {
1293 if (target != ShaderTargetLanguage::GLSL_ES300 || !parsed.valid) return features;
1294 const std::string vertex = assembleStage(parsed, ShaderStage::Vertex, "", features, target);
1295 const std::string fragment = assembleStage(parsed, ShaderStage::Fragment, "", features, target);
1296 std::vector<std::string> kept, dropped;
1297 for (const auto& f : features) {
1298 const usize defines = wordCount(vertex, "#define " + f) + wordCount(fragment, "#define " + f);
1299 (wordCount(vertex, f) + wordCount(fragment, f) > defines ? kept : dropped).push_back(f);
1300 }
1301 if (dropped.empty()) return features;
1302 if (assembleStage(parsed, ShaderStage::Vertex, "", kept, target) != withoutDefines(vertex, dropped)
1303 || assembleStage(parsed, ShaderStage::Fragment, "", kept, target) != withoutDefines(fragment, dropped)) {
1304 return features;
1305 }
1306 return kept;
1307}
1308
1309namespace {
1310
1311u32 countNewlines(const std::string& s) {
1312 u32 n = 0;
1313 for (char c : s) {
1314 if (c == '\n') ++n;
1315 }
1316 return n;
1317}
1318
1319const char* glslTypeName(ShaderPropertyType t) {
1320 switch (t) {
1321 case ShaderPropertyType::Float: return "float";
1322 case ShaderPropertyType::Vec2: return "vec2";
1323 case ShaderPropertyType::Vec3: return "vec3";
1325 case ShaderPropertyType::Color: return "vec4";
1326 case ShaderPropertyType::Int: return "int";
1327 default: return "float";
1328 }
1329}
1330
1331// =============================================================================
1332// WGSL emission — the injected headers' twins. Uniform blocks keep their GLSL
1333// member names behind short block vars, so a body ports mechanically:
1334// u_time -> tc.u_time, u_progress -> mc.u_progress, u_lights -> lc.u_lights.
1335// WGSL's uniform address-space layout equals std140 member-for-member for the
1336// param type set (f32/i32 align 4, vec2 8, vec3/vec4 16), so MaterialConstants
1337// offsets computed by computeMaterialLayout hold for both languages.
1338// =============================================================================
1339
1340const char* wgslTypeName(ShaderPropertyType t) {
1341 switch (t) {
1342 case ShaderPropertyType::Float: return "f32";
1343 case ShaderPropertyType::Vec2: return "vec2f";
1344 case ShaderPropertyType::Vec3: return "vec3f";
1346 case ShaderPropertyType::Color: return "vec4f";
1347 case ShaderPropertyType::Int: return "i32";
1348 default: return "f32";
1349 }
1350}
1351
1352// Engine-owned frame block (u_time / u_viewport), binding 3 — the GLSL
1353// kTimeHeader's twin. Injected into every WGSL stage; the device's explicit
1354// layouts make a declared-but-unused block legal, same as GL.
1355const char* kFrameHeaderWGSL =
1356 "struct FrameConstants {\n"
1357 " projection : mat4x4f,\n"
1358 " camera : vec4f,\n"
1359 " inverseViewProjection : mat4x4f,\n"
1360 " renderOrigin : vec4f,\n"
1361 "};\n"
1362 "@group(0) @binding(0) var<uniform> frame : FrameConstants;\n"
1363 "fn viewDirection(worldPos : vec3f) -> vec3f {\n"
1364 " if (frame.camera.w > 0.5) { return normalize(frame.camera.xyz - worldPos); }\n"
1365 " return frame.camera.xyz;\n"
1366 "}\n"
1367 // This device clips z to [0, 1]; the uv runs up the screen, as in GL.
1368 "fn worldFromDepth(uv : vec2f, depth : f32) -> vec3f {\n"
1369 " let clip = vec4f(uv * 2.0 - 1.0, depth, 1.0);\n"
1370 " let world = frame.inverseViewProjection * clip;\n"
1371 " return world.xyz / world.w;\n"
1372 "}\n"
1373 "fn distanceToEye(worldPos : vec3f) -> f32 {\n"
1374 " if (frame.camera.w > 0.5) { return length(worldPos - frame.camera.xyz); }\n"
1375 " return -dot(worldPos, frame.camera.xyz);\n"
1376 "}\n"
1377 "fn sceneUv(worldPos : vec3f) -> vec2f {\n"
1378 " let clip = frame.projection * vec4f(worldPos, 1.0);\n"
1379 " let w = max(clip.w, 1e-4);\n"
1380 " return clamp(clip.xy / w * 0.5 + 0.5, vec2f(0.001), vec2f(0.999));\n"
1381 "}\n"
1382 "fn sceneDistance(texel : vec4f) -> f32 {\n"
1383 " return select(texel.b * 1024.0, texel.r, texel.r < 65000.0);\n"
1384 "}\n";
1385
1386const char* kTimeHeaderWGSL =
1387 "struct TimeConstants { u_time : vec4f, u_viewport : vec4f, u_quality : vec4f };\n"
1388 "@group(0) @binding(3) var<uniform> tc : TimeConstants;\n";
1389
1390// The batch texture contract for fragment-only 2D twins: u_textures[8]
1391// de-combined into texture_2d t0..t7 (bindings 0..7) + samplers s0..s7
1392// (bindings 8..15) — the group-1 convention (WebGPUMappings). Bodies sample
1393// `textureSampleLevel(t0, s0, uv, 0.0)` where GLSL reads u_textures[0].
1395u32 materialLowUnits(const ParsedShader& parsed) {
1396 u32 mask = 0;
1397 for (const auto& p : parsed.properties) {
1398 if (p.fromParam && p.type == ShaderPropertyType::Texture && p.textureUnit >= 0
1399 && p.textureUnit < static_cast<i32>(MATERIAL_TEXTURE_UNIT_BASE)) {
1400 mask |= 1u << p.textureUnit;
1401 }
1402 }
1403 return mask;
1404}
1405
1406std::string wgslBatchTextureDecls(bool postProcess, u32 materialUnits = 0) {
1407 std::string src;
1408 for (u32 i = 0; i < 8; ++i) {
1409 // A batch unit a material texture took is that texture's binding now: the shader reads no batch texture there.
1410 if ((materialUnits & (1u << i)) != 0) continue;
1411 const std::string n = std::to_string(i);
1412 // A fullscreen pass reads the scene's DEPTH at the top engine unit, and a
1413 // depth texture is its own WGSL type with no sampler under it. PostProcess
1414 // only: unit 7 is an ordinary batch texture in every other domain.
1415 if (postProcess && i == kSceneDepthUnit) {
1416 src += "@group(1) @binding(" + n + ") var t" + n + " : texture_depth_2d;\n";
1417 continue;
1418 }
1419 src += "@group(1) @binding(" + n + ") var t" + n + " : texture_2d<f32>;\n";
1420 src += "@group(1) @binding(" + std::to_string(8 + i) + ") var s" + n + " : sampler;\n";
1421 }
1422 return src;
1423}
1424
1431std::string wgslReachedTextureDecls(const std::string& source, bool postProcess) {
1432 u32 reachedTex = 0;
1433 u32 reachedSam = 0;
1434 scanWGSLReachedUnits(source.c_str(), reachedTex, reachedSam);
1435 const u64 declared = scanWGSLBindingMask(source.c_str(), 1);
1436 std::string src;
1437 for (u32 unit = 0; unit < WGSL_MAX_TEXTURE_UNITS; ++unit) {
1438 const std::string n = std::to_string(unit);
1439 if ((reachedTex & (1u << unit)) != 0
1440 && (declared & (u64{1} << textureBindingForUnit(unit))) == 0) {
1441 // A fullscreen pass reads the scene's DEPTH at the top engine unit, and a
1442 // depth texture is its own WGSL type with no sampler under it.
1443 src += "@group(1) @binding(" + std::to_string(textureBindingForUnit(unit)) + ") var t" + n
1444 + (postProcess && unit == kSceneDepthUnit ? " : texture_depth_2d;\n"
1445 : " : texture_2d<f32>;\n");
1446 }
1447 if ((reachedSam & (1u << unit)) != 0
1448 && (declared & (u64{1} << samplerBindingForUnit(unit))) == 0) {
1449 src += "@group(1) @binding(" + std::to_string(samplerBindingForUnit(unit)) + ") var s" + n
1450 + " : sampler;\n";
1451 }
1452 }
1453 return src;
1454}
1455
1456// #pragma param texture uniforms: material units (>= 8) take the unit→binding
1457// convention in rhi/WgslBindings.hpp, and the sampler rides the param's own name with
1458// an _s suffix: textureSampleLevel(u_mask, u_mask_s, uv, 0.0).
1459//
1460// The sampler is declared only for a texture the stage samples through it. A texture read with textureLoad alone has
1461// no sampler to bind, and that is what lets a 32-bit float one (the motion pass's) be its binding: a float32 texture
1462// cannot be filtered, and a layout that pairs it with a filtering sampler is refused by the device.
1463std::string wgslMaterialTextureDecls(const ParsedShader& parsed, const std::string& body, const std::string* only = nullptr) {
1464 std::string src;
1465 const u64 declared = scanWGSLBindingMask(body.c_str(), 1);
1466 for (const auto& p : parsed.properties) {
1467 if (!p.fromParam || p.type != ShaderPropertyType::Texture || p.textureUnit < 0) continue;
1468 if (only && only->find(p.name) == std::string::npos) continue;
1469 const u32 unit = static_cast<u32>(p.textureUnit);
1470 if ((declared & (u64{1} << textureBindingForUnit(unit))) == 0) src += "@group(1) @binding(" + std::to_string(textureBindingForUnit(unit)) + ") var " + p.name +
1471 (p.layered ? " : texture_2d_array<f32>;\n" : " : texture_2d<f32>;\n");
1472 if (body.find(p.name + "_s") == std::string::npos || (declared & (u64{1} << samplerBindingForUnit(unit))) != 0) continue;
1473 src += "@group(1) @binding(" + std::to_string(samplerBindingForUnit(unit)) + ") var " + p.name +
1474 "_s : sampler;\n";
1475 }
1476 return src;
1477}
1478
1479// Lit injection twin: LightConstants (binding 2) + the lighting/shadow
1480// helpers, ported line for line from the GLSL kLitHeader. Array strides
1481// (Light = 64 bytes, vec4f = 16) satisfy WGSL's uniform layout rules, so the
1482// block matches renderer/LightConstants.hpp on both backends. sampleNormal
1483// takes the de-combined texture+sampler pair and samples mip 0 explicitly,
1484// keeping calls legal in non-uniform control flow.
1485const char* kColorHelpersWGSL = R"(fn srgbToLinear(c : vec3f) -> vec3f {
1486 return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3f(2.4)), step(vec3f(0.04045), c));
1487}
1488fn linearToSrgb(c : vec3f) -> vec3f {
1489 return mix(c * 12.92, 1.055 * pow(c, vec3f(1.0 / 2.4)) - 0.055, step(vec3f(0.0031308), c));
1490}
1491fn acesFilmic(x : vec3f) -> vec3f {
1492 return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), vec3f(0.0), vec3f(1.0));
1493}
1494fn pbrNeutral(color : vec3f) -> vec3f {
1495 let startCompression = 0.8 - 0.04;
1496 let desaturation = 0.15;
1497 var c = color;
1498 let x = min(c.r, min(c.g, c.b));
1499 var offset = 0.04;
1500 if (x < 0.08) { offset = x - 6.25 * x * x; }
1501 c = c - vec3f(offset);
1502 let peak = max(c.r, max(c.g, c.b));
1503 if (peak < startCompression) { return c; }
1504 let d = 1.0 - startCompression;
1505 let newPeak = 1.0 - d * d / (peak + d - startCompression);
1506 c = c * (newPeak / peak);
1507 let g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0);
1508 return mix(c, vec3f(newPeak), g);
1509}
1510)";
1511
1512// The light block and the shadow map as a fullscreen pass sees them: the same block the Lit shaders read, the atlas on
1513// unit 2 where a pass has nothing else, and the two questions an effect asks of them — which light is the sun, and is
1514// this point of air in its light. One tap, no filtering: a fog sample is not a surface.
1515const char* kPostLightHeaderWGSL = R"(struct Light { posDir : vec4f, color : vec4f, spot : vec4f, shadow : vec4f, shadowMap : vec4f, falloff : vec4f };
1516struct LightConstants {
1517 u_ambient : vec4f,
1518 u_lights : array<Light, 16>,
1519 u_mask2DRect : vec4f,
1520 u_shadowMatrix : array<mat4x4f, 16>,
1521 u_shadowTile : array<vec4f, 16>,
1522 u_shadowParams : vec4f,
1523 u_envIrradiance : array<vec4f, 9>,
1524 u_envParams : vec4f,
1525 u_envTint : vec4f,
1526 u_reflParams : vec4f,
1527 u_reflBox : array<vec4f, 30>,
1528 u_bakedTint : vec4f,
1529 tiledLights : array<Light, 96>,
1530 tileMask : array<vec4u, 192>,
1531 tileInfo : vec4f,
1532};
1533@group(0) @binding(2) var<uniform> lc : LightConstants;
1534fn unpackDepth(c : vec3f) -> f32 {
1535 return dot(c, vec3f(1.0, 1.0 / 255.0, 1.0 / 65025.0));
1536}
1537// The first directional light that shines: xyz = where it stands in the sky, w = 1 (0 = none),
1538// color = its colour and strength, tiles = x first atlas tile, y how many.
1539struct Sun { dir : vec4f, color : vec4f, tiles : vec2i };
1540fn findSun() -> Sun {
1541 var s : Sun;
1542 s.dir = vec4f(0.0);
1543 s.color = vec4f(0.0);
1544 s.tiles = vec2i(0, 0);
1545 for (var i = 0; i < 16; i++) {
1546 let l = lc.u_lights[i];
1547 if (l.posDir.z > 0.5 && l.posDir.z < 1.5 && l.color.a > 0.0) {
1548 s.dir = vec4f(-normalize(vec3f(l.posDir.x, l.posDir.y, l.posDir.w)), 1.0);
1549 s.color = l.color;
1550 s.tiles = vec2i(i32(l.shadowMap.x), i32(l.shadowMap.y % 8.0));
1551 return s;
1552 }
1553 }
1554 return s;
1555}
1556fn sunVisibility(worldPos : vec3f, first : i32, count : i32) -> f32 {
1557 if (lc.u_shadowParams.x < 0.5 || count <= 0) { return 1.0; }
1558 for (var k = 0; k < 16; k++) {
1559 if (k >= count) { break; }
1560 let t = first + k;
1561 let m = lc.u_shadowMatrix[t];
1562 let c = m * vec4f(worldPos, 1.0);
1563 if (c.w <= 0.0) { continue; }
1564 let proj = c.xyz / c.w;
1565 let uv = proj.xy * 0.5 + 0.5;
1566 if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || proj.z < 0.0 || proj.z > 1.0) { continue; }
1567 let rect = lc.u_shadowTile[t];
1568 let at = rect.xy + uv * rect.z;
1569 let lo = rect.xy + lc.u_shadowParams.y * 0.5;
1570 let hi = rect.xy + rect.z - lc.u_shadowParams.y * 0.5;
1571 let d = unpackDepth(textureSampleLevel(t2, s2, clamp(at, lo, hi), 0.0).rgb);
1572 return select(1.0, 0.0, d < clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - 0.0025);
1573 }
1574 return 1.0;
1575}
1576)";
1577
1578const char* kLitHeaderWGSL = R"(struct Light { posDir : vec4f, color : vec4f, spot : vec4f, shadow : vec4f, shadowMap : vec4f, falloff : vec4f };
1579struct LightConstants {
1580 u_ambient : vec4f,
1581 u_lights : array<Light, 16>,
1582 u_mask2DRect : vec4f,
1583 u_shadowMatrix : array<mat4x4f, 16>,
1584 u_shadowTile : array<vec4f, 16>,
1585 u_shadowParams : vec4f,
1586 u_envIrradiance : array<vec4f, 9>,
1587 u_envParams : vec4f,
1588 u_envTint : vec4f,
1589 u_reflParams : vec4f,
1590 u_reflBox : array<vec4f, 30>,
1591 u_bakedTint : vec4f,
1592 tiledLights : array<Light, 96>,
1593 tileMask : array<vec4u, 192>,
1594 tileInfo : vec4f,
1595 u_ambientGround : vec4f,
1596 u_tileView : mat4x4f,
1597 u_waterRect : vec4f,
1598 u_waterDepth : vec4f,
1599 u_waterSun : vec4f,
1600};
1601@group(0) @binding(2) var<uniform> lc : LightConstants;
1602struct ProbeConstants { u_probeIrradiance : array<vec4f, 1000>, u_probeTail : vec4f };
1603@group(0) @binding(7) var<uniform> pc : ProbeConstants;
1604#ifdef ES_SURFACE_3D
1605#ifndef MESH_LIGHTMAP
1606// The frame's probe atlas, a volume of bricks read per pixel, on the bake's unit: only resident 3D surfaces carry probe runs,
1607// and a variant reading a bake has that unit's 2D atlas instead.
1608@group(1) @binding(5) var t5 : texture_3d<f32>;
1609@group(1) @binding(13) var s5 : sampler;
1610#endif
1611#endif
1612struct PlanarConstants { planarProjection : mat4x4f, planarParams : vec4f };
1613@group(0) @binding(9) var<uniform> planar : PlanarConstants;
1614// Which run of that block this fragment's instance reads. WGSL has no module
1615// varying, so the entry point hands it over — the GLSL twin reads the varying
1616// straight, which is the one place the two stages differ in shape.
1617var<private> g_probeSlot : f32 = 0.0;
1618// Set by a hair shader before it lights: how much of the light a layer of strands takes, per world unit along it (0 = a surface, a hard compare).
1619var<private> g_hairShadow : f32 = 0.0;
1620// Set by a shader that lights a surface the sun seldom shadows (the sea) before it lights: the shadow is read as an edge a source with no size
1621// throws, nine taps, and not as the penumbra of the sun's size, a search and a filter of up to sixty-four.
1622var<private> g_shadowHard : f32 = 0.0;
1623// The GLSL twin's v_lightmap, handed over by the entry point like the slot above.
1624var<private> g_lightmap : vec3f = vec3f(0.0);
1625// Where the surface being lit stands, for a volume read per pixel: set by whatever lights it (the BRDF, envRadiance).
1626var<private> g_probePos : vec3f = vec3f(0.0);
1627// The mesh's own tangent frame, handed over by the entry point like the slot above; zero where the shader never sets it, which
1628// is what sends perturbNormal back to deriving a frame per pixel.
1629var<private> g_worldTangent : vec4f = vec4f(0.0);
1630fn packDepth(d : f32) -> vec3f {
1631 let enc = fract(d * vec3f(1.0, 255.0, 65025.0));
1632 return enc - enc.yzz * vec3f(1.0 / 255.0, 1.0 / 255.0, 0.0);
1633}
1634fn unpackDepth(c : vec3f) -> f32 {
1635 return dot(c, vec3f(1.0, 1.0 / 255.0, 1.0 / 65025.0));
1636}
1637fn stepFor(texel : f32, slope : f32, reach : f32) -> f32 {
1638 // How far toward the light a lookup has to ask from: one texel of doubt about where
1639 // the map sampled this surface, plus whatever `reach` texels of it are worth at the
1640 // angle it stands.
1641 return texel * (1.5 * (1.0 + slope) + reach * slope);
1642}
1643fn shadowDepth(m : mat4x4f, p : vec3f) -> f32 {
1644 let c = m * vec4f(p, 1.0);
1645 return clamp(c.z / max(c.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);
1646}
1647fn shadowTap(at : vec2f, lo : vec2f, hi : vec2f, here : f32) -> f32 {
1648#ifdef ES_RECEIVE_SHADOW
1649 // A tap that leaves its tile reads another map entirely — a neighbouring cube face,
1650 // which is the least related depth in the atlas.
1651 let d = unpackDepth(textureSampleLevel(t2, s2, clamp(at, lo, hi), 0.0).rgb);
1652 return select(1.0, 0.0, d < here);
1653#else
1654 // The map's sampler is only declared where a shader receives one.
1655 return 1.0;
1656#endif
1657}
1658fn diskTap(i : i32, n : i32, radius : f32) -> vec2f {
1659 // A spiral, not a table: the golden angle spreads any number of taps evenly over a
1660 // disc, so the pattern follows the count instead of being pasted in beside it.
1661 let a = f32(i) * 2.3999632;
1662 // Turned over in v for the reason the tile's rect is: an offset in texture space
1663 // follows the axis the texture is sampled along, and this backend's runs the other
1664 // way. A spiral is not its own mirror, so without this the two average other points.
1665 return radius * sqrt((f32(i) + 0.5) / f32(n)) * vec2f(cos(a), -sin(a));
1666}
1667// The same spiral turned by `spin` radians: a disc wider than the taps can cover without gaps between them bands where the same spiral
1668// lands on every pixel, and turning it by an angle that differs from one point of the surface to the next makes that grain instead.
1669fn diskTapSpun(i : i32, n : i32, radius : f32, spin : f32) -> vec2f {
1670 let a = f32(i) * 2.3999632 + spin;
1671 return radius * sqrt((f32(i) + 0.5) / f32(n)) * vec2f(cos(a), -sin(a));
1672}
1673// A turn for the spiral, fixed to the point of the surface (so it does not crawl as the camera moves).
1674fn shadowSpin(worldPos : vec3f) -> f32 {
1675 return 6.2831853 * fract(sin(dot(worldPos, vec3f(12.9898, 78.233, 37.719))) * 43758.5453);
1676}
1677)"
1678// Split again for the same cap; the WGSL is unchanged.
1679R"(// The spiral taps for 8, 16 and 32 points, as numbers (see the GLSL twin): each is turned by the pixel's own spin where it is used.
1680const kSpiral8 = array<vec2f, 8>(
1681 vec2f(0.2500000, 0.0000000),
1682 vec2f(-0.3192901, 0.2924959),
1683 vec2f(0.0488724, -0.5568765),
1684 vec2f(0.4024445, 0.5249175),
1685 vec2f(-0.7385351, -0.1306364),
1686 vec2f(0.6996049, -0.4450315),
1687 vec2f(-0.2340040, 0.8704838),
1688 vec2f(-0.4462715, -0.8592682)
1689);
1690const kInner5 = array<vec2f, 5>(vec2f(0.0), vec2f(1.5, 0.0), vec2f(-1.5, 0.0), vec2f(0.0, 1.5), vec2f(0.0, -1.5));
1691const kSpiral16 = array<vec2f, 16>(
1692 vec2f(0.1767767, 0.0000000),
1693 vec2f(-0.2257722, 0.2068258),
1694 vec2f(0.0345580, -0.3937712),
1695 vec2f(0.2845713, 0.3711727),
1696 vec2f(-0.5222232, -0.0923739),
1697 vec2f(0.4946953, -0.3146848),
1698 vec2f(-0.1654658, 0.6155250),
1699 vec2f(-0.3155616, -0.6075943),
1700 vec2f(0.6846422, 0.2500301),
1701 vec2f(-0.7122560, 0.2940091),
1702 vec2f(0.3433543, -0.7337287),
1703 vec2f(0.2537305, 0.8089319),
1704 vec2f(-0.7647461, -0.4431856),
1705 vec2f(0.8971339, -0.1972327),
1706 vec2f(-0.5475066, 0.7787725),
1707 vec2f(-0.1264872, -0.9760896)
1708);
1709const kSpiral32 = array<vec2f, 32>(
1710 vec2f(0.1250000, 0.0000000),
1711 vec2f(-0.1596450, 0.1462479),
1712 vec2f(0.0244362, -0.2784383),
1713 vec2f(0.2012223, 0.2624588),
1714 vec2f(-0.3692676, -0.0653182),
1715 vec2f(0.3498024, -0.2225157),
1716 vec2f(-0.1170020, 0.4352419),
1717 vec2f(-0.2231357, -0.4296341),
1718 vec2f(0.4841152, 0.1767979),
1719 vec2f(-0.5036411, 0.2078959),
1720 vec2f(0.2427881, -0.5188246),
1721 vec2f(0.1794146, 0.5720012),
1722 vec2f(-0.5407571, -0.3133795),
1723 vec2f(0.6343695, -0.1394646),
1724 vec2f(-0.3871456, 0.5506753),
1725 vec2f(-0.0894400, -0.6901996),
1726 vec2f(0.5490720, 0.4627580),
1727 vec2f(-0.7388785, 0.0305553),
1728 vec2f(0.5389548, -0.5363326),
1729 vec2f(-0.0360577, 0.7797915),
1730 vec2f(-0.5128179, -0.6145265),
1731 vec2f(0.8123597, 0.1093013),
1732 vec2f(-0.6883103, 0.4789091),
1733 vec2f(0.1880855, -0.8360615),
1734 vec2f(0.4350338, 0.7591907),
1735 vec2f(-0.8504486, -0.2713156),
1736 vec2f(0.8261021, -0.3816809),
1737 vec2f(-0.3578875, 0.8551558),
1738 vec2f(-0.3194081, -0.8880335),
1739 vec2f(0.8499090, 0.4466874),
1740 vec2f(-0.9440344, 0.2488453),
1741 vec2f(0.5365950, -0.8345303)
1742);
1743// What of the sun a sky's clouds leave at a world point. See the GLSL twin.
1744fn cloudShadow3D(worldPos : vec3f, t : i32) -> f32 {
1745#ifndef ES_RECEIVE_SHADOW
1746 return 1.0;
1747#else
1748 let uv = (lc.u_shadowMatrix[t] * vec4f(worldPos, 1.0)).xy * 0.5 + 0.5;
1749 if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { return 1.0; }
1750 let rect = lc.u_shadowTile[t];
1751 let texel = lc.u_shadowParams.y;
1752 let p = (rect.xy + uv * rect.z) / texel - 0.5;
1753 let f = fract(p);
1754 let at = (floor(p) + 0.5) * texel;
1755 let lo = rect.xy + texel * 0.5;
1756 let hi = rect.xy + rect.z - texel * 0.5;
1757 let a = textureSampleLevel(t2, s2, clamp(at, lo, hi), 0.0).a;
1758 let b = textureSampleLevel(t2, s2, clamp(at + vec2f(texel, 0.0), lo, hi), 0.0).a;
1759 let c = textureSampleLevel(t2, s2, clamp(at + vec2f(0.0, texel), lo, hi), 0.0).a;
1760 let d = textureSampleLevel(t2, s2, clamp(at + vec2f(texel), lo, hi), 0.0).a;
1761 return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
1762#endif
1763}
1764fn shadowFactor3D(worldPos : vec3f, N : vec3f, L : vec3f, source : vec2f,
1765 first : i32, count : i32) -> f32 {
1766#ifndef ES_RECEIVE_SHADOW
1767 return 1.0;
1768#else
1769 if (lc.u_shadowParams.x < 0.5) { return 1.0; }
1770 let NoL = clamp(dot(N, L), 0.0, 1.0);
1771 // Nearest tile first: a light's tiles overlap, and the first one covering a
1772 // fragment is the one that spends the most texels on it.
1773 for (var k = 0; k < 16; k++) {
1774 if (k >= count) { break; }
1775 let t = first + k;
1776 let m = lc.u_shadowMatrix[t];
1777 let lcp = m * vec4f(worldPos, 1.0);
1778 // Behind the light, where a divide by a negative w mirrors the point into the
1779 // map's own square and shadows it against whatever the light sees the other
1780 // way. A cube's six faces have five of themselves behind each one.
1781 if (lcp.w <= 0.0) { continue; }
1782 let proj = lcp.xyz / lcp.w;
1783 let uv = proj.xy * 0.5 + 0.5;
1784 // Depth counts as outside as much as the square does: this matrix and the one
1785 // that wrote the map both run z over [0, 1], so past either end is somewhere
1786 // the map never saw.
1787 if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0
1788 || proj.z < 0.0 || proj.z > 1.0) { continue; }
1789 let rect = lc.u_shadowTile[t];
1790 let biasTexels = floor(rect.w);
1791 let bias = vec2f(biasTexels * (1.0 / 64.0), rect.w - biasTexels);
1792 let slope = sqrt(1.0 - NoL * NoL) / max(NoL, bias.y);
1793 // One texel of this tile in WORLD units where this fragment stands: the matrix's
1794 // x scale is clip per world, w how far away this is (1 where the map has no eye),
1795 // and the rect over one atlas texel how many texels the square holds.
1796 let texels = max(rect.z / max(lc.u_shadowParams.y, 1e-9), 1.0);
1797 let across = length(vec3f(m[0].x, m[1].x, m[2].x));
1798 let texel = 2.0 * lcp.w / max(across * texels, 1e-9);
1799 // A step in world units toward the light, not a shifted answer, so one expression serves a cascade and a cone - but only as far
1800 // as a slope of 1.2 asks, the rest of the clearance along the normal: all of it toward the light is eleven texels on a wall the
1801 // sun grazes, further than a ceiling is thick where a texel is coarse, and the wall's top came out lit.
1802 let lean = min(slope, 1.2);
1803 let biasStep = texel * bias.x;
1804 let aside = worldPos + N * (biasStep * max(sqrt(1.0 - NoL * NoL) - lean * NoL, 0.0));
1805 let lcq = m * vec4f(aside, 1.0);
1806 let uvq = lcq.xy / max(lcq.w, 1e-6) * 0.5 + 0.5;
1807 let here = shadowDepth(m, aside + L * (biasStep * (1.0 + lean)));
1808 let at0 = rect.xy + uvq * rect.z;
1809 let lo = rect.xy + lc.u_shadowParams.y * 0.5;
1810 let hi = rect.xy + rect.z - lc.u_shadowParams.y * 0.5;
1811 // How wide the source is in the unit this map measures depth in: world units
1812 // where its w varies with position, so it has an eye to measure them from, and
1813 // the tangent of the angle it subtends where its w is 1 everywhere.
1814 let hasEye = length(vec3f(m[0].w, m[1].w, m[2].w)) > 0.5;
1815 let src = select(source.y, source.x, hasEye);
1816#ifndef ES_LIGHT_DIRECT
1817 // Hair: layers of strand cards a few millimetres apart are not a wall. The light left after a depth of them falls off with that depth, from the
1818 // nearest card (what the map holds) to this one, the way a deep shadow map reads it. A blocker within a couple of texels toward the light is
1819 // this card's own surface and does not count.
1820 if (g_hairShadow > 0.0) {
1821 let reachHair = shadowDepth(m, worldPos + L * stepFor(texel, slope, 2.0));
1822 var sumHair = 0.0;
1823 var hitsHair = 0.0;
1824 for (var i = 0; i < 8; i++) {
1825 let at = clamp(at0 + diskTap(i, 8, 2.0) * lc.u_shadowParams.y, lo, hi);
1826 let d = unpackDepth(textureSampleLevel(t2, s2, at, 0.0).rgb);
1827 if (d < reachHair) { sumHair += d; hitsHair += 1.0; }
1828 }
1829 if (hitsHair < 0.5) { return 1.0; }
1830 let Ah = length(vec3f(m[0].z, m[1].z, m[2].z));
1831 let zbh = 2.0 * (sumHair / hitsHair) - 1.0;
1832 var spanHair = (proj.z - zbh) / max(Ah, 1e-9);
1833 if (hasEye) { spanHair = lcp.w - lcp.w * (Ah - proj.z) / max(Ah - zbh, 1e-6); }
1834 return mix(1.0, exp(-g_hairShadow * max(spanHair, 0.0)), hitsHair * 0.125);
1835 }
1836#endif
1837 // A source with no size throws one edge: a tent over the 3x3 texels around the
1838 // point, weighted by where it falls among them. Equal weights step at every
1839 // texel and the map's grid shows along the edge; a 2x2 still stair-steps it.
1840#ifdef ES_LIGHT_DIRECT
1841 if (true) {
1842#else
1843 if (src <= 0.0 || g_shadowHard > 0.5) {
1844#endif
1845 let texelUv = lc.u_shadowParams.y;
1846 let f = at0 / texelUv - 1.0;
1847 let c = (floor(f) + 0.5) * texelUv;
1848 let t = fract(f);
1849 let wx = array<f32, 3>((1.0 - t.x) * 0.5, 0.5, t.x * 0.5);
1850 let wy = array<f32, 3>((1.0 - t.y) * 0.5, 0.5, t.y * 0.5);
1851 var lit = 0.0;
1852 for (var y = 0; y < 3; y++) {
1853 for (var x = 0; x < 3; x++) {
1854 lit += wx[x] * wy[y] * shadowTap(c + vec2f(f32(x), f32(y)) * texelUv, lo, hi, here);
1855 }
1856 }
1857 return lit;
1858 }
1859#ifndef ES_LIGHT_DIRECT
1860 // What blocks this fragment, over the whole disc an edge can reach across — and
1861 // against a depth that forgives that reach, since a tap r texels away lands r
1862 // texels along the surface and a one-texel bias would call the slope a blocker.
1863 // Each tap forgives as far as it stands from the point: a disc this wide forgiven as a whole would let a blocker touching the
1864 // surface (a box on a floor) through as lit for a hand's width round its foot.
1865 let spin = shadowSpin(worldPos);
1866 let turn = vec2f(cos(spin), sin(spin));
1867 // See the GLSL twin: the matrix is applied to the direction once, and each tap moves the clip position along it.
1868 let toLight = m * vec4f(L, 0.0);
1869 // The taps are round the moved point: the same step as it took, and what each tap's own distance is worth.
1870 let stepBase = biasStep * (1.0 + lean);
1871 let stepPer = texel * slope;
1872 var sum = 0.0;
1873 var hits = 0.0;
1874 // See the GLSL twin: the fragment's own texel and the four a step and a half round it, before the sparse wide disc.
1875 for (var i = 0; i < 5; i++) {
1876 let p = kInner5[i];
1877 let off = vec2f(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);
1878 let at = clamp(at0 + off * lc.u_shadowParams.y, lo, hi);
1879 let d = unpackDepth(textureSampleLevel(t2, s2, at, 0.0).rgb);
1880 let cr = lcq + toLight * (stepBase + max(length(off), 1.0) * stepPer);
1881 let reach = clamp(cr.z / max(cr.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);
1882 if (d < reach) { sum += d; hits += 1.0; }
1883 }
1884 let fewBlockers = tc.u_quality.y > 0.0 && tc.u_quality.y < 12.0;
1885 let disc = select(24.0, max(tc.u_quality.w, 0.5), tc.u_quality.w > 0.0);
1886 if (fewBlockers) {
1887 for (var i = 0; i < 8; i++) {
1888 let p = kSpiral8[i];
1889 let off = disc * vec2f(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);
1890 let at = clamp(at0 + off * lc.u_shadowParams.y, lo, hi);
1891 let d = unpackDepth(textureSampleLevel(t2, s2, at, 0.0).rgb);
1892 let cr = lcq + toLight * (stepBase + max(length(off), 1.0) * stepPer);
1893 let reach = clamp(cr.z / max(cr.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);
1894 if (d < reach) { sum += d; hits += 1.0; }
1895 }
1896 } else {
1897 for (var i = 0; i < 16; i++) {
1898 let p = kSpiral16[i];
1899 let off = disc * vec2f(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);
1900 let at = clamp(at0 + off * lc.u_shadowParams.y, lo, hi);
1901 let d = unpackDepth(textureSampleLevel(t2, s2, at, 0.0).rgb);
1902 let cr = lcq + toLight * (stepBase + max(length(off), 1.0) * stepPer);
1903 let reach = clamp(cr.z / max(cr.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);
1904 if (d < reach) { sum += d; hits += 1.0; }
1905 }
1906 }
1907 if (hits < 0.5) { return 1.0; }
1908 if (hits > select(20.5, 12.5, fewBlockers)) { return 0.0; }
1909 // How far the receiver stands beyond what blocks it, and how far from the light
1910 // that blocker is. A is the length of the map's depth row, and each kind of map
1911 // inverts its own with it: hyperbolic where it has an eye, linear where w is 1.
1912 let A = length(vec3f(m[0].z, m[1].z, m[2].z));
1913 let zb = 2.0 * (sum / hits) - 1.0;
1914 var dbw = 1.0;
1915 var span = (proj.z - zb) / max(A, 1e-9);
1916 if (hasEye) {
1917 dbw = lcp.w * (A - proj.z) / max(A - zb, 1e-6);
1918 span = lcp.w - dbw;
1919 }
1920 // A source subtending src/dbw at the blocker throws that much penumbra across the
1921 // span beyond it — which is why a shadow hardens as its caster nears what it
1922 // falls on, and why a sun's angle and a lamp's size are the same expression.
1923 let radius = clamp(src * span / max(dbw * texel, 1e-4), 0.5, disc);
1924 let wide = shadowDepth(m, aside + L * (biasStep * (1.0 + lean) + texel * radius * slope));
1925 var soft = 0.0;
1926 if (radius < 1.5 || (tc.u_quality.z > 0.0 && tc.u_quality.z < 12.0)) {
1927 for (var i = 0; i < 8; i++) {
1928 let p = kSpiral8[i];
1929 let off = radius * vec2f(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);
1930 soft += shadowTap(at0 + off * lc.u_shadowParams.y, lo, hi, wide);
1931 }
1932 return soft * (1.0 / 8.0);
1933 }
1934 if (radius < 4.0 || (tc.u_quality.z > 0.0 && tc.u_quality.z < 24.0)) {
1935 for (var i = 0; i < 16; i++) {
1936 let p = kSpiral16[i];
1937 let off = radius * vec2f(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);
1938 soft += shadowTap(at0 + off * lc.u_shadowParams.y, lo, hi, wide);
1939 }
1940 return soft * (1.0 / 16.0);
1941 }
1942 for (var i = 0; i < 32; i++) {
1943 let p = kSpiral32[i];
1944 let off = radius * vec2f(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);
1945 soft += shadowTap(at0 + off * lc.u_shadowParams.y, lo, hi, wide);
1946 }
1947 return soft * (1.0 / 32.0);
1948#endif
1949 }
1950 return 1.0;
1951#endif
1952}
1953)"
1954// Split again for the same cap; the WGSL is unchanged.
1955R"(// The coverage a cut-out's alpha gives this pixel: glTF's MASK, kept where alpha reaches the cutoff and gone where it does not, at every
1956// distance. The cut is sharpened to about a pixel (`edge` is fwidth of the alpha), so under multisampling alpha-to-coverage feathers the
1957// edge instead of stair-stepping it, and without it the cut is the hard one. Seen small, the cut-out holds its area because its mips do:
1958// the cook rescales each level's alpha to the share the full image keeps at the cutoff (preserveAlphaCoverage).
1959fn cutoutCoverage(a : f32, cutoff : f32, edge : f32) -> f32 {
1960 return (a - cutoff) / max(edge, 1e-4) + 0.5;
1961}
1962fn sampleNormal(map : texture_2d<f32>, samp : sampler, uv : vec2f) -> vec3f {
1963 let xy = textureSampleLevel(map, samp, uv, 0.0).xy * 2.0 - 1.0;
1964 return vec3f(xy, sqrt(max(0.0, 1.0 - dot(xy, xy))));
1965}
1966// Through the mip chain, with gradients the caller took before any branch.
1967fn sampleNormalGrad(map : texture_2d<f32>, samp : sampler, uv : vec2f,
1968 ddx : vec2f, ddy : vec2f) -> vec3f {
1969 let xy = textureSampleGrad(map, samp, uv, ddx, ddy).xy * 2.0 - 1.0;
1970 return vec3f(xy, sqrt(max(0.0, 1.0 - dot(xy, xy))));
1971}
1972fn scaleNormal(normal : vec3f, scale : f32) -> vec3f {
1973 let n = normal * vec3f(scale, scale, 1.0);
1974 if (dot(n, n) < 1e-12) { return vec3f(0.0, 0.0, 1.0); }
1975 return normalize(n);
1976}
1977fn perturbNormal(N : vec3f, worldPos : vec3f, uv : vec2f, tangentNormal : vec3f) -> vec3f {
1978 // The derivatives first: they are only valid in uniform control flow, and the choice below depends on a variable.
1979 let dp1 = dpdx(worldPos);
1980 // A target's rows are bottom-up here as in GL, so dpdy is GLSL's dFdy.
1981 let dp2 = dpdy(worldPos);
1982 let duv1 = dpdx(uv);
1983 let duv2 = dpdy(uv);
1984 let dp2perp = cross(dp2, N);
1985 let dp1perp = cross(N, dp1);
1986 let T = dp2perp * duv1.x + dp1perp * duv2.x;
1987 let B = dp2perp * duv1.y + dp1perp * duv2.y;
1988 let m = max(dot(T, T), dot(B, B));
1989 let scale = max(dot(dp1, dp1), dot(dp2, dp2)) * max(dot(duv1, duv1), dot(duv2, duv2));
1990 // Each axis to unit length on its own: a texture stretched more along one axis than the other (a face unwrapped into an atlas) has
1991 // a short T beside a long B, and scaling both by the longer one would leave the normal map flat along the short one.
1992 let derived = select(N, normalize(mat3x3f(T * inverseSqrt(max(dot(T, T), 1e-20)), B * inverseSqrt(max(dot(B, B), 1e-20)), N) * tangentNormal),
1993 m > scale * 1e-6);
1994 // The frame the normal map was baked in, when the geometry carries it: the tangent made square to the interpolated normal.
1995 // Chosen by select, not by returning early: behind a branch Metal sinks the derivatives above into it, where a quad the
1996 // triangle only partly covers has lost its helpers, and every pixel along an edge lost its normal map (skin-detail).
1997 let Tg = normalize(g_worldTangent.xyz - N * dot(N, g_worldTangent.xyz));
1998 let Bg = cross(N, Tg) * g_worldTangent.w;
1999 let baked = normalize(mat3x3f(Tg, Bg, N) * tangentNormal);
2000 return select(derived, baked, dot(g_worldTangent.xyz, g_worldTangent.xyz) > 1e-8);
2001}
2002// Where a world point lands in this camera's part of a screen-space mask: on the Z = 0
2003// plane, which is the plane a 2D occluder hides things in, and through this same camera
2004// so the landing agrees. Negative x = nothing to read.
2005fn mask2DUv(worldPos : vec2f) -> vec2f {
2006 let clip = frame.projection * vec4f(worldPos, 0.0, 1.0);
2007 if (clip.w <= 0.0) { return vec2f(-1.0, -1.0); }
2008 let ndc = clip.xy / clip.w * 0.5 + 0.5;
2009 return lc.u_mask2DRect.xy + ndc * lc.u_mask2DRect.zw;
2010}
2011fn mask2DChannel(m : vec4f, channel : f32) -> f32 {
2012 if (channel < 0.5) { return m.r; }
2013 if (channel < 1.5) { return m.g; }
2014 if (channel < 2.5) { return m.b; }
2015 return m.a;
2016}
2017fn shadowFactor2D(channel : f32, worldPos : vec2f) -> f32 {
2018 if (channel < 0.0 || lc.u_mask2DRect.z <= 0.0) { return 1.0; }
2019 let uv = mask2DUv(worldPos);
2020 if (uv.x < 0.0) { return 1.0; }
2021 // Channels 4 to 7 live in the second mask, which takes the shape mask's unit in a frame with no cookie.
2022 var hidden = 0.0;
2023 if (channel < 3.5) { hidden = mask2DChannel(textureSampleLevel(t7, s7, uv, 0.0), channel); }
2024 else { hidden = mask2DChannel(textureSampleLevel(t6, s6, uv, 0.0), channel - 4.0); }
2025 return 1.0 - min(hidden, 1.0);
2026}
2027// What the light's own SHAPE covers here — its cookie, drawn into the shape mask at the
2028// light's place. A light with no shape keeps the whole circle it always had.
2029fn shapeFactor2D(channel : f32, worldPos : vec2f) -> f32 {
2030 if (channel < 0.0 || lc.u_mask2DRect.z <= 0.0) { return 1.0; }
2031 let uv = mask2DUv(worldPos);
2032 if (uv.x < 0.0) { return 1.0; }
2033 return min(mask2DChannel(textureSampleLevel(t6, s6, uv, 0.0), channel), 1.0);
2034}
2035)"
2036// Split, not restructured: MSVC caps ONE string literal at 16380 bytes
2037// and this twin passed it. Adjacent literals concatenate with no cap, so
2038// the WGSL is byte-for-byte what it was.
2039R"(fn distributionGGX(NdotH : f32, a : f32) -> f32 {
2040 let a2 = a * a;
2041 let d = NdotH * NdotH * (a2 - 1.0) + 1.0;
2042 return a2 / max(3.14159265 * d * d, 1e-7);
2043}
2044fn geometrySmith(NdotV : f32, NdotL : f32, roughness : f32) -> f32 {
2045 let k = (roughness + 1.0) * (roughness + 1.0) * 0.125;
2046 return (NdotV / (NdotV * (1.0 - k) + k)) * (NdotL / (NdotL * (1.0 - k) + k));
2047}
2048// Smith's masking-shadowing for GGX, height-correlated, folded with the 1 / (4 NdotV NdotL) of the microfacet BRDF (the visibility term),
2049// at alpha = roughness^2: what the environment term above integrates and what Blender's GGX uses. The Schlick-GGX k = (r + 1)^2 / 8 it
2050// replaces shadows too much at a grazing view and a high roughness, which left the rim of a rough metal a quarter darker under a lamp.
2051fn visibilitySmithGGX(NdotV : f32, NdotL : f32, a : f32) -> f32 {
2052 let a2 = a * a;
2053 let gv = NdotL * sqrt(NdotV * NdotV * (1.0 - a2) + a2);
2054 let gl = NdotV * sqrt(NdotL * NdotL * (1.0 - a2) + a2);
2055 return 0.5 / max(gv + gl, 1e-5);
2056}
2057fn fresnelSchlick(VdotH : f32, F0 : vec3f) -> vec3f {
2058 return F0 + (vec3f(1.0) - F0) * pow(1.0 - VdotH, 5.0);
2059}
2060// The split-sum environment term of GGX (height-correlated Smith, alpha = roughness^2): the scale and bias of F0 over the hemisphere,
2061// fitted to the integral by tools/gen-dfg-fit.py (worst 3%, mean under 0.6%; Karis' fit before it was 21% low for a metal at roughness 0.5).
2062fn envBRDFApprox(NdotV : f32, roughness : f32) -> vec2f {
2063 let tx = (2.0 * (clamp(NdotV, 0.02, 1.0) - 0.02) / 0.98 - 1.0);
2064 let ty = 2.0 * clamp(roughness, 0.0, 1.0) - 1.0;
2065 let px0 = 1.0;
2066 let px1 = tx;
2067 let px2 = (3.0 * tx * px1 - 1.0 * px0) / 2.0;
2068 let px3 = (5.0 * tx * px2 - 2.0 * px1) / 3.0;
2069 let px4 = (7.0 * tx * px3 - 3.0 * px2) / 4.0;
2070 let px5 = (9.0 * tx * px4 - 4.0 * px3) / 5.0;
2071 let px6 = (11.0 * tx * px5 - 5.0 * px4) / 6.0;
2072 let py0 = 1.0;
2073 let py1 = ty;
2074 let py2 = (3.0 * ty * py1 - 1.0 * py0) / 2.0;
2075 let py3 = (5.0 * ty * py2 - 2.0 * py1) / 3.0;
2076 let py4 = (7.0 * ty * py3 - 3.0 * py2) / 4.0;
2077 let py5 = (9.0 * ty * py4 - 4.0 * py3) / 5.0;
2078 let py6 = (11.0 * ty * py5 - 5.0 * py4) / 6.0;
2079 let g = 1.0 / (clamp(NdotV, 0.02, 1.0) + 0.1);
2080 let sumMetal = (0.7771111 - 0.2780760 * py1 - 0.0654304 * py2 - 0.0705640 * py3 + 0.0859185 * py4 + 0.0016314 * py5 - 0.0014479 * py6) + px1 * (0.0048182 - 0.1346961 * py1 - 0.1342442 * py2 + 0.1115811 * py3 - 0.0497620 * py4 - 0.0098451 * py5 - 0.0004214 * py6) + px2 * (0.0004797 + 0.0654544 * py1 + 0.0215100 * py2 - 0.0948616 * py3 + 0.0774489 * py4 + 0.0139819 * py5 - 0.0151021 * py6) + px3 * (0.0022918 - 0.0244567 * py1 + 0.0056279 * py2 + 0.0393924 * py3 - 0.0613759 * py4 + 0.0099383 * py5 + 0.0092971 * py6) + px4 * (-0.0025728 + 0.0085869 * py1 - 0.0069877 * py2 - 0.0115072 * py3 + 0.0327063 * py4 - 0.0167796 * py5 + 0.0019107 * py6) + px5 * (0.0018089 - 0.0031015 * py1 + 0.0047701 * py2 + 0.0018675 * py3 - 0.0134691 * py4 + 0.0139776 * py5 - 0.0087024 * py6) + px6 * (-0.0008609 + 0.0010956 * py1 - 0.0024048 * py2 + 0.0005262 * py3 + 0.0035639 * py4 - 0.0080487 * py5 + 0.0080563 * py6) + g * (0.0220605 + 0.0049886 * py1 - 0.0108884 * py2 + 0.0359254 * py3 - 0.0336876 * py4);
2081 let sumDielectric = (0.1105178 - 0.1470108 * py1 + 0.0706290 * py2 - 0.0048613 * py3 - 0.0190413 * py4 + 0.0038142 * py5 - 0.0002643 * py6) + px1 * (-0.1400053 + 0.2220226 * py1 - 0.1204309 * py2 + 0.0033027 * py3 + 0.0348652 * py4 - 0.0115348 * py5 + 0.0015711 * py6) + px2 * (0.0993738 - 0.1696809 * py1 + 0.1055418 * py2 - 0.0166890 * py3 - 0.0245166 * py4 + 0.0153020 * py5 - 0.0048468 * py6) + px3 * (-0.0363361 + 0.0724203 * py1 - 0.0631513 * py2 + 0.0261354 * py3 + 0.0041759 * py4 - 0.0092203 * py5 + 0.0054510 * py6) + px4 * (0.0046882 - 0.0144579 * py1 + 0.0238812 * py2 - 0.0200861 * py3 + 0.0078934 * py4 - 0.0001779 * py5 - 0.0024009 * py6) + px5 * (0.0013258 - 0.0006506 * py1 - 0.0049831 * py2 + 0.0084229 * py3 - 0.0075026 * py4 + 0.0046720 * py5 - 0.0007627 * py6) + px6 * (-0.0005364 + 0.0008141 * py1 + 0.0002790 * py2 - 0.0016584 * py3 + 0.0027280 * py4 - 0.0028646 * py5 + 0.0010557 * py6) + g * (-0.0075790 + 0.0243928 * py1 - 0.0212081 * py2 + 0.0063496 * py3 + 0.0036408 * py4);
2082 let scale = (sumMetal - sumDielectric) / 0.96;
2083 return vec2f(scale, sumMetal - scale);
2084}
2085// One authority for the environment's orientation: every direction that asks the
2086// environment anything comes through here, so a turned sky cannot disagree with a
2087// turned reflection. The query turns the other way, the world under it.
2088fn envDirection(d : vec3f) -> vec3f {
2089 let a = -lc.u_envTint.a;
2090 let s = sin(a);
2091 let c = cos(a);
2092 return vec3f(c * d.x + s * d.z, d.y, -s * d.x + c * d.z);
2093}
2094fn shIrradiance(sh : array<vec4f, 9>, N : vec3f) -> vec3f {
2095 return sh[0].rgb * 0.282095
2096 + sh[1].rgb * (0.488603 * N.y)
2097 + sh[2].rgb * (0.488603 * N.z)
2098 + sh[3].rgb * (0.488603 * N.x)
2099 + sh[4].rgb * (1.092548 * N.x * N.y)
2100 + sh[5].rgb * (1.092548 * N.y * N.z)
2101 + sh[6].rgb * (0.315392 * (3.0 * N.z * N.z - 1.0))
2102 + sh[7].rgb * (1.092548 * N.x * N.z)
2103 + sh[8].rgb * (0.546274 * (N.x * N.x - N.y * N.y));
2104}
2105fn ambientFacing(dir : vec3f) -> vec3f {
2106 return lc.u_ambient.rgb + lc.u_ambientGround.rgb * (0.5 - 0.5 * dir.y);
2107}
2108fn envIrradiance(Nw : vec3f) -> vec3f {
2109 // Read in place, not passed: an array handed to a function is copied, all nine, for every pixel.
2110 let N = envDirection(Nw);
2111 let sh = lc.u_envIrradiance[0].rgb * 0.282095
2112 + lc.u_envIrradiance[1].rgb * (0.488603 * N.y)
2113 + lc.u_envIrradiance[2].rgb * (0.488603 * N.z)
2114 + lc.u_envIrradiance[3].rgb * (0.488603 * N.x)
2115 + lc.u_envIrradiance[4].rgb * (1.092548 * N.x * N.y)
2116 + lc.u_envIrradiance[5].rgb * (1.092548 * N.y * N.z)
2117 + lc.u_envIrradiance[6].rgb * (0.315392 * (3.0 * N.z * N.z - 1.0))
2118 + lc.u_envIrradiance[7].rgb * (1.092548 * N.x * N.z)
2119 + lc.u_envIrradiance[8].rgb * (0.546274 * (N.x * N.x - N.y * N.y));
2120 return ambientFacing(Nw) + max(sh, vec3f(0.0)) * lc.u_envTint.rgb;
2121}
2122// The GLSL twin's indirectIrradiance: a volume replaces the environment, because a
2123// surface has one indirect term and a volume already holds every light and bounce
2124// that reached the point.
2125#ifdef MESH_LIGHTMAP
2126fn bakedIrradiance() -> vec3f {
2127 let c = textureSampleLevel(t5, s5, g_lightmap.xy, 0.0).rgb;
2128 return c * c * 8.0;
2129}
2130#endif
2131#ifdef ES_SURFACE_3D
2132#ifndef MESH_LIGHTMAP
2133// See the GLSL twin: the grid itself, at P, through its indirection cell and the brick that names.
2134fn probeGridIrradiance(N : vec3f, P : vec3f) -> vec4f {
2135 let base = clamp(i32(g_probeSlot), 0, 99) * 10;
2136 let a = pc.u_probeIrradiance[base + 1];
2137 let b = pc.u_probeIrradiance[base + 2];
2138 let c = pc.u_probeIrradiance[base + 3];
2139 let d = pc.u_probeIrradiance[base + 4];
2140 let last = vec3f(a.w, b.w, c.w);
2141 let g = clamp((P - a.xyz) * b.xyz, vec3f(0.0), last);
2142 let cell = min(floor(g * 0.25), max(ceil(last * 0.25) - 1.0, vec3f(0.0)));
2143 let brick = textureLoad(t5, vec3i(c.xyz + cell + 0.5), 0);
2144 let first = floor(cell / brick.w) * brick.w;
2145 let uvw = (brick.xyz + (g - first * 4.0) / brick.w + 0.5) * d.xyz;
2146 var basis = array<f32, 9>(0.282095, 0.488603 * N.y, 0.488603 * N.z, 0.488603 * N.x,
2147 1.092548 * N.x * N.y, 1.092548 * N.y * N.z, 0.315392 * (3.0 * N.z * N.z - 1.0),
2148 1.092548 * N.x * N.z, 0.546274 * (N.x * N.x - N.y * N.y));
2149 var sum = vec4f(0.0);
2150 for (var i = 0; i < 9; i = i + 1) {
2151 sum += textureSampleLevel(t5, s5, uvw + vec3f(f32(i) * d.w * d.x, 0.0, 0.0), 0.0) * basis[i];
2152 }
2153 return sum;
2154}
2155#endif
2156#endif
2157// See the GLSL twin: how much of the sky a probe sees toward d, 1 where nothing was baked of it.
2158fn skyOcclusion(d : vec3f) -> f32 {
2159 let base = clamp(i32(g_probeSlot), 0, 99) * 10;
2160 var v = pc.u_probeIrradiance[base + 9].y * 0.282095
2161 + pc.u_probeIrradiance[base + 1].w * (0.488603 * d.y)
2162 + pc.u_probeIrradiance[base + 2].w * (0.488603 * d.z)
2163 + pc.u_probeIrradiance[base + 3].w * (0.488603 * d.x)
2164 + pc.u_probeIrradiance[base + 4].w * (1.092548 * d.x * d.y)
2165 + pc.u_probeIrradiance[base + 5].w * (1.092548 * d.y * d.z)
2166 + pc.u_probeIrradiance[base + 6].w * (0.315392 * (3.0 * d.z * d.z - 1.0))
2167 + pc.u_probeIrradiance[base + 7].w * (1.092548 * d.x * d.z)
2168 + pc.u_probeIrradiance[base + 8].w * (0.546274 * (d.x * d.x - d.y * d.y));
2169#ifdef ES_SURFACE_3D
2170#ifndef MESH_LIGHTMAP
2171 if (pc.u_probeIrradiance[base].w > 1.5) { v = probeGridIrradiance(d, g_probePos).a; }
2172#endif
2173#endif
2174 return mix(1.0, clamp(v, 0.0, 1.0), step(0.5, pc.u_probeIrradiance[base + 9].z));
2175}
2176// See the GLSL twin: one exit, for the shape the two share.
2177)" R"(fn indirectIrradiance(N : vec3f) -> vec3f {
2178 let base = clamp(i32(g_probeSlot), 0, 99) * 10;
2179 let mode = pc.u_probeIrradiance[base].w;
2180 var result : vec3f;
2181#ifdef ES_SURFACE_3D
2182#ifndef MESH_LIGHTMAP
2183 if (mode > 1.5) {
2184 let grid = probeGridIrradiance(N, g_probePos);
2185 let sky = step(0.5, pc.u_probeIrradiance[base + 9].z);
2186 result = max(grid.rgb, vec3f(0.0)) * lc.u_bakedTint.rgb + envIrradiance(N) * (clamp(grid.a, 0.0, 1.0) * sky);
2187 } else
2188#endif
2189#endif
2190 if (mode > 0.5) {
2191 var sh : array<vec4f, 9>;
2192 for (var i = 0; i < 9; i = i + 1) { sh[i] = pc.u_probeIrradiance[base + i]; }
2193 let sky = step(0.5, pc.u_probeIrradiance[base + 9].z);
2194 result = max(shIrradiance(sh, N), vec3f(0.0)) * lc.u_bakedTint.rgb + envIrradiance(N) * (skyOcclusion(N) * sky);
2195 } else {
2196 result = envIrradiance(N);
2197 }
2198#ifdef MESH_LIGHTMAP
2199 if (g_lightmap.z > 0.5) { result = bakedIrradiance() * lc.u_bakedTint.rgb; }
2200#endif
2201 return result;
2202}
2203// Which column of the atlas this instance reflects, from the run its own index
2204// names. Zero — an instance inside no probe, or a draw that carries no run at all
2205// — is the environment, which is what every surface reflected before probes.
2206fn reflectionColumn() -> f32 {
2207 let base = clamp(i32(g_probeSlot), 0, 99) * 10;
2208 return pc.u_probeIrradiance[base + 9].x;
2209}
2210fn octEncode(d : vec3f) -> vec2f {
2211 var p = d.xz / max(abs(d.x) + abs(d.y) + abs(d.z), 1e-6);
2212 if (d.y < 0.0) {
2213 p = (1.0 - abs(vec2f(p.y, p.x)))
2214 * vec2f(select(-1.0, 1.0, p.x >= 0.0), select(-1.0, 1.0, p.y >= 0.0));
2215 }
2216 return p * 0.5 + 0.5;
2217}
2218fn envSampleColumn(R : vec3f, mip : f32, column : f32) -> vec3f {
2219#ifndef ES_ENV_MAP
2220 return vec3f(0.0);
2221#else
2222 let face = lc.u_envParams.w;
2223 let size = face * exp2(-mip);
2224 let yOff = 2.0 * face * (1.0 - exp2(-mip)) + 2.0 * mip;
2225 let col = face + 2.0;
2226 let atlasW = col * lc.u_reflParams.x;
2227 let atlasH = 2.0 * face * (1.0 - exp2(-(lc.u_envParams.z + 1.0)))
2228 + 2.0 * (lc.u_envParams.z + 1.0);
2229 // The sky turns with the environment; a baked column does not — it was solved
2230 // in world space, and turning it would spin a room about its own middle.
2231 let uv = octEncode(select(R, envDirection(R), column < 0.5));
2232 // Kept inside this column's own face, border ring included: a tap that leaves
2233 // it reads whatever the sampler's wrap mode says, and the two backends do not
2234 // answer that alike — one repeats to the far edge, the other clamps.
2235 let lo2 = vec2f(column * col + 0.5, yOff + 0.5);
2236 let hi2 = vec2f(column * col + size + 1.5, yOff + size + 1.5);
2237 let px = clamp(vec2f(column * col + 1.0 + uv.x * size, yOff + 1.0 + uv.y * size), lo2, hi2);
2238 let t = textureSampleLevel(t3, s3, px / vec2f(atlasW, atlasH), 0.0);
2239 return t.rgb * t.rgb * (t.a * t.a * lc.u_envParams.y);
2240#endif
2241}
2242fn envSampleMip(R : vec3f, mip : f32) -> vec3f { return envSampleColumn(R, mip, 0.0); }
2243// Where the reflected ray LEAVES this column's box, aimed from there rather than
2244// from infinitely far: what makes a reflection slide across a wall as the eye moves
2245// instead of being painted onto it.
2246fn reflectionDirection(R : vec3f, P : vec3f, column : f32) -> vec3f {
2247 if (column < 0.5) { return R; }
2248 let i = i32(column) * 2 - 2;
2249 let lo = lc.u_reflBox[i].xyz;
2250 let hi = lc.u_reflBox[i + 1].xyz;
2251 // Never zero, so a ray parallel to a face divides to an infinity the min
2252 // discards rather than to the NaN that would blacken the pixel.
2253 let d = max(abs(R), vec3f(1e-6)) * (step(vec3f(0.0), R) * 2.0 - vec3f(1.0));
2254 let t = min(min(max((hi.x - P.x) / d.x, (lo.x - P.x) / d.x),
2255 max((hi.y - P.y) / d.y, (lo.y - P.y) / d.y)),
2256 max((hi.z - P.z) / d.z, (lo.z - P.z) / d.z));
2257 if (!(t > 0.0)) { return R; }
2258 return (P + R * t) - (lo + hi) * 0.5;
2259}
2260fn envRadiance(R : vec3f, roughness : f32, column : f32, P : vec3f) -> vec3f {
2261 g_probePos = P;
2262#ifdef ES_ENV_MAP
2263 if (planar.planarParams.x > 0.5) {
2264 let clip = planar.planarProjection * vec4f(P, 1.0);
2265 if (clip.w <= 0.0) { return vec3f(0.0); }
2266 let uv = clip.xy / clip.w * vec2f(0.5, 0.5 * planar.planarParams.y) + vec2f(0.5);
2267 if (any(uv < vec2f(0.0)) || any(uv > vec2f(1.0))) { return vec3f(0.0); }
2268 // A small spatial filter, not prefiltered GGX: preserves material roughness
2269 // without allocating a second blur chain or claiming an exact BRDF convolution.
2270 // Blurred by how rough the surface is, a pixel and a half at the least (a mirror is never razor sharp at this size) and
2271 // wider as the roughness grows, so a wet road's reflection softens where a puddle's stays crisp: nine taps, the middle one
2272 // weighted most. The sideways reach follows the target's shape, so the blur is round on screen.
2273 let reach = max(planar.planarParams.z * 1.5, roughness * roughness * 0.04);
2274 let r = vec2f(reach, reach * planar.planarParams.w / planar.planarParams.z);
2275 let d = r * 0.7071;
2276 let seen = textureSampleLevel(t3, s3, uv, 0.0).rgb * 0.2
2277 + (textureSampleLevel(t3, s3, clamp(uv + vec2f(r.x, 0.0), vec2f(0.0), vec2f(1.0)), 0.0).rgb
2278 + textureSampleLevel(t3, s3, clamp(uv - vec2f(r.x, 0.0), vec2f(0.0), vec2f(1.0)), 0.0).rgb
2279 + textureSampleLevel(t3, s3, clamp(uv + vec2f(0.0, r.y), vec2f(0.0), vec2f(1.0)), 0.0).rgb
2280 + textureSampleLevel(t3, s3, clamp(uv - vec2f(0.0, r.y), vec2f(0.0), vec2f(1.0)), 0.0).rgb
2281 + textureSampleLevel(t3, s3, clamp(uv + d, vec2f(0.0), vec2f(1.0)), 0.0).rgb
2282 + textureSampleLevel(t3, s3, clamp(uv - d, vec2f(0.0), vec2f(1.0)), 0.0).rgb
2283 + textureSampleLevel(t3, s3, clamp(uv + vec2f(d.x, -d.y), vec2f(0.0), vec2f(1.0)), 0.0).rgb
2284 + textureSampleLevel(t3, s3, clamp(uv + vec2f(-d.x, d.y), vec2f(0.0), vec2f(1.0)), 0.0).rgb) * 0.1;
2285 // A reflected sun or a sky's hot spot is far brighter than any picture holds, and a mirror shows all of it: the colour is
2286 // brought under a soft ceiling of 1.5 by its brightest channel (a knee from 0.75, so no edge shows where it starts), so a burning orange stays orange instead of clipping toward white.
2287 let peak = max(seen.r, max(seen.g, seen.b));
2288 let held = select(0.75 + 0.75 * (1.0 - exp(-(peak - 0.75) / 0.75)), peak, peak <= 0.75);
2289 return seen * (held / max(peak, 1e-4));
2290 }
2291#endif
2292 if (lc.u_envParams.x < 0.5) { return ambientFacing(R); }
2293 let dir = reflectionDirection(R, P, column);
2294 let lod = clamp(roughness, 0.0, 1.0) * lc.u_envParams.z;
2295 let lo = floor(lod);
2296 let a = envSampleColumn(dir, lo, column);
2297 let b = envSampleColumn(dir, min(lo + 1.0, lc.u_envParams.z), column);
2298 // A baked column is the WHOLE radiance that reached its probe — the sky, the
2299 // ambient and every bounce. Adding the flat term or the sky's tint on top
2300 // would count the light the capture already saw a second time.
2301 if (column >= 0.5) {
2302 let baked = mix(a, b, lod - lo);
2303 // What the bake saw, as the weather now says it looks: dimmer, and with less of its colour.
2304 let grey = dot(baked, vec3f(0.2126, 0.7152, 0.0722));
2305 return mix(vec3f(grey), baked, lc.u_reflParams.z) * lc.u_reflParams.y;
2306 }
2307 return (lc.u_ambient.rgb + mix(a, b, lod - lo) * lc.u_envTint.rgb) * skyOcclusion(R);
2308}
2309// Which definition of "where is the light" this surface is shaded with. One with a
2310// real third coordinate measures against the light's own; a sprite has no depth to
2311// measure against, so a positional light goes on hovering its radius above it.
2312#ifdef ES_SURFACE_3D
2313fn lightVector(pd : vec4f, sh : vec4f, worldPos : vec3f) -> vec3f {
2314 return vec3f(pd.xy, sh.z) - worldPos;
2315}
2316fn lightDistance(toLight : vec3f) -> f32 { return length(toLight); }
2317fn spotCone(sp : vec4f, sh : vec4f, toLight : vec3f, dist : f32) -> f32 {
2318 let axis = normalize(vec3f(sp.xy, sh.w));
2319 var toFrag = axis;
2320 if (dist > 0.0001) { toFrag = -toLight / dist; }
2321 return smoothstep(sp.w, sp.z, dot(axis, toFrag));
2322}
2323#else
2324fn lightVector(pd : vec4f, sh : vec4f, worldPos : vec3f) -> vec3f {
2325 return vec3f(pd.xy - worldPos.xy, max(pd.w, 1.0));
2326}
2327fn lightDistance(toLight : vec3f) -> f32 { return length(toLight.xy); }
2328fn spotCone(sp : vec4f, sh : vec4f, toLight : vec3f, dist : f32) -> f32 {
2329 // A cone aimed out of the plane has no axis IN it, and this half of the shading
2330 // has nowhere else to read one — so it lights the way an unrotated spot always has.
2331 var axis = vec2f(0.0, -1.0);
2332 if (dot(sp.xy, sp.xy) > 1e-8) { axis = normalize(sp.xy); }
2333 var toFrag = axis;
2334 if (dist > 0.0001) { toFrag = -toLight.xy / dist; }
2335 return smoothstep(sp.w, sp.z, dot(axis, toFrag));
2336}
2337#endif
2338fn towardLight(toLight : vec3f, N : vec3f) -> vec3f {
2339 if (dot(toLight, toLight) > 1e-8) { return normalize(toLight); }
2340 return N;
2341}
2342// The ramp from a light's reach down to nothing. fo.x holds it at full out to its own
2343// radius; fo.y shapes what is left. The exponent is floored because pow(0, 0) is 1 —
2344// a light that reaches nowhere would light everything.
2345fn distanceFalloff(dist : f32, reach : f32, fo : vec4f) -> f32 {
2346 let ramp = clamp((reach - dist) / max(reach - fo.x, 1e-4), 0.0, 1.0);
2347 let shaped = pow(ramp, max(fo.y, 1e-3));
2348 // See the GLSL twin: fo.y < 0 is an inverse-square light, -fo.y world units to the metre.
2349 let metres = dist / max(-fo.y, 1e-4);
2350 let q = dist / max(reach, 1e-4);
2351 let w = clamp(1.0 - q * q * q * q, 0.0, 1.0);
2352 return select(shaped, w * w / max(metres * metres, 0.01), fo.y < 0.0);
2353}
2354)"
2355// Split again for the same reason: the surface layers and the lighting that reads them.
2356R"(struct SurfaceExt { coat : vec4f, coatN : vec4f, sheen : vec4f, aniso : vec4f, scatter : vec4f, trans : vec4f, film : vec4f, misc : vec4f, strand : vec4f };
2357fn surfaceExtNone(N : vec3f) -> SurfaceExt {
2358 return SurfaceExt(vec4f(0.0), vec4f(N, 0.0), vec4f(0.0), vec4f(0.0), vec4f(0.0), vec4f(0.0), vec4f(0.0),
2359 vec4f(0.04, 0.0, 0.0, 0.0), vec4f(0.6, 0.0, 0.0, 0.0));
2360}
2361fn distributionCharlie(NdotH : f32, a : f32) -> f32 {
2362 let invA = 1.0 / max(a, 1e-3);
2363 let sin2 = max(1.0 - NdotH * NdotH, 0.0078125);
2364 return (2.0 + invA) * pow(sin2, invA * 0.5) / 6.28318531;
2365}
2366fn visibilityNeubelt(NdotV : f32, NdotL : f32) -> f32 {
2367 return 1.0 / max(4.0 * (NdotL + NdotV - NdotL * NdotV), 1e-4);
2368}
2369fn distributionGGXAniso(at : f32, ab : f32, ToH : f32, BoH : f32, NoH : f32) -> f32 {
2370 let a2 = at * ab;
2371 let d = vec3f(ab * ToH, at * BoH, a2 * NoH);
2372 let b2 = a2 / max(dot(d, d), 1e-7);
2373 return a2 * b2 * b2 / 3.14159265;
2374}
2375fn visibilityGGXAniso(at : f32, ab : f32, ToV : f32, BoV : f32, ToL : f32, BoL : f32, NoV : f32, NoL : f32) -> f32 {
2376 let lambdaV = NoL * length(vec3f(at * ToV, ab * BoV, NoV));
2377 let lambdaL = NoV * length(vec3f(at * ToL, ab * BoL, NoL));
2378 return 0.5 / max(lambdaV + lambdaL, 1e-5);
2379}
2380fn filmFresnel(F : vec3f, cosTheta : f32, film : vec4f) -> vec3f {
2381 let sinT2 = (1.0 - cosTheta * cosTheta) / (film.y * film.y);
2382 let cosT = sqrt(max(1.0 - sinT2, 0.0));
2383 let opd = 2.0 * film.y * film.z * cosT;
2384 let tint = vec3f(0.5) + vec3f(0.5) * cos(vec3f(6.28318531 * opd) / vec3f(650.0, 510.0, 475.0));
2385 return clamp(F * mix(vec3f(1.0), tint * 2.0, vec3f(film.x)), vec3f(0.0), vec3f(1.0));
2386}
2387fn applyLightingSurfaceBRDF(diffuse : vec3f, F0 : vec3f, N : vec3f, worldPos : vec3f, V : vec3f,
2388 roughness : f32, specular : f32, ao : f32, ext : SurfaceExt) -> vec3f {
2389 g_probePos = worldPos;
2390 let a = max(roughness * roughness, 1e-3);
2391 let NdotV = max(dot(N, V), 1e-4);
2392 var lit = indirectIrradiance(N) * ao;
2393 var gloss = vec3f(0.0);
2394 var extra = vec3f(0.0);
2395 // As many as are lit: read for a slot nobody uses, a light's six vectors cost more on a phone than the one light shaded.
2396 let lightCount = i32(lc.u_ambient.a);
2397 // Which of them can reach this point: see the GLSL twin.
2398 var reach3D = 0xFFFFu;
2399#ifdef ES_SURFACE_3D
2400 if (lc.tileInfo.w > 0.5) {
2401 let tileView = lc.u_tileView * vec4f(worldPos, 1.0);
2402 let viewNdc = tileView.xy / max(tileView.w, 1e-4);
2403 if (tileView.w > 1e-4 && abs(viewNdc.x) <= 1.0 && abs(viewNdc.y) <= 1.0) {
2404 let viewTiles = vec2i(i32(lc.tileInfo.y), i32(lc.tileInfo.z));
2405 let viewTile = clamp(vec2i(floor((viewNdc * 0.5 + 0.5) * vec2f(viewTiles))), vec2i(0), viewTiles - vec2i(1));
2406 reach3D = lc.tileMask[viewTile.y * viewTiles.x + viewTile.x].w >> 16u;
2407 }
2408 }
2409#endif
2410 for (var i = 0; i < lightCount; i++) {
2411 if ((reach3D & (1u << u32(i))) == 0u) { continue; }
2412 var lamp = lc.u_lights[i];
2413#ifdef ES_SURFACE_3D
2414 if (lc.u_waterRect.z > 0.0 && f32(i) == lc.u_waterSun.z) { lamp = waterIncidentSun(lamp, worldPos); }
2415#endif
2416 let term = shadeLight(lamp.posDir, lamp.color, lamp.spot, lamp.shadow,
2417 lc.u_lights[i].shadowMap, lc.u_lights[i].falloff, N, V, worldPos, a, F0, NdotV, specular, roughness, ext, true);
2418 lit += term.lit;
2419 gloss += term.gloss;
2420 extra += term.extra;
2421 }
2422#ifndef ES_LIGHT_DIRECT
2423 // The lights past the sixteen: this pixel's tile is found from where the fragment lands through the camera it was drawn by
2424 // (normalized device coordinates, the same on every backend), and only the lights whose bit is set in its mask are shaded.
2425 let tiledCount = i32(lc.tileInfo.x);
2426 if (tiledCount > 0) {
2427 let tileClip = frame.projection * vec4f(worldPos, 1.0);
2428 let tileNdc = tileClip.xy / max(tileClip.w, 1e-4);
2429 let tileCount = vec2i(i32(lc.tileInfo.y), i32(lc.tileInfo.z));
2430 let tile = clamp(vec2i(floor((tileNdc * 0.5 + 0.5) * vec2f(tileCount))), vec2i(0), tileCount - vec2i(1));
2431 let mask = lc.tileMask[tile.y * tileCount.x + tile.x];
2432 for (var w = 0; w < 3; w++) {
2433 var bits = mask.x;
2434 if (w == 1) { bits = mask.y; } else if (w == 2) { bits = mask.z; }
2435 if (bits == 0u) { continue; }
2436 for (var b = 0; b < 32; b++) {
2437 if ((bits & (1u << u32(b))) == 0u) { continue; }
2438 let k = w * 32 + b;
2439 if (k >= tiledCount) { break; }
2440 let term = shadeLight(lc.tiledLights[k].posDir, lc.tiledLights[k].color, lc.tiledLights[k].spot,
2441 lc.tiledLights[k].shadow, lc.tiledLights[k].shadowMap, lc.tiledLights[k].falloff,
2442 N, V, worldPos, a, F0, NdotV, specular, roughness, ext, false);
2443 lit += term.lit;
2444 gloss += term.gloss;
2445 extra += term.extra;
2446 }
2447 }
2448 }
2449#endif
2450 let ab = envBRDFApprox(NdotV, roughness);
2451 // The light a rough microfacet surface loses to bounces between its facets, which single-scattering GGX leaves out (a metal at roughness
2452 // 0.9 came out at half of Blender's brightness): Fdez-Aguera's term for the environment, and the same ratio on the lamps' highlight. What
2453 // the specular reflects is light the diffuse under it does not get, as in the Principled shader. Hair keeps its own lobes as authored.
2454 let Ess = ab.x + ab.y;
2455 let FssEss = F0 * ab.x + vec3f(ab.y);
2456 var FmsEms = vec3f(0.0);
2457 var kd = vec3f(1.0);
2458 if (ext.misc.y <= 0.0 || ext.strand.y > 0.0) {
2459 let Ems = 1.0 - Ess;
2460 let Favg = F0 + (vec3f(1.0) - F0) / 21.0;
2461 FmsEms = FssEss * Favg * Ems / (vec3f(1.0) - Ems * Favg);
2462 gloss *= vec3f(1.0) + F0 * (1.0 / max(Ess, 0.05) - 1.0);
2463 kd = max(vec3f(1.0) - (FssEss + FmsEms) * specular, vec3f(0.0));
2464 }
2465 var envR = reflect(-V, N);
2466 if (ext.aniso.w != 0.0 || ext.misc.y > 0.0) {
2467 let T = ext.aniso.xyz;
2468 var grain = T;
2469 if (ext.aniso.w >= 0.0 && ext.misc.y <= 0.0) { grain = cross(N, T); }
2470 let bent = normalize(cross(cross(grain, V), grain));
2471 var bendBy = abs(ext.aniso.w);
2472 if (ext.misc.y > 0.0) { bendBy = 0.55; }
2473 envR = reflect(-V, normalize(mix(N, bent, vec3f(bendBy))));
2474 }
2475 var envF = FssEss + FmsEms;
2476 if (ext.film.x > 0.0) { envF = filmFresnel(envF, NdotV, ext.film); }
2477 gloss += envRadiance(envR, roughness, reflectionColumn(), worldPos) * (ao * specular)
2478 * envF;
2479 let base = diffuse * lit * kd + gloss;
2480 var baseScale = 1.0;
2481 if (ext.coat.x > 0.0) {
2482 let coatNdotV = max(dot(ext.coatN.xyz, V), 1e-4);
2483 let cab = envBRDFApprox(coatNdotV, ext.coat.y);
2484 // coat.z is the coat's reflectance seen straight on; 0 is a varnish's 0.04.
2485 let coatF0 = select(0.04, ext.coat.z, ext.coat.z > 0.0);
2486 let Fc = (coatF0 * cab.x + cab.y) * ext.coat.x;
2487 baseScale *= 1.0 - Fc;
2488 extra += envRadiance(reflect(-V, ext.coatN.xyz), ext.coat.y, reflectionColumn(), worldPos) * (ao * Fc);
2489 }
2490 if (dot(ext.sheen.rgb, vec3f(1.0)) > 0.0) {
2491 let sheenAlbedo = 0.2 + 0.3 * ext.sheen.a;
2492 baseScale *= 1.0 - max(max(ext.sheen.r, ext.sheen.g), ext.sheen.b) * sheenAlbedo;
2493 extra += ext.sheen.rgb * (indirectIrradiance(N) * ao * sheenAlbedo);
2494 }
2495 return base * baseScale + extra;
2496}
2497fn applyLightingSurface(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f, metallic : f32,
2498 roughness : f32, specular : f32, ao : f32, ext : SurfaceExt) -> vec3f {
2499 return applyLightingSurfaceBRDF(albedo * (1.0 - metallic), mix(vec3f(ext.misc.x), albedo, vec3f(metallic)),
2500 N, worldPos, V, roughness, specular, ao, ext);
2501}
2502fn applyLightingPBR(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f, metallic : f32,
2503 roughness : f32, specular : f32, ao : f32) -> vec3f {
2504 return applyLightingSurface(albedo, N, worldPos, V, metallic, roughness, specular, ao, surfaceExtNone(N));
2505}
2506)"
2507// Split for MSVC's cap on one string literal, as above: the surface layers, then the lighting that reads them.
2508R"(struct LightTerm { lit : vec3f, gloss : vec3f, extra : vec3f };
2509// The layer of the sprite being lit, as its vertex wrote it (the layer plus 129; 0 when the surface has none to test), and whether a light's
2510// range of layers, which rides in shadowMap.y above the tile count, takes it in. See packLightLayerRange.
2511var<private> g_surfaceLayer : f32 = 0.0;
2512fn lightReachesLayer(rangeLane : f32) -> bool {
2513 if (rangeLane < 8.0 || g_surfaceLayer < 0.5) { return true; }
2514 let range = floor(rangeLane / 8.0);
2515 let lo = range % 256.0 - 128.0;
2516 let hi = 127.0 - floor(range / 256.0);
2517 let layer = g_surfaceLayer - 129.0;
2518 return layer >= lo && layer <= hi;
2519}
2520fn shadeLight(pd : vec4f, col : vec4f, sp : vec4f, sh : vec4f, sm : vec4f, fo : vec4f, N : vec3f, V : vec3f,
2521 worldPos : vec3f, a : f32, F0 : vec3f, NdotV : f32, specular : f32, roughness : f32,
2522 ext : SurfaceExt, shadow3D : bool) -> LightTerm {
2523 var lit = vec3f(0.0);
2524 var gloss = vec3f(0.0);
2525 var extra = vec3f(0.0);
2526 // A slot nothing lights from adds exactly nothing (see the GLSL twin).
2527 if (col.a == 0.0 || !lightReachesLayer(sm.y)) { return LightTerm(lit, gloss, extra); }
2528 {
2529 var L : vec3f;
2530 var atten : f32;
2531 var aim = pd.xy;
2532 var castShadow = true;
2533 if (pd.z < 0.5) {
2534 let toL = lightVector(pd, sh, worldPos);
2535 let dist = lightDistance(toL);
2536 atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);
2537 L = towardLight(toL, N);
2538 } else if (pd.z < 1.5) {
2539 atten = 1.0;
2540 L = normalize(-vec3f(pd.xy, pd.w));
2541 var toLight = vec2f(0.0, 0.0);
2542 if (dot(pd.xy, pd.xy) > 1e-8) { toLight = normalize(-pd.xy); }
2543 castShadow = sh.y > 0.0 && dot(toLight, toLight) > 0.5;
2544 aim = worldPos.xy + toLight * sh.y;
2545 if (sp.x > 0.5) { atten = atten * cloudShadow3D(worldPos, i32(sp.x) - 1); }
2546 } else {
2547 let toL = lightVector(pd, sh, worldPos);
2548 let dist = lightDistance(toL);
2549 atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);
2550 L = towardLight(toL, N);
2551 atten *= spotCone(sp, sh, toL, dist);
2552 }
2553 // Facing away, with nothing that takes light from behind: nothing from this light, and no shadow to look up (see the GLSL twin).
2554 if (atten <= 0.0 || (dot(N, L) <= 0.0 && ext.misc.y <= 0.0 && ext.coat.x <= 0.0 && ext.scatter.a <= 0.0
2555 && dot(ext.sheen.rgb, vec3f(1.0)) <= 0.0)) { return LightTerm(lit, gloss, extra); }
2556#ifndef ES_LIGHT_DIRECT
2557 if (col.a > 0.0 && atten > 0.0) {
2558 atten *= shapeFactor2D(fo.w, worldPos.xy);
2559 }
2560 if (castShadow && col.a > 0.0 && atten > 0.0) {
2561 atten *= mix(1.0, shadowFactor2D(sm.w, worldPos.xy), fo.z);
2562 }
2563#endif
2564 // See the GLSL twin: a light the tiles carry has no shadow map, and says so.
2565 if (shadow3D && sm.y % 8.0 > 0.0 && atten > 0.0) {
2566 atten *= mix(1.0,
2567 shadowFactor3D(worldPos, N, L, vec2f(sh.x, sm.z), i32(sm.x), i32(sm.y % 8.0)),
2568 fo.z);
2569 }
2570 var ndotl = max(dot(N, L), 0.0);
2571 // Hair (misc.y above zero; aniso.xyz is the strand): Kajiya-Kay diffuse, which lights a strand by how far light is from along it.
2572 if (ext.misc.y > 0.0) {
2573 let along = dot(ext.aniso.xyz, L);
2574 ndotl = mix(ndotl, sqrt(max(1.0 - along * along, 0.0)) * clamp(dot(N, L) * 0.5 + 0.65, 0.0, 1.0), ext.strand.x);
2575 }
2576 let radiance = col.rgb * (col.a * ndotl * atten);
2577 lit += radiance;
2578 if (specular > 0.0 && ext.misc.y > 0.0 && ext.strand.y <= 0.0) {
2579 // Two shifted, narrow lobes along the strand: a white one near the surface and a coloured one under it (scatter.rgb).
2580 let H = normalize(L + V);
2581 let primaryExp = clamp(2.0 / (a * a), 8.0, 900.0);
2582 let strandA = normalize(ext.aniso.xyz + N * ext.misc.z);
2583 let strandB = normalize(ext.aniso.xyz + N * ext.misc.w);
2584 let h1 = dot(strandA, H);
2585 let h2 = dot(strandB, H);
2586 let lobe1 = smoothstep(-1.0, 0.0, h1) * pow(sqrt(max(1.0 - h1 * h1, 0.0)), primaryExp);
2587 let lobe2 = smoothstep(-1.0, 0.0, h2) * pow(sqrt(max(1.0 - h2 * h2, 0.0)), primaryExp * 0.3);
2588 let lightOn = col.rgb * (col.a * atten * clamp(dot(N, L) + 0.35, 0.0, 1.0));
2589 gloss += lightOn * (lobe1 * 0.55 + lobe2 * ext.scatter.rgb * 1.6) * (ext.misc.y * specular);
2590 } else if (specular > 0.0) {
2591 let H = normalize(L + V);
2592 var brdf : f32;
2593 if (ext.misc.y > 0.0) {
2594 // Hair shaded as the Principled shader shades a card with an anisotropy (strand.y): GGX stretched along the strand, as Blender
2595 // stretches it (aspect sqrt(1 - 0.9 anisotropy)). The highlight runs across the strands as a band, the sheen a lock of hair has.
2596 let T = ext.aniso.xyz;
2597 let B = cross(N, T);
2598 let aspect = sqrt(max(1.0 - 0.9 * ext.strand.y, 0.01));
2599 let at = max(a / aspect, 0.002);
2600 let ab = max(a * aspect, 0.002);
2601 brdf = distributionGGXAniso(at, ab, dot(T, H), dot(B, H), max(dot(N, H), 0.0))
2602 * visibilityGGXAniso(at, ab, dot(T, V), dot(B, V), dot(T, L), dot(B, L), NdotV, ndotl);
2603 } else if (ext.aniso.w != 0.0) {
2604 let T = ext.aniso.xyz;
2605 let B = cross(N, T);
2606 let at = max(a * (1.0 + ext.aniso.w), 0.002);
2607 let ab = max(a * (1.0 - ext.aniso.w), 0.002);
2608 brdf = distributionGGXAniso(at, ab, dot(T, H), dot(B, H), max(dot(N, H), 0.0))
2609 * visibilityGGXAniso(at, ab, dot(T, V), dot(B, V), dot(T, L), dot(B, L), NdotV, ndotl);
2610 } else {
2611 brdf = distributionGGX(max(dot(N, H), 0.0), a) * visibilitySmithGGX(NdotV, ndotl, a);
2612 }
2613 var F = fresnelSchlick(max(dot(V, H), 0.0), F0);
2614 if (ext.film.x > 0.0) { F = filmFresnel(F, max(dot(V, H), 0.0), ext.film); }
2615 gloss += radiance * F
2616 * (brdf * 3.14159265 * specular);
2617 }
2618 if (col.a > 0.0 && atten > 0.0
2619 && (ext.coat.x > 0.0 || ext.scatter.a > 0.0 || dot(ext.sheen.rgb, vec3f(1.0)) > 0.0)) {
2620 let irr = col.rgb * (col.a * atten);
2621 let Hx = normalize(L + V);
2622 let VdotH = max(dot(V, Hx), 0.0);
2623 if (ext.coat.x > 0.0) {
2624 let coatNdotL = max(dot(ext.coatN.xyz, L), 0.0);
2625 let coatA = max(ext.coat.y * ext.coat.y, 1e-3);
2626 let coatF0 = select(0.04, ext.coat.z, ext.coat.z > 0.0);
2627 let Fc = (coatF0 + (1.0 - coatF0) * pow(1.0 - VdotH, 5.0)) * ext.coat.x;
2628 extra += irr * coatNdotL
2629 * (distributionGGX(max(dot(ext.coatN.xyz, Hx), 0.0), coatA) * (0.25 / max(VdotH * VdotH, 1e-4))
2630 * Fc * 3.14159265);
2631 }
2632 if (dot(ext.sheen.rgb, vec3f(1.0)) > 0.0) {
2633 let sheenA = max(ext.sheen.a * ext.sheen.a, 1e-3);
2634 extra += irr * ndotl * ext.sheen.rgb
2635 * (distributionCharlie(max(dot(N, Hx), 0.0), sheenA) * visibilityNeubelt(NdotV, ndotl) * 3.14159265);
2636 }
2637 if (ext.scatter.a > 0.0) {
2638 // The wrap is per channel once trans.w asks for it: red travels furthest, and every channel further where the
2639 // surface turns sharply (trans.z, a curvature 0..1), as a pre-integrated skin ramp would give.
2640 let wrapWidth = vec3f(ext.scatter.a) * mix(vec3f(1.0), vec3f(1.0, 0.45, 0.25) * (0.3 + 1.7 * ext.trans.z), ext.trans.w);
2641 let wrapped = clamp((vec3f(dot(N, L)) + wrapWidth) / (vec3f(1.0) + wrapWidth), vec3f(0.0), vec3f(1.0));
2642 extra += irr * ext.scatter.rgb * max(wrapped - vec3f(ndotl), vec3f(0.0));
2643 let Hb = normalize(L + N * 0.3);
2644 extra += irr * ext.scatter.rgb
2645 * (pow(clamp(dot(V, -Hb), 0.0, 1.0), 4.0) * ext.trans.x * (1.0 - ext.trans.y));
2646 }
2647 }
2648 }
2649 return LightTerm(lit, gloss, extra);
2650}
2651)"
2652// Split for MSVC's cap on one string literal, as above.
2653R"(// A lit sprite's light, written out as only what it is (see the GLSL twin): the general model's sums term for term, with the two 2D masks
2654// read once for the pixel and nothing of the highlight carried along.
2655fn shadeLight2D(pd : vec4f, col : vec4f, sp : vec4f, sh : vec4f, sm : vec4f, fo : vec4f, N : vec3f, worldPos : vec3f,
2656 masked : bool, shadowMask : vec4f, shapeMask : vec4f, shadow3D : bool) -> vec3f {
2657 if (col.a == 0.0 || !lightReachesLayer(sm.y)) { return vec3f(0.0); }
2658 var L : vec3f;
2659 var atten = 1.0;
2660 var castShadow = true;
2661 if (pd.z < 0.5) {
2662 let toL = lightVector(pd, sh, worldPos);
2663 let dist = lightDistance(toL);
2664 atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);
2665 L = towardLight(toL, N);
2666 } else if (pd.z < 1.5) {
2667 L = normalize(-vec3f(pd.xy, pd.w));
2668 var toLight = vec2f(0.0, 0.0);
2669 if (dot(pd.xy, pd.xy) > 1e-8) { toLight = normalize(-pd.xy); }
2670 castShadow = sh.y > 0.0 && dot(toLight, toLight) > 0.5;
2671 } else {
2672 let toL = lightVector(pd, sh, worldPos);
2673 let dist = lightDistance(toL);
2674 atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);
2675 L = towardLight(toL, N);
2676 atten *= spotCone(sp, sh, toL, dist);
2677 }
2678#ifndef ES_LIGHT_DIRECT
2679 if (masked && col.a > 0.0 && atten > 0.0) {
2680 if (fo.w >= 0.0) { atten *= min(mask2DChannel(shapeMask, fo.w), 1.0); }
2681 if (castShadow && sm.w >= 0.0 && atten > 0.0) {
2682 var hidden = 0.0;
2683 if (sm.w < 3.5) { hidden = mask2DChannel(shadowMask, sm.w); }
2684 else { hidden = mask2DChannel(shapeMask, sm.w - 4.0); }
2685 atten *= mix(1.0, 1.0 - min(hidden, 1.0), fo.z);
2686 }
2687 }
2688#endif
2689 if (shadow3D && sm.y % 8.0 > 0.0 && atten > 0.0) {
2690 atten *= mix(1.0,
2691 shadowFactor3D(worldPos, N, L, vec2f(sh.x, sm.z), i32(sm.x), i32(sm.y % 8.0)),
2692 fo.z);
2693 }
2694 return col.rgb * (col.a * max(dot(N, L), 0.0) * atten);
2695}
2696// `reach`: bit i set when loop light i can reach this quad at all (see the GLSL twin); the rest are not worked out.
2697fn applyLighting2DReach(albedo : vec3f, N : vec3f, worldPos : vec2f, ao : f32, reach : u32) -> vec3f {
2698 let P = vec3f(worldPos, 0.0);
2699 g_probePos = P;
2700 var lit = indirectIrradiance(N) * ao;
2701 var masked = false;
2702 var shadowMask = vec4f(0.0);
2703 var shapeMask = vec4f(0.0);
2704#ifndef ES_LIGHT_DIRECT
2705 if (lc.u_mask2DRect.z > 0.0) {
2706 let maskUv = mask2DUv(worldPos);
2707 if (!(maskUv.x < 0.0)) {
2708 masked = true;
2709 shadowMask = textureSampleLevel(t7, s7, maskUv, 0.0);
2710 shapeMask = textureSampleLevel(t6, s6, maskUv, 0.0);
2711 }
2712 }
2713#endif
2714 // The screen tile this pixel is in says which lights can reach it (see the GLSL twin): the fourth word is the loop's own sixteen.
2715 var reachBits = reach;
2716#ifndef ES_LIGHT_DIRECT
2717 let tiledCount = i32(lc.tileInfo.x);
2718 var tileBits = vec4u(0u);
2719 if (tiledCount > 0 || lc.tileInfo.w > 0.5) {
2720 let tileClip = frame.projection * vec4f(P, 1.0);
2721 let tileNdc = tileClip.xy / max(tileClip.w, 1e-4);
2722 let tileCount = vec2i(i32(lc.tileInfo.y), i32(lc.tileInfo.z));
2723 let tile = clamp(vec2i(floor((tileNdc * 0.5 + 0.5) * vec2f(tileCount))), vec2i(0), tileCount - vec2i(1));
2724 tileBits = lc.tileMask[tile.y * tileCount.x + tile.x];
2725 if (lc.tileInfo.w > 0.5) { reachBits = reachBits & tileBits.w; }
2726 }
2727#endif
2728 let lightCount = i32(lc.u_ambient.a);
2729 for (var i = 0; i < lightCount; i++) {
2730 if (((reachBits >> u32(i)) & 1u) == 0u) { continue; }
2731 lit += shadeLight2D(lc.u_lights[i].posDir, lc.u_lights[i].color, lc.u_lights[i].spot, lc.u_lights[i].shadow,
2732 lc.u_lights[i].shadowMap, lc.u_lights[i].falloff, N, P, masked, shadowMask, shapeMask, true);
2733 }
2734#ifndef ES_LIGHT_DIRECT
2735 if (tiledCount > 0) {
2736 for (var w = 0; w < 3; w++) {
2737 var bits = tileBits.x;
2738 if (w == 1) { bits = tileBits.y; } else if (w == 2) { bits = tileBits.z; }
2739 if (bits == 0u) { continue; }
2740 for (var b = 0; b < 32; b++) {
2741 if ((bits & (1u << u32(b))) == 0u) { continue; }
2742 let k = w * 32 + b;
2743 if (k >= tiledCount) { break; }
2744 lit += shadeLight2D(lc.tiledLights[k].posDir, lc.tiledLights[k].color, lc.tiledLights[k].spot,
2745 lc.tiledLights[k].shadow, lc.tiledLights[k].shadowMap, lc.tiledLights[k].falloff,
2746 N, P, masked, shadowMask, shapeMask, false);
2747 }
2748 }
2749 }
2750#endif
2751 return albedo * lit;
2752}
2753fn applyLighting2DAO(albedo : vec3f, N : vec3f, worldPos : vec2f, ao : f32) -> vec3f {
2754 return applyLighting2DReach(albedo, N, worldPos, ao, 65535u);
2755}
2756fn applyLighting2D(albedo : vec3f, N : vec3f, worldPos : vec2f) -> vec3f {
2757 return applyLighting2DAO(albedo, N, worldPos, 1.0);
2758}
2759// The same, for a sprite that knows its layer: layerLane is the varying the vertex stage wrote (v_lightLayer). A negative lane carries,
2760// above the layer, which lights reach the quad (packSpriteLightLane); the sixteenth light has no bit and is always worked out.
2761fn applyLighting2DLayer(albedo : vec3f, N : vec3f, worldPos : vec2f, layerLane : f32) -> vec3f {
2762 let lane = abs(layerLane);
2763 let reachLane = floor(lane * 0.001953125);
2764 g_surfaceLayer = lane - reachLane * 512.0;
2765 var reach = 65535u;
2766 if (layerLane < 0.0) { reach = u32(reachLane) + 32768u; }
2767 return applyLighting2DReach(albedo, N, worldPos, 1.0, reach);
2768}
2769)";
2770
2771// Blanks a hand-written `layout(std140) uniform <block> {...};` out of a GLSL
2772// stage: shaders predating the injected block still carry their own, and one
2773// block declared twice never links. Blanked (not cut) so line remapping lands.
2774std::string blankUniformBlock(const std::string& src, const std::string& blockName) {
2775 const std::string needle = "uniform " + blockName;
2776 const usize at = src.find(needle);
2777 if (at == std::string::npos) return src;
2778
2779 const usize lineStart = src.rfind('\n', at) == std::string::npos ? 0 : src.rfind('\n', at) + 1;
2780 // Only a declaration counts: the same words inside a comment must survive.
2781 const std::string prefix = src.substr(lineStart, at - lineStart);
2782 if (prefix.find_first_not_of(" \t") != std::string::npos
2783 && prefix.find("layout") == std::string::npos) {
2784 return src;
2785 }
2786 const usize open = src.find('{', at);
2787 if (open == std::string::npos) return src;
2788 const usize close = src.find("};", open);
2789 if (close == std::string::npos) return src;
2790
2791 std::string out = src;
2792 for (usize i = lineStart; i < close + 2; ++i) {
2793 if (out[i] != '\n') out[i] = ' ';
2794 }
2795 return out;
2796}
2797
2798std::string trimWs(const std::string& s) {
2799 const usize a = s.find_first_not_of(" \t\r\n");
2800 if (a == std::string::npos) return {};
2801 const usize b = s.find_last_not_of(" \t\r\n");
2802 return s.substr(a, b - a + 1);
2803}
2804
2805// An #if / #elif condition over the feature set: defined(NAME), defined NAME, a bare
2806// NAME (a feature is #defined to 1 on the GLSL side, anything else reads 0), integer
2807// literals, !, &&, || and parentheses.
2808class ConditionParser {
2809public:
2810 ConditionParser(const std::string& text, const std::unordered_set<std::string>& defined)
2811 : s_(text), defined_(defined) {}
2812
2813 bool evaluate() { return orExpr(); }
2814
2815private:
2816 void skipWs() { while (i_ < s_.size() && (s_[i_] == ' ' || s_[i_] == '\t' || s_[i_] == '\r')) ++i_; }
2817 bool eat(const char* tok) {
2818 skipWs();
2819 const usize n = std::strlen(tok);
2820 if (s_.compare(i_, n, tok) != 0) return false;
2821 i_ += n;
2822 return true;
2823 }
2824 std::string ident() {
2825 skipWs();
2826 const usize start = i_;
2827 while (i_ < s_.size() && (std::isalnum(static_cast<unsigned char>(s_[i_])) || s_[i_] == '_')) ++i_;
2828 return s_.substr(start, i_ - start);
2829 }
2830 bool orExpr() {
2831 bool v = andExpr();
2832 while (eat("||")) v = andExpr() || v;
2833 return v;
2834 }
2835 bool andExpr() {
2836 bool v = unary();
2837 while (eat("&&")) v = unary() && v;
2838 return v;
2839 }
2840 bool unary() {
2841 if (eat("!")) return !unary();
2842 if (eat("(")) {
2843 const bool v = orExpr();
2844 eat(")");
2845 return v;
2846 }
2847 const std::string word = ident();
2848 if (word == "defined") {
2849 const bool paren = eat("(");
2850 const bool v = defined_.count(ident()) != 0;
2851 if (paren) eat(")");
2852 return v;
2853 }
2854 if (!word.empty() && std::isdigit(static_cast<unsigned char>(word[0]))) return std::strtol(word.c_str(), nullptr, 0) != 0;
2855 return defined_.count(word) != 0;
2856 }
2857
2858 const std::string& s_;
2859 const std::unordered_set<std::string>& defined_;
2860 usize i_ = 0;
2861};
2862
2863// WGSL has no preprocessor, so feature permutations resolve at assembly time over the assembled text, with the
2864// feature set as the defined names. GLSL keeps real #defines for the driver, so both targets see the same variants.
2865std::string preprocessConditionals(const std::string& source, const std::vector<std::string>& features) {
2866 const std::unordered_set<std::string> defined(features.begin(), features.end());
2867 struct Frame {
2868 bool parentActive;
2869 bool taken;
2870 bool active;
2871 };
2872 std::vector<Frame> stack;
2873 auto activeNow = [&]() { return stack.empty() || stack.back().active; };
2874
2875 std::string out;
2876 out.reserve(source.size());
2877 LineReader in(source);
2878 std::string line;
2879 while (in.next(line)) {
2880 const std::string lead = ltrim(line);
2881 if (lead.rfind("#ifdef", 0) == 0 || lead.rfind("#ifndef", 0) == 0) {
2882 const bool neg = lead.rfind("#ifndef", 0) == 0;
2883 const std::string name = trimWs(lead.substr(neg ? 7 : 6));
2884 const bool parent = activeNow();
2885 const bool cond = parent && ((defined.count(name) != 0) != neg);
2886 stack.push_back(Frame{parent, cond, cond});
2887 continue;
2888 }
2889 if (lead.rfind("#if", 0) == 0 && (lead.size() == 3 || lead[3] == ' ' || lead[3] == '\t' || lead[3] == '(' || lead[3] == '!')) {
2890 const bool parent = activeNow();
2891 const bool cond = parent && ConditionParser(lead.substr(3), defined).evaluate();
2892 stack.push_back(Frame{parent, cond, cond});
2893 continue;
2894 }
2895 if (lead.rfind("#elif", 0) == 0 && !stack.empty()) {
2896 const bool cond = ConditionParser(lead.substr(5), defined).evaluate();
2897 Frame& f = stack.back();
2898 f.active = f.parentActive && !f.taken && cond;
2899 f.taken = f.taken || f.active;
2900 continue;
2901 }
2902 if (lead.rfind("#else", 0) == 0 && !stack.empty()) {
2903 Frame& f = stack.back();
2904 f.active = f.parentActive && !f.taken;
2905 f.taken = true;
2906 continue;
2907 }
2908 if (lead.rfind("#endif", 0) == 0) {
2909 if (!stack.empty()) stack.pop_back();
2910 continue;
2911 }
2912 if (activeNow()) {
2913 out += line;
2914 out += '\n';
2915 }
2916 }
2917 return out;
2918}
2919
2920const char* stageName(ShaderStage stage) {
2921 return stage == ShaderStage::Vertex ? "vertex" : "fragment";
2922}
2923
2924// The WGSL assembly: the stage's twin body behind the per-language injected
2925// headers, then the assembly-time feature preprocessor. Platform variants and
2926// sharedCode are GLSL-only mechanisms — twins carry their own helpers.
2927// headerLineCount is exact when the body carries no #if lines (removed lines
2928// shift the compile-log remap; acceptable for hand-authored twins).
2929bool hasFeature(const std::vector<std::string>& features, const char* name) {
2930 return std::find(features.begin(), features.end(), name) != features.end();
2931}
2932
2933ShaderParser::AssembledStage assembleWGSLStage(const ParsedShader& parsed,
2934 ShaderStage stage,
2935 const std::vector<std::string>& features) {
2937 if (!parsed.valid) return result;
2938
2939 auto bodyIt = parsed.wgslStages.find(stage);
2940 if (bodyIt == parsed.wgslStages.end()) {
2941 ES_LOG_ERROR("Shader '{}' has no WGSL twin for the {} stage (add '#pragma {} wgsl')",
2942 parsed.name, stageName(stage), stageName(stage));
2943 return result;
2944 }
2945
2946 // A `wgsl full` twin is a self-contained program (the cook-generated shape):
2947 // it carries its own declarations at the engine's binding conventions, so
2948 // injecting the shared headers would double-declare them.
2949 auto fullIt = parsed.wgslStageFull.find(stage);
2950 if (fullIt != parsed.wgslStageFull.end() && fullIt->second) {
2951 result.source = preprocessConditionals(bodyIt->second, features);
2952 result.headerLineCount = 0;
2953 return result;
2954 }
2955
2956 TextBuilder assembled;
2957 u32 headerLines = 0;
2958 auto inject = [&](const std::string& s) {
2959 assembled << s;
2960 headerLines += countNewlines(s);
2961 };
2962
2963 const bool lit = parsed.domain == "Lit";
2964 if (stage == ShaderStage::Fragment && parsed.wgslVertexIsCanonical) {
2965 // The canonical vertex's varying interface (domain-shaped) + the
2966 // engine texture contract — fragment-only twins run under the batch
2967 // conventions (PostProcess reads its input/scene as t0/s0 and t1/s1).
2968 inject(parsed.domain == "PostProcess" ? wgslPPVSOut() : wgslCanonicalVSOut(lit));
2969 // A resident 3D surface that reads no bake has the probe atlas, a volume, on unit 5 (declared with the lit header).
2970 const bool probeAtlas = lit && hasFeature(features, "ES_SURFACE_3D") && !hasFeature(features, "MESH_LIGHTMAP");
2971 inject(wgslBatchTextureDecls(parsed.domain == "PostProcess",
2972 materialLowUnits(parsed) | (probeAtlas ? (1u << LIGHTMAP_TEXTURE_UNIT) : 0u)));
2973 }
2974 inject(kFrameHeaderWGSL);
2975 inject(kTimeHeaderWGSL);
2976 if (parsed.materialBlockSize > 0) {
2977 std::string block = "struct MaterialConstants {\n";
2978 for (const auto& p : parsed.properties) {
2979 if (!p.fromParam || p.std140Offset < 0) continue;
2980 block += " " + p.name + " : " + wgslTypeName(p.type) + ",\n";
2981 }
2982 block += "};\n"
2983 "@group(0) @binding(1) var<uniform> mc : MaterialConstants;\n";
2984 inject(block);
2985 }
2986 std::string bodyText = bodyIt->second;
2987 // A hand-written vertex stage says where the shared morph helpers go (see morphHelpersWGSL).
2988 if (stage == ShaderStage::Vertex) fillHook(bodyText, "@@ES_MORPH@@", morphHelpersWGSL());
2989 if (stage == ShaderStage::Vertex && !parsed.wgslVertexHook.empty()) {
2990 fillHook(bodyText, "@@ES_VERTEX_HOOK@@", parsed.wgslVertexHook);
2991 // A material's vertex hook may read its textures too (a height field the surface is lifted by): the ones it names are declared
2992 // for this stage as well, and the device then makes their bindings visible to it.
2993 inject(wgslMaterialTextureDecls(parsed, bodyText, &parsed.wgslVertexHook));
2994 } else if (stage == ShaderStage::Vertex && !parsed.wgslVertexIsCanonical) {
2995 // Explicit vertex stages (including forward light projection) can sample
2996 // the same named material textures as canonical displacement hooks.
2997 inject(wgslMaterialTextureDecls(parsed, bodyText, &bodyText));
2998 }
2999 if (stage == ShaderStage::Fragment) {
3000 inject(wgslMaterialTextureDecls(parsed, bodyIt->second));
3001 if (lit) { inject(kLitHeaderWGSL); inject(WATER_SUN_WGSL); }
3002 if (parsed.domain == "PostProcess" && parsed.usesLights) inject(kPostLightHeaderWGSL);
3003 inject(kColorHelpersWGSL);
3004 }
3005 // The records, for a stage that names them — the same question, and the same
3006 // answer, as the GLSL side. Before the texture completion below, so the unit
3007 // this reaches for is one of the ones it sees.
3008 if (stage == ShaderStage::Vertex && namesRecords(bodyIt->second)) {
3009 inject(instanceRecordWGSL());
3010 }
3011 // Last, so it sees every declaration made above as well as the body's own. Read with this variant's features
3012 // applied: a unit declared behind a feature that is off is not declared (the mesh twin's t5 is the bake's, under
3013 // MESH_LIGHTMAP), and one reached only behind such a feature is not reached.
3014 inject(wgslReachedTextureDecls(preprocessConditionals(assembled.str() + bodyIt->second, features),
3015 parsed.domain == "PostProcess"));
3016
3017 assembled << bodyText;
3018
3019 result.source = preprocessConditionals(assembled.str(), features);
3020 result.headerLineCount = headerLines;
3021 return result;
3022}
3023
3024} // namespace
3025
3026bool ShaderParser::s_linearColor = false;
3027
3028std::string ShaderParser::canonicalVaryingsWGSL(const ParsedShader& parsed) {
3029 if (!parsed.valid || !parsed.vertexIsCanonical) return {};
3030 return wgslCanonicalVSOut(parsed.domain == "Lit");
3031}
3032
3033void ShaderParser::setLinearColorSpace(bool linear) { s_linearColor = linear; }
3034bool ShaderParser::linearColorSpace() { return s_linearColor; }
3038 const std::string& platform,
3039 const std::vector<std::string>& featuresIn,
3040 ShaderTargetLanguage target) {
3041 // The color space is a process-global compile input: every shader — batch
3042 // variants, plugin shaders, blit, materials, post effects — sees the same
3043 // ES_LINEAR world with no per-call-site wiring. It must be set before the
3044 // renderer compiles shaders; flipping it later requires a reload.
3045 std::vector<std::string> features = featuresIn;
3046 if (parsed.lightingDirect && std::find(features.begin(), features.end(), "ES_LIGHT_DIRECT") == features.end()) {
3047 features.push_back("ES_LIGHT_DIRECT");
3048 }
3049 if (s_linearColor
3050 && std::find(features.begin(), features.end(), "ES_LINEAR") == features.end()) {
3051 features.push_back("ES_LINEAR");
3052 }
3053 // A tangent frame arrives through a varying only a vertex stage that knows about it writes: the engine's own canonical one,
3054 // or a shader that declares the feature. Any other keeps reading its frame from derivatives, as it always did.
3055 if (!parsed.vertexIsCanonical
3056 && std::find(parsed.features.begin(), parsed.features.end(), "MESH_TANGENTS") == parsed.features.end()) {
3057 features.erase(std::remove(features.begin(), features.end(), std::string("MESH_TANGENTS")), features.end());
3058 }
3059 // The mesh's own position is handed down only on the engine's canonical vertex stage, for a mesh draw of a shader that asks for it: it costs a
3060 // varying, which no other shader should pay.
3061 const auto has = [](const std::vector<std::string>& list, const char* name) { return std::find(list.begin(), list.end(), name) != list.end(); };
3062 features.erase(std::remove(features.begin(), features.end(), std::string("MESH_LOCAL_POSITION")), features.end());
3063 if (parsed.vertexIsCanonical && has(parsed.features, "MESH_LOCAL_POSITION") && has(features, "MESH")) {
3064 features.push_back("MESH_LOCAL_POSITION");
3065 }
3066 if (target == ShaderTargetLanguage::WGSL) {
3067 return assembleWGSLStage(parsed, stage, features);
3068 }
3069 AssembledStage result;
3070
3071 if (!parsed.valid) return result;
3072
3073 auto stageIt = parsed.stages.find(stage);
3074 if (stageIt == parsed.stages.end()) return result;
3075
3076 TextBuilder assembled;
3077 u32 headerLines = 0;
3078
3079 if (!parsed.version.empty()) {
3080 assembled << "#version " << parsed.version << "\n";
3081 ++headerLines;
3082 }
3083 // gl_DrawID, for a vertex stage that reads a record (see instanceRecordGLSLDecls).
3084 if (glslMultiDraw() && stage == ShaderStage::Vertex) {
3085 const auto named = parsed.stages.find(stage);
3086 if (named != parsed.stages.end() && namesRecords(named->second)) {
3087 assembled << "#ifndef VULKAN\n#extension GL_ANGLE_multi_draw : require\n#endif\n";
3088 headerLines += 3;
3089 }
3090 }
3091
3092 // Feature #defines go right after #version (GLSL requires #version first), so the
3093 // shader body can #ifdef compile-time variants. Counted into headerLines so the
3094 // compile-log line remap stays accurate.
3095 for (const auto& f : features) {
3096 assembled << "#define " << f << " 1\n";
3097 ++headerLines;
3098 }
3099
3100 // sRGB transfer helpers, available to every fragment stage in both modes —
3101 // authored bodies branch on ES_LINEAR. Exact piecewise IEC 61966-2-1, so the
3102 // CPU-side conversions (light/clear colors) match bit-for-bit within fp32.
3103 if (stage == ShaderStage::Fragment) {
3104 static const char* kColorHelpers =
3105 "highp vec3 srgbToLinear(highp vec3 c) {\n"
3106 " return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));\n"
3107 "}\n"
3108 "highp vec3 linearToSrgb(highp vec3 c) {\n"
3109 " return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));\n"
3110 "}\n"
3111 // The display curve, one definition for every stage that needs it:
3112 // Narkowicz ACES. A tonemap is the OUTPUT transform, so a chain that
3113 // carries one applies it once, in the pass that also encodes.
3114 "highp vec3 acesFilmic(highp vec3 x) {\n"
3115 " return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0);\n"
3116 "}\n"
3117 // Khronos PBR Neutral (Apache-2.0, KhronosGroup/ToneMapping): hue and saturation
3118 // survive the curve, so a lit red stays red where ACES walks it to cream.
3119 "highp vec3 pbrNeutral(highp vec3 c) {\n"
3120 " const highp float startCompression = 0.8 - 0.04;\n"
3121 " const highp float desaturation = 0.15;\n"
3122 " highp float x = min(c.r, min(c.g, c.b));\n"
3123 " highp float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n"
3124 " c -= offset;\n"
3125 " highp float peak = max(c.r, max(c.g, c.b));\n"
3126 " if (peak < startCompression) return c;\n"
3127 " const highp float d = 1.0 - startCompression;\n"
3128 " highp float newPeak = 1.0 - d * d / (peak + d - startCompression);\n"
3129 " c *= newPeak / peak;\n"
3130 " highp float g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0);\n"
3131 " return mix(c, newPeak * vec3(1.0, 1.0, 1.0), g);\n"
3132 "}\n";
3133 assembled << kColorHelpers;
3134 headerLines += countNewlines(kColorHelpers);
3135 }
3136
3137 // The per-frame view-projection, injected identically into every stage (a block
3138 // declared two ways does not link) and engine-owned, so it cannot drift from the
3139 // std140 mirror in FrameConstants.hpp. highp: fragment has no default this early.
3140 // worldFromDepth takes the fullscreen pass's v_texCoord and a raw sample.
3141 // `depth * 2 - 1` is the ONE thing its WGSL twin spells differently: GL clips
3142 // z to [-1, 1], WebGPU to [0, 1]. The xy is shared — one screen triangle.
3143 static const char* kFrameHeader =
3144 "layout(std140) uniform FrameConstants {\n"
3145 " highp mat4 u_projection;\n"
3146 " highp vec4 u_camera;\n" // xyz = eye (w=1) or direction toward it (w=0)
3147 " highp mat4 u_inverseViewProjection;\n"
3148 " highp vec4 u_renderOrigin;\n" // xyz: what a position here is taken from, to be the world's own
3149 "};\n"
3150 "highp vec3 viewDirection(in highp vec3 worldPos) {\n"
3151 " return u_camera.w > 0.5 ? normalize(u_camera.xyz - worldPos) : u_camera.xyz;\n"
3152 "}\n"
3153 "highp vec3 worldFromDepth(in highp vec2 uv, in highp float depth) {\n"
3154 " highp vec4 clip = vec4(uv * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);\n"
3155 " highp vec4 world = u_inverseViewProjection * clip;\n"
3156 " return world.xyz / world.w;\n"
3157 "}\n"
3158 "highp float distanceToEye(in highp vec3 worldPos) {\n"
3159 " return u_camera.w > 0.5 ? length(worldPos - u_camera.xyz) : -dot(worldPos, u_camera.xyz);\n"
3160 "}\n"
3161 "highp vec2 sceneUv(in highp vec3 worldPos) {\n"
3162 " highp vec4 clip = u_projection * vec4(worldPos, 1.0);\n"
3163 " return clamp(clip.xy / max(clip.w, 1e-4) * 0.5 + 0.5, vec2(0.001), vec2(0.999));\n"
3164 "}\n"
3165 "highp float sceneDistance(in highp vec4 texel) {\n"
3166 " return texel.r < 65000.0 ? texel.r : texel.b * 1024.0;\n"
3167 "}\n";
3168 assembled << kFrameHeader;
3169 headerLines += countNewlines(kFrameHeader);
3170
3171 // Engine-owned frame block, injected into every stage (identical in both, so the
3172 // program links). u_time = (elapsed s, delta s, view exposure EV, 0); u_viewport = canvas
3173 // (w, h, 1/w, 1/h) in pixels; binding 3 (Shader::compile).
3174 static const char* kTimeHeader =
3175 "layout(std140) uniform TimeConstants { highp vec4 u_time; highp vec4 u_viewport; highp vec4 u_quality; };\n";
3176 assembled << kTimeHeader;
3177 headerLines += countNewlines(kTimeHeader);
3178
3179 // Auto-generated material params (#pragma param): the std140 MaterialConstants block
3180 // (non-texture params in declared order == std140 offset order) plus sampler uniforms.
3181 // Injected after the #defines so both stages share one block and the body can use the
3182 // params by name. A stage that doesn't reference them just carries an unused block.
3183 // Members carry an explicit `highp` so the block is self-contained: a fragment shader
3184 // has no default float precision until its own `precision` line, which follows this
3185 // injected header — qualifying each member avoids a "no precision specified" error.
3186 if (parsed.materialBlockSize > 0) {
3187 assembled << "layout(std140) uniform MaterialConstants {\n";
3188 ++headerLines;
3189 for (const auto& p : parsed.properties) {
3190 if (!p.fromParam || p.std140Offset < 0) continue;
3191 assembled << " highp " << glslTypeName(p.type) << " " << p.name << ";\n";
3192 ++headerLines;
3193 }
3194 assembled << "};\n";
3195 ++headerLines;
3196 }
3197 for (const auto& p : parsed.properties) {
3198 if (p.fromParam && p.type == ShaderPropertyType::Texture) {
3199 assembled << (p.layered ? "uniform highp sampler2DArray " : "uniform highp sampler2D ") << p.name << ";\n";
3200 ++headerLines;
3201 }
3202 }
3203
3204 // Lit domain: inject the shared LightConstants block (std140) + the applyLighting2D()
3205 // helper into the fragment stage. Authors write the surface (albedo) and a world-position
3206 // varying, then call the helper — the engine owns the std140 layout so a hand-written struct
3207 // can't silently mismatch renderer/LightConstants.hpp and corrupt lighting. Members + locals
3208 // carry explicit highp for the same reason MaterialConstants does: a fragment shader has no
3209 // default float precision until its `precision` line, which follows this injected header.
3210
3211 if (stage == ShaderStage::Vertex) {
3212 // Every vertex stage, not only the Lit ones: an unlit mesh reads the same
3213 // record. Spelled twice because the twin generator compiles this under
3214 // Vulkan semantics, where gl_InstanceID does not exist.
3215 assembled << "#ifdef VULKAN\n"
3216 "#define ES_INSTANCE_ID gl_InstanceIndex\n"
3217 "#else\n"
3218 "#define ES_INSTANCE_ID gl_InstanceID\n"
3219 "#endif\n";
3220 headerLines += 5;
3221 // The records themselves, for a stage that names them. Reached-not-declared
3222 // is how wgslReachedTextureDecls decides the same question: one author for
3223 // the declaration, rather than a copy in every shader that reads a record.
3224 if (namesRecords(stageIt->second)) {
3225 const std::string decl = instanceRecordGLSLDecls();
3226 assembled << decl;
3227 headerLines += static_cast<u32>(std::count(decl.begin(), decl.end(), '\n'));
3228 }
3229 }
3230 // Declared by every Lit vertex because every Lit fragment takes it in. One
3231 // that never fills it reads slot 0 (the fragment clamps), not garbage.
3232 if (stage == ShaderStage::Vertex && parsed.domain == "Lit") {
3233 assembled << "flat out highp float v_probeSlot;\n";
3234 headerLines += 1;
3235 }
3236
3237 // The light-array size and packing here MUST match renderer/LightConstants.hpp (MAX_LIGHTS,
3238 // GpuLight = four vec4s).
3239 if (stage == ShaderStage::Fragment && parsed.domain == "Lit") {
3240 static const char* kLitHeader =
3241 "struct Light { highp vec4 posDir; highp vec4 color; highp vec4 spot; highp vec4 shadow;"
3242 " highp vec4 shadowMap; highp vec4 falloff; };\n"
3243 "layout(std140) uniform LightConstants {\n"
3244 " highp vec4 u_ambient;\n"
3245 " Light u_lights[16];\n"
3246 " highp vec4 u_mask2DRect;\n" // xy = this camera's corner of a mask, zw its size
3247 " highp mat4 u_shadowMatrix[16];\n" // world -> each atlas tile's clip
3248 " highp vec4 u_shadowTile[16];\n" // xy = origin, z = side, w = bias
3249 " highp vec4 u_shadowParams;\n" // x = has map, y = one atlas texel
3250 " highp vec4 u_envIrradiance[9];\n" // SH9, rgb in xyz; zero = no environment
3251 " highp vec4 u_envParams;\n" // x = has map, y = range, z = maxLod, w = face
3252 " highp vec4 u_envTint;\n" // the ambient light's colour, scaling both halves
3253 " highp vec4 u_reflParams;\n" // x = columns in the bound atlas (1 = sky only)
3254 " highp vec4 u_reflBox[30];\n" // [2i] = column i+1's world min, [2i+1] its max
3255 " highp vec4 u_bakedTint;\n" // what baked indirect light is multiplied by
3256 " Light u_tiledLights[96];\n"
3257 " highp uvec4 u_tileMask[192];\n"
3258 " highp vec4 u_tileInfo;\n"
3259 " highp vec4 u_ambientGround;\n"
3260 " highp mat4 u_tileView;\n"
3261 " highp vec4 u_waterRect, u_waterDepth, u_waterSun;\n"
3262 "};\n"
3263 // One run of nine per INSTANCE, not one for the draw: a merged draw
3264 // holds objects standing in many places. The flag in w tells "no
3265 // volume" from "a probe in the dark".
3266 "layout(std140) uniform ProbeConstants {\n"
3267 " highp vec4 u_probeIrradiance[10 * 100];\n"
3268 " highp vec4 u_probeTail;\n" // see PROBE_BLOCK_BYTES
3269 "};\n"
3270 "layout(std140) uniform PlanarConstants {\n"
3271 " highp mat4 u_planarProjection; highp vec4 u_planarParams;\n"
3272 "};\n"
3273 "flat in highp float v_probeSlot;\n"
3274 // The frame's probe atlas, a volume of bricks read per pixel; a variant reading a bake has that sampler on this
3275 // unit, and only resident 3D surfaces carry the runs that read it — a 2D draw's batch samplers own its unit.
3276 "#ifdef ES_SURFACE_3D\n"
3277 "#ifndef MESH_LIGHTMAP\n"
3278 "uniform highp sampler3D u_probeGrid;\n"
3279 "#endif\n"
3280 "#endif\n"
3281 // Where the surface being lit stands, for that read: set by whatever lights it (the BRDF, envRadiance).
3282 "highp vec3 g_probePos = vec3(0.0);\n"
3283 // The shadow map rides the draw's third texture slot, behind the feature the
3284 // MESH vertex sources set: the batch stream owns 0..7 as a per-vertex merge
3285 // product, so a sampler pinned to slot 2 there would read someone's sprite.
3286 "#ifdef ES_RECEIVE_SHADOW\n"
3287 "uniform highp sampler2D u_shadowMap;\n"
3288 "#endif\n"
3289 "#ifdef ES_ENV_MAP\n"
3290 "uniform highp sampler2D u_envMap;\n"
3291 "#endif\n"
3292 // The 2D shadow mask, on the top slot of the batch stream's eight, and the
3293 // light-shape mask one below it. Declared for every Lit shader: a sprite
3294 // receives 2D shadows, and a mesh standing in the same scene receives them.
3295 "uniform highp sampler2D u_shadow2D;\n"
3296 "uniform highp sampler2D u_lightShape2D;\n"
3297 // 24 bits of depth across RGB — an 8-bit target is what both backends have
3298 // in common, and a metre of world depth does not survive 8 of them. The
3299 // pair lives together: two files would be two chances to disagree.
3300 "highp vec3 packDepth(in highp float d) {\n"
3301 " highp vec3 enc = fract(d * vec3(1.0, 255.0, 65025.0));\n"
3302 " return enc - enc.yzz * vec3(1.0 / 255.0, 1.0 / 255.0, 0.0);\n"
3303 "}\n"
3304 "highp float unpackDepth(in highp vec3 c) {\n"
3305 " return dot(c, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));\n"
3306 "}\n"
3307 // How far toward the light a lookup has to ask from: one texel of doubt about
3308 // where the map sampled this surface, plus whatever `reach` texels of it are
3309 // worth at the angle it stands.
3310 "highp float stepFor(in highp float texel, in highp float slope,\n"
3311 " in highp float reach) {\n"
3312 " return texel * (1.5 * (1.0 + slope) + reach * slope);\n"
3313 "}\n"
3314 "highp float shadowDepth(in highp mat4 m, in highp vec3 p) {\n"
3315 " highp vec4 c = m * vec4(p, 1.0);\n"
3316 " return clamp(c.z / max(c.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);\n"
3317 "}\n"
3318 // A tap that leaves its tile reads another map entirely — a neighbouring
3319 // cube face, which is the least related depth in the atlas.
3320 "highp float shadowTap(in highp vec2 at, in highp vec2 lo, in highp vec2 hi,\n"
3321 " in highp float here) {\n"
3322 "#ifdef ES_RECEIVE_SHADOW\n"
3323 " return unpackDepth(texture(u_shadowMap, clamp(at, lo, hi)).rgb) < here\n"
3324 " ? 0.0 : 1.0;\n"
3325 "#else\n"
3326 " return 1.0;\n"
3327 "#endif\n"
3328 "}\n"
3329 // Set by a hair shader before it lights: how much of the light a layer of strands takes, per world unit along it.
3330 "highp float g_hairShadow = 0.0;\n"
3331 // See the WGSL twin: a shader sets it before it lights to take the shadow as one hard edge.
3332 "highp float g_shadowHard = 0.0;\n"
3333 // A spiral, not a table: the golden angle spreads any number of taps evenly
3334 // over a disc, so the pattern follows the count instead of sitting beside it.
3335 "highp vec2 diskTap(in int i, in int n, in highp float radius) {\n"
3336 " highp float a = float(i) * 2.3999632;\n"
3337 " return radius * sqrt((float(i) + 0.5) / float(n)) * vec2(cos(a), sin(a));\n"
3338 "}\n"
3339 // The spiral turned point by point, so a wide penumbra grains instead of banding: see the WGSL twin.
3340 "highp vec2 diskTapSpun(in int i, in int n, in highp float radius, in highp float spin) {\n"
3341 " highp float a = float(i) * 2.3999632 + spin;\n"
3342 " return radius * sqrt((float(i) + 0.5) / float(n)) * vec2(cos(a), sin(a));\n"
3343 "}\n"
3344 "highp float shadowSpin(in highp vec3 worldPos) {\n"
3345 " return 6.2831853 * fract(sin(dot(worldPos, vec3(12.9898, 78.233, 37.719))) * 43758.5453);\n"
3346 "}\n"
3347 "// The spiral taps for 16 and 32 points, as numbers: the cos, the sin and the root of each tap do not change from one pixel to the next, so they are\n"
3348 "// not worked out in the pixel (a sin, a cos and a sqrt a tap, forty-eight taps). Each is turned by the pixel's own spin where it is used.\n"
3349 "const highp vec2 kInner5[5] = vec2[5](vec2(0.0), vec2(1.5, 0.0), vec2(-1.5, 0.0), vec2(0.0, 1.5), vec2(0.0, -1.5));\n"
3350 "const highp vec2 kSpiral8[8] = vec2[8](\n"
3351 " vec2(0.2500000, 0.0000000),\n"
3352 " vec2(-0.3192901, 0.2924959),\n"
3353 " vec2(0.0488724, -0.5568765),\n"
3354 " vec2(0.4024445, 0.5249175),\n"
3355 " vec2(-0.7385351, -0.1306364),\n"
3356 " vec2(0.6996049, -0.4450315),\n"
3357 " vec2(-0.2340040, 0.8704838),\n"
3358 " vec2(-0.4462715, -0.8592682));\n"
3359 "const highp vec2 kSpiral16[16] = vec2[16](\n"
3360 " vec2(0.1767767, 0.0000000),\n"
3361 " vec2(-0.2257722, 0.2068258),\n"
3362 " vec2(0.0345580, -0.3937712),\n"
3363 " vec2(0.2845713, 0.3711727),\n"
3364 " vec2(-0.5222232, -0.0923739),\n"
3365 " vec2(0.4946953, -0.3146848),\n"
3366 " vec2(-0.1654658, 0.6155250),\n"
3367 " vec2(-0.3155616, -0.6075943),\n"
3368 " vec2(0.6846422, 0.2500301),\n"
3369 " vec2(-0.7122560, 0.2940091),\n"
3370 " vec2(0.3433543, -0.7337287),\n"
3371 " vec2(0.2537305, 0.8089319),\n"
3372 " vec2(-0.7647461, -0.4431856),\n"
3373 " vec2(0.8971339, -0.1972327),\n"
3374 " vec2(-0.5475066, 0.7787725),\n"
3375 " vec2(-0.1264872, -0.9760896));\n"
3376 "const highp vec2 kSpiral32[32] = vec2[32](\n"
3377 " vec2(0.1250000, 0.0000000),\n"
3378 " vec2(-0.1596450, 0.1462479),\n"
3379 " vec2(0.0244362, -0.2784383),\n"
3380 " vec2(0.2012223, 0.2624588),\n"
3381 " vec2(-0.3692676, -0.0653182),\n"
3382 " vec2(0.3498024, -0.2225157),\n"
3383 " vec2(-0.1170020, 0.4352419),\n"
3384 " vec2(-0.2231357, -0.4296341),\n"
3385 " vec2(0.4841152, 0.1767979),\n"
3386 " vec2(-0.5036411, 0.2078959),\n"
3387 " vec2(0.2427881, -0.5188246),\n"
3388 " vec2(0.1794146, 0.5720012),\n"
3389 " vec2(-0.5407571, -0.3133795),\n"
3390 " vec2(0.6343695, -0.1394646),\n"
3391 " vec2(-0.3871456, 0.5506753),\n"
3392 " vec2(-0.0894400, -0.6901996),\n"
3393 " vec2(0.5490720, 0.4627580),\n"
3394 " vec2(-0.7388785, 0.0305553),\n"
3395 " vec2(0.5389548, -0.5363326),\n"
3396 " vec2(-0.0360577, 0.7797915),\n"
3397 " vec2(-0.5128179, -0.6145265),\n"
3398 " vec2(0.8123597, 0.1093013),\n"
3399 " vec2(-0.6883103, 0.4789091),\n"
3400 " vec2(0.1880855, -0.8360615),\n"
3401 " vec2(0.4350338, 0.7591907),\n"
3402 " vec2(-0.8504486, -0.2713156),\n"
3403 " vec2(0.8261021, -0.3816809),\n"
3404 " vec2(-0.3578875, 0.8551558),\n"
3405 " vec2(-0.3194081, -0.8880335),\n"
3406 " vec2(0.8499090, 0.4466874),\n"
3407 " vec2(-0.9440344, 0.2488453),\n"
3408 " vec2(0.5365950, -0.8345303));\n"
3409 // What of the sun a sky's clouds leave at a world point, from the tile the sky drew it into before the scene (RenderFrame's cloud
3410 // shadow tile): its alpha, between texels, as the map is coarse and its texels are nearest-sampled. Outside the square, all of it.
3411 "highp float cloudShadow3D(in highp vec3 worldPos, in int t) {\n"
3412 "#ifndef ES_RECEIVE_SHADOW\n"
3413 " return 1.0;\n"
3414 "#else\n"
3415 " highp vec2 uv = (u_shadowMatrix[t] * vec4(worldPos, 1.0)).xy * 0.5 + 0.5;\n"
3416 " if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) return 1.0;\n"
3417 " highp vec4 rect = u_shadowTile[t];\n"
3418 " highp float texel = u_shadowParams.y;\n"
3419 " highp vec2 p = (rect.xy + uv * rect.z) / texel - 0.5;\n"
3420 " highp vec2 f = fract(p);\n"
3421 " highp vec2 at = (floor(p) + 0.5) * texel;\n"
3422 " highp vec2 lo = rect.xy + texel * 0.5;\n"
3423 " highp vec2 hi = rect.xy + rect.z - texel * 0.5;\n"
3424 " highp float a = textureLod(u_shadowMap, clamp(at, lo, hi), 0.0).a;\n"
3425 " highp float b = textureLod(u_shadowMap, clamp(at + vec2(texel, 0.0), lo, hi), 0.0).a;\n"
3426 " highp float c = textureLod(u_shadowMap, clamp(at + vec2(0.0, texel), lo, hi), 0.0).a;\n"
3427 " highp float d = textureLod(u_shadowMap, clamp(at + vec2(texel), lo, hi), 0.0).a;\n"
3428 " return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);\n"
3429 "#endif\n"
3430 "}\n"
3431 // Visibility of a world point from the light that rendered the map. Depth is
3432 // written and compared through the SAME matrix and expression, so the two
3433 // backends' clip-z conventions cancel. 2x2 taps: one is a staircase.
3434 "highp float shadowFactor3D(in highp vec3 worldPos, in highp vec3 N, in highp vec3 L,\n"
3435 " in highp vec2 source, in int first, in int count) {\n"
3436 "#ifndef ES_RECEIVE_SHADOW\n"
3437 " return 1.0;\n"
3438 "#else\n"
3439 " if (u_shadowParams.x < 0.5) return 1.0;\n"
3440 // How steeply the surface stands to the light: one texel covers a patch of
3441 // it, and the steeper the patch the further apart its ends are. Clamped,
3442 // because edge-on is a tangent that runs away.
3443 " highp float NoL = clamp(dot(N, L), 0.0, 1.0);\n"
3444 // Nearest tile first: a light's tiles overlap, and the first one covering
3445 // a fragment is the one that spends the most texels on it.
3446 " for (int k = 0; k < 16; ++k) {\n"
3447 " if (k >= count) break;\n"
3448 " int t = first + k;\n"
3449 " highp mat4 m = u_shadowMatrix[t];\n"
3450 " highp vec4 lc = m * vec4(worldPos, 1.0);\n"
3451 // Behind the light, where a divide by a negative w mirrors the point into
3452 // the map's own square and shadows it against whatever the light sees the
3453 // other way. A cube's six faces have five of themselves behind each one.
3454 " if (lc.w <= 0.0) continue;\n"
3455 " highp vec3 proj = lc.xyz / lc.w;\n"
3456 " highp vec2 uv = proj.xy * 0.5 + 0.5;\n"
3457 // Outside every tile is lit: darkening what a map does not cover would be a
3458 // visible square of night. Depth counts as outside as much as the square
3459 // does — both matrices run z over [0, 1], so past either end is unseen.
3460 " if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0\n"
3461 " || proj.z < 0.0 || proj.z > 1.0) continue;\n"
3462 // The tile's rect is data, so a tile need not be the same size as its
3463 // neighbour and this expression does not care which one it is reading.
3464 " highp vec4 rect = u_shadowTile[t];\n"
3465 " highp float biasTexels = floor(rect.w);\n"
3466 " highp vec2 bias = vec2(biasTexels * (1.0 / 64.0), rect.w - biasTexels);\n"
3467 " highp float slope = sqrt(1.0 - NoL * NoL) / max(NoL, bias.y);\n"
3468 // One texel of this tile in WORLD units where this fragment stands: the
3469 // matrix's x scale is clip per world, w how far away this is (1 where the map
3470 // has no eye), and the rect over one atlas texel how many texels it holds.
3471 " highp float texels = max(rect.z / max(u_shadowParams.y, 1e-9), 1.0);\n"
3472 " highp float across = length(vec3(m[0][0], m[1][0], m[2][0]));\n"
3473 " highp float texel = 2.0 * lc.w / max(across * texels, 1e-9);\n"
3474 // Ask a step toward the light rather than shift the answer: a step in world
3475 // units is the same step whether a map's depth runs linearly with distance or
3476 // hyperbolically, which is what lets one expression serve a cascade and a cone.
3477 " highp float lean = min(slope, 1.2);\n"
3478 " highp float biasStep = texel * bias.x;\n"
3479 " highp vec3 aside = worldPos + N * (biasStep * max(sqrt(1.0 - NoL * NoL) - lean * NoL, 0.0));\n"
3480 " highp vec4 lcq = m * vec4(aside, 1.0);\n"
3481 " highp vec2 uvq = lcq.xy / max(lcq.w, 1e-6) * 0.5 + 0.5;\n"
3482 " highp float here = shadowDepth(m, aside + L * (biasStep * (1.0 + lean)));\n"
3483 " highp vec2 at0 = rect.xy + uvq * rect.z;\n"
3484 " highp vec2 lo = rect.xy + u_shadowParams.y * 0.5;\n"
3485 " highp vec2 hi = rect.xy + rect.z - u_shadowParams.y * 0.5;\n"
3486 // How wide the source is in the unit this map measures depth in: world units
3487 // where its w varies with position, so it has an eye to measure them from, and
3488 // the tangent of the angle it subtends where its w is 1 everywhere.
3489 " bool hasEye = length(vec3(m[0][3], m[1][3], m[2][3])) > 0.5;\n"
3490 " highp float src = hasEye ? source.x : source.y;\n"
3491 "#ifndef ES_LIGHT_DIRECT\n"
3492 // Hair: the light left after a depth of strand layers falls off with that depth, from the nearest card (what the map holds) to this one.
3493 // A blocker within a couple of texels toward the light is this card's own surface and does not count.
3494 " if (g_hairShadow > 0.0) {\n"
3495 " highp float reachHair = shadowDepth(m, worldPos + L * stepFor(texel, slope, 2.0));\n"
3496 " highp float sumHair = 0.0;\n"
3497 " highp float hitsHair = 0.0;\n"
3498 " for (int i = 0; i < 8; ++i) {\n"
3499 " highp vec2 at = clamp(at0 + diskTap(i, 8, 2.0) * u_shadowParams.y, lo, hi);\n"
3500 " highp float d = unpackDepth(texture(u_shadowMap, at).rgb);\n"
3501 " if (d < reachHair) { sumHair += d; hitsHair += 1.0; }\n"
3502 " }\n"
3503 " if (hitsHair < 0.5) return 1.0;\n"
3504 " highp float Ah = length(vec3(m[0][2], m[1][2], m[2][2]));\n"
3505 " highp float zbh = 2.0 * (sumHair / hitsHair) - 1.0;\n"
3506 " highp float spanHair = (proj.z - zbh) / max(Ah, 1e-9);\n"
3507 " if (hasEye) spanHair = lc.w - lc.w * (Ah - proj.z) / max(Ah - zbh, 1e-6);\n"
3508 " return mix(1.0, exp(-g_hairShadow * max(spanHair, 0.0)), hitsHair * 0.125);\n"
3509 " }\n"
3510 "#endif\n"
3511 // A source with no size throws one edge: a tent over the 3x3 texels around the
3512 // point, weighted by where it falls among them. Equal weights step at every
3513 // texel and the map's grid shows along the edge; a 2x2 still stair-steps it.
3514 "#ifdef ES_LIGHT_DIRECT\n"
3515 " if (true) {\n"
3516 "#else\n"
3517 " if (src <= 0.0 || g_shadowHard > 0.5) {\n"
3518 "#endif\n"
3519 " highp float texelUv = u_shadowParams.y;\n"
3520 " highp vec2 f = at0 / texelUv - 1.0;\n"
3521 " highp vec2 c = (floor(f) + 0.5) * texelUv;\n"
3522 " highp vec2 t = fract(f);\n"
3523 " highp vec3 wx = vec3((1.0 - t.x) * 0.5, 0.5, t.x * 0.5);\n"
3524 " highp vec3 wy = vec3((1.0 - t.y) * 0.5, 0.5, t.y * 0.5);\n"
3525 " highp float lit = 0.0;\n"
3526 " for (int y = 0; y < 3; ++y) {\n"
3527 " for (int x = 0; x < 3; ++x) {\n"
3528 " lit += wx[x] * wy[y] * shadowTap(c + vec2(float(x), float(y)) * texelUv,\n"
3529 " lo, hi, here);\n"
3530 " }\n"
3531 " }\n"
3532 " return lit;\n"
3533 " }\n"
3534 "#ifndef ES_LIGHT_DIRECT\n"
3535 // What blocks this fragment, over the whole disc an edge can reach across —
3536 // against a depth that forgives that reach, since a tap r texels out lands r
3537 // texels along the surface and a one-texel bias would call the slope one.
3538 // Each tap forgives as far as it stands from the point: see the WGSL twin.
3539 " highp float spin = shadowSpin(worldPos);\n"
3540 " highp vec2 turn = vec2(cos(spin), sin(spin));\n"
3541 " // The depth a tap forgives to is that of the point a step toward the light, and the step is linear in how far the tap stands: so the\n"
3542 " // matrix is applied to the direction once, and a tap moves the clip position along it instead of going through the matrix again.\n"
3543 " highp vec4 toLight = m * vec4(L, 0.0);\n"
3544 " highp float stepBase = biasStep * (1.0 + lean);\n"
3545 " highp float stepPer = texel * slope;\n"
3546 " highp float sum = 0.0;\n"
3547 " highp float hits = 0.0;\n"
3548 " for (int i = 0; i < 5; ++i) {\n"
3549 " highp vec2 p = kInner5[i];\n"
3550 " highp vec2 off = vec2(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);\n"
3551 " highp vec2 at = clamp(at0 + off * u_shadowParams.y, lo, hi);\n"
3552 " highp float d = unpackDepth(texture(u_shadowMap, at).rgb);\n"
3553 " highp vec4 cr = lcq + toLight * (stepBase + max(length(off), 1.0) * stepPer);\n"
3554 " highp float reach = clamp(cr.z / max(cr.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);\n"
3555 " if (d < reach) { sum += d; hits += 1.0; }\n"
3556 " }\n"
3557 " bool fewBlockers = u_quality.y > 0.0 && u_quality.y < 12.0;\n"
3558 " highp float disc = u_quality.w > 0.0 ? max(u_quality.w, 0.5) : 24.0;\n"
3559 " if (fewBlockers) {\n"
3560 " for (int i = 0; i < 8; ++i) {\n"
3561 " highp vec2 p = kSpiral8[i];\n"
3562 " highp vec2 off = disc * vec2(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);\n"
3563 " highp vec2 at = clamp(at0 + off * u_shadowParams.y, lo, hi);\n"
3564 " highp float d = unpackDepth(texture(u_shadowMap, at).rgb);\n"
3565 " highp vec4 cr = lcq + toLight * (stepBase + max(length(off), 1.0) * stepPer);\n"
3566 " highp float reach = clamp(cr.z / max(cr.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);\n"
3567 " if (d < reach) { sum += d; hits += 1.0; }\n"
3568 " }\n"
3569 " } else {\n"
3570 " for (int i = 0; i < 16; ++i) {\n"
3571 " highp vec2 p = kSpiral16[i];\n"
3572 " highp vec2 off = disc * vec2(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);\n"
3573 " highp vec2 at = clamp(at0 + off * u_shadowParams.y, lo, hi);\n"
3574 " highp float d = unpackDepth(texture(u_shadowMap, at).rgb);\n"
3575 " highp vec4 cr = lcq + toLight * (stepBase + max(length(off), 1.0) * stepPer);\n"
3576 " highp float reach = clamp(cr.z / max(cr.w, 1e-6) * 0.5 + 0.5, 0.0, 1.0);\n"
3577 " if (d < reach) { sum += d; hits += 1.0; }\n"
3578 " }\n"
3579 " }\n"
3580 " if (hits < 0.5) return 1.0;\n"
3581 " if (hits > (fewBlockers ? 12.5 : 20.5)) return 0.0;\n"
3582
3583 // How far the receiver stands beyond what blocks it, and how far from the
3584 // light that blocker is. A is the length of the map's depth row, and each map
3585 // inverts its own with it: hyperbolic where it has an eye, linear where w is 1.
3586 " highp float A = length(vec3(m[0][2], m[1][2], m[2][2]));\n"
3587 " highp float zb = 2.0 * (sum / hits) - 1.0;\n"
3588 " highp float dbw = 1.0;\n"
3589 " highp float span = (proj.z - zb) / max(A, 1e-9);\n"
3590 " if (hasEye) {\n"
3591 " dbw = lc.w * (A - proj.z) / max(A - zb, 1e-6);\n"
3592 " span = lc.w - dbw;\n"
3593 " }\n"
3594 // A source subtending src/dbw at the blocker throws that much penumbra across
3595 // the span beyond it — which is why a shadow hardens as its caster nears what
3596 // it falls on, and why a sun's angle and a lamp's size are one expression.
3597 " highp float radius = clamp(src * span / max(dbw * texel, 1e-4),\n"
3598 " 0.5, disc);\n"
3599 " highp float wide = shadowDepth(m, aside + L * (biasStep * (1.0 + lean) + texel * radius * slope));\n"
3600 " highp float soft = 0.0;\n"
3601 " if (radius < 1.5 || (u_quality.z > 0.0 && u_quality.z < 12.0)) {\n"
3602 " for (int i = 0; i < 8; ++i) {\n"
3603 " highp vec2 p = kSpiral8[i];\n"
3604 " highp vec2 off = radius * vec2(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);\n"
3605 " soft += shadowTap(at0 + off * u_shadowParams.y, lo, hi, wide);\n"
3606 " }\n"
3607 " return soft * (1.0 / 8.0);\n"
3608 " }\n"
3609 " if (radius < 4.0 || (u_quality.z > 0.0 && u_quality.z < 24.0)) {\n"
3610 " for (int i = 0; i < 16; ++i) {\n"
3611 " highp vec2 p = kSpiral16[i];\n"
3612 " highp vec2 off = radius * vec2(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);\n"
3613 " soft += shadowTap(at0 + off * u_shadowParams.y, lo, hi, wide);\n"
3614 " }\n"
3615 " return soft * (1.0 / 16.0);\n"
3616 " }\n"
3617 " for (int i = 0; i < 32; ++i) {\n"
3618 " highp vec2 p = kSpiral32[i];\n"
3619 " highp vec2 off = radius * vec2(p.x * turn.x - p.y * turn.y, p.x * turn.y + p.y * turn.x);\n"
3620 " soft += shadowTap(at0 + off * u_shadowParams.y, lo, hi, wide);\n"
3621 " }\n"
3622 " return soft * (1.0 / 32.0);\n"
3623
3624 "#endif\n"
3625 " }\n"
3626 " return 1.0;\n"
3627 "#endif\n"
3628 "}\n"
3629 // The coverage a cut-out's alpha gives this pixel: glTF's MASK, sharpened to about a pixel for alpha-to-coverage. See the WGSL twin.
3630 "highp float cutoutCoverage(in highp float a, in highp float cutoff, in highp float edge) {\n"
3631 " return (a - cutoff) / max(edge, 1e-4) + 0.5;\n"
3632 "}\n"
3633 // The one normal-map unpack: X and Y from RG, Z rebuilt to unit length, so a
3634 // two-channel map (BC5, or B left at 0) lights like the three-channel one. 2D
3635 // applies it screen-space; a flat surface uses vec3(0,0,1).
3636 "highp vec3 sampleNormal(in highp sampler2D map, in highp vec2 uv) {\n"
3637 " highp vec2 xy = texture(map, uv).xy * 2.0 - 1.0;\n"
3638 " return vec3(xy, sqrt(max(0.0, 1.0 - dot(xy, xy))));\n"
3639 "}\n"
3640 "highp vec3 sampleNormalGrad(in highp sampler2D map, in highp vec2 uv,\n"
3641 " in highp vec2 ddx, in highp vec2 ddy) {\n"
3642 " highp vec2 xy = textureGrad(map, uv, ddx, ddy).xy * 2.0 - 1.0;\n"
3643 " return vec3(xy, sqrt(max(0.0, 1.0 - dot(xy, xy))));\n"
3644 "}\n"
3645 "highp vec3 scaleNormal(in highp vec3 normal, in highp float scale) {\n"
3646 " highp vec3 n = normal * vec3(scale, scale, 1.0);\n"
3647 " return dot(n, n) < 1e-12 ? vec3(0.0, 0.0, 1.0) : normalize(n);\n"
3648 "}\n"
3649 // Tangent frame from screen-space derivatives, so a tangent-space normal
3650 // lands in world space without the geometry carrying a tangent channel —
3651 // which most exported models do not. Degenerate UVs return N unchanged.
3652 // MESH_TANGENTS is asked for only where the vertex stage writes the varying (the canonical stage under MESH_NORMALS, the built-in
3653 // mesh shader when lit): a fragment that declares one its vertex stage lacks fails to link.
3654 "#ifdef MESH_TANGENTS\n"
3655 "in highp vec4 v_worldTangent;\n"
3656 "#endif\n"
3657 "highp vec3 perturbNormal(in highp vec3 N, in highp vec3 worldPos,\n"
3658 " in highp vec2 uv, in highp vec3 tangentNormal) {\n"
3659 "#ifdef MESH_TANGENTS\n"
3660 // The frame the normal map was baked in: the tangent made square to the interpolated normal.
3661 " highp vec3 Tg = normalize(v_worldTangent.xyz - N * dot(N, v_worldTangent.xyz));\n"
3662 " highp vec3 Bg = cross(N, Tg) * v_worldTangent.w;\n"
3663 " return normalize(mat3(Tg, Bg, N) * tangentNormal);\n"
3664 "#else\n"
3665 " highp vec3 dp1 = dFdx(worldPos);\n"
3666 " highp vec3 dp2 = dFdy(worldPos);\n"
3667 " highp vec2 duv1 = dFdx(uv);\n"
3668 " highp vec2 duv2 = dFdy(uv);\n"
3669 " highp vec3 dp2perp = cross(dp2, N);\n"
3670 " highp vec3 dp1perp = cross(N, dp1);\n"
3671 " highp vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;\n"
3672 " highp vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;\n"
3673 // Degenerate against the surface's own scale: m falls with the fourth power
3674 // of distance, so a fixed floor turned normal maps off up close.
3675 " highp float m = max(dot(T, T), dot(B, B));\n"
3676 " highp float scale = max(dot(dp1, dp1), dot(dp2, dp2)) * max(dot(duv1, duv1), dot(duv2, duv2));\n"
3677 " if (!(m > scale * 1e-6)) return N;\n"
3678 " return normalize(mat3(T * inversesqrt(max(dot(T, T), 1e-20)), B * inversesqrt(max(dot(B, B), 1e-20)), N) * tangentNormal);\n"
3679 "#endif\n"
3680 "}\n"
3681 // Where a world point lands in this camera's part of a screen-space mask.
3682 // Measured on the Z = 0 plane, which is the plane a 2D occluder hides things
3683 // in, and drawn through this same camera so the landing agrees.
3684 "highp vec2 mask2DUv(in highp vec2 worldPos) {\n"
3685 " highp vec4 clip = u_projection * vec4(worldPos, 0.0, 1.0);\n"
3686 " if (clip.w <= 0.0) return vec2(-1.0);\n"
3687 " highp vec2 ndc = clip.xy / clip.w * 0.5 + 0.5;\n"
3688 " return u_mask2DRect.xy + ndc * u_mask2DRect.zw;\n"
3689 "}\n"
3690 "highp float mask2DChannel(in highp vec4 m, in highp float channel) {\n"
3691 " return (channel < 0.5) ? m.r : (channel < 1.5) ? m.g\n"
3692 " : (channel < 2.5) ? m.b : m.a;\n"
3693 "}\n"
3694 // What the shadow mask says here, for the light holding `channel` (negative
3695 // = one that casts none). An explicit LOD because this is read inside the
3696 // light loop, where a twin's WGSL forbids a sampled derivative.
3697 "highp float shadowFactor2D(in highp float channel, in highp vec2 worldPos) {\n"
3698 " if (channel < 0.0 || u_mask2DRect.z <= 0.0) return 1.0;\n"
3699 " highp vec2 uv = mask2DUv(worldPos);\n"
3700 " if (uv.x < 0.0) return 1.0;\n"
3701 // Clamped, because two walls over one pixel add past one and a light cannot
3702 // be hidden more than entirely.
3703 // Channels 4 to 7 live in the second mask, which takes the shape mask's unit in a frame with no cookie.
3704 " highp float hidden = (channel < 3.5)\n"
3705 " ? mask2DChannel(textureLod(u_shadow2D, uv, 0.0), channel)\n"
3706 " : mask2DChannel(textureLod(u_lightShape2D, uv, 0.0), channel - 4.0);\n"
3707 " return 1.0 - min(hidden, 1.0);\n"
3708 "}\n"
3709 // What the light's own SHAPE covers here — its cookie, drawn into the shape
3710 // mask at the light's place. A light with no shape keeps its whole circle.
3711 "highp float shapeFactor2D(in highp float channel, in highp vec2 worldPos) {\n"
3712 " if (channel < 0.0 || u_mask2DRect.z <= 0.0) return 1.0;\n"
3713 " highp vec2 uv = mask2DUv(worldPos);\n"
3714 " if (uv.x < 0.0) return 1.0;\n"
3715 " return min(mask2DChannel(textureLod(u_lightShape2D, uv, 0.0), channel), 1.0);\n"
3716 "}\n"
3717 // The microfacet terms: GGX distribution, Smith geometry (the direct-light k,
3718 // off perceptual roughness), Schlick fresnel. Guarded denominators, because a
3719 // specular weight of zero must multiply a finite number to reach exactly zero.
3720 "highp float distributionGGX(in highp float NdotH, in highp float a) {\n"
3721 " highp float a2 = a * a;\n"
3722 " highp float d = NdotH * NdotH * (a2 - 1.0) + 1.0;\n"
3723 " return a2 / max(3.14159265 * d * d, 1e-7);\n"
3724 "}\n"
3725 "highp float geometrySmith(in highp float NdotV, in highp float NdotL,\n"
3726 " in highp float roughness) {\n"
3727 " highp float k = (roughness + 1.0) * (roughness + 1.0) * 0.125;\n"
3728 " return (NdotV / (NdotV * (1.0 - k) + k)) * (NdotL / (NdotL * (1.0 - k) + k));\n"
3729 "}\n"
3730 // Height-correlated Smith visibility for GGX: see the WGSL twin.
3731 "highp float visibilitySmithGGX(in highp float NdotV, in highp float NdotL, in highp float a) {\n"
3732 " highp float a2 = a * a;\n"
3733 " highp float gv = NdotL * sqrt(NdotV * NdotV * (1.0 - a2) + a2);\n"
3734 " highp float gl = NdotV * sqrt(NdotL * NdotL * (1.0 - a2) + a2);\n"
3735 " return 0.5 / max(gv + gl, 1e-5);\n"
3736 "}\n"
3737 "highp vec3 fresnelSchlick(in highp float VdotH, in highp vec3 F0) {\n"
3738 " return F0 + (vec3(1.0) - F0) * pow(1.0 - VdotH, 5.0);\n"
3739 "}\n"
3740 // The split-sum environment term of GGX, fitted to the integral by tools/gen-dfg-fit.py. See the WGSL twin.
3741 "highp vec2 envBRDFApprox(in highp float NdotV, in highp float roughness) {\n"
3742 " highp float tx = (2.0 * (clamp(NdotV, 0.02, 1.0) - 0.02) / 0.98 - 1.0);\n"
3743 " highp float ty = 2.0 * clamp(roughness, 0.0, 1.0) - 1.0;\n"
3744 " highp float px0 = 1.0;\n"
3745 " highp float px1 = tx;\n"
3746 " highp float px2 = (3.0 * tx * px1 - 1.0 * px0) / 2.0;\n"
3747 " highp float px3 = (5.0 * tx * px2 - 2.0 * px1) / 3.0;\n"
3748 " highp float px4 = (7.0 * tx * px3 - 3.0 * px2) / 4.0;\n"
3749 " highp float px5 = (9.0 * tx * px4 - 4.0 * px3) / 5.0;\n"
3750 " highp float px6 = (11.0 * tx * px5 - 5.0 * px4) / 6.0;\n"
3751 " highp float py0 = 1.0;\n"
3752 " highp float py1 = ty;\n"
3753 " highp float py2 = (3.0 * ty * py1 - 1.0 * py0) / 2.0;\n"
3754 " highp float py3 = (5.0 * ty * py2 - 2.0 * py1) / 3.0;\n"
3755 " highp float py4 = (7.0 * ty * py3 - 3.0 * py2) / 4.0;\n"
3756 " highp float py5 = (9.0 * ty * py4 - 4.0 * py3) / 5.0;\n"
3757 " highp float py6 = (11.0 * ty * py5 - 5.0 * py4) / 6.0;\n"
3758 " highp float g = 1.0 / (clamp(NdotV, 0.02, 1.0) + 0.1);\n"
3759 " highp float sumMetal = (0.7771111 - 0.2780760 * py1 - 0.0654304 * py2 - 0.0705640 * py3 + 0.0859185 * py4 + 0.0016314 * py5 - 0.0014479 * py6) + px1 * (0.0048182 - 0.1346961 * py1 - 0.1342442 * py2 + 0.1115811 * py3 - 0.0497620 * py4 - 0.0098451 * py5 - 0.0004214 * py6) + px2 * (0.0004797 + 0.0654544 * py1 + 0.0215100 * py2 - 0.0948616 * py3 + 0.0774489 * py4 + 0.0139819 * py5 - 0.0151021 * py6) + px3 * (0.0022918 - 0.0244567 * py1 + 0.0056279 * py2 + 0.0393924 * py3 - 0.0613759 * py4 + 0.0099383 * py5 + 0.0092971 * py6) + px4 * (-0.0025728 + 0.0085869 * py1 - 0.0069877 * py2 - 0.0115072 * py3 + 0.0327063 * py4 - 0.0167796 * py5 + 0.0019107 * py6) + px5 * (0.0018089 - 0.0031015 * py1 + 0.0047701 * py2 + 0.0018675 * py3 - 0.0134691 * py4 + 0.0139776 * py5 - 0.0087024 * py6) + px6 * (-0.0008609 + 0.0010956 * py1 - 0.0024048 * py2 + 0.0005262 * py3 + 0.0035639 * py4 - 0.0080487 * py5 + 0.0080563 * py6) + g * (0.0220605 + 0.0049886 * py1 - 0.0108884 * py2 + 0.0359254 * py3 - 0.0336876 * py4);\n"
3760 " highp float sumDielectric = (0.1105178 - 0.1470108 * py1 + 0.0706290 * py2 - 0.0048613 * py3 - 0.0190413 * py4 + 0.0038142 * py5 - 0.0002643 * py6) + px1 * (-0.1400053 + 0.2220226 * py1 - 0.1204309 * py2 + 0.0033027 * py3 + 0.0348652 * py4 - 0.0115348 * py5 + 0.0015711 * py6) + px2 * (0.0993738 - 0.1696809 * py1 + 0.1055418 * py2 - 0.0166890 * py3 - 0.0245166 * py4 + 0.0153020 * py5 - 0.0048468 * py6) + px3 * (-0.0363361 + 0.0724203 * py1 - 0.0631513 * py2 + 0.0261354 * py3 + 0.0041759 * py4 - 0.0092203 * py5 + 0.0054510 * py6) + px4 * (0.0046882 - 0.0144579 * py1 + 0.0238812 * py2 - 0.0200861 * py3 + 0.0078934 * py4 - 0.0001779 * py5 - 0.0024009 * py6) + px5 * (0.0013258 - 0.0006506 * py1 - 0.0049831 * py2 + 0.0084229 * py3 - 0.0075026 * py4 + 0.0046720 * py5 - 0.0007627 * py6) + px6 * (-0.0005364 + 0.0008141 * py1 + 0.0002790 * py2 - 0.0016584 * py3 + 0.0027280 * py4 - 0.0028646 * py5 + 0.0010557 * py6) + g * (-0.0075790 + 0.0243928 * py1 - 0.0212081 * py2 + 0.0063496 * py3 + 0.0036408 * py4);\n"
3761 " highp float scale = (sumMetal - sumDielectric) / 0.96;\n"
3762 " return vec2(scale, sumMetal - scale);\n"
3763 "}\n"
3764 // The WGSL twin's envDirection, for the same reason.
3765 "highp vec3 envDirection(in highp vec3 d) {\n"
3766 " highp float a = -u_envTint.a;\n"
3767 " highp float s = sin(a);\n"
3768 " highp float c = cos(a);\n"
3769 " return vec3(c * d.x + s * d.z, d.y, -s * d.x + c * d.z);\n"
3770 "}\n"
3771 // Nine coefficients at a normal. One expression: an environment and a
3772 // probe volume differ in where the nine came from, not in what they mean.
3773 "highp vec3 shIrradiance(in highp vec4 sh[9], in highp vec3 N) {\n"
3774 " return sh[0].rgb * 0.282095\n"
3775 " + sh[1].rgb * (0.488603 * N.y)\n"
3776 " + sh[2].rgb * (0.488603 * N.z)\n"
3777 " + sh[3].rgb * (0.488603 * N.x)\n"
3778 " + sh[4].rgb * (1.092548 * N.x * N.y)\n"
3779 " + sh[5].rgb * (1.092548 * N.y * N.z)\n"
3780 " + sh[6].rgb * (0.315392 * (3.0 * N.z * N.z - 1.0))\n"
3781 " + sh[7].rgb * (1.092548 * N.x * N.z)\n"
3782 " + sh[8].rgb * (0.546274 * (N.x * N.x - N.y * N.y));\n"
3783 "}\n"
3784 // The environment's diffuse half. With no environment the coefficients
3785 // are zero and this IS the flat ambient term, which keeps every existing
3786 // scene pixel-identical rather than merely close.
3787 // A hemisphere light moves the flat term by which way this faces in the world, and by nothing with none.
3788 "highp vec3 ambientFacing(in highp vec3 dir) {\n"
3789 " return u_ambient.rgb + u_ambientGround.rgb * (0.5 - 0.5 * dir.y);\n"
3790 "}\n"
3791 "highp vec3 envIrradiance(in highp vec3 Nw) {\n"
3792 // Read in place, not passed: an array handed to a function is copied, all nine, for every pixel.
3793 " highp vec3 N = envDirection(Nw);\n"
3794 " highp vec3 sh = u_envIrradiance[0].rgb * 0.282095\n"
3795 " + u_envIrradiance[1].rgb * (0.488603 * N.y)\n"
3796 " + u_envIrradiance[2].rgb * (0.488603 * N.z)\n"
3797 " + u_envIrradiance[3].rgb * (0.488603 * N.x)\n"
3798 " + u_envIrradiance[4].rgb * (1.092548 * N.x * N.y)\n"
3799 " + u_envIrradiance[5].rgb * (1.092548 * N.y * N.z)\n"
3800 " + u_envIrradiance[6].rgb * (0.315392 * (3.0 * N.z * N.z - 1.0))\n"
3801 " + u_envIrradiance[7].rgb * (1.092548 * N.x * N.z)\n"
3802 " + u_envIrradiance[8].rgb * (0.546274 * (N.x * N.x - N.y * N.y));\n"
3803 " return ambientFacing(Nw) + max(sh, vec3(0.0)) * u_envTint.rgb;\n"
3804 "}\n"
3805 // The indirect term every lit surface starts from. A volume REPLACES the
3806 // environment rather than adding to it — a surface has one indirect term
3807 // — and its nine are world-space, so neither rotation nor tint applies.
3808 "highp int probeRun() { return clamp(int(v_probeSlot), 0, 99) * 10; }\n"
3809 // Which column of the atlas this instance reflects. Zero — inside no probe,
3810 // or a draw carrying no run at all — is the environment, which is what every
3811 // surface reflected before there were probes.
3812 "highp float reflectionColumn() { return u_probeIrradiance[probeRun() + 9].x; }\n"
3813 // A run marked 2 says where the grid is, not what it holds (ProbeStore::writeGridRun). P's grid position picks
3814 // an indirection cell, the cell names a brick's first texel and the span of cells the brick covers, and the
3815 // nine coefficients are read at the same place in nine pages, each filtered by the hardware in all three axes.
3816 // A brick holds the probes on its far faces too, so a read never filters into a neighbour.
3817 // rgb is the irradiance toward N, a the sky's visibility.
3818 "#ifdef ES_SURFACE_3D\n"
3819 "#ifndef MESH_LIGHTMAP\n"
3820 "highp vec4 probeGridIrradiance(in highp vec3 N, in highp vec3 P) {\n"
3821 " highp int base = probeRun();\n"
3822 " highp vec4 a = u_probeIrradiance[base + 1];\n"
3823 " highp vec4 b = u_probeIrradiance[base + 2];\n"
3824 " highp vec4 c = u_probeIrradiance[base + 3];\n"
3825 " highp vec4 d = u_probeIrradiance[base + 4];\n"
3826 " highp vec3 last = vec3(a.w, b.w, c.w);\n"
3827 " highp vec3 g = clamp((P - a.xyz) * b.xyz, vec3(0.0), last);\n"
3828 " highp vec3 cell = min(floor(g * 0.25), max(ceil(last * 0.25) - 1.0, vec3(0.0)));\n"
3829 " highp vec4 brick = texelFetch(u_probeGrid, ivec3(c.xyz + cell + 0.5), 0);\n"
3830 " highp vec3 first = floor(cell / brick.w) * brick.w;\n"
3831 " highp vec3 uvw = (brick.xyz + (g - first * 4.0) / brick.w + 0.5) * d.xyz;\n"
3832 " highp float basis[9];\n"
3833 " basis[0] = 0.282095;\n"
3834 " basis[1] = 0.488603 * N.y;\n"
3835 " basis[2] = 0.488603 * N.z;\n"
3836 " basis[3] = 0.488603 * N.x;\n"
3837 " basis[4] = 1.092548 * N.x * N.y;\n"
3838 " basis[5] = 1.092548 * N.y * N.z;\n"
3839 " basis[6] = 0.315392 * (3.0 * N.z * N.z - 1.0);\n"
3840 " basis[7] = 1.092548 * N.x * N.z;\n"
3841 " basis[8] = 0.546274 * (N.x * N.x - N.y * N.y);\n"
3842 " highp vec4 sum = vec4(0.0);\n"
3843 " for (int i = 0; i < 9; i++) {\n"
3844 " sum += textureLod(u_probeGrid, uvw + vec3(float(i) * d.w * d.x, 0.0, 0.0), 0.0) * basis[i];\n"
3845 " }\n"
3846 " return sum;\n"
3847 "}\n"
3848 "#endif\n"
3849 "#endif\n"
3850 // A bake outranks a volume for the same reason a volume outranks the sky:
3851 // it holds every light and bounce that reached this very point.
3852 // How much of the sky the probe this instance stands among sees toward d: nine coefficients of
3853 // visibility, cosine-convolved like the irradiance, packed in the run's spare channels (the w of
3854 // [1..8], the y of [9]; [9].z says there are any). 1 where none were baked: the sky is open.
3855 "highp float skyOcclusion(in highp vec3 d) {\n"
3856 " highp int base = probeRun();\n"
3857 " highp float v = u_probeIrradiance[base + 9].y * 0.282095\n"
3858 " + u_probeIrradiance[base + 1].w * (0.488603 * d.y)\n"
3859 " + u_probeIrradiance[base + 2].w * (0.488603 * d.z)\n"
3860 " + u_probeIrradiance[base + 3].w * (0.488603 * d.x)\n"
3861 " + u_probeIrradiance[base + 4].w * (1.092548 * d.x * d.y)\n"
3862 " + u_probeIrradiance[base + 5].w * (1.092548 * d.y * d.z)\n"
3863 " + u_probeIrradiance[base + 6].w * (0.315392 * (3.0 * d.z * d.z - 1.0))\n"
3864 " + u_probeIrradiance[base + 7].w * (1.092548 * d.x * d.z)\n"
3865 " + u_probeIrradiance[base + 8].w * (0.546274 * (d.x * d.x - d.y * d.y));\n"
3866 "#ifdef ES_SURFACE_3D\n"
3867 "#ifndef MESH_LIGHTMAP\n"
3868 " if (u_probeIrradiance[base].w > 1.5) v = probeGridIrradiance(d, g_probePos).a;\n"
3869 "#endif\n"
3870 "#endif\n"
3871 " return mix(1.0, clamp(v, 0.0, 1.0), step(0.5, u_probeIrradiance[base + 9].z));\n"
3872 "}\n"
3873 // A grid baked with sky occlusion holds the lights and their bounces WITHOUT the sky; the sky is
3874 // the frame's own (an environment, a live Sky Atmosphere) seen through what the probe sees of it,
3875 // so a room stays dark under a sky that changes.
3876 // ONE exit and no early return, here and in skyOcclusion: HLSL inlines every function, and D3D's compiler
3877 // structures the control flow of what it inlined recursively. Returns from inside branches of the
3878 // functions the light loop and the reflection inline (this one, skyOcclusion, envRadiance) took it past
3879 // its stack and killed the GPU process (0xC00000FD in D3DCompiler_47) on the lightmapped lit variant.
3880 "highp vec3 indirectIrradiance(in highp vec3 N) {\n"
3881 " highp int base = probeRun();\n"
3882 " highp float mode = u_probeIrradiance[base].w;\n"
3883 " highp vec3 result;\n"
3884 "#ifdef ES_SURFACE_3D\n"
3885 "#ifndef MESH_LIGHTMAP\n"
3886 " if (mode > 1.5) {\n"
3887 " highp vec4 grid = probeGridIrradiance(N, g_probePos);\n"
3888 " highp float sky = step(0.5, u_probeIrradiance[base + 9].z);\n"
3889 " result = max(grid.rgb, vec3(0.0)) * u_bakedTint.rgb + envIrradiance(N) * (clamp(grid.a, 0.0, 1.0) * sky);\n"
3890 " } else\n"
3891 "#endif\n"
3892 "#endif\n"
3893 " if (mode > 0.5) {\n"
3894 " highp vec4 sh[9];\n"
3895 " for (int i = 0; i < 9; i++) sh[i] = u_probeIrradiance[base + i];\n"
3896 " highp float sky = step(0.5, u_probeIrradiance[base + 9].z);\n"
3897 " result = max(shIrradiance(sh, N), vec3(0.0)) * u_bakedTint.rgb + envIrradiance(N) * (skyOcclusion(N) * sky);\n"
3898 " } else {\n"
3899 " result = envIrradiance(N);\n"
3900 " }\n"
3901 "#ifdef MESH_LIGHTMAP\n"
3902 " if (v_lightmap.z > 0.5) result = bakedIrradiance() * u_bakedTint.rgb;\n"
3903 "#endif\n"
3904 " return result;\n"
3905 "}\n"
3906 // Direction -> the octahedral unit square, +Y at the centre. The importer's
3907 // octEncode, in the shading language; the two must agree texel for texel.
3908 "highp vec2 octEncode(in highp vec3 d) {\n"
3909 " highp vec2 p = d.xz / max(abs(d.x) + abs(d.y) + abs(d.z), 1e-6);\n"
3910 " if (d.y < 0.0) {\n"
3911 " p = (1.0 - abs(p.yx)) * vec2(p.x >= 0.0 ? 1.0 : -1.0, p.y >= 0.0 ? 1.0 : -1.0);\n"
3912 " }\n"
3913 " return p * 0.5 + 0.5;\n"
3914 "}\n"
3915 // One mip of the prefiltered atlas. The mips stack downward, each face ringed
3916 // by a border texel, so the offset is a closed form rather than a table:
3917 // sum(face >> j, j < mip) = 2*face*(1 - 2^-mip), plus two rows per mip.
3918 "highp vec3 envSampleColumn(in highp vec3 R, in highp float mip,\n"
3919 " in highp float column) {\n"
3920 "#ifndef ES_ENV_MAP\n"
3921 " return vec3(0.0);\n"
3922 "#else\n"
3923 " highp float face = u_envParams.w;\n"
3924 " highp float size = face * exp2(-mip);\n"
3925 " highp float yOff = 2.0 * face * (1.0 - exp2(-mip)) + 2.0 * mip;\n"
3926 " highp float col = face + 2.0;\n"
3927 " highp float atlasW = col * u_reflParams.x;\n"
3928 " highp float atlasH = 2.0 * face * (1.0 - exp2(-(u_envParams.z + 1.0)))\n"
3929 " + 2.0 * (u_envParams.z + 1.0);\n"
3930 // The sky turns with the environment; a baked column does not — it was
3931 // solved in world space, and turning it would spin a room about its middle.
3932 " highp vec2 uv = octEncode(column < 0.5 ? envDirection(R) : R);\n"
3933 // Kept inside this column's own face, border ring included: a tap that
3934 // leaves it reads whatever the sampler's wrap mode says, and the two
3935 // backends do not answer that alike.
3936 " highp vec2 lo = vec2(column * col + 0.5, yOff + 0.5);\n"
3937 " highp vec2 hi = vec2(column * col + size + 1.5, yOff + size + 1.5);\n"
3938 " highp vec2 px = clamp(vec2(column * col + 1.0 + uv.x * size,\n"
3939 " yOff + 1.0 + uv.y * size), lo, hi);\n"
3940 // Level 0 by name, like the WGSL twin: the atlas stacks its own mips, and
3941 // one the hardware picks mixes neighbouring columns wherever the fold
3942 // makes the derivatives jump.
3943 " highp vec4 t = textureLod(u_envMap, px / vec2(atlasW, atlasH), 0.0);\n"
3944 " return t.rgb * t.rgb * (t.a * t.a * u_envParams.y);\n"
3945 "#endif\n"
3946 "}\n"
3947 "highp vec3 envSampleMip(in highp vec3 R, in highp float mip) {\n"
3948 " return envSampleColumn(R, mip, 0.0);\n"
3949 "}\n"
3950 // Where the reflected ray LEAVES this column's box, aimed from there rather
3951 // than from infinitely far: what makes a reflection slide across a wall as
3952 // the eye moves instead of being painted onto it.
3953 "highp vec3 reflectionDirection(in highp vec3 R, in highp vec3 P,\n"
3954 " in highp float column) {\n"
3955 " if (column < 0.5) return R;\n"
3956 " highp int i = int(column) * 2 - 2;\n"
3957 " highp vec3 lo = u_reflBox[i].xyz;\n"
3958 " highp vec3 hi = u_reflBox[i + 1].xyz;\n"
3959 // Never zero, so a ray parallel to a face divides to an infinity the min
3960 // discards rather than to the NaN that would blacken the pixel.
3961 " highp vec3 d = max(abs(R), vec3(1e-6)) * (step(vec3(0.0), R) * 2.0 - 1.0);\n"
3962 " highp vec3 far = max((hi - P) / d, (lo - P) / d);\n"
3963 " highp float t = min(min(far.x, far.y), far.z);\n"
3964 " if (!(t > 0.0)) return R;\n"
3965 " return (P + R * t) - (lo + hi) * 0.5;\n"
3966 "}\n"
3967 // The environment's specular half, at the roughness asked for. Without a map
3968 // this is the flat ambient term, the same way the diffuse half is.
3969 "highp vec3 envRadiance(in highp vec3 R, in highp float roughness,\n"
3970 " in highp float column, in highp vec3 P) {\n"
3971 " g_probePos = P;\n"
3972 "#ifdef ES_ENV_MAP\n"
3973 " if (u_planarParams.x > 0.5) {\n"
3974 " highp vec4 clip = u_planarProjection * vec4(P, 1.0);\n"
3975 " if (clip.w <= 0.0) return vec3(0.0);\n"
3976 " highp vec2 uv = clip.xy / clip.w * vec2(0.5, 0.5 * u_planarParams.y) + 0.5;\n"
3977 " if (any(lessThan(uv, vec2(0.0))) || any(greaterThan(uv, vec2(1.0)))) return vec3(0.0);\n"
3978 // Blurred by how rough the surface is (see the WGSL twin): a pixel and a half at the least, wider as the roughness grows.
3979 " highp float reach = max(u_planarParams.z * 1.5, roughness * roughness * 0.04);\n"
3980 " highp vec2 r = vec2(reach, reach * u_planarParams.w / u_planarParams.z);\n"
3981 " highp vec2 d = r * 0.7071;\n"
3982 " highp vec3 seen = textureLod(u_envMap, uv, 0.0).rgb * 0.2\n"
3983 " + (textureLod(u_envMap, clamp(uv + vec2(r.x, 0.0), 0.0, 1.0), 0.0).rgb\n"
3984 " + textureLod(u_envMap, clamp(uv - vec2(r.x, 0.0), 0.0, 1.0), 0.0).rgb\n"
3985 " + textureLod(u_envMap, clamp(uv + vec2(0.0, r.y), 0.0, 1.0), 0.0).rgb\n"
3986 " + textureLod(u_envMap, clamp(uv - vec2(0.0, r.y), 0.0, 1.0), 0.0).rgb\n"
3987 " + textureLod(u_envMap, clamp(uv + d, 0.0, 1.0), 0.0).rgb\n"
3988 " + textureLod(u_envMap, clamp(uv - d, 0.0, 1.0), 0.0).rgb\n"
3989 " + textureLod(u_envMap, clamp(uv + vec2(d.x, -d.y), 0.0, 1.0), 0.0).rgb\n"
3990 " + textureLod(u_envMap, clamp(uv + vec2(-d.x, d.y), 0.0, 1.0), 0.0).rgb) * 0.1;\n"
3991 // See the WGSL twin: a soft ceiling on the brightest channel, so the hue holds and no edge shows.
3992 " highp float peak = max(seen.r, max(seen.g, seen.b));\n"
3993 " highp float held = peak <= 0.75 ? peak : 0.75 + 0.75 * (1.0 - exp(-(peak - 0.75) / 0.75));\n"
3994 " return seen * (held / max(peak, 1e-4));\n"
3995 " }\n"
3996 "#endif\n"
3997 " if (u_envParams.x < 0.5) return ambientFacing(R);\n"
3998 " highp vec3 dir = reflectionDirection(R, P, column);\n"
3999 " highp float lod = clamp(roughness, 0.0, 1.0) * u_envParams.z;\n"
4000 " highp float lo = floor(lod);\n"
4001 " highp vec3 a = envSampleColumn(dir, lo, column);\n"
4002 " highp vec3 b = envSampleColumn(dir, min(lo + 1.0, u_envParams.z), column);\n"
4003 // A baked column is the WHOLE radiance that reached its probe — the sky,
4004 // the ambient and every bounce. Adding the flat term or the sky's tint on
4005 // top would count the light the capture already saw a second time.
4006 " if (column >= 0.5) {\n"
4007 " highp vec3 baked = mix(a, b, lod - lo);\n"
4008 // What the bake saw, as the weather now says it looks: dimmer, and with less of its colour.
4009 " highp float grey = dot(baked, vec3(0.2126, 0.7152, 0.0722));\n"
4010 " return mix(vec3(grey), baked, u_reflParams.z) * u_reflParams.y;\n"
4011 " }\n"
4012 // The sky's own column, as much of it as the probe sees (1 without a sky-occlusion bake).
4013 " return (u_ambient.rgb + mix(a, b, lod - lo) * u_envTint.rgb) * skyOcclusion(R);\n"
4014 "}\n"
4015 // Where a positional light is, from here, and how far. Real geometry measures
4016 // against the light's own world height; a sprite has no depth of its own and
4017 // keeps the plane's convention of one hovering its falloff radius above it.
4018 // Which definition of "where is the light" this surface is shaded with.
4019 // One with a real third coordinate measures against the light's own; a
4020 // sprite has none, so a light goes on hovering its radius above it.
4021 "#ifdef ES_SURFACE_3D\n"
4022 "highp vec3 lightVector(in highp vec4 pd, in highp vec4 sh, in highp vec3 worldPos) {\n"
4023 " return vec3(pd.xy, sh.z) - worldPos;\n"
4024 "}\n"
4025 "highp float lightDistance(in highp vec3 toLight) { return length(toLight); }\n"
4026 "highp float spotCone(in highp vec4 sp, in highp vec4 sh, in highp vec3 toLight,\n"
4027 " in highp float dist) {\n"
4028 " highp vec3 axis = normalize(vec3(sp.xy, sh.w));\n"
4029 " highp vec3 toFrag = (dist > 0.0001) ? -toLight / dist : axis;\n"
4030 " return smoothstep(sp.w, sp.z, dot(axis, toFrag));\n"
4031 "}\n"
4032 "#else\n"
4033 "highp vec3 lightVector(in highp vec4 pd, in highp vec4 sh, in highp vec3 worldPos) {\n"
4034 " return vec3(pd.xy - worldPos.xy, max(pd.w, 1.0));\n"
4035 "}\n"
4036 "highp float lightDistance(in highp vec3 toLight) { return length(toLight.xy); }\n"
4037 "highp float spotCone(in highp vec4 sp, in highp vec4 sh, in highp vec3 toLight,\n"
4038 " in highp float dist) {\n"
4039 // A cone aimed out of the plane has no axis IN it, and this half of the
4040 // shading has nowhere else to read one, so it keeps lighting the way an
4041 // unrotated spot always has.
4042 " highp vec2 axis = dot(sp.xy, sp.xy) > 1e-8 ? normalize(sp.xy) : vec2(0.0, -1.0);\n"
4043 " highp vec2 toFrag = (dist > 0.0001) ? -toLight.xy / dist : axis;\n"
4044 " return smoothstep(sp.w, sp.z, dot(axis, toFrag));\n"
4045 "}\n"
4046 "#endif\n"
4047 // A light sitting exactly on the surface has no direction to give; the plane's
4048 // convention could never produce one, real positions can. Lighting it along its
4049 // own normal is the limit that approaches from every side.
4050 "highp vec3 towardLight(in highp vec3 toLight, in highp vec3 N) {\n"
4051 " return dot(toLight, toLight) > 1e-8 ? normalize(toLight) : N;\n"
4052 "}\n"
4053 // The ramp from a light's reach down to nothing: fo.x holds it at full out to
4054 // its own radius, fo.y shapes what is left. The exponent is floored because
4055 // pow(0, 0) is 1 — a light that reaches nowhere would light everything.
4056 "highp float distanceFalloff(in highp float dist, in highp float reach,\n"
4057 " in highp vec4 fo) {\n"
4058 " highp float ramp = clamp((reach - dist) / max(reach - fo.x, 1e-4), 0.0, 1.0);\n"
4059 " highp float shaped = pow(ramp, max(fo.y, 1e-3));\n"
4060 // An inverse-square light (fo.y < 0, -fo.y world units to the metre): 1/d^2 in metres, held at 10 cm so a
4061 // surface on the lamp is bright and not infinite, and let go over the reach by (1 - (d/r)^4)^2 — three.js's
4062 // and glTF's window, so a lamp brought over from either lights the same. One exit: this inlines into the light loop.
4063 " highp float metres = dist / max(-fo.y, 1e-4);\n"
4064 " highp float q = dist / max(reach, 1e-4);\n"
4065 " highp float w = clamp(1.0 - q * q * q * q, 0.0, 1.0);\n"
4066 " return fo.y < 0.0 ? w * w / max(metres * metres, 0.01) : shaped;\n"
4067 "}\n"
4068 // What a surface has beyond a base colour and a metal/rough pair: a clear coat over it, a sheen on it, grooves that stretch
4069 // its highlight, light that scatters into it or passes through it, a thin film that tints its reflection. All zero is the
4070 // plain surface (surfaceExtNone), and every term below sits behind a branch on it, so the plain surface pays nothing.
4071 // coat x strength, y perceptual roughness coatN the coat's own normal (the geometric one, not the bump map's)
4072 // sheen rgb colour, a perceptual roughness aniso xyz tangent (unit, across N), w strength -1..1
4073 // scatter rgb colour scattered light takes, a wrap 0..1
4074 // trans x light passing through, y thickness 0..1, z curvature 0..1, w how far the wrap is per channel and curvature-shaped
4075 // film x strength, y film index, z thickness in nm
4076 // misc x dielectric reflectance at normal incidence (0.04 for an index of 1.5)
4077 "#ifdef ES_SURFACE_3D\n"
4078 "void waterIncidentSun(inout Light lamp, highp vec3 position);\n"
4079 "#endif\n"
4080 "struct SurfaceExt {\n"
4081 " highp vec4 coat;\n"
4082 " highp vec4 coatN;\n"
4083 " highp vec4 sheen;\n"
4084 " highp vec4 aniso;\n"
4085 " highp vec4 scatter;\n"
4086 " highp vec4 trans;\n"
4087 " highp vec4 film;\n"
4088 " highp vec4 misc;\n"
4089 " highp vec4 strand;\n"
4090 "};\n"
4091 "SurfaceExt surfaceExtNone(in highp vec3 N) {\n"
4092 " return SurfaceExt(vec4(0.0), vec4(N, 0.0), vec4(0.0), vec4(0.0), vec4(0.0), vec4(0.0), vec4(0.0),\n"
4093 " vec4(0.04, 0.0, 0.0, 0.0), vec4(0.6, 0.0, 0.0, 0.0));\n"
4094 "}\n"
4095 "highp float distributionCharlie(in highp float NdotH, in highp float a) {\n"
4096 " highp float invA = 1.0 / max(a, 1e-3);\n"
4097 " highp float sin2 = max(1.0 - NdotH * NdotH, 0.0078125);\n"
4098 " return (2.0 + invA) * pow(sin2, invA * 0.5) / 6.28318531;\n"
4099 "}\n"
4100 "highp float visibilityNeubelt(in highp float NdotV, in highp float NdotL) {\n"
4101 " return 1.0 / max(4.0 * (NdotL + NdotV - NdotL * NdotV), 1e-4);\n"
4102 "}\n"
4103 "highp float distributionGGXAniso(in highp float at, in highp float ab, in highp float ToH,\n"
4104 " in highp float BoH, in highp float NoH) {\n"
4105 " highp float a2 = at * ab;\n"
4106 " highp vec3 d = vec3(ab * ToH, at * BoH, a2 * NoH);\n"
4107 " highp float b2 = a2 / max(dot(d, d), 1e-7);\n"
4108 " return a2 * b2 * b2 / 3.14159265;\n"
4109 "}\n"
4110 "highp float visibilityGGXAniso(in highp float at, in highp float ab, in highp float ToV, in highp float BoV,\n"
4111 " in highp float ToL, in highp float BoL, in highp float NoV, in highp float NoL) {\n"
4112 " highp float lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV));\n"
4113 " highp float lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL));\n"
4114 " return 0.5 / max(lambdaV + lambdaL, 1e-5);\n"
4115 "}\n"
4116 "highp vec3 filmFresnel(in highp vec3 F, in highp float cosTheta, in highp vec4 film) {\n"
4117 " highp float sinT2 = (1.0 - cosTheta * cosTheta) / (film.y * film.y);\n"
4118 " highp float cosT = sqrt(max(1.0 - sinT2, 0.0));\n"
4119 " highp float opd = 2.0 * film.y * film.z * cosT;\n"
4120 " highp vec3 tint = vec3(0.5) + 0.5 * cos(6.28318531 * opd / vec3(650.0, 510.0, 475.0));\n"
4121 " return clamp(F * mix(vec3(1.0), tint * 2.0, film.x), vec3(0.0), vec3(1.0));\n"
4122 "}\n"
4123 // The body of the per-light loop, a function so that the lights the tiles carry are shaded by the same code as the sixteen.
4124 // The layer of the sprite being lit, as its vertex wrote it (the layer plus 129; 0 when the surface has none to test), and
4125 // whether a light's range of layers, which rides in shadowMap.y above the tile count, takes it in. See packLightLayerRange.
4126 "highp float g_surfaceLayer = 0.0;\n"
4127 "bool lightReachesLayer(in highp float rangeLane) {\n"
4128 " if (rangeLane < 8.0 || g_surfaceLayer < 0.5) return true;\n"
4129 " highp float range = floor(rangeLane / 8.0);\n"
4130 " highp float lo = mod(range, 256.0) - 128.0;\n"
4131 " highp float hi = 127.0 - floor(range / 256.0);\n"
4132 " highp float layer = g_surfaceLayer - 129.0;\n"
4133 " return layer >= lo && layer <= hi;\n"
4134 "}\n"
4135 "void shadeLight(in highp vec4 pd, in highp vec4 col, in highp vec4 sp, in highp vec4 sh, in highp vec4 sm,\n"
4136 " in highp vec4 fo, in highp vec3 N, in highp vec3 V, in highp vec3 worldPos,\n"
4137 " in highp float a, in highp vec3 F0, in highp float NdotV, in highp float specular,\n"
4138 " in highp float roughness, in SurfaceExt ext, inout highp vec3 lit, inout highp vec3 gloss,\n"
4139 " inout highp vec3 extra, in bool shadow3D);\n"
4140 // The lighting model in its general form; a lit 2D surface is its zero
4141 // (metallic 0, roughness 1, specular 0 leaves albedo * NdotL, pixel for pixel
4142 // what this engine has always drawn), so there is one model and not two.
4143 "highp vec3 applyLightingSurfaceBRDF(in highp vec3 diffuse, in highp vec3 F0, in highp vec3 N,\n"
4144 " in highp vec3 worldPos, in highp vec3 V,\n"
4145 " in highp float roughness, in highp float specular,\n"
4146 " in highp float ao, in SurfaceExt ext) {\n"
4147 " g_probePos = worldPos;\n"
4148 // glTF's specularFactor scales the whole lobe, so 0 removes it rather than
4149 // leaving Schlick's grazing-angle rim behind.
4150 " highp float a = max(roughness * roughness, 1e-3);\n"
4151 " highp float NdotV = max(dot(N, V), 1e-4);\n"
4152 // Occlusion darkens the light that arrives from everywhere, which is the
4153 // environment; a surface's own lights are unobstructed by it.
4154 " highp vec3 lit = indirectIrradiance(N) * ao;\n"
4155 " highp vec3 gloss = vec3(0.0);\n"
4156 " highp vec3 extra = vec3(0.0);\n"
4157 // A Light has no third coordinate, so distance stays in the plane and a
4158 // point light's height is its radius. Normal and view are the 3D part.
4159 // As many as are lit: read for a slot nobody uses, a light's six vectors cost more on a phone than the one light shaded.
4160 " int lightCount = int(u_ambient.a);\n"
4161 // Which of them can reach this point at all, from the screen tile it falls in through the view the masks were marked
4162 // through (LightStore::markLoopLights, the masks' upper half): a lamp across the street is not worked out here. A point
4163 // that view does not see finds no tile, and every light is worked out.
4164 " highp uint reach3D = 0xFFFFu;\n"
4165 "#ifdef ES_SURFACE_3D\n"
4166 " if (u_tileInfo.w > 0.5) {\n"
4167 " highp vec4 tileClip = u_tileView * vec4(worldPos, 1.0);\n"
4168 " highp vec2 tileNdc = tileClip.xy / max(tileClip.w, 1e-4);\n"
4169 " if (tileClip.w > 1e-4 && abs(tileNdc.x) <= 1.0 && abs(tileNdc.y) <= 1.0) {\n"
4170 " ivec2 tileCount = ivec2(int(u_tileInfo.y), int(u_tileInfo.z));\n"
4171 " ivec2 tile = clamp(ivec2(floor((tileNdc * 0.5 + 0.5) * vec2(tileCount))), ivec2(0), tileCount - ivec2(1));\n"
4172 " reach3D = u_tileMask[tile.y * tileCount.x + tile.x].w >> 16u;\n"
4173 " }\n"
4174 " }\n"
4175 "#endif\n"
4176 " for (int i = 0; i < lightCount; ++i) {\n"
4177 " if ((reach3D & (1u << uint(i))) == 0u) continue;\n"
4178 " Light lamp = u_lights[i];\n"
4179 "#ifdef ES_SURFACE_3D\n"
4180 " if (u_waterRect.z > 0.0 && float(i) == u_waterSun.z) waterIncidentSun(lamp, worldPos);\n"
4181 "#endif\n"
4182 " shadeLight(lamp.posDir, lamp.color, lamp.spot, lamp.shadow,\n"
4183 " u_lights[i].shadowMap, u_lights[i].falloff, N, V, worldPos, a, F0, NdotV,\n"
4184 " specular, roughness, ext, lit, gloss, extra, true);\n"
4185 " }\n"
4186 "#ifndef ES_LIGHT_DIRECT\n"
4187 // The lights past the sixteen: this pixel's tile is found from where the fragment lands through the camera it was drawn by
4188 // (normalized device coordinates, the same on every backend), and only the lights whose bit is set in its mask are shaded.
4189 " int tiledCount = int(u_tileInfo.x);\n"
4190 " if (tiledCount > 0) {\n"
4191 " highp vec4 tileClip = u_projection * vec4(worldPos, 1.0);\n"
4192 " highp vec2 tileNdc = tileClip.xy / max(tileClip.w, 1e-4);\n"
4193 " ivec2 tileCount = ivec2(int(u_tileInfo.y), int(u_tileInfo.z));\n"
4194 " ivec2 tile = clamp(ivec2(floor((tileNdc * 0.5 + 0.5) * vec2(tileCount))), ivec2(0), tileCount - ivec2(1));\n"
4195 " highp uvec4 mask = u_tileMask[tile.y * tileCount.x + tile.x];\n"
4196 " for (int w = 0; w < 3; ++w) {\n"
4197 " highp uint bits = w == 0 ? mask.x : (w == 1 ? mask.y : mask.z);\n"
4198 " if (bits == 0u) continue;\n"
4199 " for (int b = 0; b < 32; ++b) {\n"
4200 " if ((bits & (1u << uint(b))) == 0u) continue;\n"
4201 " int k = w * 32 + b;\n"
4202 " if (k >= tiledCount) break;\n"
4203 " shadeLight(u_tiledLights[k].posDir, u_tiledLights[k].color, u_tiledLights[k].spot,\n"
4204 " u_tiledLights[k].shadow, u_tiledLights[k].shadowMap, u_tiledLights[k].falloff,\n"
4205 " N, V, worldPos, a, F0, NdotV, specular, roughness, ext, lit, gloss, extra, false);\n"
4206 " }\n"
4207 " }\n"
4208 " }\n"
4209 // The environment, which for this engine is the ambient term: the same
4210 // radiance from every direction. A metal has no diffuse, so without a
4211 // reflection of it a metal is black wherever no light happens to point.
4212 "#endif\n"
4213 " highp vec2 ab = envBRDFApprox(NdotV, roughness);\n"
4214 // Multiple scattering, and the diffuse under the specular: see the WGSL twin.
4215 " highp float Ess = ab.x + ab.y;\n"
4216 " highp vec3 FssEss = F0 * ab.x + ab.y;\n"
4217 " highp vec3 FmsEms = vec3(0.0);\n"
4218 " highp vec3 kd = vec3(1.0);\n"
4219 " if (ext.misc.y <= 0.0 || ext.strand.y > 0.0) {\n"
4220 " highp float Ems = 1.0 - Ess;\n"
4221 " highp vec3 Favg = F0 + (vec3(1.0) - F0) / 21.0;\n"
4222 " FmsEms = FssEss * Favg * Ems / (vec3(1.0) - Ems * Favg);\n"
4223 " gloss *= vec3(1.0) + F0 * (1.0 / max(Ess, 0.05) - 1.0);\n"
4224 " kd = max(vec3(1.0) - (FssEss + FmsEms) * specular, vec3(0.0));\n"
4225 " }\n"
4226 " highp vec3 envR = reflect(-V, N);\n"
4227 " if (ext.aniso.w != 0.0 || ext.misc.y > 0.0) {\n"
4228 " highp vec3 T = ext.aniso.xyz;\n"
4229 " highp vec3 grain = (ext.aniso.w >= 0.0 && ext.misc.y <= 0.0) ? cross(N, T) : T;\n"
4230 " highp vec3 bent = normalize(cross(cross(grain, V), grain));\n"
4231 " envR = reflect(-V, normalize(mix(N, bent, ext.misc.y > 0.0 ? 0.55 : abs(ext.aniso.w))));\n"
4232 " }\n"
4233 " highp vec3 envF = FssEss + FmsEms;\n"
4234 " if (ext.film.x > 0.0) envF = filmFresnel(envF, NdotV, ext.film);\n"
4235 " gloss += envRadiance(envR, roughness, reflectionColumn(), worldPos)\n"
4236 " * (ao * specular)\n"
4237 " * envF;\n"
4238 " highp vec3 base = diffuse * lit * kd + gloss;\n"
4239 " highp float baseScale = 1.0;\n"
4240 " if (ext.coat.x > 0.0) {\n"
4241 " highp float coatNdotV = max(dot(ext.coatN.xyz, V), 1e-4);\n"
4242 " highp vec2 cab = envBRDFApprox(coatNdotV, ext.coat.y);\n"
4243 " highp float coatF0 = ext.coat.z > 0.0 ? ext.coat.z : 0.04;\n"
4244 " highp float Fc = (coatF0 * cab.x + cab.y) * ext.coat.x;\n"
4245 " baseScale *= 1.0 - Fc;\n"
4246 " extra += envRadiance(reflect(-V, ext.coatN.xyz), ext.coat.y, reflectionColumn(), worldPos) * (ao * Fc);\n"
4247 " }\n"
4248 " if (dot(ext.sheen.rgb, vec3(1.0)) > 0.0) {\n"
4249 " highp float sheenAlbedo = 0.2 + 0.3 * ext.sheen.a;\n"
4250 " baseScale *= 1.0 - max(max(ext.sheen.r, ext.sheen.g), ext.sheen.b) * sheenAlbedo;\n"
4251 " extra += ext.sheen.rgb * (indirectIrradiance(N) * ao * sheenAlbedo);\n"
4252 " }\n"
4253 " return base * baseScale + extra;\n"
4254 "}\n"
4255 "highp vec3 applyLightingSurface(in highp vec3 albedo, in highp vec3 N, in highp vec3 worldPos,\n"
4256 " in highp vec3 V, in highp float metallic, in highp float roughness,\n"
4257 " in highp float specular, in highp float ao, in SurfaceExt ext) {\n"
4258 " return applyLightingSurfaceBRDF(albedo * (1.0 - metallic), mix(vec3(ext.misc.x), albedo, metallic),\n"
4259 " N, worldPos, V, roughness, specular, ao, ext);\n"
4260 "}\n"
4261 "highp vec3 applyLightingPBR(in highp vec3 albedo, in highp vec3 N, in highp vec3 worldPos,\n"
4262 " in highp vec3 V, in highp float metallic,\n"
4263 " in highp float roughness, in highp float specular,\n"
4264 " in highp float ao) {\n"
4265 " return applyLightingSurface(albedo, N, worldPos, V, metallic, roughness, specular, ao, surfaceExtNone(N));\n"
4266 "}\n"
4267 "void shadeLight(in highp vec4 pd, in highp vec4 col, in highp vec4 sp, in highp vec4 sh, in highp vec4 sm,\n"
4268 " in highp vec4 fo, in highp vec3 N, in highp vec3 V, in highp vec3 worldPos,\n"
4269 " in highp float a, in highp vec3 F0, in highp float NdotV, in highp float specular,\n"
4270 " in highp float roughness, in SurfaceExt ext, inout highp vec3 lit, inout highp vec3 gloss,\n"
4271 " inout highp vec3 extra, in bool shadow3D) {\n"
4272 // A slot nothing lights from (the block holds sixteen and a scene has one or two): every term below is its colour times
4273 // its intensity, so it adds exactly nothing, but the lobe is worked out for it all the same without this.
4274 " if (col.a == 0.0 || !lightReachesLayer(sm.y)) return;\n"
4275 " highp vec3 L;\n"
4276 " highp float atten;\n"
4277 " highp vec2 target = pd.xy;\n" // shadow-ray aim point (light position by default)
4278 " bool castShadow = true;\n"
4279 " if (pd.z < 0.5) {\n"
4280 " highp vec3 toL = lightVector(pd, sh, worldPos);\n"
4281 " highp float dist = lightDistance(toL);\n"
4282 " atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);\n"
4283 " L = towardLight(toL, N);\n"
4284 " } else if (pd.z < 1.5) {\n"
4285 " atten = 1.0;\n"
4286 // pd.w is the aim's third component here; point/spot spend that slot on radius.
4287 " L = normalize(-vec3(pd.xy, pd.w));\n"
4288 // Directional rays are parallel: aim at a far point toward the light source, opt in via
4289 // a positive march distance, and require a real direction (a zeroed one casts nothing).
4290 " highp vec2 toLight = (dot(pd.xy, pd.xy) > 1e-8) ? normalize(-pd.xy) : vec2(0.0);\n"
4291 " castShadow = sh.y > 0.0 && dot(toLight, toLight) > 0.5;\n"
4292 " target = worldPos.xy + toLight * sh.y;\n"
4293 // The sky's cloud shadow on the sun, where a sky casts one: x is its tile plus one (a directional light has no cone).
4294 " if (sp.x > 0.5) atten *= cloudShadow3D(worldPos, int(sp.x) - 1);\n"
4295 " } else {\n"
4296 " highp vec3 toL = lightVector(pd, sh, worldPos);\n"
4297 " highp float dist = lightDistance(toL);\n"
4298 " atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);\n"
4299 " L = towardLight(toL, N);\n"
4300 " atten *= spotCone(sp, sh, toL, dist);\n"
4301 " }\n"
4302 // A surface facing away from the light, with nothing that takes light from behind (a coat, sheen, scattering, hair),
4303 // gets nothing from it: diffuse and highlight are both its radiance, which is NdotL times the rest. So its shadow is not
4304 // looked up, which is most of what a shadowed light costs a pixel (a soft one searches twenty-one texels before it knows
4305 // anything), and a lamp lights the far side of half of what stands round it.
4306 // Nor does one that does not reach it (past its radius, outside its cone): every term below is times atten.
4307 " if (atten <= 0.0 || (dot(N, L) <= 0.0 && ext.misc.y <= 0.0 && ext.coat.x <= 0.0 && ext.scatter.a <= 0.0\n"
4308 " && dot(ext.sheen.rgb, vec3(1.0)) <= 0.0)) return;\n"
4309 // Only pay for the mask read when the light actually reaches this fragment (skips
4310 // the zeroed/inactive slots and unlit fragments).
4311 "#ifndef ES_LIGHT_DIRECT\n"
4312 " if (col.a > 0.0 && atten > 0.0) {\n"
4313 " atten *= shapeFactor2D(fo.w, worldPos.xy);\n"
4314 " }\n"
4315 " if (castShadow && col.a > 0.0 && atten > 0.0) {\n"
4316 " atten *= mix(1.0, shadowFactor2D(sm.w, worldPos.xy), fo.z);\n"
4317 " }\n"
4318 "#endif\n"
4319 // The tiles this light rendered into, which are its own: a fragment
4320 // tested against every map in the atlas would be darkened by geometry
4321 // seen from somewhere no light reaching it is standing.
4322 // A light the tiles carry has no shadow map (the sixteen are where the lights that cast are), so its call says so and the compiler
4323 // drops the lookup from that copy of this function: a program holds the whole shadow filter once, not twice.
4324 " if (shadow3D && mod(sm.y, 8.0) > 0.0 && atten > 0.0) {\n"
4325 " atten *= mix(1.0, shadowFactor3D(worldPos, N, L, vec2(sh.x, sm.z),\n"
4326 " int(sm.x), int(mod(sm.y, 8.0))), fo.z);\n"
4327 " }\n"
4328 " highp float ndotl = max(dot(N, L), 0.0);\n"
4329 // Hair (misc.y above zero; aniso.xyz is the strand): Kajiya-Kay diffuse, which lights a strand by how far light is from along it.
4330 " if (ext.misc.y > 0.0) {\n"
4331 " highp float along = dot(ext.aniso.xyz, L);\n"
4332 " ndotl = mix(ndotl, sqrt(max(1.0 - along * along, 0.0)) * clamp(dot(N, L) * 0.5 + 0.65, 0.0, 1.0), ext.strand.x);\n"
4333 " }\n"
4334 " highp vec3 radiance = col.rgb * (col.a * ndotl * atten);\n"
4335 " lit += radiance;\n"
4336 // A uniform branch: a surface that reflects nothing does not pay for the lobe. The pi turns the engine's light intensity
4337 // into the irradiance the BRDF wants (the diffuse side cancels it against albedo/pi). Hair has two narrow lobes of its own.
4338 " if (specular > 0.0 && ext.misc.y > 0.0 && ext.strand.y <= 0.0) {\n"
4339 " highp vec3 H = normalize(L + V);\n"
4340 " highp float primaryExp = clamp(2.0 / (a * a), 8.0, 900.0);\n"
4341 " highp vec3 t1 = normalize(ext.aniso.xyz + N * ext.misc.z);\n"
4342 " highp vec3 t2 = normalize(ext.aniso.xyz + N * ext.misc.w);\n"
4343 " highp float h1 = dot(t1, H);\n"
4344 " highp float h2 = dot(t2, H);\n"
4345 " highp float lobe1 = smoothstep(-1.0, 0.0, h1) * pow(sqrt(max(1.0 - h1 * h1, 0.0)), primaryExp);\n"
4346 " highp float lobe2 = smoothstep(-1.0, 0.0, h2) * pow(sqrt(max(1.0 - h2 * h2, 0.0)), primaryExp * 0.3);\n"
4347 " highp vec3 lightOn = col.rgb * (col.a * atten * clamp(dot(N, L) + 0.35, 0.0, 1.0));\n"
4348 " gloss += lightOn * (lobe1 * 0.55 + lobe2 * ext.scatter.rgb * 1.6) * (ext.misc.y * specular);\n"
4349 " } else if (specular > 0.0) {\n"
4350 " highp vec3 H = normalize(L + V);\n"
4351 // Hair with an anisotropy: Principled's anisotropic GGX along the strand. See the WGSL twin.
4352 " highp float brdf;\n"
4353 " if (ext.misc.y > 0.0) {\n"
4354 " highp vec3 T = ext.aniso.xyz;\n"
4355 " highp vec3 B = cross(N, T);\n"
4356 " highp float aspect = sqrt(max(1.0 - 0.9 * ext.strand.y, 0.01));\n"
4357 " highp float at = max(a / aspect, 0.002);\n"
4358 " highp float ab = max(a * aspect, 0.002);\n"
4359 " brdf = distributionGGXAniso(at, ab, dot(T, H), dot(B, H), max(dot(N, H), 0.0))\n"
4360 " * visibilityGGXAniso(at, ab, dot(T, V), dot(B, V), dot(T, L), dot(B, L), NdotV, ndotl);\n"
4361 " } else if (ext.aniso.w != 0.0) {\n"
4362 " highp vec3 T = ext.aniso.xyz;\n"
4363 " highp vec3 B = cross(N, T);\n"
4364 " highp float at = max(a * (1.0 + ext.aniso.w), 0.002);\n"
4365 " highp float ab = max(a * (1.0 - ext.aniso.w), 0.002);\n"
4366 " brdf = distributionGGXAniso(at, ab, dot(T, H), dot(B, H), max(dot(N, H), 0.0))\n"
4367 " * visibilityGGXAniso(at, ab, dot(T, V), dot(B, V), dot(T, L), dot(B, L), NdotV, ndotl);\n"
4368 " } else {\n"
4369 " brdf = distributionGGX(max(dot(N, H), 0.0), a) * visibilitySmithGGX(NdotV, ndotl, a);\n"
4370 " }\n"
4371 " highp vec3 F = fresnelSchlick(max(dot(V, H), 0.0), F0);\n"
4372 " if (ext.film.x > 0.0) F = filmFresnel(F, max(dot(V, H), 0.0), ext.film);\n"
4373 " gloss += radiance * F\n"
4374 " * (brdf * 3.14159265 * specular);\n"
4375 " }\n"
4376 " if (col.a > 0.0 && atten > 0.0\n"
4377 " && (ext.coat.x > 0.0 || ext.scatter.a > 0.0 || dot(ext.sheen.rgb, vec3(1.0)) > 0.0)) {\n"
4378 " highp vec3 irr = col.rgb * (col.a * atten);\n"
4379 " highp vec3 Hx = normalize(L + V);\n"
4380 " highp float VdotH = max(dot(V, Hx), 0.0);\n"
4381 " if (ext.coat.x > 0.0) {\n"
4382 " highp float coatNdotL = max(dot(ext.coatN.xyz, L), 0.0);\n"
4383 " highp float coatA = max(ext.coat.y * ext.coat.y, 1e-3);\n"
4384 " highp float coatF0 = ext.coat.z > 0.0 ? ext.coat.z : 0.04;\n"
4385 " highp float Fc = (coatF0 + (1.0 - coatF0) * pow(1.0 - VdotH, 5.0)) * ext.coat.x;\n"
4386 " extra += irr * coatNdotL\n"
4387 " * (distributionGGX(max(dot(ext.coatN.xyz, Hx), 0.0), coatA) * (0.25 / max(VdotH * VdotH, 1e-4))\n"
4388 " * Fc * 3.14159265);\n"
4389 " }\n"
4390 " if (dot(ext.sheen.rgb, vec3(1.0)) > 0.0) {\n"
4391 " highp float sheenA = max(ext.sheen.a * ext.sheen.a, 1e-3);\n"
4392 " extra += irr * ndotl * ext.sheen.rgb\n"
4393 " * (distributionCharlie(max(dot(N, Hx), 0.0), sheenA) * visibilityNeubelt(NdotV, ndotl) * 3.14159265);\n"
4394 " }\n"
4395 " if (ext.scatter.a > 0.0) {\n"
4396 " highp vec3 wrapWidth = vec3(ext.scatter.a) * mix(vec3(1.0), vec3(1.0, 0.45, 0.25) * (0.3 + 1.7 * ext.trans.z), ext.trans.w);\n"
4397 " highp vec3 wrapped = clamp((vec3(dot(N, L)) + wrapWidth) / (vec3(1.0) + wrapWidth), vec3(0.0), vec3(1.0));\n"
4398 " extra += irr * ext.scatter.rgb * max(wrapped - vec3(ndotl), vec3(0.0));\n"
4399 " highp vec3 Hb = normalize(L + N * 0.3);\n"
4400 " extra += irr * ext.scatter.rgb\n"
4401 " * (pow(clamp(dot(V, -Hb), 0.0, 1.0), 4.0) * ext.trans.x * (1.0 - ext.trans.y));\n"
4402 " }\n"
4403 " }\n"
4404 "}\n"
4405 // A lit sprite's light: the general model at metallic 0, roughness 1, specular 0, which is albedo times what arrives, written
4406 // out as only that. The sums are the general ones term for term, so the picture is the same; what differs is what a pixel
4407 // pays: the two 2D masks are read once for the pixel and not once per light, and nothing of the highlight is carried along.
4408 // The three kinds of light keep a branch each, as the general function has them: folding point and spot into one, or
4409 // leaving early when a light does not reach, measured SLOWER on D3D (5.7 ms against 4.7). 32 screen-filling lit layers
4410 // under four lamps: 5.4 ms to 4.7 on WebGL2, 8.8 to 6.5 on WebGPU (docs/GPU_PERFORMANCE_OPTIONS.md, section 9).
4411 "void shadeLight2D(in highp vec4 pd, in highp vec4 col, in highp vec4 sp, in highp vec4 sh, in highp vec4 sm,\n"
4412 " in highp vec4 fo, in highp vec3 N, in highp vec3 worldPos, in bool masked,\n"
4413 " in highp vec4 shadowMask, in highp vec4 shapeMask, inout highp vec3 lit, in bool shadow3D) {\n"
4414 " if (col.a == 0.0 || !lightReachesLayer(sm.y)) return;\n"
4415 " highp vec3 L;\n"
4416 " highp float atten = 1.0;\n"
4417 " bool castShadow = true;\n"
4418 " if (pd.z < 0.5) {\n"
4419 " highp vec3 toL = lightVector(pd, sh, worldPos);\n"
4420 " highp float dist = lightDistance(toL);\n"
4421 " atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);\n"
4422 " L = towardLight(toL, N);\n"
4423 " } else if (pd.z < 1.5) {\n"
4424 " L = normalize(-vec3(pd.xy, pd.w));\n"
4425 " highp vec2 toLight = (dot(pd.xy, pd.xy) > 1e-8) ? normalize(-pd.xy) : vec2(0.0);\n"
4426 " castShadow = sh.y > 0.0 && dot(toLight, toLight) > 0.5;\n"
4427 " } else {\n"
4428 " highp vec3 toL = lightVector(pd, sh, worldPos);\n"
4429 " highp float dist = lightDistance(toL);\n"
4430 " atten = distanceFalloff(dist, max(pd.w, 0.0001), fo);\n"
4431 " L = towardLight(toL, N);\n"
4432 " atten *= spotCone(sp, sh, toL, dist);\n"
4433 " }\n"
4434 "#ifndef ES_LIGHT_DIRECT\n"
4435 " if (masked && col.a > 0.0 && atten > 0.0) {\n"
4436 " if (fo.w >= 0.0) atten *= min(mask2DChannel(shapeMask, fo.w), 1.0);\n"
4437 " if (castShadow && sm.w >= 0.0 && atten > 0.0) {\n"
4438 " highp float hidden = (sm.w < 3.5) ? mask2DChannel(shadowMask, sm.w) : mask2DChannel(shapeMask, sm.w - 4.0);\n"
4439 " atten *= mix(1.0, 1.0 - min(hidden, 1.0), fo.z);\n"
4440 " }\n"
4441 " }\n"
4442 "#endif\n"
4443 " if (shadow3D && mod(sm.y, 8.0) > 0.0 && atten > 0.0) {\n"
4444 " atten *= mix(1.0, shadowFactor3D(worldPos, N, L, vec2(sh.x, sm.z),\n"
4445 " int(sm.x), int(mod(sm.y, 8.0))), fo.z);\n"
4446 " }\n"
4447 " lit += col.rgb * (col.a * max(dot(N, L), 0.0) * atten);\n"
4448 "}\n"
4449 // `reach`: bit i set when loop light i can reach this quad at all (lightReachMask2D, settled where the quad was submitted);
4450 // the rest are not worked out. All sixteen bits for a surface nobody settled it for.
4451 "highp vec3 applyLighting2DReach(highp vec3 albedo, highp vec3 N, highp vec2 worldPos,\n"
4452 " highp float ao, int reach) {\n"
4453 " highp vec3 P = vec3(worldPos, 0.0);\n"
4454 " g_probePos = P;\n"
4455 " highp vec3 lit = indirectIrradiance(N) * ao;\n"
4456 " bool masked = false;\n"
4457 " highp vec4 shadowMask = vec4(0.0);\n"
4458 " highp vec4 shapeMask = vec4(0.0);\n"
4459 "#ifndef ES_LIGHT_DIRECT\n"
4460 " if (u_mask2DRect.z > 0.0) {\n"
4461 " highp vec2 maskUv = mask2DUv(worldPos);\n"
4462 " if (!(maskUv.x < 0.0)) {\n"
4463 " masked = true;\n"
4464 " shadowMask = textureLod(u_shadow2D, maskUv, 0.0);\n"
4465 " shapeMask = textureLod(u_lightShape2D, maskUv, 0.0);\n"
4466 " }\n"
4467 " }\n"
4468 "#endif\n"
4469 // The screen tile this pixel is in says which lights can reach it: the tiled ones in its first three words, and in the
4470 // fourth the loop's own sixteen (LightStore::markLoopLights), which is what spares a tilemap, whose vertices carry no reach.
4471 "#ifndef ES_LIGHT_DIRECT\n"
4472 " int tiledCount = int(u_tileInfo.x);\n"
4473 " highp uvec4 tileBits = uvec4(0u);\n"
4474 " if (tiledCount > 0 || u_tileInfo.w > 0.5) {\n"
4475 " highp vec4 tileClip = u_projection * vec4(P, 1.0);\n"
4476 " highp vec2 tileNdc = tileClip.xy / max(tileClip.w, 1e-4);\n"
4477 " ivec2 tileCount = ivec2(int(u_tileInfo.y), int(u_tileInfo.z));\n"
4478 " ivec2 tile = clamp(ivec2(floor((tileNdc * 0.5 + 0.5) * vec2(tileCount))), ivec2(0), tileCount - ivec2(1));\n"
4479 " tileBits = u_tileMask[tile.y * tileCount.x + tile.x];\n"
4480 " if (u_tileInfo.w > 0.5) reach = reach & int(tileBits.w);\n"
4481 " }\n"
4482 "#endif\n"
4483 " int lightCount = int(u_ambient.a);\n"
4484 " for (int i = 0; i < lightCount; ++i) {\n"
4485 " if (((reach >> i) & 1) == 0) continue;\n"
4486 " shadeLight2D(u_lights[i].posDir, u_lights[i].color, u_lights[i].spot, u_lights[i].shadow,\n"
4487 " u_lights[i].shadowMap, u_lights[i].falloff, N, P, masked, shadowMask, shapeMask, lit, true);\n"
4488 " }\n"
4489 "#ifndef ES_LIGHT_DIRECT\n"
4490 " if (tiledCount > 0) {\n"
4491 " for (int w = 0; w < 3; ++w) {\n"
4492 " highp uint bits = w == 0 ? tileBits.x : (w == 1 ? tileBits.y : tileBits.z);\n"
4493 " if (bits == 0u) continue;\n"
4494 " for (int b = 0; b < 32; ++b) {\n"
4495 " if ((bits & (1u << uint(b))) == 0u) continue;\n"
4496 " int k = w * 32 + b;\n"
4497 " if (k >= tiledCount) break;\n"
4498 " shadeLight2D(u_tiledLights[k].posDir, u_tiledLights[k].color, u_tiledLights[k].spot,\n"
4499 " u_tiledLights[k].shadow, u_tiledLights[k].shadowMap, u_tiledLights[k].falloff,\n"
4500 " N, P, masked, shadowMask, shapeMask, lit, false);\n"
4501 " }\n"
4502 " }\n"
4503 " }\n"
4504 "#endif\n"
4505 " return albedo * lit;\n"
4506 "}\n"
4507 "highp vec3 applyLighting2DAO(highp vec3 albedo, highp vec3 N, highp vec2 worldPos,\n"
4508 " highp float ao) {\n"
4509 " return applyLighting2DReach(albedo, N, worldPos, ao, 65535);\n"
4510 "}\n"
4511 "highp vec3 applyLighting2D(highp vec3 albedo, highp vec3 N, highp vec2 worldPos) {\n"
4512 " return applyLighting2DAO(albedo, N, worldPos, 1.0);\n"
4513 "}\n"
4514 // The same, for a sprite that knows its layer: layerLane is the varying the vertex stage wrote (v_lightLayer).
4515 // A negative lane carries, above the layer, which lights reach the quad (packSpriteLightLane): 512 apart, so the two come
4516 // apart by a power of two and whole. The sixteenth light has no bit and is always worked out.
4517 "highp vec3 applyLighting2DLayer(highp vec3 albedo, highp vec3 N, highp vec2 worldPos, highp float layerLane) {\n"
4518 " highp float lane = abs(layerLane);\n"
4519 " highp float reach = floor(lane * 0.001953125);\n"
4520 " g_surfaceLayer = lane - reach * 512.0;\n"
4521 " return applyLighting2DReach(albedo, N, worldPos, 1.0, layerLane < 0.0 ? int(reach) + 32768 : 65535);\n"
4522 "}\n";
4523 // Emitted only for a variant that has the feature, not behind an #ifdef:
4524 // a varying declared in dead text still reads as one to a tool that
4525 // pairs the stages by name, and this one has no vertex output without it.
4526 if (std::find(features.begin(), features.end(), "MESH_LIGHTMAP") != features.end()) {
4527 // The bake's atlas and where this fragment sits in it; z says whether this
4528 // object has a patch at all. Square-law over LIGHTMAP_RANGE, which the
4529 // baker encodes with.
4530 static const char* kLightmapHeader =
4531 "in highp vec3 v_lightmap;\n"
4532 "uniform highp sampler2D u_lightmap;\n"
4533 "highp vec3 bakedIrradiance() {\n"
4534 " highp vec3 c = textureLod(u_lightmap, v_lightmap.xy, 0.0).rgb;\n"
4535 " return c * c * 8.0;\n"
4536 "}\n";
4537 assembled << kLightmapHeader;
4538 headerLines += countNewlines(kLightmapHeader);
4539 }
4540 assembled << kLitHeader << WATER_SUN_GLSL;
4541 headerLines += countNewlines(WATER_SUN_GLSL);
4542 headerLines += countNewlines(kLitHeader);
4543 }
4544
4545 // The same block for a fullscreen pass that asks for it, with the two questions an effect puts to it.
4546 if (stage == ShaderStage::Fragment && parsed.domain == "PostProcess" && parsed.usesLights) {
4547 static const char* kPostLightHeader =
4548 "struct Light { highp vec4 posDir; highp vec4 color; highp vec4 spot; highp vec4 shadow;"
4549 " highp vec4 shadowMap; highp vec4 falloff; };\n"
4550 "layout(std140) uniform LightConstants {\n"
4551 " highp vec4 u_ambient;\n"
4552 " Light u_lights[16];\n"
4553 " highp vec4 u_mask2DRect;\n"
4554 " highp mat4 u_shadowMatrix[16];\n"
4555 " highp vec4 u_shadowTile[16];\n"
4556 " highp vec4 u_shadowParams;\n"
4557 " highp vec4 u_envIrradiance[9];\n"
4558 " highp vec4 u_envParams;\n"
4559 " highp vec4 u_envTint;\n"
4560 " highp vec4 u_reflParams;\n"
4561 " highp vec4 u_reflBox[30];\n"
4562 " highp vec4 u_bakedTint;\n"
4563 " Light u_tiledLights[96];\n"
4564 " highp uvec4 u_tileMask[192];\n"
4565 " highp vec4 u_tileInfo;\n"
4566 "};\n"
4567 "uniform highp sampler2D u_shadowMap;\n"
4568 "highp float unpackDepth(in highp vec3 c) {\n"
4569 " return dot(c, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));\n"
4570 "}\n"
4571 // The first directional light that shines: dir.xyz = where it stands in the sky, dir.w = 1 (0 = none).
4572 "void findSun(out highp vec4 dir, out highp vec4 color, out ivec2 tiles) {\n"
4573 " dir = vec4(0.0);\n"
4574 " color = vec4(0.0);\n"
4575 " tiles = ivec2(0);\n"
4576 " for (int i = 0; i < 16; ++i) {\n"
4577 " Light l = u_lights[i];\n"
4578 " if (l.posDir.z > 0.5 && l.posDir.z < 1.5 && l.color.a > 0.0) {\n"
4579 " dir = vec4(-normalize(vec3(l.posDir.x, l.posDir.y, l.posDir.w)), 1.0);\n"
4580 " color = l.color;\n"
4581 " tiles = ivec2(int(l.shadowMap.x), int(mod(l.shadowMap.y, 8.0)));\n"
4582 " return;\n"
4583 " }\n"
4584 " }\n"
4585 "}\n"
4586 // One tap, no filtering: a sample of air is not a surface.
4587 "highp float sunVisibility(in highp vec3 worldPos, in int first, in int count) {\n"
4588 " if (u_shadowParams.x < 0.5 || count <= 0) return 1.0;\n"
4589 " for (int k = 0; k < 16; ++k) {\n"
4590 " if (k >= count) break;\n"
4591 " int t = first + k;\n"
4592 " highp mat4 m = u_shadowMatrix[t];\n"
4593 " highp vec4 c = m * vec4(worldPos, 1.0);\n"
4594 " if (c.w <= 0.0) continue;\n"
4595 " highp vec3 proj = c.xyz / c.w;\n"
4596 " highp vec2 uv = proj.xy * 0.5 + 0.5;\n"
4597 " if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || proj.z < 0.0 || proj.z > 1.0) continue;\n"
4598 " highp vec4 rect = u_shadowTile[t];\n"
4599 " highp vec2 at = rect.xy + uv * rect.z;\n"
4600 " highp vec2 lo = rect.xy + u_shadowParams.y * 0.5;\n"
4601 " highp vec2 hi = rect.xy + rect.z - u_shadowParams.y * 0.5;\n"
4602 " highp float d = unpackDepth(texture(u_shadowMap, clamp(at, lo, hi)).rgb);\n"
4603 " return d < clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - 0.0025 ? 0.0 : 1.0;\n"
4604 " }\n"
4605 " return 1.0;\n"
4606 "}\n";
4607 assembled << kPostLightHeader;
4608 headerLines += countNewlines(kPostLightHeader);
4609 }
4610
4611 if (!platform.empty()) {
4612 auto variantIt = parsed.variants.find(platform);
4613 if (variantIt != parsed.variants.end()) {
4614 assembled << variantIt->second;
4615 headerLines += countNewlines(variantIt->second);
4616 }
4617 }
4618
4619 if (!parsed.sharedCode.empty()) {
4620 assembled << parsed.sharedCode;
4621 headerLines += countNewlines(parsed.sharedCode);
4622 }
4623
4624 // A shader that writes its own vertex stage can take a material's hook too: it says where with a marker,
4625 // and the material that borrows the stage supplies the text (see MaterialStore::shadowProgram).
4626 std::string bodyText = stageIt->second;
4627 if (stage == ShaderStage::Vertex && !parsed.vertexHook.empty()) {
4628 fillHook(bodyText, "@@ES_VERTEX_HOOK@@", parsed.vertexHook);
4629 }
4630 // A hand-written vertex stage says where the shared morph helpers go (see morphHelpersGLSL).
4631 if (stage == ShaderStage::Vertex) fillHook(bodyText, "@@ES_MORPH@@", morphHelpersGLSL());
4632 assembled << blankUniformBlock(bodyText, "FrameConstants");
4633 if (stage == ShaderStage::Vertex && namesRecords(stageIt->second)) {
4634 assembled << instanceRecordGLSLBodies();
4635 }
4636
4637 result.source = assembled.str();
4638 result.headerLineCount = headerLines;
4639 return result;
4640}
4641
4642namespace {
4643
4644std::string formatRemap(u32 logLine,
4645 const std::vector<SourceLine>& stageMap,
4646 u32 headerLineOffset,
4647 bool parenStyle) {
4648 if (logLine <= headerLineOffset) return {};
4649 const u32 bodyLine = logLine - headerLineOffset;
4650 if (bodyLine == 0 || bodyLine > stageMap.size()) return {};
4651 const SourceLine& src = stageMap[bodyLine - 1];
4652 const std::string file = src.file.empty() ? std::string("<main>") : src.file;
4653 std::string out;
4654 if (parenStyle) {
4655 out = file + "(" + std::to_string(src.line) + ")";
4656 } else {
4657 out = file + ":" + std::to_string(src.line) + ":";
4658 }
4659 return out;
4660}
4661
4662bool scanNumber(const std::string& log, usize start, usize& outEnd, u32& outNumber) {
4663 u32 num = 0;
4664 usize j = start;
4665 bool any = false;
4666 while (j < log.size() && std::isdigit(static_cast<unsigned char>(log[j]))) {
4667 num = num * 10 + static_cast<u32>(log[j] - '0');
4668 ++j;
4669 any = true;
4670 }
4671 if (!any) return false;
4672 outEnd = j;
4673 outNumber = num;
4674 return true;
4675}
4676
4677} // namespace
4678
4679std::string ShaderParser::remapCompilerLog(const std::string& log,
4680 const std::vector<SourceLine>& stageMap,
4681 u32 headerLineOffset) {
4682 if (log.empty() || stageMap.empty()) return log;
4683
4684 auto isWordChar = [](char c) {
4685 return std::isalnum(static_cast<unsigned char>(c)) || c == '_';
4686 };
4687
4688 std::string out;
4689 out.reserve(log.size());
4690 const usize n = log.size();
4691 usize i = 0;
4692 while (i < n) {
4693 const bool boundary = (i == 0) || !isWordChar(log[i - 1]);
4694 if (boundary && i + 2 < n && log[i] == '0' && log[i + 1] == ':') {
4695 usize end = 0;
4696 u32 num = 0;
4697 if (scanNumber(log, i + 2, end, num) && end < n && log[end] == ':') {
4698 std::string rep = formatRemap(num, stageMap, headerLineOffset, /*parenStyle*/ false);
4699 if (!rep.empty()) {
4700 out += rep;
4701 i = end + 1;
4702 continue;
4703 }
4704 }
4705 }
4706 if (boundary && i + 2 < n && log[i] == '0' && log[i + 1] == '(') {
4707 usize end = 0;
4708 u32 num = 0;
4709 if (scanNumber(log, i + 2, end, num) && end < n && log[end] == ')') {
4710 std::string rep = formatRemap(num, stageMap, headerLineOffset, /*parenStyle*/ true);
4711 if (!rep.empty()) {
4712 out += rep;
4713 i = end + 1;
4714 continue;
4715 }
4716 }
4717 }
4718 out += log[i++];
4719 }
4720 return out;
4721}
4722
4723// =============================================================================
4724// Private Methods
4725// =============================================================================
4726
4727void ShaderParser::parseDirective(const std::string& line,
4728 std::string& directive,
4729 std::string& argument) {
4730 directive.clear();
4731 argument.clear();
4732
4733 std::string trimmedLine = trim(line);
4734 if (trimmedLine.substr(0, 7) != "#pragma") {
4735 return;
4736 }
4737
4738 std::string rest = trim(trimmedLine.substr(7));
4739 if (rest.empty()) {
4740 return;
4741 }
4742
4743 usize spacePos = rest.find_first_of(" \t");
4744 if (spacePos == std::string::npos) {
4745 directive = rest;
4746 } else {
4747 directive = rest.substr(0, spacePos);
4748 argument = trim(rest.substr(spacePos + 1));
4749 }
4750}
4751
4752ShaderProperty ShaderParser::parseParamDirective(const std::string& argument) {
4753 ShaderProperty prop;
4754 prop.fromParam = true;
4755
4756 usize ssPos = 0;
4757 std::string typeStr;
4758 prop.name = nextToken(argument, ssPos);
4759 typeStr = nextToken(argument, ssPos);
4760 if (prop.name.empty() || typeStr.empty()) {
4761 prop.name.clear(); // signal invalid → caller drops it
4762 return prop;
4763 }
4764 prop.layered = typeStr == "textureArray";
4765 prop.type = prop.layered ? ShaderPropertyType::Texture : stringToPropertyType(typeStr);
4766
4767 // Extract the contents of a `key(...)` clause from the directive argument.
4768 auto clause = [&](const char* key) -> std::optional<std::string> {
4769 const std::string token = std::string(key) + "(";
4770 usize p = argument.find(token);
4771 if (p == std::string::npos) return std::nullopt;
4772 usize open = p + token.size();
4773 usize close = argument.find(')', open);
4774 if (close == std::string::npos) return std::nullopt;
4775 return trim(argument.substr(open, close - open));
4776 };
4777
4778 if (auto d = clause("default")) prop.defaultValue = *d;
4779 if (auto u = clause("ui")) prop.ui = *u;
4780 if (auto u = clause("unit")) prop.worldUnits = *u == "length" ? 1 : *u == "perLength" ? -1 : 0;
4781 if (auto r = clause("range")) {
4782 usize comma = r->find(',');
4783 if (comma != std::string::npos) {
4784 prop.rangeMin = static_cast<f32>(std::atof(trim(r->substr(0, comma)).c_str()));
4785 prop.rangeMax = static_cast<f32>(std::atof(trim(r->substr(comma + 1)).c_str()));
4786 prop.hasRange = true;
4787 }
4788 }
4789
4790 // Default display name: strip a leading u_ and capitalize.
4791 prop.displayName = prop.name;
4792 if (prop.displayName.size() > 2 && prop.displayName.substr(0, 2) == "u_") {
4793 prop.displayName = prop.displayName.substr(2);
4794 }
4795 if (!prop.displayName.empty()) {
4796 prop.displayName[0] = static_cast<char>(std::toupper(prop.displayName[0]));
4797 }
4798 return prop;
4799}
4800
4801namespace {
4802
4804bool namesIdentifier(const std::string& text, std::string_view word) {
4805 const auto isIdent = [](char c) { return std::isalnum(static_cast<unsigned char>(c)) || c == '_'; };
4806 for (usize at = text.find(word); at != std::string::npos; at = text.find(word, at + 1)) {
4807 const bool startOk = at == 0 || !isIdent(text[at - 1]);
4808 const usize end = at + word.size();
4809 if (startOk && (end >= text.size() || !isIdent(text[end]))) return true;
4810 }
4811 return false;
4812}
4813
4818u32 batchUnitsRead(const std::string& text) {
4819 constexpr std::string_view word = "u_textures";
4820 const auto isIdent = [](char c) { return std::isalnum(static_cast<unsigned char>(c)) || c == '_'; };
4821 u32 mask = 0;
4822 for (usize at = text.find(word); at != std::string::npos; at = text.find(word, at + 1)) {
4823 usize i = at + word.size();
4824 if ((at > 0 && isIdent(text[at - 1])) || (i < text.size() && isIdent(text[i]))) continue;
4825 // A type before the name is its declaration, whose size is no read.
4826 usize before = at;
4827 while (before > 0 && std::isspace(static_cast<unsigned char>(text[before - 1]))) --before;
4828 if (before > 0 && before < at && isIdent(text[before - 1])) continue;
4829 while (i < text.size() && std::isspace(static_cast<unsigned char>(text[i]))) ++i;
4830 if (i >= text.size() || text[i] != '[') return 0xFFu;
4831 const usize close = text.find(']', i);
4832 if (close == std::string::npos) return 0xFFu;
4833 u32 index = 0;
4834 bool literal = close > i + 1;
4835 for (usize c = i + 1; c < close && literal; ++c) {
4836 if (std::isdigit(static_cast<unsigned char>(text[c]))) index = std::min(index * 10u + static_cast<u32>(text[c] - '0'), 255u);
4837 else if (!std::isspace(static_cast<unsigned char>(text[c]))) literal = false;
4838 }
4839 if (!literal) return 0xFFu;
4840 if (index < MATERIAL_TEXTURE_UNIT_BASE) mask |= 1u << index;
4841 }
4842 return mask;
4843}
4844
4845} // namespace
4846
4854 u32 reads = 0;
4855 if (shader.domain == "Lit") {
4858 } else if (shader.domain == "Unlit") {
4859 reads = 1u << MORPH_DELTA_TEXTURE_UNIT;
4860 } else if (shader.domain == "PostProcess") {
4861 // A fullscreen pass is handed its input and the scene on 0 and 1, the shadow atlas and the environment on 2 and 3, and the
4862 // surface record and the scene's depth on 6 and 7, which its WGSL declares whether it reads them (PostProcessPipeline::renderPass):
4863 // 4 and 5 are left for a pass with more textures than the units above the base hold (a terrain's surface bake reads eight).
4864 reads = (1u << 0) | (1u << 1) | (1u << SHADOW_MAP_TEXTURE_UNIT) | (1u << ENV_MAP_TEXTURE_UNIT) | (1u << kGBufferUnit)
4865 | (1u << kSceneDepthUnit);
4866 } else {
4867 return 0;
4868 }
4869
4870 std::string glsl = shader.sharedCode + shader.vertexHook;
4871 for (const auto& [stage, source] : shader.stages) glsl += source;
4872 for (const auto& [platform, source] : shader.variants) glsl += source;
4873 std::string wgsl = shader.wgslVertexHook;
4874 for (const auto& [stage, source] : shader.wgslStages) wgsl += source;
4875 const std::string both = glsl + wgsl;
4876
4877 reads |= batchUnitsRead(both);
4878 static constexpr struct { const char* name; u32 unit; } kEngine[] = {
4882 };
4883 for (const auto& e : kEngine) {
4884 if (namesIdentifier(both, e.name)) reads |= 1u << e.unit;
4885 }
4886 u32 reachedTex = 0;
4887 u32 reachedSam = 0;
4888 scanWGSLReachedUnits(wgsl.c_str(), reachedTex, reachedSam);
4889 reads |= reachedTex | reachedSam;
4890
4891 return ~reads & ((1u << MATERIAL_TEXTURE_UNIT_BASE) - 1u);
4892}
4893
4894
4895i32 ShaderParser::takeOverflowUnit(u32& free) {
4896 for (i32 unit = static_cast<i32>(MATERIAL_TEXTURE_UNIT_BASE) - 1; unit >= 0; --unit) {
4897 if ((free & (1u << unit)) == 0) continue;
4898 free &= ~(1u << unit);
4899 return unit;
4900 }
4901 return -1;
4902}
4903
4904void ShaderParser::computeMaterialLayout(ParsedShader& shader) {
4905 // std140 size/alignment for the supported scalar/vector param types.
4906 auto sizeAlign = [](ShaderPropertyType t, u32& size, u32& align) {
4907 switch (t) {
4909 case ShaderPropertyType::Int: size = 4; align = 4; break;
4910 case ShaderPropertyType::Vec2: size = 8; align = 8; break;
4911 case ShaderPropertyType::Vec3: size = 12; align = 16; break;
4913 case ShaderPropertyType::Color: size = 16; align = 16; break;
4914 default: size = 0; align = 0; break;
4915 }
4916 };
4917 auto alignUp = [](u32 v, u32 a) -> u32 { return a == 0 ? v : (v + a - 1) & ~(a - 1); };
4918
4919 // Material texture units start above the batch path's 0..7 slots
4920 // (must match renderer/MaterialConstants.hpp MATERIAL_TEXTURE_UNIT_BASE). Past
4921 // those, a texture takes a unit below the base that THIS shader never reads.
4922 u32 textureUnit = MATERIAL_TEXTURE_UNIT_BASE;
4923 u32 overflowFree = materialOverflowUnits(shader);
4924 u32 offset = 0;
4925
4926 for (auto& p : shader.properties) {
4927 if (!p.fromParam) continue; // legacy properties-block entries are reflection-only
4928 if (p.type == ShaderPropertyType::Texture) {
4929 p.std140Offset = -1;
4930 // The top unit is the frame's per-object record, on every mesh shader
4931 // there is. Handing it out here would bind a material's texture over
4932 // the records and draw every object at the origin.
4933 if (textureUnit < MESH_INSTANCE_TEXTURE_UNIT) {
4934 p.textureUnit = static_cast<i32>(textureUnit++);
4935 continue;
4936 }
4937 const i32 low = takeOverflowUnit(overflowFree);
4938 if (low >= 0) {
4939 p.textureUnit = low;
4940 continue;
4941 }
4942 ES_LOG_ERROR("shader {}: texture param \"{}\" finds no free texture unit: units {}..{} are"
4943 " taken, and the {} domain leaves none of the engine's units below {} that this"
4944 " shader does not read",
4946 shader.domain, MATERIAL_TEXTURE_UNIT_BASE);
4947 p.textureUnit = -1;
4948 continue;
4949 }
4950 u32 size = 0, align = 0;
4951 sizeAlign(p.type, size, align);
4952 if (size == 0) { p.std140Offset = -1; continue; } // Unknown — not packed
4953 offset = alignUp(offset, align);
4954 p.std140Offset = static_cast<i32>(offset);
4955 offset += size;
4956 }
4957
4958 shader.materialBlockSize = (offset == 0) ? 0 : alignUp(offset, 16);
4959}
4960
4961ShaderProperty ShaderParser::parsePropertyAnnotation(const std::string& line) {
4962 ShaderProperty prop;
4963
4964 usize uniformPos = line.find("uniform");
4965 if (uniformPos == std::string::npos) {
4966 return prop;
4967 }
4968
4969 std::string afterUniform = trim(line.substr(uniformPos + 7));
4970 usize spacePos = afterUniform.find_first_of(" \t");
4971 if (spacePos == std::string::npos) {
4972 return prop;
4973 }
4974
4975 std::string glslType = afterUniform.substr(0, spacePos);
4976 std::string rest = trim(afterUniform.substr(spacePos));
4977
4978 usize semicolonPos = rest.find(';');
4979 if (semicolonPos == std::string::npos) {
4980 return prop;
4981 }
4982
4983 prop.name = trim(rest.substr(0, semicolonPos));
4984
4985 if (glslType == "float") {
4986 prop.type = ShaderPropertyType::Float;
4987 } else if (glslType == "vec2") {
4988 prop.type = ShaderPropertyType::Vec2;
4989 } else if (glslType == "vec3") {
4990 prop.type = ShaderPropertyType::Vec3;
4991 } else if (glslType == "vec4") {
4992 prop.type = ShaderPropertyType::Vec4;
4993 } else if (glslType == "int") {
4994 prop.type = ShaderPropertyType::Int;
4995 } else if (glslType == "sampler2D") {
4996 prop.type = ShaderPropertyType::Texture;
4997 } else {
4998 prop.type = ShaderPropertyType::Unknown;
4999 }
5000
5001 usize propStart = line.find("@property");
5002 if (propStart != std::string::npos) {
5003 usize parenStart = line.find('(', propStart);
5004 usize parenEnd = line.find(')', parenStart);
5005 if (parenStart != std::string::npos && parenEnd != std::string::npos) {
5006 std::string params = line.substr(parenStart + 1, parenEnd - parenStart - 1);
5007
5008 usize typePos = params.find("type");
5009 if (typePos != std::string::npos) {
5010 usize eqPos = params.find('=', typePos);
5011 if (eqPos != std::string::npos) {
5012 usize valStart = params.find_first_not_of(" \t", eqPos + 1);
5013 usize valEnd = params.find_first_of(" \t,)", valStart);
5014 if (valStart != std::string::npos) {
5015 std::string typeVal = params.substr(valStart, valEnd - valStart);
5016 prop.type = stringToPropertyType(typeVal);
5017 }
5018 }
5019 }
5020
5021 usize defaultPos = params.find("default");
5022 if (defaultPos != std::string::npos) {
5023 usize eqPos = params.find('=', defaultPos);
5024 if (eqPos != std::string::npos) {
5025 usize valStart = params.find_first_not_of(" \t", eqPos + 1);
5026 usize valEnd = params.find_first_of(",)", valStart);
5027 if (valStart != std::string::npos) {
5028 prop.defaultValue = trim(params.substr(valStart, valEnd - valStart));
5029 }
5030 }
5031 }
5032
5033 usize namePos = params.find("name");
5034 if (namePos != std::string::npos) {
5035 usize quoteStart = params.find('"', namePos);
5036 usize quoteEnd = params.find('"', quoteStart + 1);
5037 if (quoteStart != std::string::npos && quoteEnd != std::string::npos) {
5038 prop.displayName = params.substr(quoteStart + 1, quoteEnd - quoteStart - 1);
5039 }
5040 }
5041 }
5042 }
5043
5044 if (prop.displayName.empty()) {
5045 prop.displayName = prop.name;
5046 if (prop.displayName.size() > 2 && prop.displayName.substr(0, 2) == "u_") {
5047 prop.displayName = prop.displayName.substr(2);
5048 }
5049 if (!prop.displayName.empty()) {
5050 prop.displayName[0] = static_cast<char>(std::toupper(prop.displayName[0]));
5051 }
5052 }
5053
5054 return prop;
5055}
5056
5057ShaderPropertyType ShaderParser::stringToPropertyType(const std::string& typeStr) {
5058 if (typeStr == "float") return ShaderPropertyType::Float;
5059 if (typeStr == "vec2") return ShaderPropertyType::Vec2;
5060 if (typeStr == "vec3") return ShaderPropertyType::Vec3;
5061 if (typeStr == "vec4") return ShaderPropertyType::Vec4;
5062 if (typeStr == "color") return ShaderPropertyType::Color;
5063 if (typeStr == "int") return ShaderPropertyType::Int;
5064 if (typeStr == "texture") return ShaderPropertyType::Texture;
5066}
5067
5068std::string ShaderParser::trim(const std::string& str) {
5069 const char* whitespace = " \t\r\n";
5070 usize start = str.find_first_not_of(whitespace);
5071 if (start == std::string::npos) {
5072 return "";
5073 }
5074 usize end = str.find_last_not_of(whitespace);
5075 return str.substr(start, end - start + 1);
5076}
5077
5078} // namespace esengine::resource
5079
The samplers the engine injects into a shader, and the texture unit each is pinned to.
Backend-agnostic graphics enumerations.
WHERE one draw's entry is in the frame's per-object record texture, and what an entry says.
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
Binding points for per-material shader constants — the second tier of the engine's constant-buffer la...
Parser for unified .esshader file format.
std::ostream & operator<<(std::ostream &os, esengine::Entity e)
Definition Types.hpp:257
What a texture unit is called in WGSL, and what a WGSL source says about the group-1 bindings it hold...
static void setLinearColorSpace(bool linear)
Process-global color-space mode. When linear, every assembled stage compiles with ES_LINEAR defined (...
static std::vector< std::string > splitFeatures(const std::string &csv)
Split a comma-separated feature/switch list into trimmed, non-empty entries — the form the boundary c...
static ParsedShader parse(const std::string &source)
Parses shader source into structured format (no include support).
static std::string canonicalVaryingsWGSL(const ParsedShader &parsed)
The WGSL varying struct the engine's vertex stage emits for parsed, or empty when the shader writes i...
static std::string variantKey(const std::vector< std::string > &features)
Stable cache key for a feature set (order-independent), e.g. "GRAYSCALE|TINT". Consumers key their co...
static std::string remapCompilerLog(const std::string &log, const std::vector< SourceLine > &stageMap, u32 headerLineOffset)
Rewrites GL compile-log line references back to original files.
static u32 materialOverflowUnits(const ParsedShader &shader)
The units below the material base a texture param may take on shader (a mask): the ones it never read...
static std::string assembleStage(const ParsedShader &parsed, ShaderStage stage, const std::string &platform="", const std::vector< std::string > &features={}, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
Assembles final GLSL source for a specific stage.
static std::vector< std::string > featuresRead(const ParsedShader &parsed, const std::vector< std::string > &features, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
static AssembledStage assembleStageEx(const ParsedShader &parsed, ShaderStage stage, const std::string &platform="", const std::vector< std::string > &features={}, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
std::function< std::optional< std::string >(const std::string &)> ShaderIncludeResolver
Resolves an include path to its file contents.
ShaderTargetLanguage
Target language for stage assembly (REARCH_WGSL dual emission).
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
u64 scanWGSLBindingMask(const char *source, u32 group)
Bit mask of the @group(N) @binding(i) indices a WGSL source declares.
constexpr const char * LIGHTMAP_SAMPLER
The baked-light atlas, and the unit a lightmapped mesh samples it from.
constexpr const char * MORPH_DELTA_SAMPLER
The sampler a mesh's morph deltas arrive through, and the unit it is pinned to.
constexpr u32 SHADOW_2D_TEXTURE_UNIT
constexpr u32 samplerBindingForUnit(u32 unit)
Group-1 binding of a texture unit's sampler (see textureBindingForUnit).
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
constexpr u32 textureBindingForUnit(u32 unit)
Group-1 binding of a texture unit. Units 0-7 are the batch stream and take bindings 0-7; a material's...
static constexpr u32 MESH_INSTANCE_TEXELS
Definition GfxEnums.hpp:108
void scanWGSLReachedUnits(const char *source, u32 &textures, u32 &samplers)
The tN / sN names a WGSL source REACHES, by unit.
constexpr u32 LIGHTMAP_TEXTURE_UNIT
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
static constexpr u32 MESH_INSTANCE_TEXEL_LIGHTMAP
Definition GfxEnums.hpp:118
constexpr u32 MATERIAL_TEXTURE_UNIT_BASE
First sampler unit a material texture parameter may use (batch owns units 0..7).
constexpr u32 SHADOW_MAP_TEXTURE_UNIT
static constexpr u32 MESH_INSTANCE_TEXEL_TINT
Definition GfxEnums.hpp:112
constexpr u32 kGBufferUnit
The unit a PostProcess pass reads the scene's surface record at: what a surface IS — octahedral norma...
constexpr char WATER_SUN_GLSL[]
bool & glslMultiDraw()
Whether this process's GLSL mesh programs count through a run's entries by gl_DrawID.
constexpr u32 MORPH_DELTA_TEXTURE_UNIT
constexpr u32 kSceneDepthUnit
The unit a PostProcess pass reads the scene's DEPTH at.
constexpr const char * SHADOW_MAP_SAMPLER
The injected shadow-map sampler, and the texture unit Shader::compile pins it to.
constexpr const char * SHADOW_2D_SAMPLER
The 2D shadow mask, and the texture unit every Lit shader samples it from.
constexpr const char * ENV_MAP_SAMPLER
The injected reflection sampler, one unit past the shadow map's.
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
static constexpr u32 MESH_INSTANCE_TEXTURE_WIDTH
Definition GfxEnums.hpp:125
static constexpr u32 MESH_INSTANCE_TEXTURE_UNIT
Definition GfxEnums.hpp:133
constexpr u32 SHAPE_2D_TEXTURE_UNIT
static constexpr u32 MESH_MAX_ACTIVE_MORPHS
Definition GfxEnums.hpp:142
constexpr u32 ENV_MAP_TEXTURE_UNIT
static constexpr u32 MESH_INSTANCE_TEXEL_NORMAL
Definition GfxEnums.hpp:115
constexpr char WATER_SUN_WGSL[]
static constexpr u32 MESH_INSTANCE_TEXEL_MODEL
Definition GfxEnums.hpp:111
constexpr u32 WGSL_MAX_TEXTURE_UNITS
Units a tN / sN name can carry — the batch stream and a material's own.
constexpr const char * SHAPE_2D_SAMPLER
The 2D light-shape mask, and the unit below the shadow mask's.
constexpr u32 INSTANCE_CONSTANTS_BINDING
Indexed UBO binding point for the per-draw InstanceConstants block. Nine and not four: slot 4 is DRAW...
float f32
32-bit floating point
Definition Types.hpp:59
static constexpr u32 MESH_MAX_BONES
Definition GfxEnums.hpp:138
Result of parsing an .esshader file.
std::string version
GLSL version.
std::string errorMessage
Parse error if any.
std::unordered_map< ShaderStage, std::vector< SourceLine > > wgslStageLineMaps
Line maps for wgslStages, same convention as stageLineMaps.
std::unordered_map< ShaderStage, std::vector< SourceLine > > stageLineMaps
Per-stage line maps, parallel to stages[].
std::unordered_map< ShaderStage, std::string > stages
Stage source code.
std::unordered_map< ShaderStage, std::string > wgslStages
WGSL twin stage bodies (#pragma vertex wgsl / #pragma fragment wgsl sections), keyed like stages[].
bool valid
True if parsing succeeded.
std::vector< SourceLine > expandedLineMap
Line map for the expanded pre-parse source.
std::vector< std::string > features
std::string sharedCode
Code shared by all stages.
std::string name
Shader name.
std::unordered_map< ShaderStage, bool > wgslStageFull
Stages whose WGSL twin is a SELF-CONTAINED program (#pragma vertex wgsl full / #pragma fragment wgsl ...
bool wgslVertexIsCanonical
True when the WGSL vertex stage is the injected canonical one. The WGSL fragment assembly then also i...
bool vertexIsCanonical
True when the GLSL vertex stage is the injected canonical one.
std::vector< ShaderSwitch > switches
Material-controlled pragma switch toggles (name + default).
std::unordered_map< std::string, std::string > variants
Platform variants.
std::vector< ShaderProperty > properties
Exposed material params (pragma param / properties block).
Like assembleStage, but also reports the line count of the assembled prefix (version + variant + shar...
std::string name
Uniform name.
A material-controlled static switch (pragma switch): a boolean the material sets, selecting a compile...
A (file, line) pair identifying an original source location.