-
Notifications
You must be signed in to change notification settings - Fork 204
/
model.ts
910 lines (792 loc) · 30.2 KB
/
model.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
// luma.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
// A lot of imports, but then Model is where it all comes together...
import type {TypedArray} from '@math.gl/types';
import type {RenderPipelineProps, RenderPipelineParameters} from '@luma.gl/core';
import type {BufferLayout, Shader, VertexArray, TransformFeedback} from '@luma.gl/core';
import type {AttributeInfo, Binding, UniformValue, PrimitiveTopology} from '@luma.gl/core';
import {Device, DeviceFeature, Buffer, Texture, TextureView, Sampler} from '@luma.gl/core';
import {RenderPipeline, RenderPass, UniformStore} from '@luma.gl/core';
import {log} from '@luma.gl/core';
import {getTypedArrayFromDataType, getAttributeInfosFromLayouts} from '@luma.gl/core';
import type {ShaderModule, PlatformInfo} from '@luma.gl/shadertools';
import {ShaderAssembler, getShaderLayoutFromWGSL} from '@luma.gl/shadertools';
import type {Geometry} from '../geometry/geometry';
import {GPUGeometry, makeGPUGeometry} from '../geometry/gpu-geometry';
import {PipelineFactory} from '../lib/pipeline-factory';
import {ShaderFactory} from '../lib/shader-factory';
import {getDebugTableForShaderLayout} from '../debug/debug-shader-layout';
import {debugFramebuffer} from '../debug/debug-framebuffer';
import {deepEqual} from '../utils/deep-equal';
import {uid} from '../utils/uid';
import {splitUniformsAndBindings} from './split-uniforms-and-bindings';
import {ShaderInputs} from '../shader-inputs';
// import type {AsyncTextureProps} from '../async-texture/async-texture';
import {AsyncTexture} from '../async-texture/async-texture';
const LOG_DRAW_PRIORITY = 2;
const LOG_DRAW_TIMEOUT = 10000;
export type ModelProps = Omit<RenderPipelineProps, 'vs' | 'fs' | 'bindings'> & {
source?: string;
vs: string | null;
fs: string | null;
/** shadertool shader modules (added to shader code) */
modules?: ShaderModule[];
/** Shadertool module defines (configures shader code)*/
defines?: Record<string, string | number | boolean>;
// TODO - injections, hooks etc?
/** Shader inputs, used to generated uniform buffers and bindings */
shaderInputs?: ShaderInputs;
/** Bindings */
bindings?: Record<string, Binding | AsyncTexture>;
/** Parameters that are built into the pipeline */
parameters?: RenderPipelineParameters;
/** Geometry */
geometry?: GPUGeometry | Geometry | null;
/** @deprecated Use instanced rendering? Will be auto-detected in 9.1 */
isInstanced?: boolean;
/** instance count */
instanceCount?: number;
/** Vertex count */
vertexCount?: number;
indexBuffer?: Buffer | null;
/** @note this is really a map of buffers, not a map of attributes */
attributes?: Record<string, Buffer>;
/** */
constantAttributes?: Record<string, TypedArray>;
/** Some applications intentionally supply unused attributes and bindings, and want to disable warnings */
disableWarnings?: boolean;
/** @internal For use with {@link TransformFeedback}, WebGL only. */
varyings?: string[];
transformFeedback?: TransformFeedback;
/** Mapped uniforms for shadertool modules */
moduleSettings?: Record<string, Record<string, any>>;
/** Show shader source in browser? */
debugShaders?: 'never' | 'errors' | 'warnings' | 'always';
/** Factory used to create a {@link RenderPipeline}. Defaults to {@link Device} default factory. */
pipelineFactory?: PipelineFactory;
/** Factory used to create a {@link Shader}. Defaults to {@link Device} default factory. */
shaderFactory?: ShaderFactory;
/** Shader assembler. Defaults to the ShaderAssembler.getShaderAssembler() */
shaderAssembler?: ShaderAssembler;
};
/**
* v9 Model API
* A model
* - automatically reuses pipelines (programs) when possible
* - automatically rebuilds pipelines if necessary to accommodate changed settings
* shadertools integration
* - accepts modules and performs shader transpilation
*/
export class Model {
static defaultProps: Required<ModelProps> = {
...RenderPipeline.defaultProps,
source: undefined!,
vs: null,
fs: null,
id: 'unnamed',
handle: undefined,
userData: {},
defines: {},
modules: [],
moduleSettings: undefined!,
geometry: null,
indexBuffer: null,
attributes: {},
constantAttributes: {},
varyings: [],
isInstanced: undefined!,
instanceCount: 0,
vertexCount: 0,
shaderInputs: undefined!,
pipelineFactory: undefined!,
shaderFactory: undefined!,
transformFeedback: undefined!,
shaderAssembler: ShaderAssembler.getDefaultShaderAssembler(),
debugShaders: undefined!,
disableWarnings: undefined!
};
readonly device: Device;
readonly id: string;
// @ts-expect-error assigned in function called from constructor
readonly source: string;
// @ts-expect-error assigned in function called from constructor
readonly vs: string;
// @ts-expect-error assigned in function called from constructor
readonly fs: string;
readonly pipelineFactory: PipelineFactory;
readonly shaderFactory: ShaderFactory;
userData: {[key: string]: any} = {};
// Fixed properties (change can trigger pipeline rebuild)
/** The render pipeline GPU parameters, depth testing etc */
parameters: RenderPipelineParameters;
/** The primitive topology */
topology: PrimitiveTopology;
/** Buffer layout */
bufferLayout: BufferLayout[];
// Dynamic properties
/** Use instanced rendering */
isInstanced: boolean | undefined = undefined;
/** instance count. `undefined` means not instanced */
instanceCount: number = 0;
/** Vertex count */
vertexCount: number;
/** Index buffer */
indexBuffer: Buffer | null = null;
/** Buffer-valued attributes */
bufferAttributes: Record<string, Buffer> = {};
/** Constant-valued attributes */
constantAttributes: Record<string, TypedArray> = {};
/** Bindings (textures, samplers, uniform buffers) */
bindings: Record<string, Binding | AsyncTexture> = {};
/** Sets uniforms @deprecated Use uniform buffers and setBindings() for portability*/
uniforms: Record<string, UniformValue> = {};
/**
* VertexArray
* @note not implemented: if bufferLayout is updated, vertex array has to be rebuilt!
* @todo - allow application to define multiple vertex arrays?
* */
vertexArray: VertexArray;
/** TransformFeedback, WebGL 2 only. */
transformFeedback: TransformFeedback | null = null;
/** The underlying GPU "program". @note May be recreated if parameters change */
pipeline: RenderPipeline;
/** ShaderInputs instance */
// @ts-expect-error Assigned in function called by constructor
shaderInputs: ShaderInputs;
// @ts-expect-error Assigned in function called by constructor
_uniformStore: UniformStore;
_attributeInfos: Record<string, AttributeInfo> = {};
_gpuGeometry: GPUGeometry | null = null;
private _getModuleUniforms: (props?: Record<string, Record<string, any>>) => Record<string, any>;
private props: Required<ModelProps>;
_pipelineNeedsUpdate: string | false = 'newly created';
private _needsRedraw: string | false = 'initializing';
private _destroyed = false;
/** "Time" of last draw. Monotonically increasing timestamp */
_lastDrawTimestamp: number = -1;
constructor(device: Device, props: ModelProps) {
this.props = {...Model.defaultProps, ...props};
props = this.props;
this.id = props.id || uid('model');
this.device = device;
Object.assign(this.userData, props.userData);
// Setup shader module inputs
const moduleMap = Object.fromEntries(
this.props.modules?.map(module => [module.name, module]) || []
);
// @ts-expect-error Fix typings
this.setShaderInputs(props.shaderInputs || new ShaderInputs(moduleMap));
// Setup shader assembler
const platformInfo = getPlatformInfo(device);
// Extract modules from shader inputs if not supplied
const modules =
// @ts-expect-error shaderInputs is assigned in setShaderInputs above.
(this.props.modules?.length > 0 ? this.props.modules : this.shaderInputs?.getModules()) || [];
const isWebGPU = this.device.type === 'webgpu';
// WebGPU
// TODO - hack to support unified WGSL shader
// TODO - this is wrong, compile a single shader
if (isWebGPU && this.props.source) {
// WGSL
this.props.shaderLayout ||= getShaderLayoutFromWGSL(this.props.source);
const {source, getUniforms} = this.props.shaderAssembler.assembleWGSLShader({
platformInfo,
...this.props,
modules
});
this.source = source;
// @ts-expect-error
this._getModuleUniforms = getUniforms;
} else {
// GLSL
const {vs, fs, getUniforms} = this.props.shaderAssembler.assembleGLSLShaderPair({
platformInfo,
...this.props,
modules
});
this.vs = vs;
this.fs = fs;
// @ts-expect-error
this._getModuleUniforms = getUniforms;
}
this.vertexCount = this.props.vertexCount;
this.instanceCount = this.props.instanceCount;
this.topology = this.props.topology;
this.bufferLayout = this.props.bufferLayout;
this.parameters = this.props.parameters;
// Geometry, if provided, sets topology and vertex cound
if (props.geometry) {
this.setGeometry(props.geometry);
}
this.pipelineFactory =
props.pipelineFactory || PipelineFactory.getDefaultPipelineFactory(this.device);
this.shaderFactory = props.shaderFactory || ShaderFactory.getDefaultShaderFactory(this.device);
// Create the pipeline
// @note order is important
this.pipeline = this._updatePipeline();
this.vertexArray = device.createVertexArray({
renderPipeline: this.pipeline
});
// Now we can apply geometry attributes
if (this._gpuGeometry) {
this._setGeometryAttributes(this._gpuGeometry);
}
// Apply any dynamic settings that will not trigger pipeline change
if ('isInstanced' in props) {
this.isInstanced = props.isInstanced;
}
if (props.instanceCount) {
this.setInstanceCount(props.instanceCount);
}
if (props.vertexCount) {
this.setVertexCount(props.vertexCount);
}
if (props.indexBuffer) {
this.setIndexBuffer(props.indexBuffer);
}
if (props.attributes) {
this.setAttributes(props.attributes);
}
if (props.constantAttributes) {
this.setConstantAttributes(props.constantAttributes);
}
if (props.bindings) {
this.setBindings(props.bindings);
}
if (props.uniforms) {
this.setUniforms(props.uniforms);
}
if (props.moduleSettings) {
// log.warn('Model.props.moduleSettings is deprecated. Use Model.shaderInputs.setProps()')();
this.updateModuleSettings(props.moduleSettings);
}
if (props.transformFeedback) {
this.transformFeedback = props.transformFeedback;
}
// Catch any access to non-standard props
Object.seal(this);
}
destroy(): void {
if (this._destroyed) return;
this.pipelineFactory.release(this.pipeline);
this.shaderFactory.release(this.pipeline.vs);
if (this.pipeline.fs) {
this.shaderFactory.release(this.pipeline.fs);
}
this._uniformStore.destroy();
// TODO - mark resource as managed and destroyIfManaged() ?
this._gpuGeometry?.destroy();
this._destroyed = true;
}
// Draw call
/** Query redraw status. Clears the status. */
needsRedraw(): false | string {
// Catch any writes to already bound resources
if (this._getBindingsUpdateTimestamp() > this._lastDrawTimestamp) {
this.setNeedsRedraw('contents of bound textures or buffers updated');
}
const needsRedraw = this._needsRedraw;
this._needsRedraw = false;
return needsRedraw;
}
/** Mark the model as needing a redraw */
setNeedsRedraw(reason: string): void {
this._needsRedraw ||= reason;
}
predraw() {
// Update uniform buffers if needed
this.updateShaderInputs();
// Check if the pipeline is invalidated
this.pipeline = this._updatePipeline();
}
draw(renderPass: RenderPass): boolean {
this.predraw();
let drawSuccess: boolean;
try {
this._logDrawCallStart();
// Update the pipeline if invalidated
// TODO - inside RenderPass is likely the worst place to do this from performance perspective.
// Application can call Model.predraw() to avoid this.
this.pipeline = this._updatePipeline();
// Set pipeline state, we may be sharing a pipeline so we need to set all state on every draw
// Any caching needs to be done inside the pipeline functions
// TODO this is a busy initialized check for all bindings every frame
const syncBindings = this._getBindings();
this.pipeline.setBindings(syncBindings, {
disableWarnings: this.props.disableWarnings
});
if (!isObjectEmpty(this.uniforms)) {
this.pipeline.setUniformsWebGL(this.uniforms);
}
const {indexBuffer} = this.vertexArray;
const indexCount = indexBuffer
? indexBuffer.byteLength / (indexBuffer.indexType === 'uint32' ? 4 : 2)
: undefined;
drawSuccess = this.pipeline.draw({
renderPass,
vertexArray: this.vertexArray,
isInstanced: this.isInstanced,
vertexCount: this.vertexCount,
instanceCount: this.instanceCount,
indexCount,
transformFeedback: this.transformFeedback || undefined,
// WebGL shares underlying cached pipelines even for models that have different parameters and topology,
// so we must provide our unique parameters to each draw
// (In WebGPU most parameters are encoded in the pipeline and cannot be changed per draw call)
parameters: this.parameters,
topology: this.topology
});
} finally {
this._logDrawCallEnd();
}
this._logFramebuffer(renderPass);
// Update needsRedraw flag
if (drawSuccess) {
this._lastDrawTimestamp = this.device.timestamp;
this._needsRedraw = false;
} else {
this._needsRedraw = 'waiting for resource initialization';
}
return drawSuccess;
}
// Update fixed fields (can trigger pipeline rebuild)
/**
* Updates the optional geometry
* Geometry, set topology and bufferLayout
* @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU
*/
setGeometry(geometry: GPUGeometry | Geometry | null): void {
this._gpuGeometry?.destroy();
const gpuGeometry = geometry && makeGPUGeometry(this.device, geometry);
if (gpuGeometry) {
this.setTopology(gpuGeometry.topology || 'triangle-list');
this.bufferLayout = mergeBufferLayouts(gpuGeometry.bufferLayout, this.bufferLayout);
if (this.vertexArray) {
this._setGeometryAttributes(gpuGeometry);
}
}
this._gpuGeometry = gpuGeometry;
}
/**
* Updates the primitive topology ('triangle-list', 'triangle-strip' etc).
* @note Triggers a pipeline rebuild / pipeline cache fetch on WebGPU
*/
setTopology(topology: PrimitiveTopology): void {
if (topology !== this.topology) {
this.topology = topology;
this._setPipelineNeedsUpdate('topology');
}
}
/**
* Updates the buffer layout.
* @note Triggers a pipeline rebuild / pipeline cache fetch
*/
setBufferLayout(bufferLayout: BufferLayout[]): void {
this.bufferLayout = this._gpuGeometry
? mergeBufferLayouts(bufferLayout, this._gpuGeometry.bufferLayout)
: bufferLayout;
this._setPipelineNeedsUpdate('bufferLayout');
// Recreate the pipeline
this.pipeline = this._updatePipeline();
// vertex array needs to be updated if we update buffer layout,
// but not if we update parameters
this.vertexArray = this.device.createVertexArray({
renderPipeline: this.pipeline
});
// Reapply geometry attributes to the new vertex array
if (this._gpuGeometry) {
this._setGeometryAttributes(this._gpuGeometry);
}
}
/**
* Set GPU parameters.
* @note Can trigger a pipeline rebuild / pipeline cache fetch.
* @param parameters
*/
setParameters(parameters: RenderPipelineParameters) {
if (!deepEqual(parameters, this.parameters, 2)) {
this.parameters = parameters;
this._setPipelineNeedsUpdate('parameters');
}
}
// Update dynamic fields
/**
* Updates the instance count (used in draw calls)
* @note Any attributes with stepMode=instance need to be at least this big
*/
setInstanceCount(instanceCount: number): void {
this.instanceCount = instanceCount;
// luma.gl examples don't set props.isInstanced and rely on auto-detection
// but deck.gl sets instanceCount even for models that are not instanced.
if (this.isInstanced === undefined && instanceCount > 0) {
this.isInstanced = true;
}
this.setNeedsRedraw('instanceCount');
}
/**
* Updates the vertex count (used in draw calls)
* @note Any attributes with stepMode=vertex need to be at least this big
*/
setVertexCount(vertexCount: number): void {
this.vertexCount = vertexCount;
this.setNeedsRedraw('vertexCount');
}
/** Set the shader inputs */
setShaderInputs(shaderInputs: ShaderInputs): void {
this.shaderInputs = shaderInputs;
this._uniformStore = new UniformStore(this.shaderInputs.modules);
// Create uniform buffer bindings for all modules
for (const moduleName of Object.keys(this.shaderInputs.modules)) {
const uniformBuffer = this._uniformStore.getManagedUniformBuffer(this.device, moduleName);
this.bindings[`${moduleName}Uniforms`] = uniformBuffer;
}
this.setNeedsRedraw('shaderInputs');
}
/** Update uniform buffers from the model's shader inputs */
updateShaderInputs(): void {
this._uniformStore.setUniforms(this.shaderInputs.getUniformValues());
// TODO - this is already tracked through buffer/texture update times?
this.setNeedsRedraw('shaderInputs');
}
/**
* Sets bindings (textures, samplers, uniform buffers)
*/
setBindings(bindings: Record<string, Binding | AsyncTexture>): void {
Object.assign(this.bindings, bindings);
this.setNeedsRedraw('bindings');
}
/**
* Updates optional transform feedback. WebGL only.
*/
setTransformFeedback(transformFeedback: TransformFeedback | null): void {
this.transformFeedback = transformFeedback;
this.setNeedsRedraw('transformFeedback');
}
/**
* Sets the index buffer
* @todo - how to unset it if we change geometry?
*/
setIndexBuffer(indexBuffer: Buffer | null): void {
this.vertexArray.setIndexBuffer(indexBuffer);
this.setNeedsRedraw('indexBuffer');
}
/**
* Sets attributes (buffers)
* @note Overrides any attributes previously set with the same name
*/
setAttributes(buffers: Record<string, Buffer>, options?: {disableWarnings?: boolean}): void {
if (buffers.indices) {
log.warn(
`Model:${this.id} setAttributes() - indexBuffer should be set using setIndexBuffer()`
)();
}
for (const [bufferName, buffer] of Object.entries(buffers)) {
const bufferLayout = this.bufferLayout.find(layout =>
getAttributeNames(layout).includes(bufferName)
);
if (!bufferLayout) {
log.warn(`Model(${this.id}): Missing layout for buffer "${bufferName}".`)();
continue; // eslint-disable-line no-continue
}
// For an interleaved attribute we may need to set multiple attributes
const attributeNames = getAttributeNames(bufferLayout);
let set = false;
for (const attributeName of attributeNames) {
const attributeInfo = this._attributeInfos[attributeName];
if (attributeInfo) {
this.vertexArray.setBuffer(attributeInfo.location, buffer);
set = true;
}
}
if (!set && !(options?.disableWarnings ?? this.props.disableWarnings)) {
log.warn(
`Model(${this.id}): Ignoring buffer "${buffer.id}" for unknown attribute "${bufferName}"`
)();
}
}
this.setNeedsRedraw('attributes');
}
/**
* Sets constant attributes
* @note Overrides any attributes previously set with the same name
* Constant attributes are only supported in WebGL, not in WebGPU
* Any attribute that is disabled in the current vertex array object
* is read from the context's global constant value for that attribute location.
* @param constantAttributes
*/
setConstantAttributes(
attributes: Record<string, TypedArray>,
options?: {disableWarnings?: boolean}
): void {
for (const [attributeName, value] of Object.entries(attributes)) {
const attributeInfo = this._attributeInfos[attributeName];
if (attributeInfo) {
this.vertexArray.setConstantWebGL(attributeInfo.location, value);
} else if (!(options?.disableWarnings ?? this.props.disableWarnings)) {
log.warn(
`Model "${this.id}: Ignoring constant supplied for unknown attribute "${attributeName}"`
)();
}
}
this.setNeedsRedraw('constants');
}
// DEPRECATED METHODS
/**
* Sets individual uniforms
* @deprecated WebGL only, use uniform buffers for portability
* @param uniforms
*/
setUniforms(uniforms: Record<string, UniformValue>): void {
if (!isObjectEmpty(uniforms)) {
this.pipeline.setUniformsWebGL(uniforms);
Object.assign(this.uniforms, uniforms);
}
this.setNeedsRedraw('uniforms');
}
/**
* @deprecated Updates shader module settings (which results in uniforms being set)
*/
updateModuleSettings(props: Record<string, any>): void {
// log.warn('Model.updateModuleSettings is deprecated. Use Model.shaderInputs.setProps()')();
const {bindings, uniforms} = splitUniformsAndBindings(this._getModuleUniforms(props));
Object.assign(this.bindings, bindings);
Object.assign(this.uniforms, uniforms);
this.setNeedsRedraw('moduleSettings');
}
// Internal methods
/** Get texture / texture view from any async textures */
_getBindings(): Record<string, Binding> {
// Extract actual textures from async textures. If not loaded, null
return Object.entries(this.bindings).reduce<Record<string, Binding>>((acc, [name, binding]) => {
if (binding instanceof AsyncTexture) {
if (binding.isReady) {
acc[name] = binding.texture;
}
} else {
acc[name] = binding;
}
return acc;
}, {});
}
/** Get the timestamp of the latest updated bound GPU memory resource (buffer/texture). */
_getBindingsUpdateTimestamp(): number {
let timestamp = 0;
for (const binding of Object.values(this.bindings)) {
if (binding instanceof TextureView) {
timestamp = Math.max(timestamp, binding.texture.updateTimestamp);
} else if (binding instanceof Buffer || binding instanceof Texture) {
timestamp = Math.max(timestamp, binding.updateTimestamp);
} else if (binding instanceof AsyncTexture) {
timestamp = binding.texture
? Math.max(timestamp, binding.texture.updateTimestamp)
: // The texture will become available in the future
Infinity;
} else if (!(binding instanceof Sampler)) {
timestamp = Math.max(timestamp, binding.buffer.updateTimestamp);
}
}
return timestamp;
}
/**
* Updates the optional geometry attributes
* Geometry, sets several attributes, indexBuffer, and also vertex count
* @note Can trigger a pipeline rebuild / pipeline cache fetch on WebGPU
*/
_setGeometryAttributes(gpuGeometry: GPUGeometry): void {
// Filter geometry attribute so that we don't issue warnings for unused attributes
const attributes = {...gpuGeometry.attributes};
for (const [attributeName] of Object.entries(attributes)) {
if (
!this.pipeline.shaderLayout.attributes.find(layout => layout.name === attributeName) &&
attributeName !== 'positions'
) {
delete attributes[attributeName];
}
}
// TODO - delete previous geometry?
this.vertexCount = gpuGeometry.vertexCount;
this.setIndexBuffer(gpuGeometry.indices || null);
this.setAttributes(gpuGeometry.attributes, {disableWarnings: true});
this.setAttributes(attributes, {disableWarnings: this.props.disableWarnings});
this.setNeedsRedraw('geometry attributes');
}
/** Mark pipeline as needing update */
_setPipelineNeedsUpdate(reason: string): void {
this._pipelineNeedsUpdate ||= reason;
this.setNeedsRedraw(reason);
}
/** Update pipeline if needed */
_updatePipeline(): RenderPipeline {
if (this._pipelineNeedsUpdate) {
let prevShaderVs: Shader | null = null;
let prevShaderFs: Shader | null = null;
if (this.pipeline) {
log.log(
1,
`Model ${this.id}: Recreating pipeline because "${this._pipelineNeedsUpdate}".`
)();
prevShaderVs = this.pipeline.vs;
prevShaderFs = this.pipeline.fs;
}
this._pipelineNeedsUpdate = false;
const vs = this.shaderFactory.createShader({
id: `${this.id}-vertex`,
stage: 'vertex',
source: this.source || this.vs,
debug: this.props.debugShaders
});
let fs: Shader | null = null;
if (this.source) {
fs = vs;
} else if (this.fs) {
fs = this.shaderFactory.createShader({
id: `${this.id}-fragment`,
stage: 'fragment',
source: this.source || this.fs,
debug: this.props.debugShaders
});
}
this.pipeline = this.pipelineFactory.createRenderPipeline({
...this.props,
bufferLayout: this.bufferLayout,
topology: this.topology,
parameters: this.parameters,
// TODO - why set bindings here when we reset them every frame?
// Should we expose a BindGroup abstraction?
bindings: this._getBindings(),
vs,
fs
});
this._attributeInfos = getAttributeInfosFromLayouts(
this.pipeline.shaderLayout,
this.bufferLayout
);
if (prevShaderVs) this.shaderFactory.release(prevShaderVs);
if (prevShaderFs) this.shaderFactory.release(prevShaderFs);
}
return this.pipeline;
}
/** Throttle draw call logging */
_lastLogTime = 0;
_logOpen = false;
_logDrawCallStart(): void {
// IF level is 4 or higher, log every frame.
const logDrawTimeout = log.level > 3 ? 0 : LOG_DRAW_TIMEOUT;
if (log.level < 2 || Date.now() - this._lastLogTime < logDrawTimeout) {
return;
}
this._lastLogTime = Date.now();
this._logOpen = true;
log.group(LOG_DRAW_PRIORITY, `>>> DRAWING MODEL ${this.id}`, {collapsed: log.level <= 2})();
}
_logDrawCallEnd(): void {
if (this._logOpen) {
const shaderLayoutTable = getDebugTableForShaderLayout(this.pipeline.shaderLayout, this.id);
// log.table(logLevel, attributeTable)();
// log.table(logLevel, uniformTable)();
log.table(LOG_DRAW_PRIORITY, shaderLayoutTable)();
const uniformTable = this.shaderInputs.getDebugTable();
// Add any global uniforms
for (const [name, value] of Object.entries(this.uniforms)) {
uniformTable[name] = {value};
}
log.table(LOG_DRAW_PRIORITY, uniformTable)();
const attributeTable = this._getAttributeDebugTable();
log.table(LOG_DRAW_PRIORITY, this._attributeInfos)();
log.table(LOG_DRAW_PRIORITY, attributeTable)();
log.groupEnd(LOG_DRAW_PRIORITY)();
this._logOpen = false;
}
}
protected _drawCount = 0;
_logFramebuffer(renderPass: RenderPass): void {
const debugFramebuffers = log.get('framebuffer');
this._drawCount++;
// Update first 3 frames and then every 60 frames
if (!debugFramebuffers || (this._drawCount++ > 3 && this._drawCount % 60)) {
return;
}
// TODO - display framebuffer output in debug window
const framebuffer = renderPass.props.framebuffer;
if (framebuffer) {
debugFramebuffer(framebuffer, {id: framebuffer.id, minimap: true});
// log.image({logLevel: LOG_DRAW_PRIORITY, message: `${framebuffer.id} %c sup?`, image})();
}
}
_getAttributeDebugTable(): Record<string, Record<string, unknown>> {
const table: Record<string, Record<string, unknown>> = {};
for (const [name, attributeInfo] of Object.entries(this._attributeInfos)) {
const values = this.vertexArray.attributes[attributeInfo.location];
table[attributeInfo.location] = {
name,
type: attributeInfo.shaderType,
values: values
? this._getBufferOrConstantValues(values, attributeInfo.bufferDataType)
: 'null'
};
}
if (this.vertexArray.indexBuffer) {
const {indexBuffer} = this.vertexArray;
const values =
indexBuffer.indexType === 'uint32'
? new Uint32Array(indexBuffer.debugData)
: new Uint16Array(indexBuffer.debugData);
table.indices = {
name: 'indices',
type: indexBuffer.indexType,
values: values.toString()
};
}
return table;
}
// TODO - fix typing of luma data types
_getBufferOrConstantValues(attribute: Buffer | TypedArray, dataType: any): string {
const TypedArrayConstructor = getTypedArrayFromDataType(dataType);
const typedArray =
attribute instanceof Buffer ? new TypedArrayConstructor(attribute.debugData) : attribute;
return typedArray.toString();
}
}
// HELPERS
/** TODO - move to core, document add tests */
function mergeBufferLayouts(layouts1: BufferLayout[], layouts2: BufferLayout[]): BufferLayout[] {
const layouts = [...layouts1];
for (const attribute of layouts2) {
const index = layouts.findIndex(attribute2 => attribute2.name === attribute.name);
if (index < 0) {
layouts.push(attribute);
} else {
layouts[index] = attribute;
}
}
return layouts;
}
/** Create a shadertools platform info from the Device */
export function getPlatformInfo(device: Device): PlatformInfo {
return {
type: device.type,
shaderLanguage: device.info.shadingLanguage,
shaderLanguageVersion: device.info.shadingLanguageVersion as 100 | 300,
gpu: device.info.gpu,
// HACK - we pretend that the DeviceFeatures is a Set, it has a similar API
features: device.features as unknown as Set<DeviceFeature>
};
}
/** Get attribute names from a BufferLayout */
function getAttributeNames(bufferLayout: BufferLayout): string[] {
return bufferLayout.attributes
? bufferLayout.attributes?.map(layout => layout.attribute)
: [bufferLayout.name];
}
/** Returns true if given object is empty, false otherwise. */
function isObjectEmpty(obj: object): boolean {
let isEmpty = true;
// @ts-ignore key is unused
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for (const key in obj) {
isEmpty = false;
break;
}
return isEmpty;
}