@babylonjs/smart-filters 0.1.0-alpha

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 (138) hide show
  1. package/dist/IDisposable.d.ts +10 -0
  2. package/dist/IDisposable.d.ts.map +1 -0
  3. package/dist/IDisposable.js +2 -0
  4. package/dist/IDisposable.js.map +1 -0
  5. package/dist/blocks/aggregateBlock.d.ts +50 -0
  6. package/dist/blocks/aggregateBlock.d.ts.map +1 -0
  7. package/dist/blocks/aggregateBlock.js +103 -0
  8. package/dist/blocks/aggregateBlock.js.map +1 -0
  9. package/dist/blocks/baseBlock.d.ts +160 -0
  10. package/dist/blocks/baseBlock.d.ts.map +1 -0
  11. package/dist/blocks/baseBlock.js +256 -0
  12. package/dist/blocks/baseBlock.js.map +1 -0
  13. package/dist/blocks/copyBlock.d.ts +59 -0
  14. package/dist/blocks/copyBlock.d.ts.map +1 -0
  15. package/dist/blocks/copyBlock.js +84 -0
  16. package/dist/blocks/copyBlock.js.map +1 -0
  17. package/dist/blocks/disableableBlock.d.ts +30 -0
  18. package/dist/blocks/disableableBlock.d.ts.map +1 -0
  19. package/dist/blocks/disableableBlock.js +22 -0
  20. package/dist/blocks/disableableBlock.js.map +1 -0
  21. package/dist/blocks/inputBlock.d.ts +64 -0
  22. package/dist/blocks/inputBlock.d.ts.map +1 -0
  23. package/dist/blocks/inputBlock.js +74 -0
  24. package/dist/blocks/inputBlock.js.map +1 -0
  25. package/dist/blocks/outputBlock.d.ts +42 -0
  26. package/dist/blocks/outputBlock.d.ts.map +1 -0
  27. package/dist/blocks/outputBlock.js +74 -0
  28. package/dist/blocks/outputBlock.js.map +1 -0
  29. package/dist/blocks/shaderBlock.d.ts +68 -0
  30. package/dist/blocks/shaderBlock.d.ts.map +1 -0
  31. package/dist/blocks/shaderBlock.js +101 -0
  32. package/dist/blocks/shaderBlock.js.map +1 -0
  33. package/dist/command/command.d.ts +49 -0
  34. package/dist/command/command.d.ts.map +1 -0
  35. package/dist/command/command.js +15 -0
  36. package/dist/command/command.js.map +1 -0
  37. package/dist/command/commandBuffer.d.ts +40 -0
  38. package/dist/command/commandBuffer.d.ts.map +1 -0
  39. package/dist/command/commandBuffer.js +58 -0
  40. package/dist/command/commandBuffer.js.map +1 -0
  41. package/dist/command/commandBufferDebugger.d.ts +7 -0
  42. package/dist/command/commandBufferDebugger.d.ts.map +1 -0
  43. package/dist/command/commandBufferDebugger.js +12 -0
  44. package/dist/command/commandBufferDebugger.js.map +1 -0
  45. package/dist/connection/connectionPoint.d.ts +110 -0
  46. package/dist/connection/connectionPoint.d.ts.map +1 -0
  47. package/dist/connection/connectionPoint.js +153 -0
  48. package/dist/connection/connectionPoint.js.map +1 -0
  49. package/dist/connection/connectionPointCompatibilityState.d.ts +20 -0
  50. package/dist/connection/connectionPointCompatibilityState.d.ts.map +1 -0
  51. package/dist/connection/connectionPointCompatibilityState.js +32 -0
  52. package/dist/connection/connectionPointCompatibilityState.js.map +1 -0
  53. package/dist/connection/connectionPointDirection.d.ts +10 -0
  54. package/dist/connection/connectionPointDirection.d.ts.map +1 -0
  55. package/dist/connection/connectionPointDirection.js +11 -0
  56. package/dist/connection/connectionPointDirection.js.map +1 -0
  57. package/dist/connection/connectionPointType.d.ts +22 -0
  58. package/dist/connection/connectionPointType.d.ts.map +1 -0
  59. package/dist/connection/connectionPointType.js +17 -0
  60. package/dist/connection/connectionPointType.js.map +1 -0
  61. package/dist/connection/connectionPointWithDefault.d.ts +23 -0
  62. package/dist/connection/connectionPointWithDefault.d.ts.map +1 -0
  63. package/dist/connection/connectionPointWithDefault.js +19 -0
  64. package/dist/connection/connectionPointWithDefault.js.map +1 -0
  65. package/dist/index.d.ts +28 -0
  66. package/dist/index.d.ts.map +1 -0
  67. package/dist/index.js +28 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/optimization/dependencyGraph.d.ts +31 -0
  70. package/dist/optimization/dependencyGraph.d.ts.map +1 -0
  71. package/dist/optimization/dependencyGraph.js +77 -0
  72. package/dist/optimization/dependencyGraph.js.map +1 -0
  73. package/dist/optimization/optimizedShaderBlock.d.ts +75 -0
  74. package/dist/optimization/optimizedShaderBlock.d.ts.map +1 -0
  75. package/dist/optimization/optimizedShaderBlock.js +105 -0
  76. package/dist/optimization/optimizedShaderBlock.js.map +1 -0
  77. package/dist/optimization/smartFilterOptimizer.d.ts +72 -0
  78. package/dist/optimization/smartFilterOptimizer.d.ts.map +1 -0
  79. package/dist/optimization/smartFilterOptimizer.js +482 -0
  80. package/dist/optimization/smartFilterOptimizer.js.map +1 -0
  81. package/dist/runtime/renderTargetGenerator.d.ts +35 -0
  82. package/dist/runtime/renderTargetGenerator.d.ts.map +1 -0
  83. package/dist/runtime/renderTargetGenerator.js +153 -0
  84. package/dist/runtime/renderTargetGenerator.js.map +1 -0
  85. package/dist/runtime/shaderRuntime.d.ts +95 -0
  86. package/dist/runtime/shaderRuntime.d.ts.map +1 -0
  87. package/dist/runtime/shaderRuntime.js +120 -0
  88. package/dist/runtime/shaderRuntime.js.map +1 -0
  89. package/dist/runtime/smartFilterRuntime.d.ts +69 -0
  90. package/dist/runtime/smartFilterRuntime.d.ts.map +1 -0
  91. package/dist/runtime/smartFilterRuntime.js +57 -0
  92. package/dist/runtime/smartFilterRuntime.js.map +1 -0
  93. package/dist/runtime/strongRef.d.ts +16 -0
  94. package/dist/runtime/strongRef.d.ts.map +1 -0
  95. package/dist/runtime/strongRef.js +9 -0
  96. package/dist/runtime/strongRef.js.map +1 -0
  97. package/dist/smartFilter.d.ts +100 -0
  98. package/dist/smartFilter.d.ts.map +1 -0
  99. package/dist/smartFilter.js +154 -0
  100. package/dist/smartFilter.js.map +1 -0
  101. package/dist/utils/shaderCodeUtils.d.ts +131 -0
  102. package/dist/utils/shaderCodeUtils.d.ts.map +1 -0
  103. package/dist/utils/shaderCodeUtils.js +115 -0
  104. package/dist/utils/shaderCodeUtils.js.map +1 -0
  105. package/dist/utils/textureLoaders.d.ts +14 -0
  106. package/dist/utils/textureLoaders.d.ts.map +1 -0
  107. package/dist/utils/textureLoaders.js +22 -0
  108. package/dist/utils/textureLoaders.js.map +1 -0
  109. package/license.md +21 -0
  110. package/package.json +47 -0
  111. package/readme.md +165 -0
  112. package/src/IDisposable.ts +9 -0
  113. package/src/blocks/aggregateBlock.ts +121 -0
  114. package/src/blocks/baseBlock.ts +341 -0
  115. package/src/blocks/copyBlock.ts +103 -0
  116. package/src/blocks/disableableBlock.ts +40 -0
  117. package/src/blocks/inputBlock.ts +114 -0
  118. package/src/blocks/outputBlock.ts +97 -0
  119. package/src/blocks/shaderBlock.ts +145 -0
  120. package/src/command/command.ts +60 -0
  121. package/src/command/commandBuffer.ts +71 -0
  122. package/src/command/commandBufferDebugger.ts +13 -0
  123. package/src/connection/connectionPoint.ts +212 -0
  124. package/src/connection/connectionPointCompatibilityState.ts +31 -0
  125. package/src/connection/connectionPointDirection.ts +9 -0
  126. package/src/connection/connectionPointType.ts +30 -0
  127. package/src/connection/connectionPointWithDefault.ts +35 -0
  128. package/src/index.ts +36 -0
  129. package/src/optimization/dependencyGraph.ts +94 -0
  130. package/src/optimization/optimizedShaderBlock.ts +133 -0
  131. package/src/optimization/smartFilterOptimizer.ts +706 -0
  132. package/src/runtime/renderTargetGenerator.ts +204 -0
  133. package/src/runtime/shaderRuntime.ts +155 -0
  134. package/src/runtime/smartFilterRuntime.ts +104 -0
  135. package/src/runtime/strongRef.ts +18 -0
  136. package/src/smartFilter.ts +227 -0
  137. package/src/utils/shaderCodeUtils.ts +242 -0
  138. package/src/utils/textureLoaders.ts +28 -0
@@ -0,0 +1,706 @@
1
+ import type { Nullable } from "@babylonjs/core/types";
2
+
3
+ import type { ConnectionPoint } from "../connection/connectionPoint";
4
+ import type { Binding } from "../runtime/shaderRuntime";
5
+ import type { InputBlock } from "../blocks/inputBlock";
6
+ import type { BaseBlock } from "../blocks/baseBlock";
7
+ import { SmartFilter } from "../smartFilter.js";
8
+ import { ConnectionPointType } from "../connection/connectionPointType.js";
9
+ import { ShaderBlock } from "../blocks/shaderBlock.js";
10
+ import { isTextureInputBlock } from "../blocks/inputBlock.js";
11
+ import { OptimizedShaderBlock } from "./optimizedShaderBlock.js";
12
+ import { decorateChar, decorateSymbol, getShaderFragmentCode, undecorateSymbol } from "../utils/shaderCodeUtils.js";
13
+ import { DependencyGraph } from "./dependencyGraph.js";
14
+ import { DisableableBlock } from "../blocks/disableableBlock.js";
15
+
16
+ const showDebugData = false;
17
+
18
+ /**
19
+ * @internal
20
+ */
21
+ type RemappedSymbol = {
22
+ /**
23
+ * The type of the symbol.
24
+ */
25
+ type: "uniform" | "const" | "sampler" | "function";
26
+
27
+ /**
28
+ * The name of the symbol.
29
+ */
30
+ name: string;
31
+
32
+ /**
33
+ * The name of the symbol after it has been remapped.
34
+ */
35
+ remappedName: string;
36
+
37
+ /**
38
+ * The declaration of the symbol. For "function" it is the function code.
39
+ */
40
+ declaration: string;
41
+
42
+ /**
43
+ * The ShaderBlock(s) that owns the symbol.
44
+ */
45
+ owners: ShaderBlock[];
46
+
47
+ /**
48
+ * The InputBlock that owns the texture. Only used for type="sampler".
49
+ */
50
+ inputBlock: InputBlock<ConnectionPointType.Texture> | undefined;
51
+ };
52
+
53
+ /**
54
+ * @internal
55
+ */
56
+ export type StackItem = {
57
+ /**
58
+ * The connection points to which to connect the output of the optimized block, once the optimized block has been created.
59
+ */
60
+ inputsToConnectTo: ConnectionPoint[];
61
+
62
+ /**
63
+ * The connection point to process.
64
+ */
65
+ outputConnectionPoint: ConnectionPoint;
66
+ };
67
+
68
+ /**
69
+ * Options for the smart filter optimizer.
70
+ */
71
+ export interface ISmartFilterOptimizerOptions {
72
+ /**
73
+ * The maximum number of samplers allowed in the fragment shader. Default: 8
74
+ */
75
+ maxSamplersInFragmentShader?: number;
76
+
77
+ /**
78
+ * If true, the optimizer will remove the disabled blocks from the optimized smart filter. Default: false
79
+ * It allows more aggressive optimizations, but removed blocks will no longer be available in the optimized smart filter.
80
+ */
81
+ removeDisabledBlocks?: boolean;
82
+ }
83
+
84
+ /**
85
+ * Optimizes a smart filter by aggregating blocks whenever possible, to reduce the number of draw calls.
86
+ */
87
+ export class SmartFilterOptimizer {
88
+ private _sourceSmartFilter: SmartFilter;
89
+ private _options: ISmartFilterOptimizerOptions;
90
+ private _blockStack: StackItem[] = [];
91
+ private _blockToStackItem: Map<BaseBlock, StackItem> = new Map();
92
+ private _savedBlockStack: StackItem[] = [];
93
+ private _savedBlockToStackItem: Map<BaseBlock, StackItem> = new Map();
94
+
95
+ private _symbolOccurrences: { [name: string]: number } = {};
96
+ private _remappedSymbols: Array<RemappedSymbol> = [];
97
+ private _blockToMainFunctionName: Map<BaseBlock, string> = new Map();
98
+ private _mainFunctionNameToCode: Map<string, string> = new Map();
99
+ private _dependencyGraph: DependencyGraph<string> = new DependencyGraph<string>();
100
+ private _vertexShaderCode: string | undefined;
101
+ private _textureRatio: number | undefined;
102
+ private _forceUnoptimized: boolean = false;
103
+
104
+ /**
105
+ * Creates a new smart filter optimizer
106
+ * @param smartFilter - The smart filter to optimize
107
+ * @param options - Options for the optimizer
108
+ */
109
+ constructor(smartFilter: SmartFilter, options?: ISmartFilterOptimizerOptions) {
110
+ this._sourceSmartFilter = smartFilter;
111
+ this._options = {
112
+ maxSamplersInFragmentShader: 8,
113
+ ...options,
114
+ };
115
+ }
116
+
117
+ /**
118
+ * Optimizes the smart filter by aggregating blocks whenever possible, to lower the number of rendering passes
119
+ * @returns The optimized smart filter, or null if the optimization failed
120
+ */
121
+ public optimize(): Nullable<SmartFilter> {
122
+ this._blockStack = [];
123
+ this._blockToStackItem = new Map();
124
+
125
+ let newSmartFilter: Nullable<SmartFilter> = null;
126
+
127
+ this._sourceSmartFilter._workWithAggregateFreeGraph(() => {
128
+ if (
129
+ this._sourceSmartFilter.output.connectedTo &&
130
+ !isTextureInputBlock(this._sourceSmartFilter.output.connectedTo.ownerBlock)
131
+ ) {
132
+ const connectionsToReconnect: [ConnectionPoint, ConnectionPoint][] = [];
133
+
134
+ if (this._options.removeDisabledBlocks) {
135
+ const alreadyVisitedBlocks = new Set<BaseBlock>();
136
+ this._disconnectDisabledBlocks(
137
+ this._sourceSmartFilter.output.connectedTo.ownerBlock,
138
+ alreadyVisitedBlocks,
139
+ connectionsToReconnect
140
+ );
141
+ }
142
+
143
+ newSmartFilter = new SmartFilter(this._sourceSmartFilter.name + " - optimized");
144
+
145
+ // We must recheck isTextureInputBlock because all shader blocks may have been disconnected by the previous code
146
+ if (!isTextureInputBlock(this._sourceSmartFilter.output.connectedTo.ownerBlock)) {
147
+ // Make sure all the connections in the graph have a runtimeData associated to them
148
+ // Note that the value of the runtimeData may not be set yet, we just need the objects to be created and propagated correctly
149
+ this._sourceSmartFilter.output.ownerBlock.prepareForRuntime();
150
+ this._sourceSmartFilter.output.ownerBlock.propagateRuntimeData();
151
+
152
+ const item: StackItem = {
153
+ inputsToConnectTo: [newSmartFilter.output],
154
+ outputConnectionPoint: this._sourceSmartFilter.output.connectedTo,
155
+ };
156
+
157
+ this._blockStack.push(item);
158
+ this._blockToStackItem.set(item.outputConnectionPoint.ownerBlock, item);
159
+
160
+ while (this._blockStack.length > 0) {
161
+ const { inputsToConnectTo, outputConnectionPoint } = this._blockStack.pop()!;
162
+
163
+ const newBlock = this._processBlock(newSmartFilter, outputConnectionPoint);
164
+
165
+ if (newBlock) {
166
+ for (const inputToConnectTo of inputsToConnectTo) {
167
+ inputToConnectTo.connectTo(newBlock.output);
168
+ }
169
+ }
170
+ }
171
+ } else {
172
+ newSmartFilter.output.connectTo(this._sourceSmartFilter.output.connectedTo);
173
+ }
174
+
175
+ if (this._options.removeDisabledBlocks) {
176
+ // We must reconnect the connections that were reconnected differently by the disconnect process, so that the original graph is left unmodified
177
+ for (const [input, connectedTo] of connectionsToReconnect) {
178
+ input.connectTo(connectedTo);
179
+ }
180
+ }
181
+ }
182
+ });
183
+
184
+ return newSmartFilter;
185
+ }
186
+
187
+ private _disconnectDisabledBlocks(
188
+ block: BaseBlock,
189
+ alreadyVisitedBlocks: Set<BaseBlock>,
190
+ inputsToReconnect: [ConnectionPoint, ConnectionPoint][]
191
+ ) {
192
+ if (alreadyVisitedBlocks.has(block)) {
193
+ return;
194
+ }
195
+
196
+ alreadyVisitedBlocks.add(block);
197
+
198
+ for (const input of block.inputs) {
199
+ if (!input.connectedTo || input.type !== ConnectionPointType.Texture) {
200
+ continue;
201
+ }
202
+
203
+ this._disconnectDisabledBlocks(input.connectedTo.ownerBlock, alreadyVisitedBlocks, inputsToReconnect);
204
+ }
205
+
206
+ if (block instanceof DisableableBlock && block.disabled.runtimeData.value) {
207
+ block.disconnectFromGraph(inputsToReconnect);
208
+ }
209
+ }
210
+
211
+ private _initialize() {
212
+ this._symbolOccurrences = {};
213
+ this._remappedSymbols = [];
214
+ this._blockToMainFunctionName = new Map();
215
+ this._mainFunctionNameToCode = new Map();
216
+ this._dependencyGraph = new DependencyGraph();
217
+ this._vertexShaderCode = undefined;
218
+ this._textureRatio = undefined;
219
+ this._forceUnoptimized = false;
220
+ }
221
+
222
+ private _makeSymbolUnique(symbolName: string): string {
223
+ let newVarName = symbolName;
224
+ if (!this._symbolOccurrences[symbolName]) {
225
+ this._symbolOccurrences[symbolName] = 1;
226
+ } else {
227
+ this._symbolOccurrences[symbolName]++;
228
+ newVarName += "_" + this._symbolOccurrences[symbolName];
229
+ }
230
+
231
+ return newVarName;
232
+ }
233
+
234
+ private _processHelperFunctions(block: ShaderBlock, code: string): string {
235
+ const functions = block.getShaderProgram().fragment.functions;
236
+
237
+ if (functions.length === 1) {
238
+ // There's only the main function, so we don't need to do anything
239
+ return code;
240
+ }
241
+
242
+ const replaceFuncNames: Array<[RegExp, string]> = [];
243
+
244
+ for (const func of functions) {
245
+ let funcName = func.name;
246
+
247
+ if (funcName === block.getShaderProgram().fragment.mainFunctionName) {
248
+ continue;
249
+ }
250
+
251
+ funcName = undecorateSymbol(funcName);
252
+
253
+ const regexFindCurName = new RegExp(decorateSymbol(funcName), "g");
254
+
255
+ const existingRemapped = this._remappedSymbols.find(
256
+ (s) =>
257
+ s.type === "function" &&
258
+ s.name === funcName &&
259
+ s.owners[0] &&
260
+ s.owners[0].getClassName() === block.getClassName()
261
+ );
262
+
263
+ const newVarName = existingRemapped?.remappedName ?? decorateSymbol(this._makeSymbolUnique(funcName));
264
+
265
+ if (!existingRemapped) {
266
+ replaceFuncNames.push([regexFindCurName, newVarName]);
267
+
268
+ let funcCode = func.code;
269
+ for (const [regex, replacement] of replaceFuncNames) {
270
+ funcCode = funcCode.replace(regex, replacement);
271
+ }
272
+
273
+ this._remappedSymbols.push({
274
+ type: "function",
275
+ name: funcName,
276
+ remappedName: newVarName,
277
+ declaration: funcCode,
278
+ owners: [block],
279
+ inputBlock: undefined,
280
+ });
281
+ }
282
+
283
+ code = code.replace(regexFindCurName, newVarName);
284
+ }
285
+
286
+ return code;
287
+ }
288
+
289
+ private _processVariables(
290
+ block: ShaderBlock,
291
+ code: string,
292
+ varDecl: "const" | "uniform",
293
+ declarations?: string,
294
+ hasValue = false,
295
+ forceSingleInstance = false
296
+ ): [string, Array<string>] {
297
+ if (!declarations) {
298
+ return [code, []];
299
+ }
300
+
301
+ let rex = `${varDecl}\\s+(\\S+)\\s+${decorateChar}(\\w+)${decorateChar}\\s*`;
302
+ if (hasValue) {
303
+ rex += "=\\s*(.+);";
304
+ } else {
305
+ rex += ";";
306
+ }
307
+
308
+ const samplerList = [];
309
+ const rx = new RegExp(rex, "g");
310
+
311
+ let match = rx.exec(declarations);
312
+ while (match !== null) {
313
+ const singleInstance = forceSingleInstance || varDecl === "const";
314
+ const varType = match[1]!;
315
+ const varName = match[2]!;
316
+ const varValue = hasValue ? match[3]! : null;
317
+
318
+ let newVarName: Nullable<string> = null;
319
+
320
+ if (varType === "sampler2D") {
321
+ samplerList.push(decorateSymbol(varName));
322
+ } else {
323
+ const existingRemapped = this._remappedSymbols.find(
324
+ (s) =>
325
+ s.type === varDecl &&
326
+ s.name === varName &&
327
+ s.owners[0] &&
328
+ s.owners[0].getClassName() === block.getClassName()
329
+ );
330
+ if (existingRemapped && singleInstance) {
331
+ newVarName = existingRemapped.remappedName;
332
+ if (varDecl === "uniform") {
333
+ existingRemapped.owners.push(block);
334
+ }
335
+ } else {
336
+ newVarName = decorateSymbol(this._makeSymbolUnique(varName));
337
+
338
+ this._remappedSymbols.push({
339
+ type: varDecl,
340
+ name: varName,
341
+ remappedName: newVarName,
342
+ declaration: `${varDecl} ${varType} ${newVarName}${hasValue ? " = " + varValue : ""};`,
343
+ owners: [block],
344
+ inputBlock: undefined,
345
+ });
346
+ }
347
+ }
348
+
349
+ if (newVarName) {
350
+ code = code.replace(new RegExp(decorateSymbol(varName), "g"), newVarName);
351
+ }
352
+
353
+ match = rx.exec(declarations);
354
+ }
355
+
356
+ return [code, samplerList];
357
+ }
358
+
359
+ private _processSampleTexture(
360
+ block: ShaderBlock,
361
+ code: string,
362
+ sampler: string,
363
+ samplers: string[],
364
+ inputTextureBlock?: InputBlock<ConnectionPointType.Texture>
365
+ ): string {
366
+ const rx = new RegExp(`sampleTexture\\s*\\(\\s*${decorateChar}${sampler}${decorateChar}\\s*,\\s*(.*?)\\s*\\)`);
367
+
368
+ let newSamplerName = sampler;
369
+
370
+ const existingRemapped = this._remappedSymbols.find(
371
+ (s) => s.type === "sampler" && s.inputBlock && s.inputBlock === inputTextureBlock
372
+ );
373
+ if (existingRemapped) {
374
+ // The texture is shared by multiple blocks. We must reuse the same sampler name
375
+ newSamplerName = existingRemapped.remappedName;
376
+ } else {
377
+ newSamplerName = decorateSymbol(this._makeSymbolUnique(newSamplerName));
378
+
379
+ this._remappedSymbols.push({
380
+ type: "sampler",
381
+ name: sampler,
382
+ remappedName: newSamplerName,
383
+ declaration: `uniform sampler2D ${newSamplerName};`,
384
+ owners: [block],
385
+ inputBlock: inputTextureBlock,
386
+ });
387
+ }
388
+
389
+ if (samplers.indexOf(newSamplerName) === -1) {
390
+ samplers.push(newSamplerName);
391
+ }
392
+
393
+ let match = rx.exec(code);
394
+ while (match !== null) {
395
+ const uv = match[1]!;
396
+
397
+ code =
398
+ code.substring(0, match.index) +
399
+ `texture2D(${newSamplerName}, ${uv})` +
400
+ code.substring(match.index + match[0]!.length);
401
+
402
+ match = rx.exec(code);
403
+ }
404
+
405
+ return code;
406
+ }
407
+
408
+ private _canBeOptimized(block: BaseBlock): boolean {
409
+ if (block.disableOptimization) {
410
+ return false;
411
+ }
412
+
413
+ if (block instanceof ShaderBlock) {
414
+ if (block.getShaderProgram().vertex !== this._vertexShaderCode) {
415
+ return false;
416
+ }
417
+
418
+ if (block.textureRatio !== this._textureRatio) {
419
+ return false;
420
+ }
421
+ }
422
+
423
+ return true;
424
+ }
425
+
426
+ // Processes a block given one of its output connection point
427
+ // Returns the name of the main function in the shader code
428
+ private _optimizeBlock(
429
+ optimizedBlock: OptimizedShaderBlock,
430
+ outputConnectionPoint: ConnectionPoint,
431
+ samplers: string[]
432
+ ): string {
433
+ const block = outputConnectionPoint.ownerBlock;
434
+
435
+ if (block instanceof ShaderBlock) {
436
+ if (this._textureRatio === undefined) {
437
+ this._textureRatio = block.textureRatio;
438
+ }
439
+
440
+ const shaderProgram = block.getShaderProgram();
441
+
442
+ if (!shaderProgram) {
443
+ throw new Error(`Shader program not found for block "${block.name}"!`);
444
+ }
445
+
446
+ // We get the shader code of the main function only
447
+ let code = getShaderFragmentCode(shaderProgram, true);
448
+
449
+ this._vertexShaderCode = this._vertexShaderCode ?? shaderProgram.vertex;
450
+
451
+ // Generates a unique name for the fragment main function (if not already generated)
452
+ const shaderFuncName = shaderProgram.fragment.mainFunctionName;
453
+
454
+ let newShaderFuncName = this._blockToMainFunctionName.get(block);
455
+
456
+ if (!newShaderFuncName) {
457
+ newShaderFuncName = undecorateSymbol(shaderFuncName);
458
+ newShaderFuncName = decorateSymbol(this._makeSymbolUnique(newShaderFuncName));
459
+
460
+ this._blockToMainFunctionName.set(block, newShaderFuncName);
461
+ this._dependencyGraph.addElement(newShaderFuncName);
462
+ }
463
+
464
+ // Replaces the main function name by the new one
465
+ code = code.replace(shaderFuncName, newShaderFuncName);
466
+
467
+ // Removes the vUV declaration if it exists
468
+ code = code.replace(/varying\s+vec2\s+vUV\s*;/g, "");
469
+
470
+ // Replaces the texture2D calls by sampleTexture for easier processing
471
+ code = code.replace(/texture2D/g, "sampleTexture");
472
+
473
+ // Processes the functions other than the main function
474
+ code = this._processHelperFunctions(block, code);
475
+
476
+ // Processes the constants to make them unique
477
+ code = this._processVariables(block, code, "const", shaderProgram.fragment.const, true)[0];
478
+
479
+ // Processes the uniform inputs to make them unique. Also extract the list of samplers
480
+ let samplerList: string[] = [];
481
+ [code, samplerList] = this._processVariables(block, code, "uniform", shaderProgram.fragment.uniform, false);
482
+
483
+ let additionalSamplers = [];
484
+ [code, additionalSamplers] = this._processVariables(
485
+ block,
486
+ code,
487
+ "uniform",
488
+ shaderProgram.fragment.uniformSingle,
489
+ false,
490
+ true
491
+ );
492
+
493
+ samplerList.push(...additionalSamplers);
494
+
495
+ // Processes the texture inputs
496
+ for (const sampler of samplerList) {
497
+ const samplerName = undecorateSymbol(sampler);
498
+
499
+ const input = block.findInput(samplerName);
500
+ if (!input) {
501
+ // No connection point found corresponding to this texture: it must be a texture used internally by the filter (here we are assuming that the shader code is not bugged!)
502
+ code = this._processSampleTexture(block, code, samplerName, samplers);
503
+ continue;
504
+ }
505
+
506
+ // input found. Is it connected?
507
+ if (!input.connectedTo) {
508
+ throw `The connection point corresponding to the input named "${samplerName}" in block named "${block.name}" is not connected!`;
509
+ }
510
+
511
+ const parentBlock = input.connectedTo.ownerBlock;
512
+
513
+ if (isTextureInputBlock(parentBlock)) {
514
+ // input is connected to an InputBlock of type "Texture": we must directly sample a texture
515
+ code = this._processSampleTexture(block, code, samplerName, samplers, parentBlock);
516
+ } else if (this._forceUnoptimized || !this._canBeOptimized(parentBlock)) {
517
+ // the block connected to this input cannot be optimized: we must directly sample its output texture
518
+ code = this._processSampleTexture(block, code, samplerName, samplers);
519
+ let stackItem = this._blockToStackItem.get(parentBlock);
520
+ if (!stackItem) {
521
+ stackItem = {
522
+ inputsToConnectTo: [],
523
+ outputConnectionPoint: input.connectedTo,
524
+ };
525
+ this._blockStack.push(stackItem);
526
+ this._blockToStackItem.set(parentBlock, stackItem);
527
+ }
528
+ // creates a new input connection point for the texture in the optimized block
529
+ const connectionPoint = optimizedBlock._registerInput(samplerName, ConnectionPointType.Texture);
530
+ stackItem.inputsToConnectTo.push(connectionPoint);
531
+ } else {
532
+ let parentFuncName: string;
533
+
534
+ if (this._blockToMainFunctionName.has(parentBlock)) {
535
+ // The parent block has already been processed. We can directly use the main function name
536
+ parentFuncName = this._blockToMainFunctionName.get(parentBlock)!;
537
+ } else {
538
+ // Recursively processes the block connected to this input to get the main function name of the parent block
539
+ parentFuncName = this._optimizeBlock(optimizedBlock, input.connectedTo, samplers);
540
+ this._dependencyGraph.addDependency(newShaderFuncName, parentFuncName);
541
+ }
542
+
543
+ // The texture samplerName is not used anymore by the block, as it is replaced by a call to the main function of the parent block
544
+ // We remap it to an non existent sampler name, because the code that binds the texture still exists in the ShaderBinding.bind function.
545
+ // We don't want this code to have any effect, as it could overwrite (and remove) the texture binding of another block using this same sampler name!
546
+ this._remappedSymbols.push({
547
+ type: "sampler",
548
+ name: samplerName,
549
+ remappedName: "L(° O °L)",
550
+ declaration: ``,
551
+ owners: [block],
552
+ inputBlock: undefined,
553
+ });
554
+
555
+ // We have to replace the call(s) to sampleTexture by a call to the main function of the parent block
556
+ const rx = new RegExp(`sampleTexture\\s*\\(\\s*${sampler}\\s*,\\s*(.*?)\\s*\\)`);
557
+
558
+ let match = rx.exec(code);
559
+ while (match !== null) {
560
+ const uv = match[1];
561
+
562
+ code =
563
+ code.substring(0, match.index) +
564
+ `${parentFuncName}(${uv})` +
565
+ code.substring(match.index + match[0]!.length);
566
+ match = rx.exec(code);
567
+ }
568
+ }
569
+ }
570
+
571
+ this._mainFunctionNameToCode.set(newShaderFuncName, code);
572
+
573
+ return newShaderFuncName;
574
+ }
575
+
576
+ throw `Unhandled block type! className=${block.getClassName()}`;
577
+ }
578
+
579
+ private _saveBlockStackState(): void {
580
+ this._savedBlockStack = this._blockStack.slice();
581
+ this._savedBlockToStackItem = new Map();
582
+
583
+ for (const [key, value] of this._blockToStackItem) {
584
+ value.inputsToConnectTo = value.inputsToConnectTo.slice();
585
+ this._savedBlockToStackItem.set(key, value);
586
+ }
587
+ }
588
+
589
+ private _restoreBlockStackState(): void {
590
+ this._blockStack.length = 0;
591
+ this._blockStack.push(...this._savedBlockStack);
592
+
593
+ this._blockToStackItem.clear();
594
+ for (const [key, value] of this._savedBlockToStackItem) {
595
+ this._blockToStackItem.set(key, value);
596
+ }
597
+ }
598
+
599
+ private _processBlock(newSmartFilter: SmartFilter, outputConnectionPoint: ConnectionPoint): Nullable<ShaderBlock> {
600
+ this._saveBlockStackState();
601
+ this._initialize();
602
+
603
+ let optimizedBlock = new OptimizedShaderBlock(newSmartFilter, "optimized");
604
+
605
+ const samplers: string[] = [];
606
+ let mainFuncName = this._optimizeBlock(optimizedBlock, outputConnectionPoint, samplers);
607
+
608
+ if (samplers.length > this._options.maxSamplersInFragmentShader!) {
609
+ // Too many samplers for the optimized block.
610
+ // We must force the unoptimized mode and regenerate the block, which will be unoptimized this time
611
+ newSmartFilter.removeBlock(optimizedBlock);
612
+
613
+ this._initialize();
614
+
615
+ optimizedBlock = new OptimizedShaderBlock(newSmartFilter, "unoptimized");
616
+
617
+ this._forceUnoptimized = true;
618
+ samplers.length = 0;
619
+
620
+ this._restoreBlockStackState();
621
+
622
+ mainFuncName = this._optimizeBlock(optimizedBlock, outputConnectionPoint, samplers);
623
+ }
624
+
625
+ // Collects all the shader code
626
+ let code = "";
627
+ this._dependencyGraph.walk((element: string) => {
628
+ code += this._mainFunctionNameToCode.get(element)! + "\n";
629
+ });
630
+
631
+ // Sets the remapping of the shader variables
632
+ const blockOwnerToShaderBinding = new Map<ShaderBlock, Binding>();
633
+
634
+ let codeUniforms = "";
635
+ let codeConsts = "";
636
+ let codeFunctions = "";
637
+
638
+ for (const s of this._remappedSymbols) {
639
+ switch (s.type) {
640
+ case "const":
641
+ codeConsts += s.declaration + "\n";
642
+ break;
643
+ case "uniform":
644
+ case "sampler":
645
+ codeUniforms += s.declaration + "\n";
646
+ break;
647
+ case "function":
648
+ codeFunctions += s.declaration + "\n";
649
+ break;
650
+ }
651
+
652
+ for (const block of s.owners) {
653
+ let shaderBinding = blockOwnerToShaderBinding.get(block);
654
+ if (!shaderBinding) {
655
+ shaderBinding = block.getShaderBinding();
656
+ blockOwnerToShaderBinding.set(block, shaderBinding);
657
+ }
658
+
659
+ switch (s.type) {
660
+ case "uniform":
661
+ case "sampler":
662
+ shaderBinding.addShaderVariableRemapping(decorateSymbol(s.name), s.remappedName);
663
+ break;
664
+ }
665
+ }
666
+ }
667
+
668
+ // Builds and sets the final shader code
669
+ code = codeFunctions + code;
670
+ if (showDebugData) {
671
+ code = code.replace(/^ {16}/gm, "");
672
+ code = code!.replace(/\r/g, "");
673
+ code = code!.replace(/\n(\n)*/g, "\n");
674
+
675
+ console.log(`=================== BLOCK (forceUnoptimized=${this._forceUnoptimized}) ===================`);
676
+ console.log(codeUniforms);
677
+ console.log(codeConsts);
678
+ console.log(code);
679
+ console.log("remappedSymbols=", this._remappedSymbols);
680
+ console.log("samplers=", samplers);
681
+ }
682
+
683
+ optimizedBlock.setShaderProgram({
684
+ vertex: this._vertexShaderCode,
685
+ fragment: {
686
+ const: codeConsts,
687
+ uniform: codeUniforms,
688
+ mainFunctionName: mainFuncName,
689
+ functions: [
690
+ {
691
+ name: mainFuncName,
692
+ code,
693
+ },
694
+ ],
695
+ },
696
+ });
697
+
698
+ if (this._textureRatio !== undefined) {
699
+ optimizedBlock.textureRatio = this._textureRatio;
700
+ }
701
+
702
+ optimizedBlock.setShaderBindings(Array.from(blockOwnerToShaderBinding.values()));
703
+
704
+ return optimizedBlock;
705
+ }
706
+ }