@galacean/engine-shader-compiler 2.0.0-alpha.52 → 2.0.0-alpha.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +40 -4
  2. package/bundler/cli.js +199 -104
  3. package/bundler/precompile.cjs.js +117 -47
  4. package/bundler/precompile.js +117 -47
  5. package/bundler/rollup.cjs.js +115 -45
  6. package/bundler/rollup.js +115 -45
  7. package/dist/browser.js +13421 -6555
  8. package/dist/browser.js.map +1 -1
  9. package/dist/browser.min.js +1 -1
  10. package/dist/browser.min.js.map +1 -1
  11. package/dist/main.js +1758 -8450
  12. package/dist/main.js.map +1 -1
  13. package/dist/module.js +1730 -8427
  14. package/dist/module.js.map +1 -1
  15. package/dist/precompile.main.js +2280 -0
  16. package/dist/precompile.main.js.map +1 -0
  17. package/dist/precompile.module.js +2276 -0
  18. package/dist/precompile.module.js.map +1 -0
  19. package/package.json +24 -13
  20. package/types/GLESBackend.d.ts +22 -0
  21. package/types/ShaderBackend.d.ts +15 -0
  22. package/types/ShaderCompilation.d.ts +40 -0
  23. package/types/ShaderCompiler.d.ts +42 -14
  24. package/types/ShaderInstructionEncoder.d.ts +46 -14
  25. package/types/ShaderPrecompiler.d.ts +31 -0
  26. package/types/bundler/precompile.d.ts +26 -3
  27. package/types/bundler/rollup.d.ts +23 -2
  28. package/types/codeGen/CodeGenVisitor.d.ts +11 -6
  29. package/types/codeGen/GLES100.d.ts +3 -5
  30. package/types/codeGen/GLES300.d.ts +14 -7
  31. package/types/codeGen/GLESVisitor.d.ts +55 -9
  32. package/types/codeGen/VisitorContext.d.ts +88 -29
  33. package/types/codeGen/types.d.ts +1 -1
  34. package/types/index.d.ts +4 -1
  35. package/types/precompile.d.ts +1 -0
  36. package/dist/browser.verbose.js +0 -9601
  37. package/dist/browser.verbose.js.map +0 -1
  38. package/dist/browser.verbose.min.js +0 -2
  39. package/dist/browser.verbose.min.js.map +0 -1
  40. package/dist/main.verbose.js +0 -9598
  41. package/dist/main.verbose.js.map +0 -1
  42. package/dist/module.verbose.js +0 -9591
  43. package/dist/module.verbose.js.map +0 -1
  44. package/types/GSError.d.ts +0 -16
  45. package/types/ParserUtils.d.ts +0 -43
  46. package/types/Preprocessor.d.ts +0 -30
  47. package/types/ShaderCompilerUtils.d.ts +0 -10
  48. package/types/common/BaseLexer.d.ts +0 -51
  49. package/types/common/BaseToken.d.ts +0 -35
  50. package/types/common/IBaseSymbol.d.ts +0 -5
  51. package/types/common/ShaderPosition.d.ts +0 -8
  52. package/types/common/ShaderRange.d.ts +0 -8
  53. package/types/common/SymbolTable.d.ts +0 -13
  54. package/types/common/SymbolTableStack.d.ts +0 -17
  55. package/types/common/enums/Keyword.d.ts +0 -124
  56. package/types/common/enums/ShaderStage.d.ts +0 -5
  57. package/types/common/index.d.ts +0 -5
  58. package/types/common/types.d.ts +0 -101
  59. package/types/lalr/CFG.d.ts +0 -5
  60. package/types/lalr/LALR1.d.ts +0 -27
  61. package/types/lalr/Production.d.ts +0 -9
  62. package/types/lalr/State.d.ts +0 -20
  63. package/types/lalr/StateItem.d.ts +0 -20
  64. package/types/lalr/Utils.d.ts +0 -22
  65. package/types/lalr/index.d.ts +0 -2
  66. package/types/lalr/types.d.ts +0 -14
  67. package/types/lexer/Lexer.d.ts +0 -143
  68. package/types/lexer/index.d.ts +0 -1
  69. package/types/parser/AST.d.ts +0 -502
  70. package/types/parser/Grammar.d.ts +0 -11
  71. package/types/parser/GrammarSymbol.d.ts +0 -128
  72. package/types/parser/SemanticAnalyzer.d.ts +0 -42
  73. package/types/parser/ShaderInfo.d.ts +0 -10
  74. package/types/parser/ShaderTargetParser.d.ts +0 -26
  75. package/types/parser/builtin/functions.d.ts +0 -34
  76. package/types/parser/builtin/index.d.ts +0 -2
  77. package/types/parser/builtin/variables.d.ts +0 -11
  78. package/types/parser/index.d.ts +0 -2
  79. package/types/parser/symbolTable/FnSymbol.d.ts +0 -6
  80. package/types/parser/symbolTable/StructSymbol.d.ts +0 -6
  81. package/types/parser/symbolTable/SymbolDataType.d.ts +0 -8
  82. package/types/parser/symbolTable/SymbolInfo.d.ts +0 -22
  83. package/types/parser/symbolTable/VarSymbol.d.ts +0 -8
  84. package/types/parser/symbolTable/index.d.ts +0 -6
  85. package/types/parser/types.d.ts +0 -24
  86. package/types/sourceParser/ShaderSourceFactory.d.ts +0 -8
  87. package/types/sourceParser/ShaderSourceParser.d.ts +0 -30
  88. package/types/sourceParser/ShaderSourceSymbol.d.ts +0 -10
  89. package/types/sourceParser/SourceLexer.d.ts +0 -19
  90. package/types/sourceParser/index.d.ts +0 -1
  91. package/verbose/package.json +0 -10
@@ -0,0 +1,2280 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var analyzer = require('@galacean/engine-shader-parser/internal/analyzer');
6
+ var engineCore = require('@galacean/engine-core');
7
+ var engineMath = require('@galacean/engine-math');
8
+ var internal = require('@galacean/engine-shader-parser/internal');
9
+
10
+ function _set_prototype_of(o, p) {
11
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
12
+ o.__proto__ = p;
13
+
14
+ return o;
15
+ };
16
+
17
+ return _set_prototype_of(o, p);
18
+ }
19
+
20
+ function _inherits(subClass, superClass) {
21
+ if (typeof superClass !== "function" && superClass !== null) {
22
+ throw new TypeError("Super expression must either be null or a function");
23
+ }
24
+
25
+ subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
26
+
27
+ if (superClass) _set_prototype_of(subClass, superClass);
28
+ }
29
+
30
+ function _instanceof(left, right) {
31
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
32
+ return !!right[Symbol.hasInstance](left);
33
+ } else return left instanceof right;
34
+ }
35
+
36
+ function _is_native_reflect_construct() {
37
+ // Since Reflect.construct can't be properly polyfilled, some
38
+ // implementations (e.g. core-js@2) don't set the correct internal slots.
39
+ // Those polyfills don't allow us to subclass built-ins, so we need to
40
+ // use our fallback implementation.
41
+ try {
42
+ // If the internal slots aren't set, this throws an error similar to
43
+ // TypeError: this is not a Boolean object.
44
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
45
+ } catch (_) {}
46
+ return (_is_native_reflect_construct = function() {
47
+ return !!result;
48
+ })();
49
+ }
50
+
51
+ function _construct(Parent, args, Class) {
52
+ if (_is_native_reflect_construct()) _construct = Reflect.construct;
53
+ else {
54
+ _construct = function construct(Parent, args, Class) {
55
+ var a = [null];
56
+ a.push.apply(a, args);
57
+ var Constructor = Function.bind.apply(Parent, a);
58
+ var instance = new Constructor();
59
+
60
+ if (Class) _set_prototype_of(instance, Class.prototype);
61
+
62
+ return instance;
63
+ };
64
+ }
65
+
66
+ return _construct.apply(null, arguments);
67
+ }
68
+
69
+ function _get_prototype_of(o) {
70
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
71
+ return o.__proto__ || Object.getPrototypeOf(o);
72
+ };
73
+
74
+ return _get_prototype_of(o);
75
+ }
76
+
77
+ function _is_native_function(fn) {
78
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
79
+ }
80
+
81
+ function _wrap_native_super(Class) {
82
+ var _cache = typeof Map === "function" ? new Map() : undefined;
83
+ _wrap_native_super = function(Class) {
84
+ if (Class === null || !_is_native_function(Class)) return Class;
85
+ if (typeof Class !== "function") throw new TypeError("Super expression must either be null or a function");
86
+ if (typeof _cache !== "undefined") {
87
+ if (_cache.has(Class)) return _cache.get(Class);
88
+ _cache.set(Class, Wrapper);
89
+ }
90
+
91
+ function Wrapper() {
92
+ return _construct(Class, arguments, _get_prototype_of(this).constructor);
93
+ }
94
+ Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } });
95
+
96
+ return _set_prototype_of(Wrapper, Class);
97
+ };
98
+
99
+ return _wrap_native_super(Class);
100
+ }
101
+
102
+ function _array_like_to_array(arr, len) {
103
+ if (len == null || len > arr.length) len = arr.length;
104
+
105
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
106
+
107
+ return arr2;
108
+ }
109
+
110
+ function _unsupported_iterable_to_array(o, minLen) {
111
+ if (!o) return;
112
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
113
+
114
+ var n = Object.prototype.toString.call(o).slice(8, -1);
115
+
116
+ if (n === "Object" && o.constructor) n = o.constructor.name;
117
+ if (n === "Map" || n === "Set") return Array.from(n);
118
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
119
+ }
120
+
121
+ function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
122
+ var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
123
+
124
+ if (it) return (it = it.call(o)).next.bind(it);
125
+ // Fallback for engines without symbol support
126
+ if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike && o && typeof o.length === "number") {
127
+ if (it) o = it;
128
+
129
+ var i = 0;
130
+
131
+ return function() {
132
+ if (i >= o.length) return { done: true };
133
+
134
+ return { done: false, value: o[i++] };
135
+ };
136
+ }
137
+
138
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
139
+ }
140
+
141
+ function _defineProperties(target, props) {
142
+ for (var i = 0; i < props.length; i++) {
143
+ var descriptor = props[i];
144
+ descriptor.enumerable = descriptor.enumerable || false;
145
+ descriptor.configurable = true;
146
+
147
+ if ("value" in descriptor) descriptor.writable = true;
148
+
149
+ Object.defineProperty(target, descriptor.key, descriptor);
150
+ }
151
+ }
152
+ function _create_class(Constructor, protoProps, staticProps) {
153
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
154
+ if (staticProps) _defineProperties(Constructor, staticProps);
155
+
156
+ return Constructor;
157
+ }
158
+
159
+ /** @internal */ var VisitorContext = /*#__PURE__*/ function() {
160
+ function VisitorContext() {
161
+ this._lookupSymbol = new internal.SymbolInfo("", null);
162
+ this._structRoles = new Map();
163
+ this._vertexUnresolvedVariableRoles = new Map();
164
+ this._fragmentUnresolvedVariableRoles = new Map();
165
+ this._vertexAmbiguousVariableNames = new Set();
166
+ this._fragmentAmbiguousVariableNames = new Set();
167
+ this.attributeStructs = [];
168
+ this.attributeList = [];
169
+ this.varyingStructs = [];
170
+ this.varyingList = [];
171
+ this.mrtStructs = [];
172
+ this.mrtList = [];
173
+ this._referencedGlobalSymbols = new Set();
174
+ this._referencedGlobalMacroASTs = [];
175
+ this._structVariableRoles = new Map();
176
+ this.codeCache = new Map();
177
+ this.fragmentReturnModes = new Map();
178
+ this.terminalInterfaceReturns = new Set();
179
+ this.reset();
180
+ }
181
+ var _proto = VisitorContext.prototype;
182
+ _proto.reset = function reset(resetAll) {
183
+ if (resetAll === void 0) resetAll = true;
184
+ this.codeCache.clear();
185
+ this.fragmentReturnModes.clear();
186
+ this.terminalInterfaceReturns.clear();
187
+ if (resetAll) {
188
+ this.attributeStructs.length = 0;
189
+ this.attributeList.length = 0;
190
+ this.varyingStructs.length = 0;
191
+ this.varyingList.length = 0;
192
+ this.mrtStructs.length = 0;
193
+ this.mrtList.length = 0;
194
+ this._structRoles.clear();
195
+ this._vertexUnresolvedVariableRoles.clear();
196
+ this._fragmentUnresolvedVariableRoles.clear();
197
+ this._vertexAmbiguousVariableNames.clear();
198
+ this._fragmentAmbiguousVariableNames.clear();
199
+ }
200
+ this._referencedAttributeList = Object.create(null);
201
+ this._referencedVaryingList = Object.create(null);
202
+ this._referencedMRTList = Object.create(null);
203
+ this._referencedGlobals = Object.create(null);
204
+ this._referencedGlobalSymbols.clear();
205
+ this._globalSymbolQueries = Object.create(null);
206
+ this._referencedGlobalMacroASTs.length = 0;
207
+ if (resetAll) {
208
+ this._structVariableRoles.clear();
209
+ this._passSymbolTable = undefined;
210
+ }
211
+ };
212
+ /**
213
+ * Finds the shared interface role of custom-struct declaration candidates.
214
+ * @param declarations - Exact parser struct identities resolved at one type occurrence.
215
+ * @returns Interface role, or `undefined` when the type is not an unambiguous interface struct.
216
+ */ _proto.getStructRole = function getStructRole(declarations) {
217
+ var resolvedRole;
218
+ for(var _iterator = _create_for_of_iterator_helper_loose(declarations), _step; !(_step = _iterator()).done;){
219
+ var declaration = _step.value;
220
+ var role = this._structRoles.get(declaration);
221
+ if (!role || resolvedRole && resolvedRole !== role) return;
222
+ resolvedRole = role;
223
+ }
224
+ return resolvedRole;
225
+ };
226
+ /**
227
+ * Tests the exact interface role of one struct declaration.
228
+ * @param declaration - Parser struct identity.
229
+ * @param role - Expected interface role.
230
+ * @returns Whether the declaration owns that role.
231
+ */ _proto.hasStructRole = function hasStructRole(declaration, role) {
232
+ return this._structRoles.get(declaration) === role;
233
+ };
234
+ /**
235
+ * Registers stage-interface struct types for constant-time role lookup.
236
+ * @param role - Interface role shared by the supplied structs.
237
+ * @param structs - Struct declarations derived from parser IR.
238
+ * @internal
239
+ */ _proto.registerStructTypes = function registerStructTypes(role, structs) {
240
+ for(var _iterator = _create_for_of_iterator_helper_loose(structs), _step; !(_step = _iterator()).done;){
241
+ var struct = _step.value;
242
+ this._structRoles.set(struct, role);
243
+ }
244
+ };
245
+ /**
246
+ * Registers a resolved variable that holds an interface struct.
247
+ * @param variable - Parser symbol identity for the declaration.
248
+ * @param role - Struct interface role.
249
+ * @param stage - Optional stage from whose entry the variable is reachable. Omit when only exact
250
+ * symbol lookup is required.
251
+ */ _proto.registerStructVar = function registerStructVar(variable, role, stage) {
252
+ this._structVariableRoles.set(variable, role);
253
+ if (stage === undefined) return;
254
+ var roles = stage === internal.EShaderStage.VERTEX ? this._vertexUnresolvedVariableRoles : this._fragmentUnresolvedVariableRoles;
255
+ var ambiguous = stage === internal.EShaderStage.VERTEX ? this._vertexAmbiguousVariableNames : this._fragmentAmbiguousVariableNames;
256
+ var name = variable.ident;
257
+ if (ambiguous.has(name)) return;
258
+ var existing = roles.get(name);
259
+ if (existing && existing !== role) {
260
+ roles.delete(name);
261
+ ambiguous.add(name);
262
+ } else {
263
+ roles.set(name, role);
264
+ }
265
+ };
266
+ /**
267
+ * Finds an interface role for a global macro value that has no lexical symbol identity.
268
+ * @param variableName - Bare variable name in the macro replacement AST.
269
+ * @returns A role only when every stage-reachable declaration with that name agrees.
270
+ */ _proto.getUnresolvedStructVarRole = function getUnresolvedStructVarRole(variableName) {
271
+ var roles = this.stage === internal.EShaderStage.VERTEX ? this._vertexUnresolvedVariableRoles : this._fragmentUnresolvedVariableRoles;
272
+ var ambiguous = this.stage === internal.EShaderStage.VERTEX ? this._vertexAmbiguousVariableNames : this._fragmentAmbiguousVariableNames;
273
+ return ambiguous.has(variableName) ? undefined : roles.get(variableName);
274
+ };
275
+ /**
276
+ * Finds the shared interface role of branch-visible variable candidates.
277
+ * @param symbols - Exact parser symbols resolved at one reference.
278
+ * @returns Interface role, or `undefined` when the reference is not an unambiguous interface value.
279
+ */ _proto.getStructVarRole = function getStructVarRole(symbols) {
280
+ var resolvedRole;
281
+ for(var _iterator = _create_for_of_iterator_helper_loose(symbols), _step; !(_step = _iterator()).done;){
282
+ var symbol = _step.value;
283
+ if (!_instanceof(symbol, internal.VarSymbol)) return;
284
+ var role = this._structVariableRoles.get(symbol);
285
+ if (!role || resolvedRole && resolvedRole !== role) return;
286
+ resolvedRole = role;
287
+ }
288
+ return resolvedRole;
289
+ };
290
+ /**
291
+ * Marks a value-return belonging to a fragment entry for backend lowering.
292
+ * @param statement - Exact return statement identity.
293
+ * @param mode - Fragment output contract of the containing entry declaration.
294
+ */ _proto.registerFragmentReturn = function registerFragmentReturn(statement, mode) {
295
+ this.fragmentReturnModes.set(statement, mode);
296
+ };
297
+ /**
298
+ * Finds the output contract for a fragment-entry return statement.
299
+ * @param statement - Return statement identity.
300
+ * @returns Output mode, or `undefined` for ordinary helper/vertex returns.
301
+ */ _proto.getFragmentReturnMode = function getFragmentReturnMode(statement) {
302
+ return this.fragmentReturnModes.get(statement);
303
+ };
304
+ /** Marks a syntactically final interface return whose control-flow exit can be omitted. */ _proto.registerTerminalInterfaceReturn = function registerTerminalInterfaceReturn(statement) {
305
+ this.terminalInterfaceReturns.add(statement);
306
+ };
307
+ /**
308
+ * Tests whether an interface return is the final syntactic statement in its function.
309
+ * @param statement - Return statement identity.
310
+ * @returns Whether backend lowering may omit a trailing `return;`.
311
+ */ _proto.isTerminalInterfaceReturn = function isTerminalInterfaceReturn(statement) {
312
+ return this.terminalInterfaceReturns.has(statement);
313
+ };
314
+ _proto.referenceAttribute = function referenceAttribute(ident) {
315
+ this._referenceProp(ident.lexeme, this.attributeList, this._referencedAttributeList);
316
+ };
317
+ _proto.referenceVarying = function referenceVarying(ident) {
318
+ this._referenceProp(ident.lexeme, this.varyingList, this._referencedVaryingList);
319
+ };
320
+ _proto.referenceMRTProp = function referenceMRTProp(ident) {
321
+ this._referenceProp(ident.lexeme, this.mrtList, this._referencedMRTList);
322
+ };
323
+ _proto.referenceGlobal = function referenceGlobal(ident, type) {
324
+ var _this__globalSymbolQueries, _ident;
325
+ var _;
326
+ var queries = (_ = (_this__globalSymbolQueries = this._globalSymbolQueries)[_ident = ident]) != null ? _ : _this__globalSymbolQueries[_ident] = Object.create(null);
327
+ var symbols = queries[type];
328
+ if (!symbols) {
329
+ var _this__referencedGlobals, _ident1;
330
+ this._lookupSymbol.set(ident, type);
331
+ symbols = queries[type] = this._passSymbolTable.getSymbols(this._lookupSymbol, true, []);
332
+ var _1;
333
+ var namedSymbols = (_1 = (_this__referencedGlobals = this._referencedGlobals)[_ident1 = ident]) != null ? _1 : _this__referencedGlobals[_ident1] = [];
334
+ for(var _iterator = _create_for_of_iterator_helper_loose(symbols), _step; !(_step = _iterator()).done;){
335
+ var symbol = _step.value;
336
+ if (!this._referencedGlobalSymbols.has(symbol)) {
337
+ this._referencedGlobalSymbols.add(symbol);
338
+ namedSymbols.push(symbol);
339
+ }
340
+ }
341
+ }
342
+ // Repeated uses still establish edges from each declaration's owner.
343
+ this.onReferenceGlobal == null ? void 0 : this.onReferenceGlobal.call(this, symbols);
344
+ };
345
+ // Track which IO props are actually referenced (drives in/out emission). A missing member is no
346
+ // longer flagged here — that's the parser's struct-field check (UndeclaredStructMember).
347
+ _proto._referenceProp = function _referenceProp(name, list, refList) {
348
+ if (!refList[name]) refList[name] = list.filter(function(item) {
349
+ return item.ident.lexeme === name;
350
+ });
351
+ this.onReferenceStructProps == null ? void 0 : this.onReferenceStructProps.call(this, refList[name]);
352
+ };
353
+ return VisitorContext;
354
+ }();
355
+
356
+ var TempArray = /*#__PURE__*/ function() {
357
+ function TempArray() {
358
+ this.array = new Array();
359
+ }
360
+ var _proto = TempArray.prototype;
361
+ _proto.dispose = function dispose() {
362
+ this.array.length = 0;
363
+ };
364
+ return TempArray;
365
+ }();
366
+
367
+ /**
368
+ * @internal
369
+ * The code generator
370
+ */ var CodeGenVisitor = /*#__PURE__*/ function() {
371
+ function CodeGenVisitor() {
372
+ this.context = new VisitorContext();
373
+ }
374
+ var _proto = CodeGenVisitor.prototype;
375
+ _proto.cache = function cache(node, code) {
376
+ this.context.codeCache.set(node, code);
377
+ return code;
378
+ };
379
+ _proto.getCachedCode = function getCachedCode(node) {
380
+ return this.context.codeCache.get(node);
381
+ };
382
+ _proto.defaultCodeGen = function defaultCodeGen(children) {
383
+ var pool = CodeGenVisitor._tmpArrayPool;
384
+ var ret = pool.get();
385
+ ret.dispose();
386
+ for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
387
+ var child = _step.value;
388
+ if (_instanceof(child, internal.BaseToken)) {
389
+ // Legacy opaque `#define` lexemes carry the directive verbatim; expression-style defines use the AST path
390
+ ret.array.push(child.lexeme);
391
+ } else {
392
+ ret.array.push(child.codeGen(this));
393
+ }
394
+ }
395
+ var result = ret.array.join(" ");
396
+ ret.dispose();
397
+ pool.return(ret);
398
+ return result;
399
+ };
400
+ _proto.visitPostfixExpression = function visitPostfixExpression(node) {
401
+ var children = node.children;
402
+ var derivationLength = children.length;
403
+ var context = this.context;
404
+ if (derivationLength === 3) {
405
+ var postExpr = children[0];
406
+ var prop = children[2];
407
+ if (_instanceof(prop, internal.BaseToken)) {
408
+ // Direct variables use parser symbol identity so lexical shadowing cannot inherit an IO role
409
+ // from a same-named declaration. Macro-expanded identifiers can lack a resolved symbol, so
410
+ // only that zero-symbol path consults the current stage's unambiguous name-to-role map.
411
+ var role;
412
+ var directRoot = internal.ParserUtils.unwrapBareIdentifier(postExpr, {
413
+ allowParens: true
414
+ });
415
+ if (directRoot) {
416
+ var symbols = directRoot.resolvedValueSymbols();
417
+ var unresolvedName = internal.ParserUtils.extractDirectIdentLexeme(postExpr);
418
+ role = symbols.length ? context.getStructVarRole(symbols) : unresolvedName ? context.getUnresolvedStructVarRole(unresolvedName) : undefined;
419
+ }
420
+ if (role) {
421
+ if (role === internal.ShaderStructRole.Attribute) context.referenceAttribute(prop);
422
+ else if (role === internal.ShaderStructRole.Varying) context.referenceVarying(prop);
423
+ else context.referenceMRTProp(prop);
424
+ return prop.lexeme;
425
+ }
426
+ return postExpr.codeGen(this) + "." + prop.lexeme;
427
+ } else {
428
+ return postExpr.codeGen(this) + "." + prop.codeGen(this);
429
+ }
430
+ } else if (derivationLength === 4) {
431
+ var identNode = children[0];
432
+ var indexNode = children[2];
433
+ return identNode.codeGen(this) + "[" + indexNode.codeGen(this) + "]";
434
+ }
435
+ return this.defaultCodeGen(node.children);
436
+ };
437
+ _proto.visitVariableIdentifier = function visitVariableIdentifier(node) {
438
+ for(var _iterator = _create_for_of_iterator_helper_loose(node.referenceGlobalSymbolNames), _step; !(_step = _iterator()).done;){
439
+ var name = _step.value;
440
+ this.context.referenceGlobal(name, internal.ESymbolType.Any);
441
+ }
442
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(node.resolvedSymbols()), _step1; !(_step1 = _iterator1()).done;){
443
+ var symbol = _step1.value;
444
+ if (_instanceof(symbol, internal.FnSymbol)) this.referenceFunction(symbol, node.location.start.index, node._branch);
445
+ }
446
+ return node.getLexeme(this);
447
+ };
448
+ _proto.referenceFunction = function referenceFunction(symbol, referenceIndex, branch) {
449
+ this.context.referenceGlobal(symbol.ident, internal.ESymbolType.FN);
450
+ };
451
+ _proto.visitFunctionCall = function visitFunctionCall(node) {
452
+ var call = node.children[0];
453
+ if (_instanceof(call.fnSymbol, internal.FnSymbol)) {
454
+ var _call_fnSymbols;
455
+ for(var _iterator = _create_for_of_iterator_helper_loose(((_call_fnSymbols = call.fnSymbols) == null ? void 0 : _call_fnSymbols.length) ? call.fnSymbols : [
456
+ call.fnSymbol
457
+ ]), _step; !(_step = _iterator()).done;){
458
+ var symbol = _step.value;
459
+ this.referenceFunction(symbol, node.location.start.index, node._branch);
460
+ }
461
+ var paramList = call.children[2];
462
+ if (_instanceof(paramList, internal.ASTNode.FunctionCallParameterList)) {
463
+ var astNodes = paramList.paramNodes;
464
+ var finalSymbol = this.context._referencedGlobals[call.fnSymbol.ident].find(function(candidate) {
465
+ return _instanceof(candidate, internal.FnSymbol) && candidate.equal(call.fnSymbol);
466
+ });
467
+ var paramInfoList = (finalSymbol != null ? finalSymbol : call.fnSymbol).astNode.protoType.parameterList;
468
+ var context = this.context;
469
+ var params = astNodes.filter(function(_, i) {
470
+ var _paramInfoList_i;
471
+ var parameter = paramInfoList == null ? void 0 : (_paramInfoList_i = paramInfoList[i]) == null ? void 0 : _paramInfoList_i.astNode;
472
+ // Drop struct-IO parameters (attribute/varying/mrt) — they're flattened
473
+ // into top-level declarations and no longer exist as function-call args.
474
+ return !_instanceof(parameter, internal.ASTNode.ParameterDeclaration) || !parameter.symbol || !context.getStructVarRole([
475
+ parameter.symbol
476
+ ]);
477
+ });
478
+ var paramsCode = "";
479
+ for(var i = 0, length = params.length; i < length; i++){
480
+ var astNode = params[i];
481
+ var code = astNode.codeGen(this);
482
+ if (_instanceof(astNode, internal.ASTNode.MacroCallArgBlock) || i === 0) {
483
+ paramsCode += code;
484
+ } else {
485
+ paramsCode += ", " + code;
486
+ }
487
+ }
488
+ return call.fnSymbol.ident + "(" + paramsCode + ")";
489
+ }
490
+ }
491
+ return this.defaultCodeGen(node.children);
492
+ };
493
+ _proto.visitMacroCallFunction = function visitMacroCallFunction(node) {
494
+ var children = node.children;
495
+ var paramList = children[2];
496
+ if (_instanceof(paramList, internal.ASTNode.FunctionCallParameterList)) {
497
+ var astNodes = paramList.paramNodes;
498
+ var context = this.context;
499
+ // Drop bare IO-struct args only when the macro aliases a user fn (whose
500
+ // formal was flattened). All other shapes preserve args verbatim.
501
+ var params;
502
+ if (node.isFunctionLikeMacro || !node.aliasesNonBuiltinIdent) {
503
+ params = astNodes;
504
+ } else {
505
+ params = astNodes.filter(function(arg) {
506
+ if (_instanceof(arg, internal.ASTNode.AssignmentExpression)) {
507
+ var variableParam = internal.ParserUtils.unwrapBareIdentifier(arg, {
508
+ allowParens: false
509
+ });
510
+ if (variableParam && context.getStructVarRole(variableParam.resolvedValueSymbols())) {
511
+ return false;
512
+ }
513
+ }
514
+ return true;
515
+ });
516
+ }
517
+ var paramsCode = "";
518
+ for(var i = 0, length = params.length; i < length; i++){
519
+ var argNode = params[i];
520
+ var code = argNode.codeGen(this);
521
+ if (_instanceof(argNode, internal.ASTNode.MacroCallArgBlock) || i === 0) {
522
+ paramsCode += code;
523
+ } else {
524
+ paramsCode += ", " + code;
525
+ }
526
+ }
527
+ return node.macroName + "(" + paramsCode + ")";
528
+ } else {
529
+ return this.defaultCodeGen(node.children);
530
+ }
531
+ };
532
+ _proto.visitStatementList = function visitStatementList(node) {
533
+ var children = node.children;
534
+ if (children.length === 1) {
535
+ return children[0].codeGen(this);
536
+ } else {
537
+ return children[0].codeGen(this) + "\n" + children[1].codeGen(this);
538
+ }
539
+ };
540
+ /**
541
+ * Code-generate a `#define` macro parsed as expression AST. Produces a `#define`
542
+ * directive whose value is the AST-rewritten string — so varying flattening
543
+ * happens naturally via `visitPostfixExpression` inside the AST walk.
544
+ */ _proto.visitMacroDefine = function visitMacroDefine(node) {
545
+ // For function-like macros, preserve the original `(params)` lexeme verbatim —
546
+ // the parameter list is user-authored text that shouldn't be canonicalized.
547
+ var paramsLexeme = "";
548
+ if (node.isFunction) {
549
+ var paramsToken = node.children[2];
550
+ if (_instanceof(paramsToken, internal.BaseToken)) paramsLexeme = paramsToken.lexeme;
551
+ }
552
+ var valueCode = node.valueExpression ? node.valueExpression.codeGen(this) : "";
553
+ // Newlines around the directive keep `#` at the start of its physical line per
554
+ // GLSL ES 3.0 §3.4, regardless of how surrounding tokens are joined.
555
+ return "\n#define " + node.macroName + paramsLexeme + (valueCode ? " " + valueCode : "") + "\n";
556
+ };
557
+ _proto.visitSingleDeclaration = function visitSingleDeclaration(node) {
558
+ return this.defaultCodeGen(node.children);
559
+ };
560
+ _proto.visitGlobalVariableDeclaration = function visitGlobalVariableDeclaration(node) {
561
+ var children = node.children;
562
+ var fullType = children[0];
563
+ if (_instanceof(fullType, internal.ASTNode.FullySpecifiedType) && fullType.typeSpecifier.isCustom) {
564
+ var context = this.context;
565
+ // Global interface variables are flattened and therefore are not emitted as uniforms.
566
+ if (context.getStructVarRole([
567
+ node.declarator.symbol
568
+ ])) {
569
+ return "";
570
+ }
571
+ context.referenceGlobal(fullType.type, internal.ESymbolType.STRUCT);
572
+ }
573
+ return "uniform " + this.defaultCodeGen(children);
574
+ };
575
+ _proto.visitDeclaration = function visitDeclaration(node) {
576
+ var context = this.context;
577
+ var children = node.children;
578
+ var child = children[0];
579
+ if (_instanceof(child, internal.ASTNode.InitDeclaratorList)) {
580
+ var first = child.children[0];
581
+ var _child_declarator;
582
+ var declarator = (_child_declarator = child.declarator) != null ? _child_declarator : _instanceof(first, internal.ASTNode.SingleDeclaration) ? first.declarator : undefined;
583
+ var role = declarator && context.getStructVarRole([
584
+ declarator.symbol
585
+ ]);
586
+ if (role === internal.ShaderStructRole.Varying || role === internal.ShaderStructRole.Mrt) return "";
587
+ }
588
+ return this.defaultCodeGen(children);
589
+ };
590
+ _proto.visitFunctionParameterList = function visitFunctionParameterList(node) {
591
+ var context = this.context;
592
+ var params = node.parameterInfoList.filter(function(item) {
593
+ var parameter = item.astNode;
594
+ return !_instanceof(parameter, internal.ASTNode.ParameterDeclaration) || !parameter.symbol || !context.getStructVarRole([
595
+ parameter.symbol
596
+ ]);
597
+ });
598
+ var out = "";
599
+ for(var i = 0, length = params.length; i < length; i++){
600
+ var item = params[i];
601
+ var astNode = item.astNode;
602
+ var code = astNode.codeGen(this);
603
+ if (_instanceof(astNode, internal.ASTNode.MacroParamBlock) || i === 0) {
604
+ out += code;
605
+ } else {
606
+ out += ", " + code;
607
+ }
608
+ }
609
+ return out;
610
+ };
611
+ _proto.visitFunctionHeader = function visitFunctionHeader(node) {
612
+ var returnType = node.returnType.typeSpecifier;
613
+ if (this.context.getStructRole(returnType.structDeclarations) === internal.ShaderStructRole.Varying) {
614
+ return "void " + node.ident.lexeme + "(";
615
+ }
616
+ return this.defaultCodeGen(node.children);
617
+ };
618
+ _proto.visitJumpStatement = function visitJumpStatement(node) {
619
+ var children = node.children;
620
+ var cmd = children[0];
621
+ if (cmd.type === internal.Keyword.RETURN) {
622
+ var expr = children[1];
623
+ if (_instanceof(expr, internal.ASTNode.Expression)) {
624
+ var returnVar = internal.ParserUtils.unwrapNodeByType(expr, internal.NoneTerminal.variable_identifier);
625
+ if (returnVar && this.context.getStructVarRole(returnVar.resolvedValueSymbols()) === internal.ShaderStructRole.Varying) {
626
+ return this.context.isTerminalInterfaceReturn(node) ? "" : "return;";
627
+ }
628
+ var returnFnCall = internal.ParserUtils.unwrapNodeByType(expr, internal.NoneTerminal.function_call);
629
+ var calledFunction = returnFnCall == null ? void 0 : returnFnCall.children[0];
630
+ var returnDeclarations = _instanceof(calledFunction == null ? void 0 : calledFunction.fnSymbol, internal.FnSymbol) ? calledFunction.fnSymbol.astNode.protoType.returnType.typeSpecifier.structDeclarations : [];
631
+ if (this.context.getStructRole(returnDeclarations) === internal.ShaderStructRole.Varying) {
632
+ var call = "" + expr.codeGen(this) + ";";
633
+ return this.context.isTerminalInterfaceReturn(node) ? call : "{ " + call + " return; }";
634
+ }
635
+ }
636
+ }
637
+ return this.defaultCodeGen(children);
638
+ };
639
+ _proto.visitFunctionIdentifier = function visitFunctionIdentifier(node) {
640
+ return this.defaultCodeGen(node.children);
641
+ };
642
+ _proto.visitTypeSpecifier = function visitTypeSpecifier(node) {
643
+ return this.defaultCodeGen(node.children);
644
+ };
645
+ _proto.visitStructSpecifier = function visitStructSpecifier(node) {
646
+ var _this = this;
647
+ var context = this.context;
648
+ var varyingStructs = context.varyingStructs, attributeStructs = context.attributeStructs, mrtStructs = context.mrtStructs;
649
+ var isVaryingStruct = varyingStructs.indexOf(node) !== -1;
650
+ var isAttributeStruct = attributeStructs.indexOf(node) !== -1;
651
+ var isMRTStruct = mrtStructs.indexOf(node) !== -1;
652
+ if (isVaryingStruct || isAttributeStruct || isMRTStruct) {
653
+ var _result;
654
+ var result = [];
655
+ (_result = result).push.apply(_result, [].concat(node.macroExpressions.map(function(item) {
656
+ return {
657
+ text: _instanceof(item, internal.BaseToken) ? item.lexeme : item.codeGen(_this),
658
+ index: item.location.start.index
659
+ };
660
+ })));
661
+ for(var _iterator = _create_for_of_iterator_helper_loose(node.propList), _step; !(_step = _iterator()).done;){
662
+ var prop = _step.value;
663
+ var _context__referencedVaryingList_name, _context__referencedAttributeList_name, _context__referencedMRTList_name;
664
+ var name = prop.ident.lexeme;
665
+ if (isVaryingStruct && ((_context__referencedVaryingList_name = context._referencedVaryingList[name]) == null ? void 0 : _context__referencedVaryingList_name.indexOf(prop)) >= 0) {
666
+ result.push({
667
+ text: "" + this.getVaryingProp(prop) + "\n",
668
+ index: prop.ident.location.start.index
669
+ });
670
+ } else if (isAttributeStruct && ((_context__referencedAttributeList_name = context._referencedAttributeList[name]) == null ? void 0 : _context__referencedAttributeList_name.indexOf(prop)) >= 0) {
671
+ result.push({
672
+ text: "" + this.getAttributeProp(prop) + "\n",
673
+ index: prop.ident.location.start.index
674
+ });
675
+ } else if (isMRTStruct && ((_context__referencedMRTList_name = context._referencedMRTList[name]) == null ? void 0 : _context__referencedMRTList_name.indexOf(prop)) >= 0) {
676
+ result.push({
677
+ text: "" + this.getMRTProp(prop) + "\n",
678
+ index: prop.ident.location.start.index
679
+ });
680
+ }
681
+ }
682
+ var text = result.sort(function(a, b) {
683
+ return a.index - b.index;
684
+ }).map(function(item) {
685
+ return item.text;
686
+ }).join("");
687
+ return text;
688
+ } else {
689
+ return this.defaultCodeGen(node.children);
690
+ }
691
+ };
692
+ _proto.visitFunctionDefinition = function visitFunctionDefinition(fnNode) {
693
+ var fnName = fnNode.protoType.ident.lexeme;
694
+ var context = this.context;
695
+ var terminal = internal.ParserUtils.lastStatement(fnNode.statements);
696
+ if (_instanceof(terminal, internal.ASTNode.JumpStatement)) context.registerTerminalInterfaceReturn(terminal);
697
+ if (fnName == context.stageEntry) {
698
+ var statements = fnNode.statements.codeGen(this);
699
+ return "void main() " + statements;
700
+ } else {
701
+ return this.defaultCodeGen(fnNode.children);
702
+ }
703
+ };
704
+ return CodeGenVisitor;
705
+ }();
706
+ CodeGenVisitor._tmpArrayPool = new engineCore.ReturnableObjectPool(TempArray, 10);
707
+
708
+ /**
709
+ * @internal
710
+ */ var ShaderInstructionEncoder = /*#__PURE__*/ function() {
711
+ function ShaderInstructionEncoder() {}
712
+ /**
713
+ * Marks compiler-owned text without placing parser objects in the instruction stream.
714
+ * @param text - Declaration or derived declaration text.
715
+ * @param owner - Neutral declaration identity, if runtime selection is required.
716
+ * @param activate - Whether this is the declaration's original source position.
717
+ * @returns Intermediate source consumed by the instruction encoder.
718
+ * @internal
719
+ */ ShaderInstructionEncoder.declaration = function declaration(text, owner, activate) {
720
+ if (activate === void 0) activate = true;
721
+ if (!owner) return text;
722
+ var activation = activate ? "\0D" + owner.id + "," + owner.group + "," + owner.sourceScope + "\0\n" : "";
723
+ return text ? activation + "\0T" + owner.id + "\0\n" + text + "\n\0E\0\n" : activation;
724
+ };
725
+ /**
726
+ * Marks derived text shared by any selected, reachable declaration without activating an owner.
727
+ * @param text - Shared derived declaration text.
728
+ * @param owners - Declarations that require the text; an empty list never retains it.
729
+ * @returns Intermediate source consumed by the instruction encoder.
730
+ * @internal
731
+ */ ShaderInstructionEncoder.sharedDeclaration = function sharedDeclaration(text, owners) {
732
+ return text ? "\0T" + owners.map(function(owner) {
733
+ return owner.id;
734
+ }).join(",") + "\0\n" + text + "\n\0E\0\n" : "";
735
+ };
736
+ /**
737
+ * Records a declaration dependency for variant-time reachability after ownership selection.
738
+ * @param from - Referencing declaration identity, or zero for a stage root.
739
+ * @param to - Referenced declaration identity.
740
+ * @returns Intermediate source consumed by the instruction encoder.
741
+ * @internal
742
+ */ ShaderInstructionEncoder.reference = function reference(from, to) {
743
+ return "\0R" + from + "," + to + "\0\n";
744
+ };
745
+ /**
746
+ * Removes private emission markers from the public source view after instruction encoding.
747
+ * @param source - Encoded intermediate stage source.
748
+ * @returns GLSL source without compiler metadata.
749
+ * @internal
750
+ */ ShaderInstructionEncoder.source = function source(source) {
751
+ return source.indexOf("\0") < 0 ? source : source.replace(/\0[^\0]*\0\n?/g, "");
752
+ };
753
+ /**
754
+ * Encodes generated GLSL directives into runtime-selectable instructions.
755
+ * @param glsl - Generated stage source.
756
+ * @param preprocessorExpressions - Parser-owned expression trees keyed by logical directive text.
757
+ * @returns Runtime shader instruction stream.
758
+ * @throws Error when a conditional directive is malformed or has a deterministic evaluation failure.
759
+ * @internal
760
+ */ ShaderInstructionEncoder.parse = function parse(glsl, preprocessorExpressions) {
761
+ var instructions = [];
762
+ var length = glsl.length;
763
+ var pos = 0;
764
+ var owners;
765
+ var backfillStack = [];
766
+ while(pos < length){
767
+ var directiveStart = ShaderInstructionEncoder._findDirectiveStart(glsl, pos, length);
768
+ if (directiveStart === -1) {
769
+ ShaderInstructionEncoder._pushText(instructions, glsl, pos, length, owners);
770
+ break;
771
+ }
772
+ if (directiveStart > pos) {
773
+ ShaderInstructionEncoder._pushText(instructions, glsl, pos, directiveStart, owners);
774
+ }
775
+ var lineEnd = ShaderInstructionEncoder._findLogicalLineEnd(glsl, directiveStart, length);
776
+ var line = glsl.substring(directiveStart, lineEnd).replace(/\\(?:\r\n|\n|\r)/g, "");
777
+ pos = lineEnd < length ? lineEnd + 1 : length;
778
+ if (line.charCodeAt(0) === 0) {
779
+ var kind = line.charAt(1);
780
+ if (kind === "D") {
781
+ var fields = line.slice(2, -1).split(",").map(Number);
782
+ instructions.push([
783
+ engineCore.ShaderPreprocessorDirective.Declaration,
784
+ fields[0],
785
+ fields[1],
786
+ fields[2]
787
+ ]);
788
+ } else if (kind === "R") {
789
+ var fields1 = line.slice(2, -1).split(",").map(Number);
790
+ instructions.push([
791
+ engineCore.ShaderPreprocessorDirective.Reference,
792
+ fields1[0],
793
+ fields1[1]
794
+ ]);
795
+ } else {
796
+ var ids = line.slice(2, -1);
797
+ owners = kind === "T" ? ids ? ids.split(",").map(Number) : [] : undefined;
798
+ }
799
+ continue;
800
+ }
801
+ var match = ShaderInstructionEncoder._DIRECTIVE_RE.exec(line);
802
+ if (!match) {
803
+ var text = lineEnd < length ? line + "\n" : line;
804
+ ShaderInstructionEncoder._pushText(instructions, text, 0, text.length, owners);
805
+ continue;
806
+ }
807
+ var keyword = match[1];
808
+ var rest = match[2].trim();
809
+ switch(keyword){
810
+ case "ifdef":
811
+ {
812
+ var idx = instructions.length;
813
+ instructions.push([
814
+ engineCore.ShaderPreprocessorDirective.IfDef,
815
+ rest,
816
+ -1
817
+ ]);
818
+ backfillStack.push([
819
+ idx
820
+ ]);
821
+ break;
822
+ }
823
+ case "ifndef":
824
+ {
825
+ var idx1 = instructions.length;
826
+ instructions.push([
827
+ engineCore.ShaderPreprocessorDirective.IfNdef,
828
+ rest,
829
+ -1
830
+ ]);
831
+ backfillStack.push([
832
+ idx1
833
+ ]);
834
+ break;
835
+ }
836
+ case "if":
837
+ {
838
+ var cond = ShaderInstructionEncoder._parseCondition(rest, preprocessorExpressions);
839
+ var idx2 = instructions.length;
840
+ ShaderInstructionEncoder._pushConditionInstruction(instructions, cond);
841
+ backfillStack.push([
842
+ idx2
843
+ ]);
844
+ break;
845
+ }
846
+ case "elif":
847
+ {
848
+ var stack = backfillStack[backfillStack.length - 1];
849
+ var prevIdx = stack[stack.length - 1];
850
+ var elseIdx = instructions.length;
851
+ instructions.push([
852
+ engineCore.ShaderPreprocessorDirective.Else,
853
+ -1
854
+ ]);
855
+ stack.push(elseIdx);
856
+ ShaderInstructionEncoder._backfillJump(instructions[prevIdx], instructions.length);
857
+ var cond1 = ShaderInstructionEncoder._parseCondition(rest, preprocessorExpressions);
858
+ var idx3 = instructions.length;
859
+ ShaderInstructionEncoder._pushConditionInstruction(instructions, cond1);
860
+ stack.push(idx3);
861
+ break;
862
+ }
863
+ case "else":
864
+ {
865
+ var stack1 = backfillStack[backfillStack.length - 1];
866
+ var prevIdx1 = stack1[stack1.length - 1];
867
+ var elseIdx1 = instructions.length;
868
+ instructions.push([
869
+ engineCore.ShaderPreprocessorDirective.Else,
870
+ -1
871
+ ]);
872
+ stack1.push(elseIdx1);
873
+ ShaderInstructionEncoder._backfillJump(instructions[prevIdx1], instructions.length);
874
+ break;
875
+ }
876
+ case "endif":
877
+ {
878
+ var endifIdx = instructions.length;
879
+ instructions.push([
880
+ engineCore.ShaderPreprocessorDirective.Endif
881
+ ]);
882
+ var stack2 = backfillStack.pop();
883
+ if (stack2) {
884
+ var afterEndif = endifIdx + 1;
885
+ for(var j = 0; j < stack2.length; j++){
886
+ var inst = instructions[stack2[j]];
887
+ if (inst[0] === engineCore.ShaderPreprocessorDirective.Else) {
888
+ inst[1] = afterEndif;
889
+ } else {
890
+ ShaderInstructionEncoder._backfillJump(inst, afterEndif, true);
891
+ }
892
+ }
893
+ }
894
+ break;
895
+ }
896
+ case "define":
897
+ {
898
+ var funcMatch = ShaderInstructionEncoder._FUNC_MACRO_RE.exec(rest);
899
+ if (funcMatch) {
900
+ var params = funcMatch[2].split(",").map(function(p) {
901
+ return p.trim();
902
+ }).filter(function(p) {
903
+ return p.length > 0;
904
+ });
905
+ instructions.push([
906
+ engineCore.ShaderPreprocessorDirective.DefineFunc,
907
+ funcMatch[1],
908
+ params,
909
+ ShaderInstructionEncoder._stripLineComment(funcMatch[3].trim())
910
+ ]);
911
+ } else {
912
+ var separator = ShaderInstructionEncoder._findInlineWhitespace(rest);
913
+ if (separator === rest.length) {
914
+ instructions.push([
915
+ engineCore.ShaderPreprocessorDirective.Define,
916
+ rest
917
+ ]);
918
+ } else {
919
+ instructions.push([
920
+ engineCore.ShaderPreprocessorDirective.DefineVal,
921
+ rest.substring(0, separator),
922
+ ShaderInstructionEncoder._stripLineComment(rest.substring(separator + 1).trim())
923
+ ]);
924
+ }
925
+ }
926
+ break;
927
+ }
928
+ case "undef":
929
+ {
930
+ instructions.push([
931
+ engineCore.ShaderPreprocessorDirective.Undef,
932
+ rest
933
+ ]);
934
+ break;
935
+ }
936
+ }
937
+ }
938
+ return instructions;
939
+ };
940
+ ShaderInstructionEncoder._pushConditionInstruction = function _pushConditionInstruction(instructions, cond) {
941
+ if (cond.t === "def") {
942
+ instructions.push([
943
+ engineCore.ShaderPreprocessorDirective.IfDef,
944
+ cond.m,
945
+ -1
946
+ ]);
947
+ } else if (cond.t === "ndef") {
948
+ instructions.push([
949
+ engineCore.ShaderPreprocessorDirective.IfNdef,
950
+ cond.m,
951
+ -1
952
+ ]);
953
+ } else if (cond.t === "cmp") {
954
+ instructions.push([
955
+ engineCore.ShaderPreprocessorDirective.IfCmp,
956
+ cond.m,
957
+ cond.op,
958
+ cond.v,
959
+ -1
960
+ ]);
961
+ } else {
962
+ instructions.push([
963
+ engineCore.ShaderPreprocessorDirective.IfExpr,
964
+ cond,
965
+ -1
966
+ ]);
967
+ }
968
+ };
969
+ ShaderInstructionEncoder._parseCondition = function _parseCondition(expression, preprocessorExpressions) {
970
+ var _preprocessorExpressions_get;
971
+ var result = (_preprocessorExpressions_get = preprocessorExpressions == null ? void 0 : preprocessorExpressions.get(expression)) != null ? _preprocessorExpressions_get : internal.parsePreprocessorExpression(expression);
972
+ if ("error" in result) {
973
+ if (!result.error.certain && result.hasExpandableIdentifier) return {
974
+ t: "deferred",
975
+ e: expression
976
+ };
977
+ throw new Error(result.error.message);
978
+ }
979
+ if (result.evaluationError) throw new Error(result.evaluationError);
980
+ var compact = internal.toPreprocessorCondition(result.condition);
981
+ if (compact && !result.hasExpandableIdentifier) return compact;
982
+ return result.hasExpandableIdentifier ? {
983
+ t: "deferred",
984
+ e: expression
985
+ } : result.condition;
986
+ };
987
+ ShaderInstructionEncoder._findDirectiveStart = function _findDirectiveStart(source, from, length) {
988
+ var i = from;
989
+ while(i < length){
990
+ var j = i;
991
+ while(j < length){
992
+ var c = source.charCodeAt(j);
993
+ if (c === 32 /* space */ || c === 9 /* tab */ ) {
994
+ j++;
995
+ } else {
996
+ break;
997
+ }
998
+ }
999
+ if (j < length && (source.charCodeAt(j) === 35 /* '#' */ || source.charCodeAt(j) === 0)) return i;
1000
+ var nl = source.indexOf("\n", i);
1001
+ if (nl === -1) break;
1002
+ i = nl + 1;
1003
+ }
1004
+ return -1;
1005
+ };
1006
+ ShaderInstructionEncoder._findLogicalLineEnd = function _findLogicalLineEnd(source, start, length) {
1007
+ var lineEnd = source.indexOf("\n", start);
1008
+ while(lineEnd !== -1){
1009
+ var beforeBreak = source.charCodeAt(lineEnd - 1) === 13 ? lineEnd - 2 : lineEnd - 1;
1010
+ if (beforeBreak < start || source.charCodeAt(beforeBreak) !== 92) return lineEnd;
1011
+ lineEnd = source.indexOf("\n", lineEnd + 1);
1012
+ }
1013
+ return length;
1014
+ };
1015
+ ShaderInstructionEncoder._findInlineWhitespace = function _findInlineWhitespace(source) {
1016
+ var index = 0;
1017
+ while(index < source.length){
1018
+ var charCode = source.charCodeAt(index);
1019
+ if (charCode === 32 /* space */ || charCode === 9 /* tab */ ) break;
1020
+ index++;
1021
+ }
1022
+ return index;
1023
+ };
1024
+ ShaderInstructionEncoder._pushText = function _pushText(instructions, source, from, to, owners) {
1025
+ if (from >= to) return;
1026
+ var last = instructions.length > 0 ? instructions[instructions.length - 1] : null;
1027
+ var directive = owners === undefined ? engineCore.ShaderPreprocessorDirective.Text : engineCore.ShaderPreprocessorDirective.OwnedText;
1028
+ if (last && last[0] === directive && (owners === undefined || last.length === owners.length + 2 && owners.every(function(owner, index) {
1029
+ return last[index + 2] === owner;
1030
+ }))) {
1031
+ last[1] += source.substring(from, to);
1032
+ } else {
1033
+ instructions.push(owners === undefined ? [
1034
+ directive,
1035
+ source.substring(from, to)
1036
+ ] : [].concat([
1037
+ directive,
1038
+ source.substring(from, to)
1039
+ ], owners));
1040
+ }
1041
+ };
1042
+ /**
1043
+ * Backfill jump offset of an IF/ELIF instruction.
1044
+ * When onlyPlaceholder is true, only backfill if the current value is still -1
1045
+ */ ShaderInstructionEncoder._backfillJump = function _backfillJump(inst, target, onlyPlaceholder) {
1046
+ if (onlyPlaceholder === void 0) onlyPlaceholder = false;
1047
+ var directive = inst[0];
1048
+ if (directive === engineCore.ShaderPreprocessorDirective.IfDef || directive === engineCore.ShaderPreprocessorDirective.IfNdef) {
1049
+ if (!onlyPlaceholder || inst[2] === -1) inst[2] = target;
1050
+ } else if (directive === engineCore.ShaderPreprocessorDirective.IfCmp) {
1051
+ if (!onlyPlaceholder || inst[4] === -1) inst[4] = target;
1052
+ } else if (directive === engineCore.ShaderPreprocessorDirective.IfExpr) {
1053
+ if (!onlyPlaceholder || inst[2] === -1) inst[2] = target;
1054
+ }
1055
+ };
1056
+ ShaderInstructionEncoder._stripLineComment = function _stripLineComment(s) {
1057
+ var idx = s.indexOf("//");
1058
+ return idx >= 0 ? s.substring(0, idx).trimEnd() : s;
1059
+ };
1060
+ return ShaderInstructionEncoder;
1061
+ }();
1062
+ ShaderInstructionEncoder._DIRECTIVE_RE = /^[ \t]*#[ \t]*(if|ifdef|ifndef|elif|else|endif|define|undef)\b(.*)/;
1063
+ ShaderInstructionEncoder._FUNC_MACRO_RE = /^(\w+)\(([^)]*)\)\s*(.*)/;
1064
+
1065
+ /**
1066
+ * @internal
1067
+ */ var GLESVisitor = /*#__PURE__*/ function(CodeGenVisitor) {
1068
+ _inherits(GLESVisitor, CodeGenVisitor);
1069
+ function GLESVisitor() {
1070
+ var _this;
1071
+ _this = CodeGenVisitor.apply(this, arguments) || this, _this._globalCodeArray = [], _this._forwardFunctionDeclarations = new Map(), _this._forwardStructIndices = new Map(), _this._structCodeSegments = new Map(), _this._forwardVariableIndices = new Map(), _this._variableCodeSegments = new Map(), _this._declarationOwners = new Map(), _this._deferredPrototypes = new Map(), _this._declarationReferences = new Map(), _this._outerMacroDeclarations = [];
1072
+ return _this;
1073
+ }
1074
+ var _proto = GLESVisitor.prototype;
1075
+ /**
1076
+ * Clears pass-local output retained by the pooled visitor.
1077
+ */ _proto.reset = function reset() {
1078
+ var _this = this, globalCodeArray = _this._globalCodeArray;
1079
+ globalCodeArray.length = 0;
1080
+ this._forwardFunctionDeclarations.clear();
1081
+ this._forwardStructIndices.clear();
1082
+ this._structCodeSegments.clear();
1083
+ this._forwardVariableIndices.clear();
1084
+ this._variableCodeSegments.clear();
1085
+ this._deferredPrototypes.clear();
1086
+ this._declarationReferences.clear();
1087
+ this._currentDeclaration = undefined;
1088
+ };
1089
+ /**
1090
+ * Releases references retained by an idle visitor when its pool is collected.
1091
+ * @internal
1092
+ */ _proto.dispose = function dispose() {
1093
+ this.context.reset();
1094
+ this.reset();
1095
+ };
1096
+ /**
1097
+ * Emits target-specific declarations that precede generated global code.
1098
+ * @param data - Parser-owned shader facts.
1099
+ * @param out - Destination code segments.
1100
+ */ _proto.getOtherGlobal = function getOtherGlobal(data, out) {
1101
+ for(var _iterator = _create_for_of_iterator_helper_loose(data.globalPrecisions), _step; !(_step = _iterator()).done;){
1102
+ var precision = _step.value;
1103
+ out.push({
1104
+ text: precision.codeGen(this),
1105
+ index: precision.location.start.index
1106
+ });
1107
+ }
1108
+ };
1109
+ /**
1110
+ * Generates vertex and fragment source from neutral parser facts.
1111
+ * @param ir - Request-owned neutral shader IR.
1112
+ * @param coreInfo - Entry and stage-interface facts derived from the same IR.
1113
+ * @returns Generated vertex and fragment source.
1114
+ */ _proto.generate = function generate(ir, coreInfo) {
1115
+ var _this = this;
1116
+ var _context_attributeStructs, _context_attributeList, _context_varyingStructs, _context_varyingList, _context_mrtStructs, _context_mrtList;
1117
+ this.context.reset();
1118
+ this.reset();
1119
+ var node = ir.program;
1120
+ var shaderData = node.shaderData;
1121
+ var context = this.context;
1122
+ context._passSymbolTable = shaderData.symbolTable;
1123
+ var outerGlobalMacroDeclarations = coreInfo.outerGlobalMacroDeclarations;
1124
+ var io = coreInfo.io;
1125
+ (_context_attributeStructs = context.attributeStructs).push.apply(_context_attributeStructs, [].concat(io.attributeStructs));
1126
+ (_context_attributeList = context.attributeList).push.apply(_context_attributeList, [].concat(io.attributeList));
1127
+ (_context_varyingStructs = context.varyingStructs).push.apply(_context_varyingStructs, [].concat(io.varyingStructs));
1128
+ (_context_varyingList = context.varyingList).push.apply(_context_varyingList, [].concat(io.varyingList));
1129
+ (_context_mrtStructs = context.mrtStructs).push.apply(_context_mrtStructs, [].concat(io.mrtStructs));
1130
+ (_context_mrtList = context.mrtList).push.apply(_context_mrtList, [].concat(io.mrtList));
1131
+ context.registerStructTypes(internal.ShaderStructRole.Attribute, io.attributeStructs);
1132
+ context.registerStructTypes(internal.ShaderStructRole.Varying, io.varyingStructs);
1133
+ context.registerStructTypes(internal.ShaderStructRole.Mrt, io.mrtStructs);
1134
+ io.structVariableRoles.forEach(function(role, variable) {
1135
+ return context.registerStructVar(variable, role);
1136
+ });
1137
+ io.vertexStructVariableRoles.forEach(function(role, variable) {
1138
+ context.registerStructVar(variable, role, internal.EShaderStage.VERTEX);
1139
+ });
1140
+ io.fragmentStructVariableRoles.forEach(function(role, variable) {
1141
+ context.registerStructVar(variable, role, internal.EShaderStage.FRAGMENT);
1142
+ });
1143
+ this._sourceIR = ir;
1144
+ this._outerMacroDeclarations = outerGlobalMacroDeclarations;
1145
+ try {
1146
+ coreInfo.deferredDeclarationOwnership.forEach(function(owner, symbol) {
1147
+ return _this._declarationOwners.set(symbol.astNode, owner);
1148
+ });
1149
+ if (this._declarationOwners.size) {
1150
+ var nextId = 0;
1151
+ var nextGroup = 0;
1152
+ this._declarationOwners.forEach(function(owner) {
1153
+ nextId = Math.max(nextId, owner.id);
1154
+ nextGroup = Math.max(nextGroup, owner.group);
1155
+ });
1156
+ // Reachability follows the selected declaration, including dependencies without an override.
1157
+ shaderData.symbolTable.forEach(function(symbol) {
1158
+ if (symbol.astNode && !_this._declarationOwners.has(symbol.astNode)) {
1159
+ _this._declarationOwners.set(symbol.astNode, {
1160
+ id: ++nextId,
1161
+ group: ++nextGroup,
1162
+ sourceScope: symbol.sourceScope
1163
+ });
1164
+ }
1165
+ });
1166
+ context.onReferenceGlobal = function(symbols) {
1167
+ var _this_currentDeclarationOwner;
1168
+ var _this_currentDeclarationOwner_id;
1169
+ var from = (_this_currentDeclarationOwner_id = (_this_currentDeclarationOwner = _this.currentDeclarationOwner) == null ? void 0 : _this_currentDeclarationOwner.id) != null ? _this_currentDeclarationOwner_id : 0;
1170
+ for(var _iterator = _create_for_of_iterator_helper_loose(symbols), _step; !(_step = _iterator()).done;){
1171
+ var symbol = _step.value;
1172
+ _this._referenceDeclaration(from, symbol.astNode);
1173
+ }
1174
+ };
1175
+ var propDeclarations = new Map();
1176
+ for(var _iterator = _create_for_of_iterator_helper_loose([].concat(io.attributeStructs, io.varyingStructs, io.mrtStructs)), _step; !(_step = _iterator()).done;){
1177
+ var struct = _step.value;
1178
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(struct.propList), _step1; !(_step1 = _iterator1()).done;){
1179
+ var prop = _step1.value;
1180
+ propDeclarations.set(prop, struct);
1181
+ }
1182
+ }
1183
+ context.onReferenceStructProps = function(props) {
1184
+ var _this_currentDeclarationOwner;
1185
+ var _this_currentDeclarationOwner_id;
1186
+ var from = (_this_currentDeclarationOwner_id = (_this_currentDeclarationOwner = _this.currentDeclarationOwner) == null ? void 0 : _this_currentDeclarationOwner.id) != null ? _this_currentDeclarationOwner_id : 0;
1187
+ for(var _iterator = _create_for_of_iterator_helper_loose(props), _step; !(_step = _iterator()).done;){
1188
+ var prop = _step.value;
1189
+ _this._referenceDeclaration(from, propDeclarations.get(prop));
1190
+ }
1191
+ };
1192
+ }
1193
+ if (coreInfo.unsupportedDeferredDeclarations.length) {
1194
+ throw internal.mapExpandedShaderError(new internal.GSError(internal.GSErrorName.CompilationError, "Deferred inheritance requires exact signatures and cannot resolve a known partial-coverage conflict.", coreInfo.unsupportedDeferredDeclarations[0].astNode.location, ir.source, undefined, "UnsupportedDeferredDeclaration"), ir.source, ir.sourceMap);
1195
+ }
1196
+ return {
1197
+ vertex: this._vertexMain(coreInfo.vertexEntry, shaderData, outerGlobalMacroDeclarations),
1198
+ fragment: this._fragmentMain(coreInfo.fragmentEntry, shaderData, outerGlobalMacroDeclarations)
1199
+ };
1200
+ } finally{
1201
+ this._sourceIR = undefined;
1202
+ this._outerMacroDeclarations = [];
1203
+ this._declarationOwners.clear();
1204
+ context.onReferenceGlobal = undefined;
1205
+ context.onReferenceStructProps = undefined;
1206
+ }
1207
+ };
1208
+ _proto._vertexMain = function _vertexMain(entryInfo, data, outerGlobalMacroDeclarations) {
1209
+ var context = this.context;
1210
+ context.stage = internal.EShaderStage.VERTEX;
1211
+ context.stageEntry = entryInfo.name;
1212
+ // Attribute/varying structs were collected in ShaderCoreInfo
1213
+ // Pre-walk global `#define` values so referenced struct properties emit `attribute`/`varying` declarations.
1214
+ this._preRegisterGlobalMacroRefs(outerGlobalMacroDeclarations);
1215
+ var globalCodeArray = this._globalCodeArray;
1216
+ context.referenceGlobal(entryInfo.name, internal.ESymbolType.FN);
1217
+ this._getGlobalSymbol(globalCodeArray);
1218
+ this._getCustomStruct(context.attributeStructs, globalCodeArray);
1219
+ this._getCustomStruct(context.varyingStructs, globalCodeArray);
1220
+ this._getGlobalMacroDeclarations(outerGlobalMacroDeclarations, globalCodeArray);
1221
+ this.getOtherGlobal(data, globalCodeArray);
1222
+ this._emitDeclarationReferences(globalCodeArray);
1223
+ var globalCode = globalCodeArray.sort(function(a, b) {
1224
+ return a.index - b.index;
1225
+ }).map(function(item) {
1226
+ return item.text;
1227
+ }).join("\n");
1228
+ context.reset(false);
1229
+ this.reset();
1230
+ return globalCode;
1231
+ };
1232
+ _proto._fragmentMain = function _fragmentMain(entryInfo, data, outerGlobalMacroStatements) {
1233
+ var _this = this;
1234
+ var context = this.context;
1235
+ context.stage = internal.EShaderStage.FRAGMENT;
1236
+ context.stageEntry = entryInfo.name;
1237
+ this.prepareFragment(entryInfo, outerGlobalMacroStatements);
1238
+ // Every value-return must preserve early-exit control flow after entry return values are
1239
+ // lowered into fragment outputs.
1240
+ entryInfo.functions.forEach(function(fnSymbol) {
1241
+ var returnType = fnSymbol.astNode.protoType.returnType;
1242
+ var mode = returnType.type === internal.Keyword.VEC4 ? "color" : returnType.typeSpecifier.structDeclarations.some(function(struct) {
1243
+ return context.hasStructRole(struct, internal.ShaderStructRole.Mrt);
1244
+ }) ? "mrt" : undefined;
1245
+ if (mode) {
1246
+ var statements = fnSymbol.astNode.statements;
1247
+ _this._registerFragmentReturns(statements, mode, internal.ParserUtils.lastStatement(statements));
1248
+ }
1249
+ });
1250
+ // Struct-variable identities are already populated from ShaderCoreInfo; just pre-walk macro
1251
+ // refs so struct codegen sees the references.
1252
+ this._preRegisterGlobalMacroRefs(outerGlobalMacroStatements);
1253
+ var globalCodeArray = this._globalCodeArray;
1254
+ context.referenceGlobal(entryInfo.name, internal.ESymbolType.FN);
1255
+ this._getGlobalSymbol(globalCodeArray);
1256
+ this._getCustomStruct(context.varyingStructs, globalCodeArray);
1257
+ this._getCustomStruct(context.mrtStructs, globalCodeArray);
1258
+ this._getGlobalMacroDeclarations(outerGlobalMacroStatements, globalCodeArray);
1259
+ this.getOtherGlobal(data, globalCodeArray);
1260
+ this._emitDeclarationReferences(globalCodeArray);
1261
+ var globalCode = globalCodeArray.sort(function(a, b) {
1262
+ return a.index - b.index;
1263
+ }).map(function(item) {
1264
+ return item.text;
1265
+ }).join("\n");
1266
+ context.reset();
1267
+ this.reset();
1268
+ return globalCode;
1269
+ };
1270
+ _proto.prepareFragment = function prepareFragment(entryInfo, outerGlobalMacroStatements) {
1271
+ };
1272
+ /**
1273
+ * Pre-walk `#define` values in global macro declarations and register any
1274
+ * `structVar.prop` member accesses as referenced struct props. This must run before
1275
+ * struct codegen emits the declaration lists (`attribute …`, `varying …`, `MRT …`),
1276
+ * otherwise properties used only from macros would be missing from the output.
1277
+ */ _proto._preRegisterGlobalMacroRefs = function _preRegisterGlobalMacroRefs(macros) {
1278
+ for(var _iterator = _create_for_of_iterator_helper_loose(macros), _step; !(_step = _iterator()).done;){
1279
+ var macro = _step.value;
1280
+ this._walkMacroDefineTokens(macro.children);
1281
+ }
1282
+ };
1283
+ _proto._walkMacroDefineTokens = function _walkMacroDefineTokens(children) {
1284
+ for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
1285
+ var child = _step.value;
1286
+ if (_instanceof(child, internal.ASTNode.MacroDefine)) {
1287
+ // Codegen the value once so the enclosed `visitPostfixExpression` calls
1288
+ // register their struct-prop references. The returned string is discarded
1289
+ // — the real emit happens later in `_getGlobalMacroDeclarations`.
1290
+ if (child.valueExpression) child.valueExpression.codeGen(this);
1291
+ } else if (_instanceof(child, internal.TreeNode)) {
1292
+ var previous = this._currentDeclaration;
1293
+ if (_instanceof(child, internal.ASTNode.FunctionDefinition)) this._currentDeclaration = child;
1294
+ this._walkMacroDefineTokens(child.children);
1295
+ this._currentDeclaration = previous;
1296
+ }
1297
+ }
1298
+ };
1299
+ _proto._registerFragmentReturns = function _registerFragmentReturns(node, mode, terminal) {
1300
+ if (_instanceof(node, internal.ASTNode.JumpStatement) && node.children.length === 3) {
1301
+ this.context.registerFragmentReturn(node, mode);
1302
+ if (node === terminal) this.context.registerTerminalInterfaceReturn(node);
1303
+ return;
1304
+ }
1305
+ for(var _iterator = _create_for_of_iterator_helper_loose(node.children), _step; !(_step = _iterator()).done;){
1306
+ var child = _step.value;
1307
+ if (_instanceof(child, internal.TreeNode)) this._registerFragmentReturns(child, mode, terminal);
1308
+ }
1309
+ };
1310
+ _proto._getGlobalSymbol = function _getGlobalSymbol(out) {
1311
+ var context = this.context;
1312
+ // Set iteration includes dependencies discovered while generating earlier declarations.
1313
+ for(var _iterator = _create_for_of_iterator_helper_loose(context._referencedGlobalSymbols), _step; !(_step = _iterator()).done;){
1314
+ var sm = _step.value;
1315
+ this._currentDeclaration = sm.astNode;
1316
+ var codeGenResult = sm.astNode.codeGen(this);
1317
+ this._currentDeclaration = undefined;
1318
+ if (!codeGenResult) continue;
1319
+ var text = codeGenResult + (sm.type === internal.ESymbolType.VAR ? ";" : "");
1320
+ if (!sm.isInMacroBranch) {
1321
+ var segment = {
1322
+ text: this._declaration(text, sm.astNode),
1323
+ index: sm.astNode.location.start.index
1324
+ };
1325
+ out.push(segment);
1326
+ if (_instanceof(sm.astNode, internal.ASTNode.StructSpecifier)) this._structCodeSegments.set(sm.astNode, segment);
1327
+ if (_instanceof(sm.astNode, internal.ASTNode.VariableDeclaration)) this._variableCodeSegments.set(sm.astNode, segment);
1328
+ }
1329
+ }
1330
+ this._getForwardDeclarations(out);
1331
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(this._deferredPrototypes.values()), _step1; !(_step1 = _iterator1()).done;){
1332
+ var segment1 = _step1.value;
1333
+ out.push(segment1);
1334
+ }
1335
+ for(var _iterator2 = _create_for_of_iterator_helper_loose(this._forwardFunctionDeclarations), _step2; !(_step2 = _iterator2()).done;){
1336
+ var _step_value = _step2.value, definition = _step_value[0], text1 = _step_value[1];
1337
+ if (!definition.isInMacroBranch) out.push({
1338
+ text: text1,
1339
+ index: definition.location.start.index
1340
+ });
1341
+ }
1342
+ };
1343
+ _proto.referenceFunction = function referenceFunction(symbol, referenceIndex, branch) {
1344
+ var _this = this;
1345
+ CodeGenVisitor.prototype.referenceFunction.call(this, symbol, referenceIndex, branch);
1346
+ var definition = symbol.astNode;
1347
+ var declarations = this._forwardFunctionDeclarations;
1348
+ if (symbol.ident === this.context.stageEntry) return;
1349
+ var candidates = this.context._referencedGlobals[symbol.ident].filter(function(candidate) {
1350
+ return _instanceof(candidate, internal.FnSymbol) && candidate.equal(symbol);
1351
+ });
1352
+ var owner = this._declarationOwners.get(definition);
1353
+ if (owner) {
1354
+ var _this1, _loop = function() {
1355
+ var candidate = _step.value;
1356
+ var replacement = candidate.astNode;
1357
+ var nextOwner = _this1._declarationOwners.get(replacement);
1358
+ if (!nextOwner || nextOwner.group !== owner.group || nextOwner.sourceScope <= owner.sourceScope || replacement.location.start.index <= referenceIndex) return "continue";
1359
+ var prototype = replacement.protoType;
1360
+ var anchor = definition.location.start.index;
1361
+ var previous = _this1._deferredPrototypes.get(replacement);
1362
+ if (previous && previous.index <= anchor) return "continue";
1363
+ if (!_this1._isContextIndependent(prototype) || _this1._hasDeclarationContextBarrier(anchor, prototype.location.start.index, false)) {
1364
+ _this1._unsupportedForwardDeclaration(prototype);
1365
+ }
1366
+ var outer = _this1._outerMacroDeclarations.find(function(macro) {
1367
+ return macro.location.start.index <= anchor && macro.location.end.index >= definition.location.end.index;
1368
+ });
1369
+ var _outer_location_start_index;
1370
+ var typeAnchor = (_outer_location_start_index = outer == null ? void 0 : outer.location.start.index) != null ? _outer_location_start_index : anchor;
1371
+ _this1._prepareForwardTypes(prototype.returnType.typeSpecifier.structDeclarations, anchor, typeAnchor);
1372
+ var _prototype_parameterList;
1373
+ for(var _iterator = _create_for_of_iterator_helper_loose((_prototype_parameterList = prototype.parameterList) != null ? _prototype_parameterList : []), _step1; !(_step1 = _iterator()).done;){
1374
+ var parameter = _step1.value;
1375
+ var _parameter_typeInfo;
1376
+ var _parameter_typeInfo_structDeclarations;
1377
+ _this1._prepareForwardTypes((_parameter_typeInfo_structDeclarations = (_parameter_typeInfo = parameter.typeInfo) == null ? void 0 : _parameter_typeInfo.structDeclarations) != null ? _parameter_typeInfo_structDeclarations : [], anchor, typeAnchor);
1378
+ }
1379
+ // Selection is determined at the later definition, so the prototype must not replay its guard here.
1380
+ _this1._deferredPrototypes.set(replacement, {
1381
+ text: _this1._declaration("" + prototype.codeGen(_this1) + ";", replacement, false),
1382
+ index: typeAnchor
1383
+ });
1384
+ };
1385
+ for(var _iterator = _create_for_of_iterator_helper_loose(candidates), _step; !(_step = _iterator()).done;)_this1 = this, _loop();
1386
+ return;
1387
+ }
1388
+ if (candidates.some(function(candidate) {
1389
+ return candidate.astNode === definition;
1390
+ })) return;
1391
+ var compatible = candidates.filter(function(candidate) {
1392
+ return _this._canBranchesOverlap(candidate.branchSignature, branch);
1393
+ });
1394
+ var preceding = compatible.filter(function(candidate) {
1395
+ return candidate.astNode.location.start.index < referenceIndex;
1396
+ });
1397
+ if (internal.canInheritanceBranchesCover(preceding.map(function(candidate) {
1398
+ return candidate.branchSignature;
1399
+ }), branch)) return;
1400
+ var replacement = compatible.find(function(candidate) {
1401
+ return candidate.astNode.location.start.index > referenceIndex;
1402
+ });
1403
+ if (replacement) {
1404
+ // An inherited helper can call a declaration whose overriding body occurs later. Keep the
1405
+ // original declaration's macro/type context and emit only the final backend signature there.
1406
+ var prototype = replacement.astNode.protoType;
1407
+ var anchor = definition.location.start.index;
1408
+ var text = "" + prototype.codeGen(this) + ";";
1409
+ var signature = this._getForwardSignature(prototype);
1410
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(candidates), _step1; !(_step1 = _iterator1()).done;){
1411
+ var candidate = _step1.value;
1412
+ if (this._canBranchesOverlap(candidate.branchSignature, symbol.branchSignature) && this._getForwardSignature(candidate.astNode.protoType) !== signature) {
1413
+ this._unsupportedForwardDeclaration(candidate.astNode.protoType);
1414
+ }
1415
+ }
1416
+ if (declarations.has(definition)) return;
1417
+ if (!this._isContextIndependent(prototype) || this._hasDeclarationContextBarrier(anchor, prototype.location.start.index, false)) {
1418
+ this._unsupportedForwardDeclaration(prototype);
1419
+ }
1420
+ var outerMacro = this._outerMacroDeclarations.find(function(macro) {
1421
+ return macro.location.start.index <= anchor && macro.location.end.index >= definition.location.end.index;
1422
+ });
1423
+ var _outerMacro_location_start_index;
1424
+ var typeAnchor = (_outerMacro_location_start_index = outerMacro == null ? void 0 : outerMacro.location.start.index) != null ? _outerMacro_location_start_index : anchor;
1425
+ this._prepareForwardTypes(prototype.returnType.typeSpecifier.structDeclarations, anchor, typeAnchor);
1426
+ var _prototype_parameterList;
1427
+ for(var _iterator2 = _create_for_of_iterator_helper_loose((_prototype_parameterList = prototype.parameterList) != null ? _prototype_parameterList : []), _step2; !(_step2 = _iterator2()).done;){
1428
+ var parameter = _step2.value;
1429
+ var _parameter_typeInfo;
1430
+ if (_instanceof(parameter.astNode, internal.ASTNode.ParameterDeclaration) && parameter.astNode.symbol && this.context.getStructVarRole([
1431
+ parameter.astNode.symbol
1432
+ ])) {
1433
+ continue;
1434
+ }
1435
+ var _parameter_typeInfo_structDeclarations;
1436
+ this._prepareForwardTypes((_parameter_typeInfo_structDeclarations = (_parameter_typeInfo = parameter.typeInfo) == null ? void 0 : _parameter_typeInfo.structDeclarations) != null ? _parameter_typeInfo_structDeclarations : [], anchor, typeAnchor);
1437
+ }
1438
+ declarations.set(definition, text);
1439
+ }
1440
+ };
1441
+ _proto._getForwardSignature = function _getForwardSignature(prototype) {
1442
+ var _this, _loop = function() {
1443
+ var parameter = _step.value;
1444
+ var declaration = parameter.astNode;
1445
+ if (_instanceof(declaration, internal.ASTNode.ParameterDeclaration) && declaration.symbol && _this.context.getStructVarRole([
1446
+ declaration.symbol
1447
+ ])) return "continue";
1448
+ var tokens = [];
1449
+ var visit = function(node) {
1450
+ if (_instanceof(node, internal.BaseToken)) {
1451
+ if (node !== parameter.ident && node.type !== internal.Keyword.IN) tokens.push(node.lexeme);
1452
+ } else {
1453
+ node.children.forEach(visit);
1454
+ }
1455
+ };
1456
+ visit(declaration);
1457
+ var text = tokens.join(" ");
1458
+ if (text !== "void") parameters.push(text);
1459
+ };
1460
+ var parameters = [];
1461
+ var _prototype_parameterList;
1462
+ for(var _iterator = _create_for_of_iterator_helper_loose((_prototype_parameterList = prototype.parameterList) != null ? _prototype_parameterList : []), _step; !(_step = _iterator()).done;)_this = this, _loop();
1463
+ return prototype.returnType.codeGen(this) + "(" + parameters.join(",") + ")";
1464
+ };
1465
+ _proto._canBranchesOverlap = function _canBranchesOverlap(left, right) {
1466
+ return internal.getLexicalDeclarationCoexistence(left, right) !== "exclusive" && !internal.canInheritanceBranchesCover([], [].concat(left, right));
1467
+ };
1468
+ _proto.visitVariableIdentifier = function visitVariableIdentifier(node) {
1469
+ var _this, _loop = function() {
1470
+ var _this1, _loop = function() {
1471
+ var candidate = _step1.value;
1472
+ if (candidate.astNode.location.start.index <= node.location.start.index) return "continue";
1473
+ if (owner) {
1474
+ var nextOwner = _this1._declarationOwners.get(candidate.astNode);
1475
+ if (!nextOwner || nextOwner.group !== owner.group || nextOwner.sourceScope <= owner.sourceScope) return "continue";
1476
+ }
1477
+ var declaration = candidate.astNode;
1478
+ if (!_instanceof(candidate, internal.VarSymbol) || !candidate.isUniform || !_instanceof(declaration, internal.ASTNode.VariableDeclaration)) {
1479
+ _this1._unsupportedForwardDeclaration(declaration);
1480
+ }
1481
+ var macro = _this1._outerMacroDeclarations.find(function(item) {
1482
+ return item.location.start.index <= declaration.location.start.index && item.location.end.index >= declaration.location.end.index;
1483
+ });
1484
+ var _macro_location_end_index;
1485
+ if (!_this1._isContextIndependent(declaration) || _this1._hasDeclarationContextBarrier(anchor, (_macro_location_end_index = macro == null ? void 0 : macro.location.end.index) != null ? _macro_location_end_index : declaration.location.end.index, true)) {
1486
+ _this1._unsupportedForwardDeclaration(declaration);
1487
+ }
1488
+ _this1._prepareForwardTypes(candidate.dataType.structDeclarations, anchor);
1489
+ var _this__forwardVariableIndices_get;
1490
+ _this1._forwardVariableIndices.set(declaration, Math.min((_this__forwardVariableIndices_get = _this1._forwardVariableIndices.get(declaration)) != null ? _this__forwardVariableIndices_get : Infinity, anchor));
1491
+ };
1492
+ var symbol = _step.value;
1493
+ var _this_context__referencedGlobals_symbol_ident;
1494
+ if (!_instanceof(symbol, internal.VarSymbol) || !symbol.isUniform) return "continue";
1495
+ var candidates = (_this_context__referencedGlobals_symbol_ident = _this.context._referencedGlobals[symbol.ident]) == null ? void 0 : _this_context__referencedGlobals_symbol_ident.filter(function(candidate) {
1496
+ return _instanceof(candidate, internal.VarSymbol);
1497
+ });
1498
+ var owner = _this._declarationOwners.get(symbol.astNode);
1499
+ if (!candidates || !owner && candidates.includes(symbol)) return "continue";
1500
+ var preceding = candidates.filter(function(candidate) {
1501
+ return candidate.astNode.location.start.index < node.location.start.index;
1502
+ });
1503
+ if (!owner && internal.canInheritanceBranchesCover(preceding.map(function(candidate) {
1504
+ return candidate.branchSignature;
1505
+ }), node._branch)) return "continue";
1506
+ var oldMacro = _this._outerMacroDeclarations.find(function(macro) {
1507
+ return macro.location.start.index <= symbol.astNode.location.start.index && macro.location.end.index >= symbol.astNode.location.end.index;
1508
+ });
1509
+ var _oldMacro_location_start_index;
1510
+ var anchor = (_oldMacro_location_start_index = oldMacro == null ? void 0 : oldMacro.location.start.index) != null ? _oldMacro_location_start_index : symbol.astNode.location.start.index;
1511
+ for(var _iterator = _create_for_of_iterator_helper_loose(candidates), _step1; !(_step1 = _iterator()).done;)_this1 = _this, _loop();
1512
+ };
1513
+ var code = CodeGenVisitor.prototype.visitVariableIdentifier.call(this, node);
1514
+ for(var _iterator = _create_for_of_iterator_helper_loose(node.resolvedSymbols()), _step; !(_step = _iterator()).done;)_this = this, _loop();
1515
+ return code;
1516
+ };
1517
+ _proto._getForwardDeclarations = function _getForwardDeclarations(out) {
1518
+ var _this, _loop = function() {
1519
+ var _step_value = _step1.value, declaration = _step_value[0], index = _step_value[1];
1520
+ var owner = _this._declarationOwners.get(declaration);
1521
+ var macro = _this._outerMacroDeclarations.find(function(item) {
1522
+ return item.location.start.index <= declaration.location.start.index && item.location.end.index >= declaration.location.end.index;
1523
+ });
1524
+ if (!macro) {
1525
+ var previous = _instanceof(declaration, internal.ASTNode.StructSpecifier) ? _this._structCodeSegments.get(declaration) : _this._variableCodeSegments.get(declaration);
1526
+ if (previous) {
1527
+ if (owner) previous.text = _this._declaration("", declaration);
1528
+ else out.splice(out.indexOf(previous), 1);
1529
+ }
1530
+ out.push({
1531
+ text: code(declaration),
1532
+ index: index
1533
+ });
1534
+ } else if (owner) {
1535
+ out.push({
1536
+ text: code(declaration),
1537
+ index: index
1538
+ });
1539
+ } else {
1540
+ var group = guarded.get(macro);
1541
+ if (!group) guarded.set(macro, group = {
1542
+ index: index,
1543
+ declarations: []
1544
+ });
1545
+ group.index = Math.min(group.index, index);
1546
+ group.declarations.push(declaration);
1547
+ }
1548
+ };
1549
+ var _this1 = this;
1550
+ var guarded = new Map();
1551
+ var declarations = Array.from(this._forwardStructIndices);
1552
+ for(var _iterator = _create_for_of_iterator_helper_loose(this._forwardVariableIndices), _step; !(_step = _iterator()).done;){
1553
+ var entry = _step.value;
1554
+ declarations.push(entry);
1555
+ }
1556
+ var code = function(declaration) {
1557
+ return _this1._declaration(declaration.codeGen(_this1) + (_instanceof(declaration, internal.ASTNode.VariableDeclaration) ? ";" : ""), declaration, false);
1558
+ };
1559
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(declarations), _step1; !(_step1 = _iterator1()).done;)_this = this, _loop();
1560
+ for(var _iterator2 = _create_for_of_iterator_helper_loose(guarded), _step2; !(_step2 = _iterator2()).done;){
1561
+ var _step_value = _step2.value, macro = _step_value[0], group = _step_value[1];
1562
+ var segments = macro.macroExpressions.map(function(item) {
1563
+ return {
1564
+ text: _instanceof(item, internal.BaseToken) ? item.lexeme : item.codeGen(_this1),
1565
+ index: item.location.start.index
1566
+ };
1567
+ });
1568
+ for(var _iterator3 = _create_for_of_iterator_helper_loose(group.declarations), _step3; !(_step3 = _iterator3()).done;){
1569
+ var declaration = _step3.value;
1570
+ segments.push({
1571
+ text: code(declaration),
1572
+ index: declaration.location.start.index
1573
+ });
1574
+ }
1575
+ out.push({
1576
+ text: segments.sort(function(a, b) {
1577
+ return a.index - b.index;
1578
+ }).map(function(item) {
1579
+ return item.text;
1580
+ }).join("\n"),
1581
+ index: group.index
1582
+ });
1583
+ }
1584
+ };
1585
+ _proto.visitTypeSpecifier = function visitTypeSpecifier(node) {
1586
+ var _this, _loop = function() {
1587
+ var type = _step.value;
1588
+ if (!type.ident || _this.context.getStructRole([
1589
+ type
1590
+ ])) return "continue";
1591
+ // A function-local struct can shadow a global name without participating in inheritance.
1592
+ var parent = type.parent;
1593
+ while(parent && !_instanceof(parent, internal.ASTNode.GlobalDeclaration) && !_instanceof(parent, internal.ASTNode.FunctionDefinition)){
1594
+ parent = parent.parent;
1595
+ }
1596
+ if (_instanceof(parent, internal.ASTNode.FunctionDefinition)) return "continue";
1597
+ _this.context.referenceGlobal(type.ident.lexeme, internal.ESymbolType.STRUCT);
1598
+ var final = _this.context._referencedGlobals[type.ident.lexeme];
1599
+ var owner = _this._declarationOwners.get(type);
1600
+ if (!owner && final.some(function(symbol) {
1601
+ return symbol.astNode === type;
1602
+ })) return "continue";
1603
+ var oldMacro = _this._outerMacroDeclarations.find(function(item) {
1604
+ return item.location.start.index <= type.location.start.index && item.location.end.index >= type.location.end.index;
1605
+ });
1606
+ var _oldMacro_location_start_index;
1607
+ _this._prepareForwardTypes(final.filter(function(symbol) {
1608
+ if (!owner) return true;
1609
+ var nextOwner = _this1._declarationOwners.get(symbol.astNode);
1610
+ return (nextOwner == null ? void 0 : nextOwner.group) === owner.group && nextOwner.sourceScope > owner.sourceScope;
1611
+ }).map(function(symbol) {
1612
+ return symbol.astNode;
1613
+ }).filter(function(item) {
1614
+ return _instanceof(item, internal.ASTNode.StructSpecifier);
1615
+ }), (_oldMacro_location_start_index = oldMacro == null ? void 0 : oldMacro.location.start.index) != null ? _oldMacro_location_start_index : type.location.start.index);
1616
+ };
1617
+ var _this1 = this;
1618
+ var call = _instanceof(node.parent, internal.ASTNode.FunctionIdentifier) ? node.parent.parent : undefined;
1619
+ if (_instanceof(call, internal.ASTNode.FunctionCallGeneric) && _instanceof(call.fnSymbol, internal.FnSymbol)) {
1620
+ return CodeGenVisitor.prototype.visitTypeSpecifier.call(this, node);
1621
+ }
1622
+ for(var _iterator = _create_for_of_iterator_helper_loose(node.structDependencies), _step; !(_step = _iterator()).done;)_this = this, _loop();
1623
+ return CodeGenVisitor.prototype.visitTypeSpecifier.call(this, node);
1624
+ };
1625
+ _proto._prepareForwardTypes = function _prepareForwardTypes(types, anchor, hoistAnchor) {
1626
+ var _this, _loop = function() {
1627
+ var type = _step.value;
1628
+ var _this__forwardStructIndices_get;
1629
+ if (((_this__forwardStructIndices_get = _this._forwardStructIndices.get(type)) != null ? _this__forwardStructIndices_get : Infinity) <= anchor) return "continue";
1630
+ if (type.ident) {
1631
+ _this.context.referenceGlobal(type.ident.lexeme, internal.ESymbolType.STRUCT);
1632
+ var final = _this.context._referencedGlobals[type.ident.lexeme];
1633
+ if (!final.some(function(symbol) {
1634
+ return symbol.astNode === type;
1635
+ })) {
1636
+ _this._prepareForwardTypes(final.map(function(symbol) {
1637
+ return symbol.astNode;
1638
+ }).filter(function(item) {
1639
+ return _instanceof(item, internal.ASTNode.StructSpecifier);
1640
+ }), anchor, hoistAnchor);
1641
+ return "continue";
1642
+ }
1643
+ }
1644
+ var needsHoist = type.location.start.index > anchor;
1645
+ var macro = _this._outerMacroDeclarations.find(function(item) {
1646
+ return item.location.start.index <= type.location.start.index && item.location.end.index >= type.location.end.index;
1647
+ });
1648
+ var _macro_location_end_index;
1649
+ if (needsHoist && (!_this._isContextIndependent(type) || _this._hasDeclarationContextBarrier(hoistAnchor, (_macro_location_end_index = macro == null ? void 0 : macro.location.end.index) != null ? _macro_location_end_index : type.location.end.index, true))) {
1650
+ _this._unsupportedForwardDeclaration(type);
1651
+ }
1652
+ var dependencyAnchor = needsHoist ? hoistAnchor : type.location.start.index;
1653
+ for(var _iterator = _create_for_of_iterator_helper_loose(type.propList), _step1; !(_step1 = _iterator()).done;){
1654
+ var property = _step1.value;
1655
+ _this._prepareForwardTypes(property.typeInfo.structDeclarations, dependencyAnchor);
1656
+ }
1657
+ if (needsHoist) _this._forwardStructIndices.set(type, hoistAnchor);
1658
+ };
1659
+ if (hoistAnchor === void 0) hoistAnchor = anchor;
1660
+ if (this.context.getStructRole(types)) return;
1661
+ for(var _iterator = _create_for_of_iterator_helper_loose(types), _step; !(_step = _iterator()).done;)_this = this, _loop();
1662
+ };
1663
+ _proto._isContextIndependent = function _isContextIndependent(node) {
1664
+ var _this = this;
1665
+ if (_instanceof(node, internal.ASTNode.VariableIdentifier) || _instanceof(node, internal.ASTNode.MacroCallSymbol) || _instanceof(node, internal.ASTNode.MacroCallFunction)) return false;
1666
+ if (_instanceof(node, internal.ASTNode.TypeSpecifier) && node.isCustom && !node.structDeclarations.length) return false;
1667
+ return node.children.every(function(child) {
1668
+ return _instanceof(child, internal.TreeNode) ? _this._isContextIndependent(child) : child.type < internal.Keyword.MACRO_IF || child.type > internal.Keyword.MACRO_DEFINE_PARAMS;
1669
+ });
1670
+ };
1671
+ _proto._hasDeclarationContextBarrier = function _hasDeclarationContextBarrier(start, end, includeMacros) {
1672
+ var visit = function(node, inFunction) {
1673
+ if (inFunction === void 0) inFunction = false;
1674
+ if (node.location.end.index <= start || node.location.start.index >= end) return false;
1675
+ if (_instanceof(node, internal.ASTNode.PrecisionSpecifier) && !inFunction) return true;
1676
+ if (includeMacros && _instanceof(node, internal.ASTNode.MacroDefine)) return true;
1677
+ inFunction || (inFunction = _instanceof(node, internal.ASTNode.FunctionDefinition));
1678
+ return node.children.some(function(child) {
1679
+ return _instanceof(child, internal.TreeNode) ? visit(child, inFunction) : includeMacros && child.location.start.index > start && child.location.start.index < end && (child.type === internal.Keyword.MACRO_UNDEF || child.type === internal.Keyword.MACRO_DEFINE_EXPRESSION);
1680
+ });
1681
+ };
1682
+ return visit(this._sourceIR.program);
1683
+ };
1684
+ _proto._unsupportedForwardDeclaration = function _unsupportedForwardDeclaration(node) {
1685
+ var ir = this._sourceIR;
1686
+ throw internal.mapExpandedShaderError(new internal.GSError(internal.GSErrorName.CompilationError, "Inherited declarations require incompatible forward signatures or depend on a later macro or precision context.", node.location, ir.source, undefined, "UnsupportedForwardDeclaration"), ir.source, ir.sourceMap);
1687
+ };
1688
+ _proto._getCustomStruct = function _getCustomStruct(structNodes, out) {
1689
+ for(var _iterator = _create_for_of_iterator_helper_loose(structNodes), _step; !(_step = _iterator()).done;){
1690
+ var node = _step.value;
1691
+ var text = node.codeGen(this);
1692
+ if (!node.isInMacroBranch) {
1693
+ out.push({
1694
+ text: this._declaration(text, node),
1695
+ index: node.location.start.index
1696
+ });
1697
+ }
1698
+ }
1699
+ };
1700
+ _proto._getGlobalMacroDeclarations = function _getGlobalMacroDeclarations(macros, out) {
1701
+ var _this = this;
1702
+ var context = this.context;
1703
+ var referencedGlobalMacroASTs = context._referencedGlobalMacroASTs;
1704
+ referencedGlobalMacroASTs.length = 0;
1705
+ for(var _iterator = _create_for_of_iterator_helper_loose(context._referencedGlobalSymbols), _step; !(_step = _iterator()).done;){
1706
+ var symbol = _step.value;
1707
+ if (symbol.isInMacroBranch) referencedGlobalMacroASTs.push(symbol.astNode);
1708
+ }
1709
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(macros), _step1; !(_step1 = _iterator1()).done;){
1710
+ var macro = _step1.value;
1711
+ var text = void 0;
1712
+ var child = macro.children[0];
1713
+ if (_instanceof(child, internal.ASTNode.GlobalMacroIfStatement)) {
1714
+ var _result;
1715
+ var result = [];
1716
+ (_result = result).push.apply(_result, [].concat(macro.macroExpressions.map(function(item) {
1717
+ return {
1718
+ text: _instanceof(item, internal.BaseToken) ? item.lexeme : item.codeGen(_this),
1719
+ index: item.location.start.index
1720
+ };
1721
+ })));
1722
+ this._visitGlobalMacroIfStatement(child, result);
1723
+ text = result.sort(function(a, b) {
1724
+ return a.index - b.index;
1725
+ }).map(function(item) {
1726
+ return item.text;
1727
+ }).join("\n");
1728
+ } else if (_instanceof(child, internal.BaseToken) && child.type === internal.Keyword.MACRO_DEFINE_EXPRESSION) {
1729
+ // Legacy opaque `#define` — its lexeme is the complete directive text,
1730
+ // newlines included; emit verbatim.
1731
+ text = child.lexeme;
1732
+ } else {
1733
+ text = macro.codeGen(this);
1734
+ }
1735
+ out.push({
1736
+ text: text,
1737
+ index: macro.location.start.index
1738
+ });
1739
+ }
1740
+ };
1741
+ _proto._visitGlobalMacroIfStatement = function _visitGlobalMacroIfStatement(node, out) {
1742
+ var children = node.children;
1743
+ for(var i = 0; i < children.length; i++){
1744
+ var child = children[i];
1745
+ if (_instanceof(child, internal.ASTNode.PrecisionSpecifier)) {
1746
+ out.push({
1747
+ text: child.codeGen(this),
1748
+ index: child.location.start.index
1749
+ });
1750
+ } else if (_instanceof(child, internal.ASTNode.FunctionDefinition)) {
1751
+ var text = this.context._referencedGlobalMacroASTs.indexOf(child) !== -1 ? this.getCachedCode(child) : this._forwardFunctionDeclarations.get(child);
1752
+ if (text !== undefined) {
1753
+ out.push({
1754
+ text: this._declaration(text, child),
1755
+ index: child.location.start.index
1756
+ });
1757
+ }
1758
+ } else if (_instanceof(child, internal.ASTNode.StructSpecifier)) {
1759
+ if (this._forwardStructIndices.has(child)) {
1760
+ var text1 = this._declaration("", child);
1761
+ if (text1) out.push({
1762
+ text: text1,
1763
+ index: child.location.start.index
1764
+ });
1765
+ continue;
1766
+ }
1767
+ var context = this.context;
1768
+ var stage = context.stage;
1769
+ if (context._referencedGlobalMacroASTs.indexOf(child) !== -1 || (stage === internal.EShaderStage.VERTEX ? context.hasStructRole(child, internal.ShaderStructRole.Attribute) || context.hasStructRole(child, internal.ShaderStructRole.Varying) : context.hasStructRole(child, internal.ShaderStructRole.Varying) || context.hasStructRole(child, internal.ShaderStructRole.Mrt))) {
1770
+ var _this_getCachedCode;
1771
+ out.push({
1772
+ text: this._declaration((_this_getCachedCode = this.getCachedCode(child)) != null ? _this_getCachedCode : "", child),
1773
+ index: child.location.start.index
1774
+ });
1775
+ }
1776
+ } else if (_instanceof(child, internal.ASTNode.VariableDeclarationList)) {
1777
+ var variableDeclarations = child.variableDeclarations;
1778
+ for(var i1 = 0; i1 < variableDeclarations.length; i1++){
1779
+ var variableDeclaration = variableDeclarations[i1];
1780
+ if (this.context._referencedGlobalMacroASTs.indexOf(variableDeclaration) !== -1) {
1781
+ var _this_getCachedCode1;
1782
+ out.push({
1783
+ text: this._declaration(this._forwardVariableIndices.has(variableDeclaration) ? "" : "" + ((_this_getCachedCode1 = this.getCachedCode(variableDeclaration)) != null ? _this_getCachedCode1 : "") + ";", variableDeclaration),
1784
+ index: variableDeclaration.location.start.index
1785
+ });
1786
+ }
1787
+ }
1788
+ }
1789
+ if (_instanceof(child, internal.TreeNode)) {
1790
+ this._visitGlobalMacroIfStatement(child, out);
1791
+ }
1792
+ }
1793
+ };
1794
+ _proto._referenceDeclaration = function _referenceDeclaration(from, node) {
1795
+ var owner = this._declarationOwners.get(node);
1796
+ if (!owner) return;
1797
+ var targets = this._declarationReferences.get(from);
1798
+ if (!targets) this._declarationReferences.set(from, targets = new Set());
1799
+ targets.add(owner.id);
1800
+ };
1801
+ _proto._emitDeclarationReferences = function _emitDeclarationReferences(out) {
1802
+ for(var _iterator = _create_for_of_iterator_helper_loose(this._declarationReferences), _step; !(_step = _iterator()).done;){
1803
+ var _step_value = _step.value, from = _step_value[0], targets = _step_value[1];
1804
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(targets), _step1; !(_step1 = _iterator1()).done;){
1805
+ var to = _step1.value;
1806
+ out.push({
1807
+ text: ShaderInstructionEncoder.reference(from, to),
1808
+ index: -1
1809
+ });
1810
+ }
1811
+ }
1812
+ };
1813
+ _proto._declaration = function _declaration(text, node, activate) {
1814
+ if (activate === void 0) activate = true;
1815
+ return ShaderInstructionEncoder.declaration(text, this._declarationOwners.get(node), activate);
1816
+ };
1817
+ _create_class(GLESVisitor, [
1818
+ {
1819
+ key: "currentDeclarationOwner",
1820
+ get: /** Ownership of the declaration currently generating dependencies. @internal */ function get() {
1821
+ return this._currentDeclaration && this._declarationOwners.get(this._currentDeclaration);
1822
+ }
1823
+ }
1824
+ ]);
1825
+ return GLESVisitor;
1826
+ }(CodeGenVisitor);
1827
+
1828
+ var GLES100Visitor = /*#__PURE__*/ function(GLESVisitor) {
1829
+ _inherits(GLES100Visitor, GLESVisitor);
1830
+ function GLES100Visitor() {
1831
+ return GLESVisitor.apply(this, arguments) || this;
1832
+ }
1833
+ var _proto = GLES100Visitor.prototype;
1834
+ _proto.getAttributeProp = function getAttributeProp(prop) {
1835
+ return "attribute " + prop.typeInfo.typeLexeme + " " + prop.ident.lexeme + ";";
1836
+ };
1837
+ _proto.getVaryingProp = function getVaryingProp(prop) {
1838
+ return "varying " + prop.typeInfo.typeLexeme + " " + prop.ident.lexeme + ";";
1839
+ };
1840
+ _proto.getMRTProp = function getMRTProp() {
1841
+ return "";
1842
+ };
1843
+ _proto.visitPostfixExpression = function visitPostfixExpression(node) {
1844
+ var children = node.children;
1845
+ var postExpr = children[0];
1846
+ var context = this.context;
1847
+ var directRoot = _instanceof(postExpr, internal.ASTNode.PostfixExpression) ? internal.ParserUtils.unwrapBareIdentifier(postExpr, {
1848
+ allowParens: true
1849
+ }) : undefined;
1850
+ var _directRoot_resolvedValueSymbols;
1851
+ var directSymbols = (_directRoot_resolvedValueSymbols = directRoot == null ? void 0 : directRoot.resolvedValueSymbols()) != null ? _directRoot_resolvedValueSymbols : [];
1852
+ var unresolvedName = _instanceof(postExpr, internal.ASTNode.PostfixExpression) ? internal.ParserUtils.extractDirectIdentLexeme(postExpr) : null;
1853
+ var directRole = directRoot ? directSymbols.length ? context.getStructVarRole(directSymbols) : unresolvedName ? context.getUnresolvedStructVarRole(unresolvedName) : undefined : undefined;
1854
+ if (directRole === internal.ShaderStructRole.Mrt) {
1855
+ var propReferenced = children[2];
1856
+ var prop = context.mrtList.find(function(item) {
1857
+ return item.ident.lexeme === propReferenced.lexeme;
1858
+ });
1859
+ // The parser already validated struct fields (UndeclaredStructMember); a miss here is an
1860
+ // already-errored shader, so emit nothing rather than re-report.
1861
+ if (!prop) return "";
1862
+ return "gl_FragData[" + prop.mrtIndex + "]";
1863
+ }
1864
+ return GLESVisitor.prototype.visitPostfixExpression.call(this, node);
1865
+ };
1866
+ _proto.visitJumpStatement = function visitJumpStatement(node) {
1867
+ var mode = this.context.getFragmentReturnMode(node);
1868
+ var terminal = this.context.isTerminalInterfaceReturn(node);
1869
+ if (mode === "mrt") return terminal ? "" : "return;";
1870
+ if (mode === "color") {
1871
+ var expression = node.children[1];
1872
+ var assignment = "gl_FragColor = " + expression.codeGen(this) + ";";
1873
+ return terminal ? assignment : "{ " + assignment + " return; }";
1874
+ }
1875
+ return GLESVisitor.prototype.visitJumpStatement.call(this, node);
1876
+ };
1877
+ return GLES100Visitor;
1878
+ }(GLESVisitor);
1879
+
1880
+ var V3_GL_FragColor = "GS_glFragColor";
1881
+ var V3_GL_FragData = "GS_glFragData";
1882
+ var GLES300Visitor = /*#__PURE__*/ function(GLESVisitor) {
1883
+ _inherits(GLES300Visitor, GLESVisitor);
1884
+ function GLES300Visitor() {
1885
+ var _this;
1886
+ _this = GLESVisitor.apply(this, arguments) || this, _this._outputDeclarations = new Map(), _this._fragDataArrayRequired = false, _this._fragDataIndices = new Map(), _this._scannedFragmentFunctions = new Set();
1887
+ return _this;
1888
+ }
1889
+ var _proto = GLES300Visitor.prototype;
1890
+ _proto.reset = function reset() {
1891
+ GLESVisitor.prototype.reset.call(this);
1892
+ this._outputDeclarations.clear();
1893
+ this._fragDataArrayRequired = false;
1894
+ this._fragDataIndices.clear();
1895
+ this._scannedFragmentFunctions.clear();
1896
+ };
1897
+ _proto.getOtherGlobal = function getOtherGlobal(data, out) {
1898
+ GLESVisitor.prototype.getOtherGlobal.call(this, data, out);
1899
+ for(var _iterator = _create_for_of_iterator_helper_loose(this._outputDeclarations.values()), _step; !(_step = _iterator()).done;){
1900
+ var output = _step.value;
1901
+ out.push({
1902
+ text: output.unconditional ? output.text : ShaderInstructionEncoder.sharedDeclaration(output.text, Array.from(output.owners.values())),
1903
+ // A source macro block can start at zero and contain the first output use.
1904
+ index: -1
1905
+ });
1906
+ }
1907
+ };
1908
+ _proto.getAttributeProp = function getAttributeProp(prop) {
1909
+ return "in " + prop.typeInfo.typeLexeme + " " + prop.ident.lexeme + ";";
1910
+ };
1911
+ _proto.getVaryingProp = function getVaryingProp(prop) {
1912
+ var qualifier = this.context.stage === internal.EShaderStage.FRAGMENT ? "in" : "out";
1913
+ return qualifier + " " + prop.typeInfo.typeLexeme + " " + prop.ident.lexeme + ";";
1914
+ };
1915
+ _proto.getMRTProp = function getMRTProp(prop) {
1916
+ return "layout(location = " + prop.mrtIndex + ") out vec4 " + prop.ident.lexeme + ";";
1917
+ };
1918
+ _proto.visitFunctionIdentifier = function visitFunctionIdentifier(node) {
1919
+ var children = node.children;
1920
+ var typeSpecifier = children[0];
1921
+ if (typeSpecifier.children.length !== 1 || typeSpecifier.structDependencies.length) {
1922
+ // Struct constructors still need the shared type-dependency visitor.
1923
+ return GLESVisitor.prototype.visitFunctionIdentifier.call(this, node);
1924
+ }
1925
+ var ident = node.lexeme;
1926
+ switch(node.ident){
1927
+ case "texture2D":
1928
+ case "textureCube":
1929
+ ident = "texture";
1930
+ break;
1931
+ case "texture2DProj":
1932
+ ident = "textureProj";
1933
+ break;
1934
+ case "texture2DLodEXT":
1935
+ case "textureCubeLodEXT":
1936
+ ident = "textureLod";
1937
+ break;
1938
+ case "texture2DGradEXT":
1939
+ case "textureCubeGradEXT":
1940
+ ident = "textureGrad";
1941
+ break;
1942
+ case "texture2DProjLodEXT":
1943
+ ident = "textureProjLod";
1944
+ break;
1945
+ case "texture2DProjGradEXT":
1946
+ ident = "textureProjGrad";
1947
+ break;
1948
+ }
1949
+ return ident;
1950
+ };
1951
+ _proto.visitVariableIdentifier = function visitVariableIdentifier(node) {
1952
+ var context = this.context;
1953
+ if (context.stage === internal.EShaderStage.FRAGMENT && node.builtinSemantic === internal.ShaderBuiltinSemantic.FragmentOutput0) {
1954
+ this._registerFragColorVariable();
1955
+ return V3_GL_FragColor;
1956
+ }
1957
+ if (context.stage === internal.EShaderStage.FRAGMENT && node.builtinSemantic === internal.ShaderBuiltinSemantic.FragmentDepth) {
1958
+ return "gl_FragDepth";
1959
+ }
1960
+ if (context.stage === internal.EShaderStage.FRAGMENT && node.builtinSemantic === internal.ShaderBuiltinSemantic.FragmentOutputArray) {
1961
+ this._registerFragDataArray();
1962
+ return V3_GL_FragData;
1963
+ }
1964
+ return GLESVisitor.prototype.visitVariableIdentifier.call(this, node);
1965
+ };
1966
+ _proto.visitPostfixExpression = function visitPostfixExpression(node) {
1967
+ if (!this._fragDataArrayRequired) {
1968
+ var index = this._fragDataIndices.get(node);
1969
+ if (index !== undefined) return this._registerFragDataVariable(index);
1970
+ }
1971
+ return GLESVisitor.prototype.visitPostfixExpression.call(this, node);
1972
+ };
1973
+ _proto.visitJumpStatement = function visitJumpStatement(node) {
1974
+ var mode = this.context.getFragmentReturnMode(node);
1975
+ var terminal = this.context.isTerminalInterfaceReturn(node);
1976
+ if (mode === "mrt") return terminal ? "" : "return;";
1977
+ if (mode === "color") {
1978
+ this._registerFragColorVariable();
1979
+ var expression = node.children[1];
1980
+ var assignment = V3_GL_FragColor + " = " + expression.codeGen(this) + ";";
1981
+ return terminal ? assignment : "{ " + assignment + " return; }";
1982
+ }
1983
+ return GLESVisitor.prototype.visitJumpStatement.call(this, node);
1984
+ };
1985
+ _proto._registerFragColorVariable = function _registerFragColorVariable() {
1986
+ this._registerOutput(V3_GL_FragColor, "out vec4 " + V3_GL_FragColor + ";");
1987
+ };
1988
+ _proto._registerOutput = function _registerOutput(name, text) {
1989
+ var output = this._outputDeclarations.get(name);
1990
+ if (!output) this._outputDeclarations.set(name, output = {
1991
+ text: text,
1992
+ owners: new Map(),
1993
+ unconditional: false
1994
+ });
1995
+ var owner = this.currentDeclarationOwner;
1996
+ if (owner) output.owners.set(owner.id, owner);
1997
+ else output.unconditional = true;
1998
+ };
1999
+ _proto.prepareFragment = function prepareFragment(entryInfo, outerGlobalMacroStatements) {
2000
+ var pending = entryInfo.functions.slice();
2001
+ while(pending.length){
2002
+ var _pending;
2003
+ var fn = pending.pop();
2004
+ if (this._scannedFragmentFunctions.has(fn)) continue;
2005
+ this._scannedFragmentFunctions.add(fn);
2006
+ this._scanFragmentOutputs(fn.astNode);
2007
+ (_pending = pending).push.apply(_pending, [].concat(fn.calledFunctions));
2008
+ }
2009
+ for(var _iterator = _create_for_of_iterator_helper_loose(outerGlobalMacroStatements), _step; !(_step = _iterator()).done;){
2010
+ var macro = _step.value;
2011
+ this._scanFragmentOutputs(macro);
2012
+ }
2013
+ };
2014
+ _proto._scanFragmentOutputs = function _scanFragmentOutputs(node) {
2015
+ if (_instanceof(node, internal.ASTNode.PostfixExpression) && node.children.length === 4) {
2016
+ var _ParserUtils_unwrapBareIdentifier;
2017
+ var base = node.children[0];
2018
+ var index = node.children[2];
2019
+ if (_instanceof(base, internal.TreeNode) && _instanceof(index, internal.TreeNode) && ((_ParserUtils_unwrapBareIdentifier = internal.ParserUtils.unwrapBareIdentifier(base, {
2020
+ allowParens: true
2021
+ })) == null ? void 0 : _ParserUtils_unwrapBareIdentifier.builtinSemantic) === internal.ShaderBuiltinSemantic.FragmentOutputArray) {
2022
+ var value = internal.ParserUtils.constIntegerValue(index);
2023
+ if (value === undefined || value < 0) this._fragDataArrayRequired = true;
2024
+ else this._fragDataIndices.set(node, value);
2025
+ this._scanFragmentOutputs(index);
2026
+ return;
2027
+ }
2028
+ }
2029
+ if (_instanceof(node, internal.ASTNode.VariableIdentifier) && node.builtinSemantic === internal.ShaderBuiltinSemantic.FragmentOutputArray) {
2030
+ this._fragDataArrayRequired = true;
2031
+ return;
2032
+ }
2033
+ for(var _iterator = _create_for_of_iterator_helper_loose(node.children), _step; !(_step = _iterator()).done;){
2034
+ var child = _step.value;
2035
+ if (_instanceof(child, internal.TreeNode)) this._scanFragmentOutputs(child);
2036
+ }
2037
+ };
2038
+ _proto._registerFragDataArray = function _registerFragDataArray() {
2039
+ this._registerOutput(V3_GL_FragData, "layout(location = 0) out vec4 " + V3_GL_FragData + "[gl_MaxDrawBuffers];");
2040
+ };
2041
+ _proto._registerFragDataVariable = function _registerFragDataVariable(index) {
2042
+ var name = "" + V3_GL_FragData + index;
2043
+ this._registerOutput(name, "layout(location = " + index + ") out vec4 " + name + ";");
2044
+ return name;
2045
+ };
2046
+ return GLES300Visitor;
2047
+ }(GLESVisitor);
2048
+
2049
+ /**
2050
+ * Static internal facade for GLES source generation.
2051
+ * @internal
2052
+ */ var GLESBackend = /*#__PURE__*/ function() {
2053
+ function GLESBackend() {}
2054
+ /**
2055
+ * Generates one GLES program with request-owned visitor state.
2056
+ * @param ir - Request-owned neutral parser IR consumed read-only.
2057
+ * @param coreInfo - Entry and stage-interface facts derived from the same IR.
2058
+ * @param target - GLES language version to emit.
2059
+ * @returns Generated vertex and fragment source.
2060
+ * @internal
2061
+ */ GLESBackend.generate = function generate(ir, coreInfo, target) {
2062
+ var glesInfo = new internal.GLESShaderInfo(ir, coreInfo);
2063
+ if (glesInfo.mrtOutputIssues.length || glesInfo.invalidMrtReturnLocations.length) {
2064
+ engineCore.Logger.error("MRT outputs require unique non-negative locations, vec4 members, and returns through an assigned struct variable.");
2065
+ return undefined;
2066
+ }
2067
+ if (glesInfo.invalidVaryingReturnLocations.length) {
2068
+ engineCore.Logger.error("Varying vertex entries must return a struct variable or same-type function result.");
2069
+ return undefined;
2070
+ }
2071
+ if (glesInfo.structMemberOwnerIssues.length) {
2072
+ engineCore.Logger.error("A struct member reference cannot be lowered safely across runtime macro expansion.");
2073
+ return undefined;
2074
+ }
2075
+ return target === engineCore.ShaderLanguage.GLSLES100 ? GLESBackend._generateWithPool(GLESBackend._gles100VisitorPool, ir, coreInfo) : GLESBackend._generateWithPool(GLESBackend._gles300VisitorPool, ir, coreInfo);
2076
+ };
2077
+ GLESBackend._generateWithPool = function _generateWithPool(pool, ir, coreInfo) {
2078
+ var visitor = pool.get();
2079
+ try {
2080
+ return visitor.generate(ir, coreInfo);
2081
+ } catch (error) {
2082
+ visitor.dispose();
2083
+ if (!_instanceof(error, internal.GSError)) throw error;
2084
+ engineCore.Logger.error("" + (error.file ? "" + error.file + ": " : "") + (error.code ? "" + error.code + ": " : "") + error.toString());
2085
+ return undefined;
2086
+ } finally{
2087
+ pool.return(visitor);
2088
+ }
2089
+ };
2090
+ return GLESBackend;
2091
+ }();
2092
+ GLESBackend._gles100VisitorPool = new engineCore.ReturnableObjectPool(GLES100Visitor);
2093
+ GLESBackend._gles300VisitorPool = new engineCore.ReturnableObjectPool(GLES300Visitor);
2094
+
2095
+ var ShaderSourceParseError = /*#__PURE__*/ function(Error1) {
2096
+ _inherits(ShaderSourceParseError, Error1);
2097
+ function ShaderSourceParseError(errors) {
2098
+ var _this;
2099
+ _this = Error1.call(this, errors.map(function(error) {
2100
+ return error.toString();
2101
+ }).join("\n")) || this, _this.errors = errors;
2102
+ _this.name = "ShaderSourceParseError";
2103
+ return _this;
2104
+ }
2105
+ return ShaderSourceParseError;
2106
+ }(_wrap_native_super(Error));
2107
+ /**
2108
+ * Rejects a partial ShaderLab structure when source parsing produced errors.
2109
+ * @param result - ShaderLab source-parser result.
2110
+ * @returns Complete parsed ShaderLab structure.
2111
+ * @throws ShaderSourceParseError when structural source diagnostics exist.
2112
+ * @internal
2113
+ */ function requireValidShaderSource(result) {
2114
+ if (result.errors.length) throw new ShaderSourceParseError(result.errors);
2115
+ return result.shaderSource;
2116
+ }
2117
+ /**
2118
+ * Generates one backend program from a parser-owned pass without reparsing it.
2119
+ * @param parsed - Neutral parser output.
2120
+ * @param vertexEntry - Vertex entry name.
2121
+ * @param fragmentEntry - Fragment entry name.
2122
+ * @param backend - Target GLES language.
2123
+ * @param coreInfo - Optional stage facts already derived from this exact parser result.
2124
+ * @returns Generated program, or `undefined` when parser or entry admission fails.
2125
+ * @internal
2126
+ */ function generateParsedShaderPassData(parsed, vertexEntry, fragmentEntry, backend, coreInfo) {
2127
+ if (parsed.blockingErrors.length) {
2128
+ for(var _iterator = _create_for_of_iterator_helper_loose(parsed.blockingErrors), _step; !(_step = _iterator()).done;){
2129
+ var error = _step.value;
2130
+ engineCore.Logger.error(error.toString());
2131
+ }
2132
+ return undefined;
2133
+ }
2134
+ if (!parsed.ir) return undefined;
2135
+ var resolvedCoreInfo = coreInfo != null ? coreInfo : internal.ShaderCoreInfo.create(parsed.ir, vertexEntry, fragmentEntry);
2136
+ return generateShaderProgram(parsed.ir, resolvedCoreInfo, backend, parsed.preprocessorExpressions);
2137
+ }
2138
+ function generateShaderProgram(ir, coreInfo, backend, preprocessorExpressions) {
2139
+ if (!coreInfo.vertexEntry.functions.length) {
2140
+ engineCore.Logger.error("Vertex entry function '" + coreInfo.vertexEntry.name + "' not found.");
2141
+ return undefined;
2142
+ }
2143
+ if (!coreInfo.fragmentEntry.functions.length) {
2144
+ engineCore.Logger.error("Fragment entry function '" + coreInfo.fragmentEntry.name + "' not found.");
2145
+ return undefined;
2146
+ }
2147
+ if (coreInfo.vertexEntry.hasDefiniteAmbiguity) {
2148
+ engineCore.Logger.error("Vertex entry function '" + coreInfo.vertexEntry.name + "' resolves to multiple declarations.");
2149
+ return undefined;
2150
+ }
2151
+ if (coreInfo.fragmentEntry.hasDefiniteAmbiguity) {
2152
+ engineCore.Logger.error("Fragment entry function '" + coreInfo.fragmentEntry.name + "' resolves to multiple declarations.");
2153
+ return undefined;
2154
+ }
2155
+ if (coreInfo.roleConflicts.length) {
2156
+ engineCore.Logger.error("A shader IO struct cannot serve multiple stage-interface roles.");
2157
+ return undefined;
2158
+ }
2159
+ var result = GLESBackend.generate(ir, coreInfo, backend);
2160
+ if (result) {
2161
+ result.vertexShaderInstructions = ShaderInstructionEncoder.parse(result.vertex, preprocessorExpressions);
2162
+ result.fragmentShaderInstructions = ShaderInstructionEncoder.parse(result.fragment, preprocessorExpressions);
2163
+ result.vertex = ShaderInstructionEncoder.source(result.vertex);
2164
+ result.fragment = ShaderInstructionEncoder.source(result.fragment);
2165
+ }
2166
+ return result;
2167
+ }
2168
+ /**
2169
+ * Converts parser-owned render states into JSON-safe precompile data.
2170
+ * @param renderStates - Parsed render-state maps.
2171
+ * @returns Serializable constant and variable maps.
2172
+ * @internal
2173
+ */ function serializeRenderStates(renderStates) {
2174
+ var constantMap = {};
2175
+ for(var key in renderStates.constantMap){
2176
+ var value = renderStates.constantMap[key];
2177
+ if (_instanceof(value, engineMath.Color)) {
2178
+ constantMap[key] = [
2179
+ value.r,
2180
+ value.g,
2181
+ value.b,
2182
+ value.a
2183
+ ];
2184
+ } else {
2185
+ constantMap[key] = value;
2186
+ }
2187
+ }
2188
+ return {
2189
+ constantMap: constantMap,
2190
+ variableMap: renderStates.variableMap
2191
+ };
2192
+ }
2193
+ /**
2194
+ * Formats a parser failure with include-source attribution.
2195
+ * @param error - Parser failure.
2196
+ * @returns User-facing error text.
2197
+ * @internal
2198
+ */ function formatShaderError(error) {
2199
+ var text = error.toString();
2200
+ return _instanceof(error, internal.GSError) && error.file ? error.file + ": " + text : text;
2201
+ }
2202
+
2203
+ /**
2204
+ * Offline-only ShaderLab to `.shaderc` compiler with deterministic validation.
2205
+ *
2206
+ * This class is intentionally excluded from the runtime compiler entry. CLI and bundler adapters import
2207
+ * it from `@galacean/engine-shader-compiler/precompile`.
2208
+ */ var ShaderPrecompiler = /*#__PURE__*/ function() {
2209
+ function ShaderPrecompiler() {
2210
+ this._includeMap = Object.create(null);
2211
+ this._chunkOutputCache = new Map();
2212
+ this._sourceParserObjectPool = new analyzer.ParserObjectPool();
2213
+ this._parserObjectPool = new analyzer.ParserObjectPool();
2214
+ this._validatedParser = analyzer.createValidatedShaderTargetParser(this._parserObjectPool);
2215
+ }
2216
+ var _proto = ShaderPrecompiler.prototype;
2217
+ /**
2218
+ * Replaces the logical include registry used by offline compilation.
2219
+ * @param includeMap - Canonical or normalizable include keys mapped to chunk sources.
2220
+ * @throws Error when multiple keys collide after normalization.
2221
+ */ _proto.setIncludeMap = function setIncludeMap(includeMap) {
2222
+ this._includeMap = analyzer.normalizeShaderIncludeMap(includeMap);
2223
+ this._chunkOutputCache.clear();
2224
+ };
2225
+ /**
2226
+ * Compiles complete ShaderLab source into a serializable `.shaderc` structure.
2227
+ * @param sourceCode - Complete ShaderLab source.
2228
+ * @param platformTarget - Target GLES language.
2229
+ * @param sourceFile - Optional logical root location used for relative includes and attribution.
2230
+ * @returns Serializable precompiled shader.
2231
+ * @throws Error when structural parsing, pass validation, or backend generation fails.
2232
+ */ _proto.precompile = function precompile(sourceCode, platformTarget, sourceFile) {
2233
+ var _this = this;
2234
+ this._chunkOutputCache.clear();
2235
+ var shaderSource = requireValidShaderSource(analyzer.ShaderSourceParser.parseStrict(sourceCode, this._sourceParserObjectPool));
2236
+ return {
2237
+ name: shaderSource.name,
2238
+ platformTarget: platformTarget,
2239
+ subShaders: shaderSource.subShaders.map(function(subShader) {
2240
+ return {
2241
+ name: subShader.name,
2242
+ tags: subShader.tags,
2243
+ passes: subShader.passes.map(function(pass) {
2244
+ if (pass.isUsePass) {
2245
+ return {
2246
+ name: pass.name,
2247
+ isUsePass: true,
2248
+ tags: pass.tags,
2249
+ renderStates: serializeRenderStates(pass.renderStates)
2250
+ };
2251
+ }
2252
+ var parsed = analyzer.parseValidatedShaderPass(pass.contents, _this._includeMap, _this._chunkOutputCache, sourceFile, _this._parserObjectPool, _this._validatedParser, pass.contentScopeStarts);
2253
+ if (parsed.blockingErrors.length) {
2254
+ throw new Error([].concat([
2255
+ 'Shader pass "' + shaderSource.name + "." + subShader.name + "." + pass.name + '" precompile failed:'
2256
+ ], parsed.blockingErrors.map(formatShaderError)).join("\n"));
2257
+ }
2258
+ var coreInfo = parsed.ir ? analyzer.ShaderCoreInfo.create(parsed.ir, pass.vertexEntry, pass.fragmentEntry, analyzer.branchAnalysis.getDeclarationCoexistence, analyzer.branchAnalysis.getBranchCoverage) : undefined;
2259
+ var program = generateParsedShaderPassData(parsed, pass.vertexEntry, pass.fragmentEntry, platformTarget, coreInfo);
2260
+ if (!program) {
2261
+ throw new Error('Shader pass "' + shaderSource.name + "." + subShader.name + "." + pass.name + '" precompile failed, please check the shader source code.');
2262
+ }
2263
+ return {
2264
+ name: pass.name,
2265
+ isUsePass: false,
2266
+ tags: pass.tags,
2267
+ renderStates: serializeRenderStates(pass.renderStates),
2268
+ vertexShaderInstructions: program.vertexShaderInstructions,
2269
+ fragmentShaderInstructions: program.fragmentShaderInstructions
2270
+ };
2271
+ })
2272
+ };
2273
+ })
2274
+ };
2275
+ };
2276
+ return ShaderPrecompiler;
2277
+ }();
2278
+
2279
+ exports.ShaderPrecompiler = ShaderPrecompiler;
2280
+ //# sourceMappingURL=precompile.main.js.map