@luma.gl/core 9.3.0-alpha.8 → 9.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/adapter/device.d.ts +1 -1
  2. package/dist/adapter/device.d.ts.map +1 -1
  3. package/dist/adapter/device.js +3 -2
  4. package/dist/adapter/device.js.map +1 -1
  5. package/dist/adapter/luma.d.ts.map +1 -1
  6. package/dist/adapter/luma.js +2 -1
  7. package/dist/adapter/luma.js.map +1 -1
  8. package/dist/dist.dev.js +328 -173
  9. package/dist/dist.min.js +5 -5
  10. package/dist/factories/bind-group-factory.d.ts.map +1 -1
  11. package/dist/factories/bind-group-factory.js +14 -5
  12. package/dist/factories/bind-group-factory.js.map +1 -1
  13. package/dist/index.cjs +317 -173
  14. package/dist/index.cjs.map +4 -4
  15. package/dist/index.d.ts +2 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +2 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/portable/shader-block-writer.d.ts +51 -0
  20. package/dist/portable/shader-block-writer.d.ts.map +1 -0
  21. package/dist/portable/shader-block-writer.js +185 -0
  22. package/dist/portable/shader-block-writer.js.map +1 -0
  23. package/dist/portable/uniform-store.d.ts +52 -20
  24. package/dist/portable/uniform-store.d.ts.map +1 -1
  25. package/dist/portable/uniform-store.js +71 -26
  26. package/dist/portable/uniform-store.js.map +1 -1
  27. package/dist/shadertypes/data-types/data-type-decoder.js +2 -2
  28. package/dist/shadertypes/data-types/data-type-decoder.js.map +1 -1
  29. package/dist/shadertypes/data-types/decode-data-types.js +2 -2
  30. package/dist/shadertypes/data-types/decode-data-types.js.map +1 -1
  31. package/dist/shadertypes/shader-types/shader-block-layout.d.ts +72 -0
  32. package/dist/shadertypes/shader-types/shader-block-layout.d.ts.map +1 -0
  33. package/dist/shadertypes/shader-types/shader-block-layout.js +209 -0
  34. package/dist/shadertypes/shader-types/shader-block-layout.js.map +1 -0
  35. package/dist/shadertypes/texture-types/texture-format-decoder.js +1 -1
  36. package/dist/shadertypes/texture-types/texture-format-decoder.js.map +1 -1
  37. package/dist/shadertypes/texture-types/texture-format-table.js +2 -2
  38. package/dist/shadertypes/texture-types/texture-format-table.js.map +1 -1
  39. package/dist/shadertypes/vertex-types/vertex-format-decoder.d.ts.map +1 -1
  40. package/dist/shadertypes/vertex-types/vertex-format-decoder.js +41 -3
  41. package/dist/shadertypes/vertex-types/vertex-format-decoder.js.map +1 -1
  42. package/dist/shadertypes/vertex-types/vertex-formats.d.ts +6 -6
  43. package/dist/shadertypes/vertex-types/vertex-formats.d.ts.map +1 -1
  44. package/package.json +2 -2
  45. package/src/adapter/device.ts +4 -2
  46. package/src/adapter/luma.ts +1 -0
  47. package/src/factories/bind-group-factory.ts +23 -5
  48. package/src/index.ts +7 -1
  49. package/src/portable/shader-block-writer.ts +254 -0
  50. package/src/portable/uniform-store.ts +92 -37
  51. package/src/shadertypes/data-types/data-type-decoder.ts +2 -2
  52. package/src/shadertypes/data-types/decode-data-types.ts +2 -2
  53. package/src/shadertypes/shader-types/shader-block-layout.ts +340 -0
  54. package/src/shadertypes/shader-types/shader-types.ts +5 -5
  55. package/src/shadertypes/texture-types/texture-format-decoder.ts +1 -1
  56. package/src/shadertypes/texture-types/texture-format-table.ts +2 -2
  57. package/src/shadertypes/vertex-types/vertex-format-decoder.ts +47 -3
  58. package/src/shadertypes/vertex-types/vertex-formats.ts +18 -5
  59. package/dist/portable/uniform-buffer-layout.d.ts +0 -42
  60. package/dist/portable/uniform-buffer-layout.d.ts.map +0 -1
  61. package/dist/portable/uniform-buffer-layout.js +0 -274
  62. package/dist/portable/uniform-buffer-layout.js.map +0 -1
  63. package/src/portable/uniform-buffer-layout.ts +0 -384
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "../src/utils/stats-manager.ts", "../src/utils/log.ts", "../src/utils/uid.ts", "../src/adapter/resources/resource.ts", "../src/adapter/resources/buffer.ts", "../src/shadertypes/data-types/data-type-decoder.ts", "../src/shadertypes/vertex-types/vertex-format-decoder.ts", "../src/shadertypes/texture-types/texture-format-table.ts", "../src/shadertypes/texture-types/texture-format-decoder.ts", "../src/shadertypes/image-types/image-types.ts", "../src/adapter/device.ts", "../src/adapter/luma.ts", "../src/adapter/adapter.ts", "../src/adapter/canvas-surface.ts", "../src/adapter/canvas-observer.ts", "../src/utils/promise-utils.ts", "../src/utils/assert.ts", "../src/adapter/canvas-context.ts", "../src/adapter/presentation-context.ts", "../src/adapter/resources/sampler.ts", "../src/adapter/resources/texture.ts", "../src/adapter/resources/texture-view.ts", "../src/adapter/resources/external-texture.ts", "../src/adapter-utils/format-compiler-log.ts", "../src/adapter/resources/shader.ts", "../src/adapter/resources/framebuffer.ts", "../src/adapter/resources/render-pipeline.ts", "../src/adapter/resources/shared-render-pipeline.ts", "../src/adapter/resources/compute-pipeline.ts", "../src/factories/pipeline-factory.ts", "../src/factories/shader-factory.ts", "../src/adapter-utils/bind-groups.ts", "../src/factories/bind-group-factory.ts", "../src/adapter/resources/render-pass.ts", "../src/adapter/resources/compute-pass.ts", "../src/adapter/resources/command-encoder.ts", "../src/adapter/resources/command-buffer.ts", "../src/shadertypes/shader-types/shader-type-decoder.ts", "../src/adapter-utils/get-attribute-from-layouts.ts", "../src/adapter/resources/vertex-array.ts", "../src/adapter/resources/transform-feedback.ts", "../src/adapter/resources/query-set.ts", "../src/adapter/resources/fence.ts", "../src/adapter/resources/pipeline-layout.ts", "../src/shadertypes/data-types/decode-data-types.ts", "../src/utils/array-utils-flat.ts", "../src/utils/is-array.ts", "../src/portable/uniform-buffer-layout.ts", "../src/utils/array-equal.ts", "../src/portable/uniform-block.ts", "../src/portable/uniform-store.ts", "../src/shadertypes/texture-types/texture-layout.ts", "../src/shadertypes/texture-types/pixel-utils.ts"],
4
- "sourcesContent": ["// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// MAIN API ACCESS POINT\nexport type {AttachDeviceProps, CreateDeviceProps} from './adapter/luma';\nexport {luma} from './adapter/luma';\n\n// ADAPTER (DEVICE AND GPU RESOURCE INTERFACES)\nexport {Adapter} from './adapter/adapter';\n\nexport type {\n DeviceProps,\n DeviceInfo,\n DeviceFeature,\n DeviceTextureFormatCapabilities\n} from './adapter/device';\nexport {Device, DeviceFeatures, DeviceLimits} from './adapter/device';\n\nexport type {CanvasContextProps} from './adapter/canvas-context';\nexport {CanvasContext} from './adapter/canvas-context';\nexport type {PresentationContextProps} from './adapter/presentation-context';\nexport {PresentationContext} from './adapter/presentation-context';\n\n// GPU RESOURCES\nexport {Resource, type ResourceProps} from './adapter/resources/resource';\n\nexport {Buffer, type BufferProps, type BufferMapCallback} from './adapter/resources/buffer';\n\nexport {Texture, type TextureProps} from './adapter/resources/texture';\n\nexport {TextureView, type TextureViewProps} from './adapter/resources/texture-view';\n\nexport type {ExternalTextureProps} from './adapter/resources/external-texture';\nexport {ExternalTexture} from './adapter/resources/external-texture';\n\nexport type {ShaderProps} from './adapter/resources/shader';\nexport {Shader} from './adapter/resources/shader';\n\nexport type {SamplerProps, SamplerParameters} from './adapter/resources/sampler';\nexport {Sampler} from './adapter/resources/sampler';\n\nexport type {FramebufferProps} from './adapter/resources/framebuffer';\nexport {Framebuffer} from './adapter/resources/framebuffer';\n\nexport type {RenderPipelineProps} from './adapter/resources/render-pipeline';\nexport {RenderPipeline} from './adapter/resources/render-pipeline';\nexport {\n SharedRenderPipeline,\n type SharedRenderPipelineProps\n} from './adapter/resources/shared-render-pipeline';\nexport type {PipelineFactoryProps} from './factories/pipeline-factory';\nexport {PipelineFactory} from './factories/pipeline-factory';\nexport {ShaderFactory} from './factories/shader-factory';\nexport {_getDefaultBindGroupFactory} from './factories/bind-group-factory';\n\nexport type {RenderPassProps} from './adapter/resources/render-pass';\nexport {RenderPass} from './adapter/resources/render-pass';\n\nexport type {ComputePipelineProps} from './adapter/resources/compute-pipeline';\nexport {ComputePipeline} from './adapter/resources/compute-pipeline';\n\nexport type {ComputePassProps} from './adapter/resources/compute-pass';\nexport {ComputePass} from './adapter/resources/compute-pass';\n\nexport type {CommandEncoderProps} from './adapter/resources/command-encoder';\nexport {CommandEncoder} from './adapter/resources/command-encoder';\n\nexport type {CommandBufferProps} from './adapter/resources/command-buffer';\nexport {CommandBuffer} from './adapter/resources/command-buffer';\n\nexport type {VertexArrayProps} from './adapter/resources/vertex-array';\nexport {VertexArray} from './adapter/resources/vertex-array';\n\nexport type {TransformFeedbackProps, BufferRange} from './adapter/resources/transform-feedback';\nexport {TransformFeedback} from './adapter/resources/transform-feedback';\n\nexport type {QuerySetProps} from './adapter/resources/query-set';\nexport {QuerySet} from './adapter/resources/query-set';\n\nexport {Fence, type FenceProps} from './adapter/resources/fence';\n\nexport type {PipelineLayoutProps} from './adapter/resources/pipeline-layout';\nexport {PipelineLayout} from './adapter/resources/pipeline-layout';\n\n// PORTABLE API - UNIFORM BUFFERS\nexport {UniformBufferLayout} from './portable/uniform-buffer-layout';\nexport {UniformBlock} from './portable/uniform-block';\nexport {UniformStore} from './portable/uniform-store';\n// TEXTURE TYPES\n\n// API TYPES\nexport type {CompilerMessage} from './adapter/types/compiler-message';\n\nexport type {ExternalImage} from './shadertypes/image-types/image-types';\n\nexport {\n type CopyExternalImageOptions,\n type CopyImageDataOptions,\n type TextureReadOptions,\n type TextureWriteOptions\n} from './adapter/resources/texture';\n\nexport type {Parameters, PrimitiveTopology, IndexFormat} from './adapter/types/parameters';\n\nexport type {\n CullMode,\n FrontFace,\n RasterizationParameters,\n CompareFunction,\n StencilOperation,\n DepthStencilParameters,\n BlendFactor,\n BlendOperation,\n ColorParameters,\n MultisampleParameters,\n RenderPassParameters,\n RenderPipelineParameters,\n PolygonMode,\n ProvokingVertex\n} from './adapter/types/parameters';\n\nexport type {ColorAttachment, DepthStencilAttachment} from './adapter/types/attachments';\n\nexport type {\n ShaderLayout,\n ComputeShaderLayout,\n AttributeDeclaration,\n BindingDeclaration,\n Binding,\n Bindings,\n BindingsByGroup,\n UniformBufferBindingLayout,\n StorageBufferBindingLayout,\n TextureBindingLayout,\n SamplerBindingLayout,\n StorageTextureBindingLayout\n} from './adapter/types/shader-layout';\nexport type {BufferLayout, BufferAttributeLayout} from './adapter/types/buffer-layout';\nexport type {\n // Deprecated, todo\n AttributeBinding,\n UniformBinding,\n UniformBlockBinding,\n VaryingBinding\n} from './adapter/types/shader-layout';\n\nexport type {UniformValue} from './adapter/types/uniforms';\nexport type {\n CompositeUniformValue,\n CompositeUniformValueArray,\n CompositeUniformValueStruct\n} from './adapter/types/uniforms';\n\n// TYPED ARRAY TYPES\n\nexport type {\n NumberArray,\n TypedArray,\n TypedArrayConstructor,\n BigTypedArray,\n BigTypedArrayConstructor\n} from './types';\n\n// GPU TYPE UTILS - BASIC DATA TYPES\n\nexport {\n type PrimitiveDataType,\n type SignedDataType,\n type NormalizedDataType,\n type DataTypeInfo,\n type PrimitiveDataTypeT,\n type SignedDataTypeT,\n type TypedArrayConstructorT,\n type NormalizedTypedArrayConstructorT\n} from './shadertypes/data-types/data-types';\nexport {dataTypeDecoder} from './shadertypes/data-types/data-type-decoder';\nexport {getTypedArrayConstructor} from './shadertypes/data-types/decode-data-types';\n\nexport {\n type AttributeShaderTypeT,\n type AttributeShaderType,\n type ArrayShaderType,\n type CompositeShaderType,\n type StructShaderType,\n type VariableShaderTypeT,\n type VariableShaderType\n} from './shadertypes/shader-types/shader-types';\nexport {\n shaderTypeDecoder,\n getAttributeShaderTypeInfo,\n getVariableShaderTypeInfo,\n type AttributeShaderTypeInfo\n} from './shadertypes/shader-types/shader-type-decoder';\n\n// GPU TYPE UTILS - VERTEX ARRAYs\n\nexport {\n type VertexFormat,\n type VertexFormatDataTypeT\n} from './shadertypes/vertex-types/vertex-formats';\n\nexport {vertexFormatDecoder} from './shadertypes/vertex-types/vertex-format-decoder';\n\n// GPU TYPE UTILS - Texture Formats\n\nexport {\n type TextureFormat,\n type TextureFormatColor,\n type TextureFormatDepthStencil,\n type CompressedTextureFormat,\n type TextureCompression,\n type TextureFormatInfo,\n type TextureFormatCapabilities,\n type TextureMemoryLayout\n} from './shadertypes/texture-types/texture-formats';\nexport {type TextureFormatDataTypeT} from './shadertypes/texture-types/texture-format-generics';\n\nexport {\n type TextureFormatDecoder,\n textureFormatDecoder\n} from './shadertypes/texture-types/texture-format-decoder';\n\nexport {getTextureImageView, setTextureImageData} from './shadertypes/texture-types/texture-layout';\nexport {type PixelData, readPixel, writePixel} from './shadertypes/texture-types/pixel-utils';\n\nexport {isExternalImage, getExternalImageSize} from './shadertypes/image-types/image-types';\n\n// GENERAL EXPORTS - FOR APPLICATIONS\n\nexport type {StatsManager} from './utils/stats-manager'; // TODO - should this be moved to probe.gl?\n\n// ADAPTER UTILS - for implementing Device adapters (@luma.gl/webgl and @luma.gl/webgpu)\n\nexport type {\n CopyBufferToBufferOptions,\n CopyBufferToTextureOptions,\n CopyTextureToBufferOptions,\n CopyTextureToTextureOptions\n} from './adapter/resources/command-encoder';\n\n// INTERNAL UTILS - for use in other luma.gl modules only\nexport {log} from './utils/log';\nexport {\n getShaderLayoutBinding,\n normalizeBindingsByGroup,\n flattenBindingsByGroup\n} from './adapter-utils/bind-groups';\nexport {assert, assertDefined} from './utils/assert';\nexport {getScratchArray} from './utils/array-utils-flat';\nexport type {AttributeInfo} from './adapter-utils/get-attribute-from-layouts';\nexport {getAttributeInfosFromLayouts} from './adapter-utils/get-attribute-from-layouts';\n\n// TEST EXPORTS\nexport {\n getTextureFormatDefinition as _getTextureFormatDefinition,\n getTextureFormatTable as _getTextureFormatTable\n} from './shadertypes/texture-types/texture-format-table';\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Stat, Stats} from '@probe.gl/stats';\n\nconst GPU_TIME_AND_MEMORY_STATS = 'GPU Time and Memory';\nconst GPU_TIME_AND_MEMORY_STAT_ORDER = [\n 'Adapter',\n 'GPU',\n 'GPU Type',\n 'GPU Backend',\n 'Frame Rate',\n 'CPU Time',\n 'GPU Time',\n 'GPU Memory',\n 'Buffer Memory',\n 'Texture Memory',\n 'Referenced Buffer Memory',\n 'Referenced Texture Memory',\n 'Swap Chain Texture'\n] as const;\nconst ORDERED_STATS_CACHE = new WeakMap<\n Stats,\n {orderedStatNames: readonly string[]; statCount: number}\n>();\nconst ORDERED_STAT_NAME_SET_CACHE = new WeakMap<readonly string[], Set<string>>();\n\n/**\n * Helper class managing a collection of probe.gl stats objects\n */\nexport class StatsManager {\n stats = new Map();\n\n getStats(name: string): Stats {\n return this.get(name);\n }\n\n get(name: string): Stats {\n if (!this.stats.has(name)) {\n this.stats.set(name, new Stats({id: name}));\n }\n\n const stats = this.stats.get(name);\n if (name === GPU_TIME_AND_MEMORY_STATS) {\n initializeStats(stats, GPU_TIME_AND_MEMORY_STAT_ORDER);\n }\n\n return stats;\n }\n}\n\n/** Global stats for all luma.gl devices */\nexport const lumaStats: StatsManager = new StatsManager();\n\nfunction initializeStats(stats: Stats, orderedStatNames: readonly string[]): void {\n const statsMap = stats.stats;\n let addedOrderedStat = false;\n for (const statName of orderedStatNames) {\n if (!statsMap[statName]) {\n stats.get(statName);\n addedOrderedStat = true;\n }\n }\n\n const statCount = Object.keys(statsMap).length;\n const cachedStats = ORDERED_STATS_CACHE.get(stats);\n if (\n !addedOrderedStat &&\n cachedStats?.orderedStatNames === orderedStatNames &&\n cachedStats.statCount === statCount\n ) {\n return;\n }\n\n const reorderedStats: Record<string, Stat> = {};\n let orderedStatNamesSet = ORDERED_STAT_NAME_SET_CACHE.get(orderedStatNames);\n if (!orderedStatNamesSet) {\n orderedStatNamesSet = new Set(orderedStatNames);\n ORDERED_STAT_NAME_SET_CACHE.set(orderedStatNames, orderedStatNamesSet);\n }\n\n for (const statName of orderedStatNames) {\n if (statsMap[statName]) {\n reorderedStats[statName] = statsMap[statName];\n }\n }\n\n for (const [statName, stat] of Object.entries(statsMap)) {\n if (!orderedStatNamesSet.has(statName)) {\n reorderedStats[statName] = stat;\n }\n }\n\n for (const statName of Object.keys(statsMap)) {\n delete statsMap[statName];\n }\n\n Object.assign(statsMap, reorderedStats);\n ORDERED_STATS_CACHE.set(stats, {orderedStatNames, statCount});\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Log} from '@probe.gl/log';\n\n/** Global log instance */\nexport const log: Log = new Log({id: 'luma.gl'});\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst uidCounters: Record<string, number> = {};\n\n/**\n * Returns a UID.\n * @param id= - Identifier base name\n * @return uid\n **/\nexport function uid(id: string = 'id'): string {\n uidCounters[id] = uidCounters[id] || 1;\n const count = uidCounters[id]++;\n return `${id}-${count}`;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {Stat, Stats} from '@probe.gl/stats';\nimport {uid} from '../../utils/uid';\n\nconst CPU_HOTSPOT_PROFILER_MODULE = 'cpu-hotspot-profiler';\nconst RESOURCE_COUNTS_STATS = 'GPU Resource Counts';\nconst LEGACY_RESOURCE_COUNTS_STATS = 'Resource Counts';\nconst GPU_TIME_AND_MEMORY_STATS = 'GPU Time and Memory';\nconst BASE_RESOURCE_COUNT_ORDER = [\n 'Resources',\n 'Buffers',\n 'Textures',\n 'Samplers',\n 'TextureViews',\n 'Framebuffers',\n 'QuerySets',\n 'Shaders',\n 'RenderPipelines',\n 'ComputePipelines',\n 'PipelineLayouts',\n 'VertexArrays',\n 'RenderPasss',\n 'ComputePasss',\n 'CommandEncoders',\n 'CommandBuffers'\n] as const;\nconst WEBGL_RESOURCE_COUNT_ORDER = [\n 'Resources',\n 'Buffers',\n 'Textures',\n 'Samplers',\n 'TextureViews',\n 'Framebuffers',\n 'QuerySets',\n 'Shaders',\n 'RenderPipelines',\n 'SharedRenderPipelines',\n 'ComputePipelines',\n 'PipelineLayouts',\n 'VertexArrays',\n 'RenderPasss',\n 'ComputePasss',\n 'CommandEncoders',\n 'CommandBuffers'\n] as const;\nconst BASE_RESOURCE_COUNT_STAT_ORDER = BASE_RESOURCE_COUNT_ORDER.flatMap(resourceType => [\n `${resourceType} Created`,\n `${resourceType} Active`\n]);\nconst WEBGL_RESOURCE_COUNT_STAT_ORDER = WEBGL_RESOURCE_COUNT_ORDER.flatMap(resourceType => [\n `${resourceType} Created`,\n `${resourceType} Active`\n]);\nconst ORDERED_STATS_CACHE = new WeakMap<\n Stats,\n {orderedStatNames: readonly string[]; statCount: number}\n>();\nconst ORDERED_STAT_NAME_SET_CACHE = new WeakMap<readonly string[], Set<string>>();\n\ntype CpuHotspotProfiler = {\n enabled?: boolean;\n activeDefaultFramebufferAcquireDepth?: number;\n statsBookkeepingTimeMs?: number;\n statsBookkeepingCalls?: number;\n transientCanvasResourceCreates?: number;\n transientCanvasTextureCreates?: number;\n transientCanvasTextureViewCreates?: number;\n transientCanvasSamplerCreates?: number;\n transientCanvasFramebufferCreates?: number;\n};\n\nexport type ResourceProps = {\n /** Name of resource, mainly for debugging purposes. A unique name will be assigned if not provided */\n id?: string;\n /** Handle for the underlying resources (WebGL object or WebGPU handle) */\n handle?: any;\n /** User provided data stored on this resource */\n userData?: {[key: string]: any};\n};\n\n/**\n * Base class for GPU (WebGPU/WebGL) Resources\n */\nexport abstract class Resource<Props extends ResourceProps> {\n /** Default properties for resource */\n static defaultProps: Required<ResourceProps> = {\n id: 'undefined',\n handle: undefined,\n userData: undefined!\n };\n\n abstract get [Symbol.toStringTag](): string;\n\n toString(): string {\n return `${this[Symbol.toStringTag] || this.constructor.name}:\"${this.id}\"`;\n }\n\n /** props.id, for debugging. */\n id: string;\n /** The props that this resource was created with */\n readonly props: Required<Props>;\n /** User data object, reserved for the application */\n readonly userData: Record<string, unknown> = {};\n /** The device that this resource is associated with */\n abstract readonly device: Device;\n /** The handle for the underlying resource, e.g. WebGL object or WebGPU handle */\n abstract readonly handle: unknown;\n /** The device that this resource is associated with - TODO can we remove this dup? */\n private _device: Device;\n\n /** Whether this resource has been destroyed */\n destroyed: boolean = false;\n /** For resources that allocate GPU memory */\n private allocatedBytes: number = 0;\n /** Stats bucket currently holding the tracked allocation */\n private allocatedBytesName: string | null = null;\n /** Attached resources will be destroyed when this resource is destroyed. Tracks auto-created \"sub\" resources. */\n private _attachedResources = new Set<Resource<ResourceProps>>();\n\n /**\n * Create a new Resource. Called from Subclass\n */\n constructor(device: Device, props: Props, defaultProps: Required<Props>) {\n if (!device) {\n throw new Error('no device');\n }\n this._device = device;\n this.props = selectivelyMerge<Props>(props, defaultProps);\n\n const id =\n this.props.id !== 'undefined' ? (this.props.id as string) : uid(this[Symbol.toStringTag]);\n this.props.id = id;\n this.id = id;\n this.userData = this.props.userData || {};\n\n this.addStats();\n }\n\n /**\n * destroy can be called on any resource to release it before it is garbage collected.\n */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyResource();\n }\n\n /** @deprecated Use destroy() */\n delete(): this {\n this.destroy();\n return this;\n }\n\n /**\n * Combines a map of user props and default props, only including props from defaultProps\n * @returns returns a map of overridden default props\n */\n getProps(): object {\n return this.props;\n }\n\n // ATTACHED RESOURCES\n\n /**\n * Attaches a resource. Attached resources are auto destroyed when this resource is destroyed\n * Called automatically when sub resources are auto created but can be called by application\n */\n attachResource(resource: Resource<ResourceProps>): void {\n this._attachedResources.add(resource);\n }\n\n /**\n * Detach an attached resource. The resource will no longer be auto-destroyed when this resource is destroyed.\n */\n detachResource(resource: Resource<ResourceProps>): void {\n this._attachedResources.delete(resource);\n }\n\n /**\n * Destroys a resource (only if owned), and removes from the owned (auto-destroy) list for this resource.\n */\n destroyAttachedResource(resource: Resource<ResourceProps>): void {\n if (this._attachedResources.delete(resource)) {\n resource.destroy();\n }\n }\n\n /** Destroy all owned resources. Make sure the resources are no longer needed before calling. */\n destroyAttachedResources(): void {\n for (const resource of this._attachedResources) {\n resource.destroy();\n }\n // don't remove while we are iterating\n this._attachedResources = new Set<Resource<ResourceProps>>();\n }\n\n // PROTECTED METHODS\n\n /** Perform all destroy steps. Can be called by derived resources when overriding destroy() */\n protected destroyResource(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyAttachedResources();\n this.removeStats();\n this.destroyed = true;\n }\n\n /** Called by .destroy() to track object destruction. Subclass must call if overriding destroy() */\n protected removeStats(): void {\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const statsObjects = [\n this._device.statsManager.getStats(RESOURCE_COUNTS_STATS),\n this._device.statsManager.getStats(LEGACY_RESOURCE_COUNTS_STATS)\n ];\n const orderedStatNames = getResourceCountStatOrder(this._device);\n for (const stats of statsObjects) {\n initializeStats(stats, orderedStatNames);\n }\n const name = this.getStatsName();\n for (const stats of statsObjects) {\n stats.get('Resources Active').decrementCount();\n stats.get(`${name}s Active`).decrementCount();\n }\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n }\n\n /** Called by subclass to track memory allocations */\n protected trackAllocatedMemory(bytes: number, name = this.getStatsName()): void {\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const stats = this._device.statsManager.getStats(GPU_TIME_AND_MEMORY_STATS);\n\n if (this.allocatedBytes > 0 && this.allocatedBytesName) {\n stats.get('GPU Memory').subtractCount(this.allocatedBytes);\n stats.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes);\n }\n\n stats.get('GPU Memory').addCount(bytes);\n stats.get(`${name} Memory`).addCount(bytes);\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n this.allocatedBytes = bytes;\n this.allocatedBytesName = name;\n }\n\n /** Called by subclass to track handle-backed memory allocations separately from owned allocations */\n protected trackReferencedMemory(bytes: number, name = this.getStatsName()): void {\n this.trackAllocatedMemory(bytes, `Referenced ${name}`);\n }\n\n /** Called by subclass to track memory deallocations */\n protected trackDeallocatedMemory(name = this.getStatsName()): void {\n if (this.allocatedBytes === 0) {\n this.allocatedBytesName = null;\n return;\n }\n\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const stats = this._device.statsManager.getStats(GPU_TIME_AND_MEMORY_STATS);\n stats.get('GPU Memory').subtractCount(this.allocatedBytes);\n stats.get(`${this.allocatedBytesName || name} Memory`).subtractCount(this.allocatedBytes);\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n this.allocatedBytes = 0;\n this.allocatedBytesName = null;\n }\n\n /** Called by subclass to deallocate handle-backed memory tracked via trackReferencedMemory() */\n protected trackDeallocatedReferencedMemory(name = this.getStatsName()): void {\n this.trackDeallocatedMemory(`Referenced ${name}`);\n }\n\n /** Called by resource constructor to track object creation */\n private addStats(): void {\n const name = this.getStatsName();\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const statsObjects = [\n this._device.statsManager.getStats(RESOURCE_COUNTS_STATS),\n this._device.statsManager.getStats(LEGACY_RESOURCE_COUNTS_STATS)\n ];\n const orderedStatNames = getResourceCountStatOrder(this._device);\n for (const stats of statsObjects) {\n initializeStats(stats, orderedStatNames);\n }\n for (const stats of statsObjects) {\n stats.get('Resources Created').incrementCount();\n stats.get('Resources Active').incrementCount();\n stats.get(`${name}s Created`).incrementCount();\n stats.get(`${name}s Active`).incrementCount();\n }\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n recordTransientCanvasResourceCreate(this._device, name);\n }\n\n /** Canonical resource name used for stats buckets. */\n protected getStatsName(): string {\n return getCanonicalResourceName(this);\n }\n}\n\n/**\n * Combines a map of user props and default props, only including props from defaultProps\n * @param props\n * @param defaultProps\n * @returns returns a map of overridden default props\n */\nfunction selectivelyMerge<Props>(props: Props, defaultProps: Required<Props>): Required<Props> {\n const mergedProps = {...defaultProps};\n for (const key in props) {\n if (props[key] !== undefined) {\n mergedProps[key] = props[key];\n }\n }\n return mergedProps;\n}\n\nfunction initializeStats(stats: Stats, orderedStatNames: readonly string[]): void {\n const statsMap = stats.stats;\n let addedOrderedStat = false;\n for (const statName of orderedStatNames) {\n if (!statsMap[statName]) {\n stats.get(statName);\n addedOrderedStat = true;\n }\n }\n\n const statCount = Object.keys(statsMap).length;\n const cachedStats = ORDERED_STATS_CACHE.get(stats);\n if (\n !addedOrderedStat &&\n cachedStats?.orderedStatNames === orderedStatNames &&\n cachedStats.statCount === statCount\n ) {\n return;\n }\n\n const reorderedStats: Record<string, Stat> = {};\n let orderedStatNamesSet = ORDERED_STAT_NAME_SET_CACHE.get(orderedStatNames);\n if (!orderedStatNamesSet) {\n orderedStatNamesSet = new Set(orderedStatNames);\n ORDERED_STAT_NAME_SET_CACHE.set(orderedStatNames, orderedStatNamesSet);\n }\n\n for (const statName of orderedStatNames) {\n if (statsMap[statName]) {\n reorderedStats[statName] = statsMap[statName];\n }\n }\n\n for (const [statName, stat] of Object.entries(statsMap)) {\n if (!orderedStatNamesSet.has(statName)) {\n reorderedStats[statName] = stat;\n }\n }\n\n for (const statName of Object.keys(statsMap)) {\n delete statsMap[statName];\n }\n\n Object.assign(statsMap, reorderedStats);\n ORDERED_STATS_CACHE.set(stats, {orderedStatNames, statCount});\n}\n\nfunction getResourceCountStatOrder(device: Device): readonly string[] {\n return device.type === 'webgl' ? WEBGL_RESOURCE_COUNT_STAT_ORDER : BASE_RESOURCE_COUNT_STAT_ORDER;\n}\n\nfunction getCpuHotspotProfiler(device: Device): CpuHotspotProfiler | null {\n const profiler = device.userData[CPU_HOTSPOT_PROFILER_MODULE] as CpuHotspotProfiler | undefined;\n return profiler?.enabled ? profiler : null;\n}\n\nfunction getTimestamp(): number {\n return globalThis.performance?.now?.() ?? Date.now();\n}\n\nfunction recordTransientCanvasResourceCreate(device: Device, name: string): void {\n const profiler = getCpuHotspotProfiler(device);\n if (!profiler || !profiler.activeDefaultFramebufferAcquireDepth) {\n return;\n }\n\n profiler.transientCanvasResourceCreates = (profiler.transientCanvasResourceCreates || 0) + 1;\n\n switch (name) {\n case 'Texture':\n profiler.transientCanvasTextureCreates = (profiler.transientCanvasTextureCreates || 0) + 1;\n break;\n case 'TextureView':\n profiler.transientCanvasTextureViewCreates =\n (profiler.transientCanvasTextureViewCreates || 0) + 1;\n break;\n case 'Sampler':\n profiler.transientCanvasSamplerCreates = (profiler.transientCanvasSamplerCreates || 0) + 1;\n break;\n case 'Framebuffer':\n profiler.transientCanvasFramebufferCreates =\n (profiler.transientCanvasFramebufferCreates || 0) + 1;\n break;\n default:\n break;\n }\n}\n\nfunction getCanonicalResourceName(resource: Resource<any>): string {\n let prototype = Object.getPrototypeOf(resource);\n\n while (prototype) {\n const parentPrototype = Object.getPrototypeOf(prototype);\n if (!parentPrototype || parentPrototype === Resource.prototype) {\n return (\n getPrototypeToStringTag(prototype) ||\n resource[Symbol.toStringTag] ||\n resource.constructor.name\n );\n }\n prototype = parentPrototype;\n }\n\n return resource[Symbol.toStringTag] || resource.constructor.name;\n}\n\nfunction getPrototypeToStringTag(prototype: object): string | null {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag);\n if (typeof descriptor?.get === 'function') {\n return descriptor.get.call(prototype);\n }\n if (typeof descriptor?.value === 'string') {\n return descriptor.value;\n }\n return null;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\n/** Callback for Buffer.mapAndReadAsync */\nexport type BufferMapCallback<T> = (arrayBuffer: ArrayBuffer, lifetime: 'mapped' | 'copied') => T;\n\nexport type BufferProps = ResourceProps & {\n /** Supply a handle to connect to an existing device-specific buffer */\n handle?: WebGLBuffer;\n /** Specifies how this buffer can be used */\n usage?: number;\n /** Length in bytes of memory to be allocated. If not specified, `byteLength` of `props.data` will be used. */\n byteLength?: number;\n /** Byte offset into the newly created Buffer to store data at */\n byteOffset?: number;\n /** If props.usage includes Buffer.INDEX. Note: uint8 indices are automatically converted to uint16 for WebGPU compatibility */\n indexType?: 'uint8' | 'uint16' | 'uint32';\n /** Data to initialize the buffer with. */\n data?: ArrayBuffer | ArrayBufferView | null;\n /** Callback to initialize data without copy */\n onMapped?: BufferMapCallback<void>;\n};\n\n/** Abstract GPU buffer */\nexport abstract class Buffer extends Resource<BufferProps> {\n /** Index buffer */\n static INDEX = 0x0010;\n /** Vertex buffer */\n static VERTEX = 0x0020;\n /** Uniform buffer */\n static UNIFORM = 0x0040;\n /** Storage buffer */\n static STORAGE = 0x0080;\n static INDIRECT = 0x0100;\n static QUERY_RESOLVE = 0x0200;\n\n // Usage Flags\n static MAP_READ = 0x01;\n static MAP_WRITE = 0x02;\n static COPY_SRC = 0x0004;\n static COPY_DST = 0x0008;\n\n override get [Symbol.toStringTag](): string {\n return 'Buffer';\n }\n\n /** The usage with which this buffer was created */\n readonly usage: number;\n /** For index buffers, whether indices are 8, 16 or 32 bit. Note: uint8 indices are automatically converted to uint16 for WebGPU compatibility */\n readonly indexType?: 'uint8' | 'uint16' | 'uint32';\n /** Length of buffer in bytes */\n abstract byteLength: number;\n /** \"Time\" of last update, can be used to check if redraw is needed */\n updateTimestamp: number;\n\n constructor(device: Device, props: BufferProps) {\n const deducedProps = {...props};\n\n // Deduce indexType\n if ((props.usage || 0) & Buffer.INDEX && !props.indexType) {\n if (props.data instanceof Uint32Array) {\n deducedProps.indexType = 'uint32';\n } else if (props.data instanceof Uint16Array) {\n deducedProps.indexType = 'uint16';\n } else if (props.data instanceof Uint8Array) {\n deducedProps.indexType = 'uint8';\n }\n }\n\n // Remove data from props before storing, we don't want to hold on to a big chunk of memory\n delete deducedProps.data;\n\n super(device, deducedProps, Buffer.defaultProps);\n\n this.usage = deducedProps.usage || 0;\n this.indexType = deducedProps.indexType;\n\n // TODO - perhaps this should be set on async write completion?\n this.updateTimestamp = device.incrementTimestamp();\n }\n\n /**\n * Create a copy of this Buffer with new byteLength, with same props but of the specified size.\n * @note Does not copy contents of the cloned Buffer.\n */\n clone(props: {byteLength: number}): Buffer {\n return this.device.createBuffer({...this.props, ...props});\n }\n\n /** Write data to buffer */\n abstract write(\n data: ArrayBufferLike | ArrayBufferView | SharedArrayBuffer,\n byteOffset?: number\n ): void;\n\n abstract mapAndWriteAsync(\n onMapped: BufferMapCallback<void | Promise<void>>,\n byteOffset?: number,\n byteLength?: number\n ): Promise<void>;\n\n /** Reads data asynchronously, returns a copy of the buffer data */\n abstract readAsync(byteOffset?: number, byteLength?: number): Promise<Uint8Array>;\n\n /** Maps buffer data to CPU memory. Mapped memory is only accessible in the callback */\n abstract mapAndReadAsync<T>(\n onMapped: BufferMapCallback<T>,\n byteOffset?: number,\n byteLength?: number\n ): Promise<T>;\n\n /** Read data synchronously. @note WebGL2 only */\n abstract readSyncWebGL(byteOffset?: number, byteLength?: number): Uint8Array;\n\n // PROTECTED METHODS (INTENDED FOR USE BY OTHER FRAMEWORK CODE ONLY)\n\n /** Max amount of debug data saved. Two vec4's */\n static DEBUG_DATA_MAX_LENGTH = 32;\n\n /** A partial CPU-side copy of the data in this buffer, for debugging purposes */\n debugData: ArrayBuffer = new ArrayBuffer(0);\n\n /** This doesn't handle partial non-zero offset updates correctly */\n protected _setDebugData(\n data: ArrayBufferView | ArrayBufferLike | null,\n _byteOffset: number,\n byteLength: number\n ): void {\n let arrayBufferView: ArrayBufferView | null = null;\n let arrayBuffer: ArrayBufferLike | null;\n if (ArrayBuffer.isView(data)) {\n arrayBufferView = data;\n arrayBuffer = data.buffer;\n } else {\n arrayBuffer = data;\n }\n const debugDataLength = Math.min(\n data ? data.byteLength : byteLength,\n Buffer.DEBUG_DATA_MAX_LENGTH\n );\n if (arrayBuffer === null) {\n this.debugData = new ArrayBuffer(debugDataLength);\n } else {\n const sourceByteOffset = Math.min(arrayBufferView?.byteOffset || 0, arrayBuffer.byteLength);\n const availableByteLength = Math.max(0, arrayBuffer.byteLength - sourceByteOffset);\n const copyByteLength = Math.min(debugDataLength, availableByteLength);\n this.debugData = new Uint8Array(arrayBuffer, sourceByteOffset, copyByteLength).slice().buffer;\n }\n }\n\n static override defaultProps: Required<BufferProps> = {\n ...Resource.defaultProps,\n usage: 0, // Buffer.COPY_DST | Buffer.COPY_SRC\n byteLength: 0,\n byteOffset: 0,\n data: null,\n indexType: 'uint16',\n onMapped: undefined!\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray, TypedArrayConstructor} from '../../types';\nimport {\n PrimitiveDataType,\n SignedDataType,\n NormalizedDataType,\n DataTypeInfo,\n TypedArrayConstructorT\n} from './data-types';\n\nexport class DataTypeDecoder {\n /**\n * Gets info about a data type constant (signed or normalized)\n * @returns underlying primitive / signed types, byte length, normalization, integer, signed flags\n */\n getDataTypeInfo<T extends NormalizedDataType = NormalizedDataType>(type: T): DataTypeInfo<T> {\n const [signedType, primitiveType, byteLength] = NORMALIZED_TYPE_MAP[type];\n const normalized: boolean = type.includes('norm');\n const integer: boolean = !normalized && !type.startsWith('float');\n const signed: boolean = type.startsWith('s');\n return {\n signedType: signedType as DataTypeInfo<T>['signedType'],\n primitiveType: primitiveType as DataTypeInfo<T>['primitiveType'],\n byteLength: byteLength as DataTypeInfo<T>['byteLength'],\n normalized: normalized as DataTypeInfo<T>['normalized'],\n integer: integer as DataTypeInfo<T>['integer'],\n signed: signed as DataTypeInfo<T>['signed']\n // TODO - add webglOnly flag\n };\n }\n\n /** Build a vertex format from a signed data type and a component */\n getNormalizedDataType(signedDataType: SignedDataType): NormalizedDataType {\n const dataType: NormalizedDataType = signedDataType;\n // prettier-ignore\n switch (dataType) {\n case 'uint8': return 'unorm8';\n case 'sint8': return 'snorm8';\n case 'uint16': return 'unorm16';\n case 'sint16': return 'snorm16';\n default: return dataType;\n }\n }\n\n /** Align offset to 1, 2 or 4 elements (4, 8 or 16 bytes) */\n alignTo(size: number, count: number): number {\n // prettier-ignore\n switch (count) {\n case 1: return size; // Pad upwards to even multiple of 2\n case 2: return size + (size % 2); // Pad upwards to even multiple of 2\n default: return size + ((4 - (size % 4)) % 4); // Pad upwards to even multiple of 4\n }\n }\n\n /** Returns the VariableShaderType that corresponds to a typed array */\n getDataType(arrayOrType: TypedArray | TypedArrayConstructor): SignedDataType {\n const Constructor = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;\n if (Constructor === Uint8ClampedArray) {\n return 'uint8';\n }\n const info = Object.values(NORMALIZED_TYPE_MAP).find(entry => Constructor === entry[4]);\n if (!info) {\n throw new Error(Constructor.name);\n }\n return info[0];\n }\n\n /** Returns the TypedArray that corresponds to a shader data type */\n getTypedArrayConstructor<T extends NormalizedDataType>(\n type: NormalizedDataType\n ): TypedArrayConstructorT<T> {\n const [, , , , Constructor] = NORMALIZED_TYPE_MAP[type];\n return Constructor as unknown as TypedArrayConstructorT<T>;\n }\n}\n\n/** Entry point for decoding luma.gl data types */\nexport const dataTypeDecoder = new DataTypeDecoder();\n\nconst NORMALIZED_TYPE_MAP = {\n uint8: ['uint8', 'u32', 1, false, Uint8Array],\n sint8: ['sint8', 'i32', 1, false, Int8Array],\n unorm8: ['uint8', 'f32', 1, true, Uint8Array],\n snorm8: ['sint8', 'f32', 1, true, Int8Array],\n uint16: ['uint16', 'u32', 2, false, Uint16Array],\n sint16: ['sint16', 'i32', 2, false, Int16Array],\n unorm16: ['uint16', 'u32', 2, true, Uint16Array],\n snorm16: ['sint16', 'i32', 2, true, Int16Array],\n float16: ['float16', 'f16', 2, false, Uint16Array],\n float32: ['float32', 'f32', 4, false, Float32Array],\n uint32: ['uint32', 'u32', 4, false, Uint32Array],\n sint32: ['sint32', 'i32', 4, false, Int32Array]\n} satisfies Record<\n NormalizedDataType,\n [\n SignedDataType,\n PrimitiveDataType,\n bytes: 1 | 2 | 4,\n normalized: boolean,\n arrayConstructor: TypedArrayConstructor\n ]\n>;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '../../types';\nimport type {NormalizedDataType, PrimitiveDataType, SignedDataType} from '../data-types/data-types';\nimport type {VertexFormat, VertexFormatInfo} from './vertex-formats';\nimport {dataTypeDecoder} from '../data-types/data-type-decoder';\n\nexport class VertexFormatDecoder {\n /**\n * Decodes a vertex format, returning type, components, byte length and flags (integer, signed, normalized)\n */\n getVertexFormatInfo<T extends VertexFormat = VertexFormat>(format: T): VertexFormatInfo<T> {\n // Strip the -webgl ending if present\n let webglOnly: boolean | undefined;\n if (format.endsWith('-webgl')) {\n format.replace('-webgl', '');\n webglOnly = true;\n }\n // split components from type\n const [type_, count] = format.split('x');\n const type = type_ as NormalizedDataType;\n const components = (count ? parseInt(count) : 1) as 1 | 2 | 3 | 4;\n // decode the type\n const decodedType = dataTypeDecoder.getDataTypeInfo(type);\n const result: VertexFormatInfo = {\n type,\n components,\n byteLength: decodedType.byteLength * components,\n integer: decodedType.integer,\n signed: decodedType.signed,\n normalized: decodedType.normalized\n };\n if (webglOnly) {\n result.webglOnly = true;\n }\n return result;\n }\n\n /** Build a vertex format from a signed data type and a component */\n makeVertexFormat(\n signedDataType: SignedDataType,\n components: 1 | 2 | 3 | 4,\n normalized?: boolean\n ): VertexFormat {\n const dataType: NormalizedDataType = normalized\n ? dataTypeDecoder.getNormalizedDataType(signedDataType)\n : signedDataType;\n\n switch (dataType) {\n // TODO - Special cases for WebGL (not supported on WebGPU), overrides the check below\n case 'unorm8':\n if (components === 1) {\n return 'unorm8';\n }\n if (components === 3) {\n return 'unorm8x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'snorm8':\n case 'uint8':\n case 'sint8':\n // WebGPU 8 bit formats must be aligned to 16 bit boundaries');\n // fall through\n case 'uint16':\n case 'sint16':\n case 'unorm16':\n case 'snorm16':\n case 'float16':\n // WebGPU 16 bit formats must be aligned to 32 bit boundaries\n if (components === 1 || components === 3) {\n throw new Error(`size: ${components}`);\n }\n return `${dataType}x${components}`;\n\n default:\n return components === 1 ? dataType : `${dataType}x${components}`;\n }\n }\n\n /** Get the vertex format for an attribute with TypedArray and size */\n getVertexFormatFromAttribute(\n typedArray: TypedArray,\n size: number,\n normalized?: boolean\n ): VertexFormat {\n if (!size || size > 4) {\n throw new Error(`size ${size}`);\n }\n\n const components = size as 1 | 2 | 3 | 4;\n const signedDataType = dataTypeDecoder.getDataType(typedArray);\n return this.makeVertexFormat(signedDataType, components, normalized);\n }\n\n /**\n * Return a \"default\" vertex format for a certain shader data type\n * The simplest vertex format that matches the shader attribute's data type\n */\n\n getCompatibleVertexFormat(opts: {\n primitiveType: PrimitiveDataType;\n components: 1 | 2 | 3 | 4;\n }): VertexFormat {\n let vertexType: NormalizedDataType;\n switch (opts.primitiveType) {\n case 'f32':\n vertexType = 'float32';\n break;\n case 'i32':\n vertexType = 'sint32';\n break;\n case 'u32':\n vertexType = 'uint32';\n break;\n case 'f16':\n return opts.components <= 2 ? 'float16x2' : 'float16x4';\n }\n\n // TODO logic does not work for float16\n if (opts.components === 1) {\n return vertexType;\n }\n return `${vertexType}x${opts.components}`;\n }\n}\n\n/** Decoder for luma.gl vertex types */\nexport const vertexFormatDecoder = new VertexFormatDecoder();\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n TextureFormat,\n TextureFormatColorUncompressed,\n TextureFormatDepthStencil,\n TextureFeature,\n TextureFormatInfo,\n TextureFormatCompressed\n} from './texture-formats';\n/* eslint-disable camelcase */\n\n// Define local device feature strings to optimize minification\nconst texture_compression_bc: TextureFeature = 'texture-compression-bc';\nconst texture_compression_astc: TextureFeature = 'texture-compression-astc';\nconst texture_compression_etc2: TextureFeature = 'texture-compression-etc2';\nconst texture_compression_etc1_webgl: TextureFeature = 'texture-compression-etc1-webgl';\nconst texture_compression_pvrtc_webgl: TextureFeature = 'texture-compression-pvrtc-webgl';\nconst texture_compression_atc_webgl: TextureFeature = 'texture-compression-atc-webgl';\n\nconst float32_renderable: TextureFeature = 'float32-renderable-webgl';\nconst float16_renderable: TextureFeature = 'float16-renderable-webgl';\nconst rgb9e5ufloat_renderable: TextureFeature = 'rgb9e5ufloat-renderable-webgl';\nconst snorm8_renderable: TextureFeature = 'snorm8-renderable-webgl';\nconst norm16_webgl: TextureFeature = 'norm16-webgl';\nconst norm16_renderable: TextureFeature = 'norm16-renderable-webgl';\nconst snorm16_renderable: TextureFeature = 'snorm16-renderable-webgl';\n\nconst float32_filterable: TextureFeature = 'float32-filterable';\nconst float16_filterable: TextureFeature = 'float16-filterable-webgl';\n\n/** https://www.w3.org/TR/webgpu/#texture-format-caps */\n\n/** Internal type representing texture capabilities */\ntype TextureFormatDefinition = Partial<TextureFormatInfo> & {\n /** for compressed texture formats */\n f?: TextureFeature;\n /** renderable if feature is present. false means the spec does not support this format */\n render?: TextureFeature | false;\n /** filterable if feature is present. false means the spec does not support this format */\n filter?: TextureFeature | false;\n blend?: TextureFeature | false;\n store?: TextureFeature | false;\n\n /** (bytes per pixel), for memory usage calculations. */\n b?: number;\n /** channels */\n c?: number;\n bpp?: number;\n /** packed */\n p?: number;\n\n /** If not supported on WebGPU */\n wgpu?: false;\n};\n\nexport function getTextureFormatDefinition(format: TextureFormat): TextureFormatDefinition {\n const info = TEXTURE_FORMAT_TABLE[format];\n if (!info) {\n throw new Error(`Unsupported texture format ${format}`);\n }\n return info;\n}\n\nexport function getTextureFormatTable(): Readonly<Record<TextureFormat, TextureFormatDefinition>> {\n return TEXTURE_FORMAT_TABLE;\n}\n\n// prettier-ignore\nconst TEXTURE_FORMAT_COLOR_DEPTH_TABLE: Readonly<Record<TextureFormatColorUncompressed | TextureFormatDepthStencil, TextureFormatDefinition>> = {\n // 8-bit formats\n 'r8unorm': {},\n 'rg8unorm': {},\n 'rgb8unorm-webgl': {},\n 'rgba8unorm': {},\n 'rgba8unorm-srgb': {},\n\n 'r8snorm': {render: snorm8_renderable},\n 'rg8snorm': {render: snorm8_renderable},\n 'rgb8snorm-webgl': {},\n 'rgba8snorm': {render: snorm8_renderable},\n\n 'r8uint': {},\n 'rg8uint': {},\n 'rgba8uint': {},\n\n 'r8sint': {},\n 'rg8sint': {},\n 'rgba8sint': {},\n\n 'bgra8unorm': {},\n 'bgra8unorm-srgb': {},\n\n\n 'r16unorm': {f: norm16_webgl, render: norm16_renderable},\n 'rg16unorm': {f: norm16_webgl, render: norm16_renderable},\n 'rgb16unorm-webgl': {f: norm16_webgl, render: false}, // rgb not renderable\n 'rgba16unorm': {f: norm16_webgl, render: norm16_renderable},\n\n 'r16snorm': {f: norm16_webgl, render: snorm16_renderable},\n 'rg16snorm': {f: norm16_webgl, render: snorm16_renderable},\n 'rgb16snorm-webgl': {f: norm16_webgl, render: false}, // rgb not renderable\n 'rgba16snorm': {f: norm16_webgl, render: snorm16_renderable},\n\n 'r16uint': {},\n 'rg16uint': {},\n 'rgba16uint': {},\n\n 'r16sint': {},\n 'rg16sint': {},\n 'rgba16sint': {},\n\n 'r16float': {render: float16_renderable, filter: 'float16-filterable-webgl'},\n 'rg16float': {render: float16_renderable, filter: float16_filterable},\n 'rgba16float': {render: float16_renderable, filter: float16_filterable},\n\n 'r32uint': {},\n 'rg32uint': {},\n 'rgba32uint': {},\n\n 'r32sint': {},\n 'rg32sint': {},\n 'rgba32sint': {},\n\n 'r32float': {render: float32_renderable, filter: float32_filterable},\n 'rg32float': {render: false, filter: float32_filterable},\n 'rgb32float-webgl': {render: float32_renderable, filter: float32_filterable},\n 'rgba32float': {render: float32_renderable, filter: float32_filterable},\n\n // Packed 16-bit formats\n 'rgba4unorm-webgl': {channels: 'rgba', bitsPerChannel: [4, 4, 4, 4], packed: true},\n 'rgb565unorm-webgl': {channels: 'rgb', bitsPerChannel: [5, 6, 5, 0], packed: true},\n 'rgb5a1unorm-webgl': {channels: 'rgba', bitsPerChannel: [5, 5, 5, 1], packed: true},\n\n // Packed 32 bit formats\n 'rgb9e5ufloat': {channels: 'rgb', packed: true, render: rgb9e5ufloat_renderable}, // , filter: true},\n 'rg11b10ufloat': {channels: 'rgb', bitsPerChannel: [11, 11, 10, 0], packed: true, p: 1,render: float32_renderable},\n 'rgb10a2unorm': {channels: 'rgba', bitsPerChannel: [10, 10, 10, 2], packed: true, p: 1},\n 'rgb10a2uint': {channels: 'rgba', bitsPerChannel: [10, 10, 10, 2], packed: true, p: 1},\n\n // Depth/stencil Formats\n \n // Depth and stencil formats\n stencil8: {attachment: 'stencil', bitsPerChannel: [8, 0, 0, 0], dataType: 'uint8'},\n 'depth16unorm': {attachment: 'depth', bitsPerChannel: [16, 0, 0, 0], dataType: 'uint16'},\n 'depth24plus': {attachment: 'depth', bitsPerChannel: [24, 0, 0, 0], dataType: 'uint32'},\n 'depth32float': {attachment: 'depth', bitsPerChannel: [32, 0, 0, 0], dataType: 'float32'},\n // The depth component of the \"depth24plus\" and \"depth24plus-stencil8\" formats may be implemented as either a 24-bit depth value or a \"depth32float\" value.\n 'depth24plus-stencil8': {attachment: 'depth-stencil', bitsPerChannel: [24, 8, 0, 0], packed: true},\n // \"depth32float-stencil8\" feature\n 'depth32float-stencil8': {attachment: 'depth-stencil', bitsPerChannel: [32, 8, 0, 0], packed: true},\n};\n\n// prettier-ignore\nconst TEXTURE_FORMAT_COMPRESSED_TABLE: Readonly<Record<TextureFormatCompressed, TextureFormatDefinition>> = {\n\n // BC compressed formats: check device.features.has(\"texture-compression-bc\");\n\n 'bc1-rgb-unorm-webgl': {f: texture_compression_bc},\n 'bc1-rgb-unorm-srgb-webgl': {f: texture_compression_bc},\n\n 'bc1-rgba-unorm': {f: texture_compression_bc},\n 'bc1-rgba-unorm-srgb': {f: texture_compression_bc},\n 'bc2-rgba-unorm': {f: texture_compression_bc},\n 'bc2-rgba-unorm-srgb': {f: texture_compression_bc},\n 'bc3-rgba-unorm': {f: texture_compression_bc},\n 'bc3-rgba-unorm-srgb': {f: texture_compression_bc},\n 'bc4-r-unorm': {f: texture_compression_bc},\n 'bc4-r-snorm': {f: texture_compression_bc},\n 'bc5-rg-unorm': {f: texture_compression_bc},\n 'bc5-rg-snorm': {f: texture_compression_bc},\n 'bc6h-rgb-ufloat': {f: texture_compression_bc},\n 'bc6h-rgb-float': {f: texture_compression_bc},\n 'bc7-rgba-unorm': {f: texture_compression_bc},\n 'bc7-rgba-unorm-srgb': {f: texture_compression_bc},\n\n // WEBGL_compressed_texture_etc: device.features.has(\"texture-compression-etc2\")\n // Note: Supposedly guaranteed availability compressed formats in WebGL2, but through CPU decompression\n\n 'etc2-rgb8unorm': {f: texture_compression_etc2},\n 'etc2-rgb8unorm-srgb': {f: texture_compression_etc2},\n 'etc2-rgb8a1unorm': {f: texture_compression_etc2},\n 'etc2-rgb8a1unorm-srgb': {f: texture_compression_etc2},\n 'etc2-rgba8unorm': {f: texture_compression_etc2},\n 'etc2-rgba8unorm-srgb': {f: texture_compression_etc2},\n\n 'eac-r11unorm': {f: texture_compression_etc2},\n 'eac-r11snorm': {f: texture_compression_etc2},\n 'eac-rg11unorm': {f: texture_compression_etc2},\n 'eac-rg11snorm': {f: texture_compression_etc2},\n\n // X_ASTC compressed formats: device.features.has(\"texture-compression-astc\")\n\n 'astc-4x4-unorm': {f: texture_compression_astc},\n 'astc-4x4-unorm-srgb': {f: texture_compression_astc},\n 'astc-5x4-unorm': {f: texture_compression_astc},\n 'astc-5x4-unorm-srgb': {f: texture_compression_astc},\n 'astc-5x5-unorm': {f: texture_compression_astc},\n 'astc-5x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-6x5-unorm': {f: texture_compression_astc},\n 'astc-6x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-6x6-unorm': {f: texture_compression_astc},\n 'astc-6x6-unorm-srgb': {f: texture_compression_astc},\n 'astc-8x5-unorm': {f: texture_compression_astc},\n 'astc-8x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-8x6-unorm': {f: texture_compression_astc},\n 'astc-8x6-unorm-srgb': {f: texture_compression_astc},\n 'astc-8x8-unorm': {f: texture_compression_astc},\n 'astc-8x8-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x5-unorm': {f: texture_compression_astc},\n 'astc-10x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x6-unorm': {f: texture_compression_astc},\n 'astc-10x6-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x8-unorm': {f: texture_compression_astc},\n 'astc-10x8-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x10-unorm': {f: texture_compression_astc},\n 'astc-10x10-unorm-srgb': {f: texture_compression_astc},\n 'astc-12x10-unorm': {f: texture_compression_astc},\n 'astc-12x10-unorm-srgb': {f: texture_compression_astc},\n 'astc-12x12-unorm': {f: texture_compression_astc},\n 'astc-12x12-unorm-srgb': {f: texture_compression_astc},\n\n // WEBGL_compressed_texture_pvrtc\n\n 'pvrtc-rgb4unorm-webgl': {f: texture_compression_pvrtc_webgl},\n 'pvrtc-rgba4unorm-webgl': {f: texture_compression_pvrtc_webgl},\n 'pvrtc-rgb2unorm-webgl': {f: texture_compression_pvrtc_webgl},\n 'pvrtc-rgba2unorm-webgl': {f: texture_compression_pvrtc_webgl},\n\n // WEBGL_compressed_texture_etc1\n\n 'etc1-rbg-unorm-webgl': {f: texture_compression_etc1_webgl},\n\n // WEBGL_compressed_texture_atc\n\n 'atc-rgb-unorm-webgl': {f: texture_compression_atc_webgl},\n 'atc-rgba-unorm-webgl': {f: texture_compression_atc_webgl},\n 'atc-rgbai-unorm-webgl': {f: texture_compression_atc_webgl}\n};\n\nexport const TEXTURE_FORMAT_TABLE: Readonly<Record<TextureFormat, TextureFormatDefinition>> = {\n ...TEXTURE_FORMAT_COLOR_DEPTH_TABLE,\n ...TEXTURE_FORMAT_COMPRESSED_TABLE\n};\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NormalizedDataType} from '../data-types/data-types';\nimport {dataTypeDecoder} from '../data-types/data-type-decoder';\nimport type {\n TextureFormat,\n TextureFormatCompressed,\n TextureFormatInfo,\n TextureFormatCapabilities,\n TextureFormatColor,\n TextureMemoryLayout,\n TextureFormatDepthStencil\n} from './texture-formats';\nimport {getTextureFormatDefinition} from './texture-format-table';\n\nconst RGB_FORMAT_REGEX = /^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/;\nconst COLOR_FORMAT_PREFIXES = ['rgb', 'rgba', 'bgra'];\nconst DEPTH_FORMAT_PREFIXES = ['depth', 'stencil'];\n// prettier-ignore\nconst COMPRESSED_TEXTURE_FORMAT_PREFIXES = [\n 'bc1', 'bc2', 'bc3', 'bc4', 'bc5', 'bc6', 'bc7', 'etc1', 'etc2', 'eac', 'atc', 'astc', 'pvrtc'\n];\n\n// HELPERS - MEMORY LAYOUT\n\n/** Options to calculate a texture layout */\nexport type TextureMemoryLayoutOptions = {\n /** Number of bytes per pixel */\n format: TextureFormat;\n /** Width of the texture in pixels */\n width: number;\n /** Height of the texture in pixels */\n height: number;\n /** Number of images in the texture */\n depth: number;\n /** Alignment of each row */\n byteAlignment: number;\n};\n\n/** Class that helps applications work with texture formats */\nexport class TextureFormatDecoder {\n /** Checks if a texture format is color */\n isColor(format: TextureFormat): format is TextureFormatColor {\n return COLOR_FORMAT_PREFIXES.some(prefix => format.startsWith(prefix));\n }\n\n /** Checks if a texture format is depth or stencil */\n isDepthStencil(format: TextureFormat): format is TextureFormatDepthStencil {\n return DEPTH_FORMAT_PREFIXES.some(prefix => format.startsWith(prefix));\n }\n\n /** Checks if a texture format is compressed */\n isCompressed(format: TextureFormat): format is TextureFormatCompressed {\n return COMPRESSED_TEXTURE_FORMAT_PREFIXES.some(prefix => format.startsWith(prefix));\n }\n\n /** Returns information about a texture format, e.g. attachment type, components, byte length and flags (integer, signed, normalized) */\n getInfo(format: TextureFormat): TextureFormatInfo {\n return getTextureFormatInfo(format);\n }\n\n /** \"static\" capabilities of a texture format. @note Needs to be adjusted against current device */\n getCapabilities(format: TextureFormat): TextureFormatCapabilities {\n return getTextureFormatCapabilities(format);\n }\n\n /** Computes the memory layout for a texture, in particular including row byte alignment */\n computeMemoryLayout(opts: TextureMemoryLayoutOptions): TextureMemoryLayout {\n return computeTextureMemoryLayout(opts);\n }\n}\n\n/** Decoder for luma.gl texture types */\nexport const textureFormatDecoder = new TextureFormatDecoder();\n\n// HELPERS - MEMORY LAYOUT\n\n/** Get the memory layout of a texture */\nfunction computeTextureMemoryLayout({\n format,\n width,\n height,\n depth,\n byteAlignment\n}: TextureMemoryLayoutOptions): TextureMemoryLayout {\n const formatInfo = textureFormatDecoder.getInfo(format);\n const {\n bytesPerPixel,\n bytesPerBlock = bytesPerPixel,\n blockWidth = 1,\n blockHeight = 1,\n compressed = false\n } = formatInfo;\n const blockColumns = compressed ? Math.ceil(width / blockWidth) : width;\n const blockRows = compressed ? Math.ceil(height / blockHeight) : height;\n // byteAlignment comes from the backend/call site. WebGPU buffer copies use 256, queue.writeTexture uses 1.\n const unpaddedBytesPerRow = blockColumns * bytesPerBlock;\n const bytesPerRow = Math.ceil(unpaddedBytesPerRow / byteAlignment) * byteAlignment;\n const rowsPerImage = blockRows;\n const byteLength = bytesPerRow * rowsPerImage * depth;\n\n return {\n bytesPerPixel,\n bytesPerRow,\n rowsPerImage,\n depthOrArrayLayers: depth,\n bytesPerImage: bytesPerRow * rowsPerImage,\n byteLength\n };\n}\n\n// HELPERS - CAPABILITIES\n\nfunction getTextureFormatCapabilities(format: TextureFormat): TextureFormatCapabilities {\n const info = getTextureFormatDefinition(format);\n\n const formatCapabilities: Required<TextureFormatCapabilities> = {\n format,\n create: info.f ?? true,\n render: info.render ?? true,\n filter: info.filter ?? true,\n blend: info.blend ?? true,\n store: info.store ?? true\n };\n\n const formatInfo = getTextureFormatInfo(format);\n const isDepthStencil = format.startsWith('depth') || format.startsWith('stencil');\n const isSigned = formatInfo?.signed;\n const isInteger = formatInfo?.integer;\n const isWebGLSpecific = formatInfo?.webgl;\n const isCompressed = Boolean(formatInfo?.compressed);\n\n // Only uncompressed color formats can be used as color-renderable attachments.\n formatCapabilities.render &&= !isDepthStencil && !isCompressed;\n // signed and integer formats are not filterable\n formatCapabilities.filter &&= !isDepthStencil && !isSigned && !isInteger && !isWebGLSpecific;\n\n return formatCapabilities;\n}\n\n// HELPER - FORMAT INFO\n\n/**\n * Decodes a texture format, returning e.g. attatchment type, components, byte length and flags (integer, signed, normalized)\n */\nexport function getTextureFormatInfo(format: TextureFormat): TextureFormatInfo {\n let formatInfo: TextureFormatInfo = getTextureFormatInfoUsingTable(format);\n\n if (textureFormatDecoder.isCompressed(format)) {\n formatInfo.channels = 'rgb';\n formatInfo.components = 3;\n formatInfo.bytesPerPixel = 1;\n formatInfo.srgb = false;\n formatInfo.compressed = true;\n formatInfo.bytesPerBlock = getCompressedTextureBlockByteLength(format);\n\n const blockSize = getCompressedTextureBlockSize(format);\n if (blockSize) {\n formatInfo.blockWidth = blockSize.blockWidth;\n formatInfo.blockHeight = blockSize.blockHeight;\n }\n }\n\n // Fill in missing information that can be derived from the format string\n const matches = !formatInfo.packed ? RGB_FORMAT_REGEX.exec(format as string) : null;\n if (matches) {\n const [, channels, length, type, srgb, suffix] = matches;\n const dataType = `${type}${length}` as NormalizedDataType;\n const decodedType = dataTypeDecoder.getDataTypeInfo(dataType);\n const bits = decodedType.byteLength * 8;\n const components = (channels?.length ?? 1) as 1 | 2 | 3 | 4;\n const bitsPerChannel: [number, number, number, number] = [\n bits,\n components >= 2 ? bits : 0,\n components >= 3 ? bits : 0,\n components >= 4 ? bits : 0\n ];\n\n formatInfo = {\n format,\n attachment: formatInfo.attachment,\n dataType: decodedType.signedType,\n components,\n channels: channels as 'r' | 'rg' | 'rgb' | 'rgba',\n integer: decodedType.integer,\n signed: decodedType.signed,\n normalized: decodedType.normalized,\n bitsPerChannel,\n bytesPerPixel: decodedType.byteLength * components,\n packed: formatInfo.packed,\n srgb: formatInfo.srgb\n };\n\n if (suffix === '-webgl') {\n formatInfo.webgl = true;\n }\n // dataType - overwritten by decodedType\n if (srgb === '-srgb') {\n formatInfo.srgb = true;\n }\n }\n\n if (format.endsWith('-webgl')) {\n formatInfo.webgl = true;\n }\n if (format.endsWith('-srgb')) {\n formatInfo.srgb = true;\n }\n\n return formatInfo;\n}\n\n/** Decode texture format info from the table */\nfunction getTextureFormatInfoUsingTable(format: TextureFormat): TextureFormatInfo {\n const info = getTextureFormatDefinition(format);\n\n const bytesPerPixel = info.bytesPerPixel || 1;\n const bitsPerChannel = info.bitsPerChannel || [8, 8, 8, 8];\n delete info.bitsPerChannel;\n delete info.bytesPerPixel;\n delete info.f;\n delete info.render;\n delete info.filter;\n delete info.blend;\n delete info.store;\n\n const formatInfo: TextureFormatInfo = {\n ...info,\n format,\n attachment: info.attachment || 'color',\n channels: info.channels || 'r',\n components: (info.components || info.channels?.length || 1) as 1 | 2 | 3 | 4,\n bytesPerPixel,\n bitsPerChannel,\n dataType: info.dataType || 'uint8',\n srgb: info.srgb ?? false,\n packed: info.packed ?? false,\n webgl: info.webgl ?? false,\n integer: info.integer ?? false,\n signed: info.signed ?? false,\n normalized: info.normalized ?? false,\n compressed: info.compressed ?? false\n };\n\n return formatInfo;\n}\n\n/** Parses ASTC block widths from format string */\nfunction getCompressedTextureBlockSize(\n format: TextureFormatCompressed\n): {blockWidth: number; blockHeight: number} | null {\n const REGEX = /.*-(\\d+)x(\\d+)-.*/;\n const matches = REGEX.exec(format as string);\n if (matches) {\n const [, blockWidth, blockHeight] = matches;\n return {blockWidth: Number(blockWidth), blockHeight: Number(blockHeight)};\n }\n\n if (\n format.startsWith('bc') ||\n format.startsWith('etc1') ||\n format.startsWith('etc2') ||\n format.startsWith('eac') ||\n format.startsWith('atc')\n ) {\n return {blockWidth: 4, blockHeight: 4};\n }\n\n if (format.startsWith('pvrtc-rgb4') || format.startsWith('pvrtc-rgba4')) {\n return {blockWidth: 4, blockHeight: 4};\n }\n\n if (format.startsWith('pvrtc-rgb2') || format.startsWith('pvrtc-rgba2')) {\n return {blockWidth: 8, blockHeight: 4};\n }\n\n return null;\n}\n\nfunction getCompressedTextureBlockByteLength(format: TextureFormatCompressed): number {\n if (\n format.startsWith('bc1') ||\n format.startsWith('bc4') ||\n format.startsWith('etc1') ||\n format.startsWith('etc2-rgb8') ||\n format.startsWith('etc2-rgb8a1') ||\n format.startsWith('eac-r11') ||\n format === 'atc-rgb-unorm-webgl'\n ) {\n return 8;\n }\n\n if (\n format.startsWith('bc2') ||\n format.startsWith('bc3') ||\n format.startsWith('bc5') ||\n format.startsWith('bc6h') ||\n format.startsWith('bc7') ||\n format.startsWith('etc2-rgba8') ||\n format.startsWith('eac-rg11') ||\n format.startsWith('astc') ||\n format === 'atc-rgba-unorm-webgl' ||\n format === 'atc-rgbai-unorm-webgl'\n ) {\n return 16;\n }\n\n if (format.startsWith('pvrtc')) {\n return 8;\n }\n\n return 16;\n}\n\n/*\n'r8unorm':\t{s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n'r8snorm':\t{s: \"float\"}, // \t\t\u2713\t\t},\n'r8uint':\t{s: \"uint\"}, // \t\u2713\t\u2713\t\t},\n'r8sint':\t{s: \"sint\"}, // \t\u2713\t\u2713\t\t},\n'rg8unorm':\t{s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n'rg8snorm':\t{s: \"float\"}, // \t\t\u2713\t\t},\n'rg8uint':\t{s: \"uint\"}, // \t\u2713\t\u2713\t\t},\n'rg8sint':\t{s: \"sint\"}, // \t\u2713\t\u2713\t\t},\n'rgba8unorm':\t{s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t\u2713},\n'rgba8unorm-srgb': {s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n'rgba8snorm':\t{s: \"float\"}, // \t\t\u2713\t\t\u2713},\n'rgba8uint':\t{s: \"uint\"}, // \t\u2713\t\u2713\t\t\u2713},\n'rgba8sint':\t{s: \"sint\"}, // \t\u2713\t\u2713\t\t\u2713},\n'bgra8unorm':\t{s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n'bgra8unorm-srgb': {s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n// 16-bit per component\t\t\t\t\t\n'r16uint': {s: \"uint\"}, // \t\u2713\t\u2713\t\t},\n'r16sint': {s: \"sint\"}, // \t\u2713\t\u2713\t\t},\n'r16float': {s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n'rg16uint': {s: \"uint\"}, // \t\u2713\t\u2713\t\t},\n'rg16sint': {s: \"sint\"}, // \t\u2713\t\u2713\t\t},\n'rg16float': {s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n'rgba16uint': {s: \"uint\"}, // \t\u2713\t\u2713\t\t\u2713},\n'rgba16sint': {s: \"sint\"}, // \t\u2713\t\u2713\t\t\u2713},\n'rgba16float': {s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t\u2713},\n// 32-bit per component\t\t\t\t\t\n'r32uint': {s: \"uint\"}, // \t\u2713\t\t\t\u2713},\n'r32sint': {s: \"sint\"}, // \t\u2713\t\t\t\u2713},\n'r32float': {\"unfilterable-float\"\t\u2713\t\u2713\t\t\u2713},\n'rg32uint': {s: \"uint\"}, // \t\u2713\t\t\t\u2713},\n'rg32sint': {s: \"sint\"}, // \t\u2713\t\t\t\u2713},\n'rg32float': {\"unfilterable-float\"\t\u2713\t\t\t\u2713},\n'rgba32uint': {s: \"uint\"}, // \t\u2713\t\t\t\u2713},\n'rgba32sint': {s: \"sint\"}, // \t\u2713\t\t\t\u2713},\n'rgba32float': {\"unfilterable-float\"\t\u2713\t\t\t\u2713},\n// mixed component width\t\t\t\t\t\n'rgb10a2unorm': {s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t}\n'rg11b10ufloat': {s: \"float\"}, // \t\t\u2713\t\t}\n// Format\tBytes per texel\tAspect\tGPUTextureSampleType\tValid image copy source\tValid image copy destination\n'stencil8': {1 \u2212 4\tstencil\t\"uint\"\t\u2713}\n'depth16unorm': {2\tdepth\t\"depth\"\t\u2713}\n'depth24plus': {4\tdepth\t\"depth\"\t\u2717}\n'depth24plus': {stencil8\t4 \u2212 8\tdepth\t\"depth\"\t\u2717}\n'stencil': {s: \"uint\"}, // \t\u2713}\n'depth32float': {4\tdepth\t\"depth\"\t\u2713\t\u2717}\n'depth24unorm': {stencil8\t4\tdepth\t\"depth\"\t\u2717}\n'stencil': {s: \"uint\"}, // \t\u2713}\n'depth32float': {stencil8}\n\n// Format\tBytes per block\tGPUTextureSampleType\tBlock Size\tFeature\n'rgb9e5ufloat': {c: 4, s: \"float\",\tbpp: 4/(1*1)},\n\n'bc1-rgba-unorm': {c: 4. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc1-rgba-unorm-srgb': {c: 4. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc2-rgba-unorm': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc2-rgba-unorm-srgb': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc3-rgba-unorm': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc3-rgba-unorm-srgb': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc4-r-unorm': {c: 1. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc4-r-snorm': {c: 1. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc5-rg-unorm': {c: 2. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc5-rg-snorm': { },\n'bc6h-rgb-ufloat': {\t16 },\n'bc6h-rgb-float': { },\n'bc7-rgba-unorm': {\t16 },\n'bc7-rgba-unorm-srgb': { },\n\n'etc2-rgb8unorm': {\t8\t\"float\"\t4 \u00D7 4\ttexture-compression-etc2 },\n'etc2-rgb8unorm-srgb': { },\n'etc2-rgb8a1unorm': {\t8 },\n'etc2-rgb8a1unorm-srgb': { },\n'etc2-rgba8unorm': {\t16 },\n'etc2-rgba8unorm-srgb': { },\n\n'eac-r11unorm': {\t8 },\n'eac-r11snorm': { },\n'eac-rg11unorm': {\t16 },\n'eac-rg11snorm': { },\n\n'astc-4x4-unorm': {\t16\t\"float\"\t4 \u00D7 4\ttexture-compression-astc },\n'astc-4x4-unorm-srgb': { },\n'astc-5x4-unorm': {\t16\t5 \u00D7 4 },\n'astc-5x4-unorm-srgb': { },\n'astc-5x5-unorm': {\t16\t5 \u00D7 5 },\n'astc-5x5-unorm-srgb': { },\n'astc-6x5-unorm': {\t16\t6 \u00D7 5 },\n'astc-6x5-unorm-srgb': { },\n'astc-6x6-unorm': {\t16\t6 \u00D7 6 },\n'astc-6x6-unorm-srgb': { },\n'astc-8x5-unorm': {\t16\t8 \u00D7 5 },\n'astc-8x5-unorm-srgb': { },\n'astc-8x6-unorm': {\t16\t8 \u00D7 6 },\n'astc-8x6-unorm-srgb': { },\n'astc-8x8-unorm': {\t16\t8 \u00D7 8 },\n'astc-8x8-unorm-srgb': { },\n'astc-10x5-unorm': {\t16\t10 \u00D7 5 },\n'astc-10x5-unorm-srgb': { },\n'astc-10x6-unorm': {\t16\t10 \u00D7 6 },\n'astc-10x6-unorm-srgb': { },\n'astc-10x8-unorm': {\t16\t10 \u00D7 8 },\n'astc-10x8-unorm-srgb': { },\n'astc-10x10-unorm': {\t16\t10 \u00D7 10 },\n'astc-10x10-unorm-srgb': { },\n'astc-12x10-unorm': {\t16\t12 \u00D7 10 },\n'astc-12x10-unorm-srgb': { },\n'astc-12x12-unorm': {\t16 },\n*/\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Built-in data types that can be used to initialize textures\n * @note ImageData can be used for contiguous 8 bit data via Uint8ClampedArray\n */\nexport type ExternalImage =\n | ImageBitmap\n | ImageData\n | HTMLImageElement\n | HTMLVideoElement\n | VideoFrame\n | HTMLCanvasElement\n | OffscreenCanvas;\n\n/** Check if data is an external image */\nexport function isExternalImage(data: unknown): data is ExternalImage {\n return (\n (typeof ImageData !== 'undefined' && data instanceof ImageData) ||\n (typeof ImageBitmap !== 'undefined' && data instanceof ImageBitmap) ||\n (typeof HTMLImageElement !== 'undefined' && data instanceof HTMLImageElement) ||\n (typeof HTMLVideoElement !== 'undefined' && data instanceof HTMLVideoElement) ||\n (typeof VideoFrame !== 'undefined' && data instanceof VideoFrame) ||\n (typeof HTMLCanvasElement !== 'undefined' && data instanceof HTMLCanvasElement) ||\n (typeof OffscreenCanvas !== 'undefined' && data instanceof OffscreenCanvas)\n );\n}\n\n/** Determine size (width and height) of provided image data */\nexport function getExternalImageSize(data: ExternalImage): {width: number; height: number} {\n if (\n (typeof ImageData !== 'undefined' && data instanceof ImageData) ||\n (typeof ImageBitmap !== 'undefined' && data instanceof ImageBitmap) ||\n (typeof HTMLCanvasElement !== 'undefined' && data instanceof HTMLCanvasElement) ||\n (typeof OffscreenCanvas !== 'undefined' && data instanceof OffscreenCanvas)\n ) {\n return {width: data.width, height: data.height};\n }\n if (typeof HTMLImageElement !== 'undefined' && data instanceof HTMLImageElement) {\n return {width: data.naturalWidth, height: data.naturalHeight};\n }\n if (typeof HTMLVideoElement !== 'undefined' && data instanceof HTMLVideoElement) {\n return {width: data.videoWidth, height: data.videoHeight};\n }\n if (typeof VideoFrame !== 'undefined' && data instanceof VideoFrame) {\n // TODO: is this the right choice for width and height?\n return {width: data.displayWidth, height: data.displayHeight};\n }\n throw new Error('Unknown image type');\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {StatsManager, lumaStats} from '../utils/stats-manager';\nimport {log} from '../utils/log';\nimport {uid} from '../utils/uid';\nimport type {VertexFormat, VertexFormatInfo} from '../shadertypes/vertex-types/vertex-formats';\nimport type {\n TextureFormat,\n TextureFormatInfo,\n CompressedTextureFormat\n} from '../shadertypes/texture-types/texture-formats';\nimport type {CanvasContext, CanvasContextProps} from './canvas-context';\nimport type {PresentationContext, PresentationContextProps} from './presentation-context';\nimport type {BufferProps} from './resources/buffer';\nimport {Buffer} from './resources/buffer';\nimport type {RenderPipeline, RenderPipelineProps} from './resources/render-pipeline';\nimport type {SharedRenderPipeline} from './resources/shared-render-pipeline';\nimport type {ComputePipeline, ComputePipelineProps} from './resources/compute-pipeline';\nimport type {Sampler, SamplerProps} from './resources/sampler';\nimport type {Shader, ShaderProps} from './resources/shader';\nimport type {Texture, TextureProps} from './resources/texture';\nimport type {ExternalTexture, ExternalTextureProps} from './resources/external-texture';\nimport type {Framebuffer, FramebufferProps} from './resources/framebuffer';\nimport type {RenderPass, RenderPassProps} from './resources/render-pass';\nimport type {ComputePass, ComputePassProps} from './resources/compute-pass';\nimport type {CommandEncoder, CommandEncoderProps} from './resources/command-encoder';\nimport type {CommandBuffer} from './resources/command-buffer';\nimport type {VertexArray, VertexArrayProps} from './resources/vertex-array';\nimport type {TransformFeedback, TransformFeedbackProps} from './resources/transform-feedback';\nimport type {QuerySet, QuerySetProps} from './resources/query-set';\nimport type {Fence} from './resources/fence';\nimport type {Bindings, ComputeShaderLayout, ShaderLayout} from './types/shader-layout';\n\nimport {vertexFormatDecoder} from '../shadertypes/vertex-types/vertex-format-decoder';\nimport {textureFormatDecoder} from '../shadertypes/texture-types/texture-format-decoder';\nimport type {ExternalImage} from '../shadertypes/image-types/image-types';\nimport {isExternalImage, getExternalImageSize} from '../shadertypes/image-types/image-types';\nimport {getTextureFormatTable} from '../shadertypes/texture-types/texture-format-table';\n\n/**\n * Identifies the GPU vendor and driver.\n * @note Chrome WebGPU does not provide much information, though more can be enabled with\n * @see https://developer.chrome.com/blog/new-in-webgpu-120#adapter_information_updates\n * chrome://flags/#enable-webgpu-developer-features\n */\nexport type DeviceInfo = {\n /** Type of device */\n type: 'webgl' | 'webgpu' | 'null' | 'unknown';\n /** Vendor (name of GPU vendor, Apple, nVidia etc */\n vendor: string;\n /** Renderer (usually driver name) */\n renderer: string;\n /** version of driver */\n version: string;\n /** family of GPU */\n gpu: 'nvidia' | 'amd' | 'intel' | 'apple' | 'software' | 'unknown';\n /** Type of GPU () */\n gpuType: 'discrete' | 'integrated' | 'cpu' | 'unknown';\n /** GPU architecture */\n gpuArchitecture?: string; // 'common-3' on Apple\n /** GPU driver backend. Can sometimes be sniffed */\n gpuBackend?: 'opengl' | 'opengles' | 'metal' | 'd3d11' | 'd3d12' | 'vulkan' | 'unknown';\n /** If this is a fallback adapter */\n fallback?: boolean;\n /** Shader language supported by device.createShader() */\n shadingLanguage: 'wgsl' | 'glsl';\n /** Highest supported shader language version: GLSL 3.00 = 300, WGSL 1.00 = 100 */\n shadingLanguageVersion: number;\n};\n\n/** Limits for a device (max supported sizes of resources, max number of bindings etc) */\nexport abstract class DeviceLimits {\n /** max number of TextureDimension1D */\n abstract maxTextureDimension1D: number;\n /** max number of TextureDimension2D */\n abstract maxTextureDimension2D: number;\n /** max number of TextureDimension3D */\n abstract maxTextureDimension3D: number;\n /** max number of TextureArrayLayers */\n abstract maxTextureArrayLayers: number;\n /** max number of BindGroups */\n abstract maxBindGroups: number;\n /** max number of DynamicUniformBuffers per PipelineLayout */\n abstract maxDynamicUniformBuffersPerPipelineLayout: number;\n /** max number of DynamicStorageBuffers per PipelineLayout */\n abstract maxDynamicStorageBuffersPerPipelineLayout: number;\n /** max number of SampledTextures per ShaderStage */\n abstract maxSampledTexturesPerShaderStage: number;\n /** max number of Samplers per ShaderStage */\n abstract maxSamplersPerShaderStage: number;\n /** max number of StorageBuffers per ShaderStage */\n abstract maxStorageBuffersPerShaderStage: number;\n /** max number of StorageTextures per ShaderStage */\n abstract maxStorageTexturesPerShaderStage: number;\n /** max number of UniformBuffers per ShaderStage */\n abstract maxUniformBuffersPerShaderStage: number;\n /** max number of UniformBufferBindingSize */\n abstract maxUniformBufferBindingSize: number;\n /** max number of StorageBufferBindingSize */\n abstract maxStorageBufferBindingSize: number;\n /** min UniformBufferOffsetAlignment */\n abstract minUniformBufferOffsetAlignment: number;\n /** min StorageBufferOffsetAlignment */\n abstract minStorageBufferOffsetAlignment: number;\n /** max number of VertexBuffers */\n abstract maxVertexBuffers: number;\n /** max number of VertexAttributes */\n abstract maxVertexAttributes: number;\n /** max number of VertexBufferArrayStride */\n abstract maxVertexBufferArrayStride: number;\n /** max number of InterStageShaderComponents */\n abstract maxInterStageShaderVariables: number;\n /** max number of ComputeWorkgroupStorageSize */\n abstract maxComputeWorkgroupStorageSize: number;\n /** max number of ComputeInvocations per Workgroup */\n abstract maxComputeInvocationsPerWorkgroup: number;\n /** max ComputeWorkgroupSizeX */\n abstract maxComputeWorkgroupSizeX: number;\n /** max ComputeWorkgroupSizeY */\n abstract maxComputeWorkgroupSizeY: number;\n /** max ComputeWorkgroupSizeZ */\n abstract maxComputeWorkgroupSizeZ: number;\n /** max ComputeWorkgroupsPerDimension */\n abstract maxComputeWorkgroupsPerDimension: number;\n}\n\nfunction formatErrorLogArguments(context: unknown, args: unknown[]): unknown[] {\n const formattedContext = formatErrorLogValue(context);\n const formattedArgs = args.map(formatErrorLogValue).filter(arg => arg !== undefined);\n return [formattedContext, ...formattedArgs].filter(arg => arg !== undefined);\n}\n\nfunction formatErrorLogValue(value: unknown): unknown {\n if (value === undefined) {\n return undefined;\n }\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return value;\n }\n if (value instanceof Error) {\n return value.message;\n }\n if (Array.isArray(value)) {\n return value.map(formatErrorLogValue);\n }\n if (typeof value === 'object') {\n if (hasCustomToString(value)) {\n const stringValue = String(value);\n if (stringValue !== '[object Object]') {\n return stringValue;\n }\n }\n\n if (looksLikeGPUCompilationMessage(value)) {\n return formatGPUCompilationMessage(value);\n }\n\n return value.constructor?.name || 'Object';\n }\n\n return String(value);\n}\n\nfunction hasCustomToString(value: object): boolean {\n return (\n 'toString' in value &&\n typeof value.toString === 'function' &&\n value.toString !== Object.prototype.toString\n );\n}\n\nfunction looksLikeGPUCompilationMessage(value: object): value is {\n message?: unknown;\n type?: unknown;\n lineNum?: unknown;\n linePos?: unknown;\n} {\n return 'message' in value && 'type' in value;\n}\n\nfunction formatGPUCompilationMessage(value: {\n message?: unknown;\n type?: unknown;\n lineNum?: unknown;\n linePos?: unknown;\n}): string {\n const type = typeof value.type === 'string' ? value.type : 'message';\n const message = typeof value.message === 'string' ? value.message : '';\n const lineNum = typeof value.lineNum === 'number' ? value.lineNum : null;\n const linePos = typeof value.linePos === 'number' ? value.linePos : null;\n const location =\n lineNum !== null && linePos !== null\n ? ` @ ${lineNum}:${linePos}`\n : lineNum !== null\n ? ` @ ${lineNum}`\n : '';\n return `${type}${location}: ${message}`.trim();\n}\n\n/** Set-like class for features (lets apps check for WebGL / WebGPU extensions) */\nexport class DeviceFeatures {\n protected features: Set<DeviceFeature>;\n protected disabledFeatures?: Partial<Record<DeviceFeature, boolean>>;\n\n constructor(\n features: DeviceFeature[] = [],\n disabledFeatures: Partial<Record<DeviceFeature, boolean>>\n ) {\n this.features = new Set<DeviceFeature>(features);\n this.disabledFeatures = disabledFeatures || {};\n }\n\n *[Symbol.iterator](): IterableIterator<DeviceFeature> {\n yield* this.features;\n }\n\n has(feature: DeviceFeature): boolean {\n return !this.disabledFeatures?.[feature] && this.features.has(feature);\n }\n}\n\n/** Device feature names */\nexport type DeviceFeature =\n | WebGPUDeviceFeature\n | WebGLDeviceFeature\n | WebGLCompressedTextureFeatures;\n// | ChromeExperimentalFeatures\n\n/** Chrome-specific extensions. Expected to eventually become standard features. */\n// export type ChromeExperimentalFeatures = ;\n\nexport type WebGPUDeviceFeature =\n | 'depth-clip-control'\n | 'depth32float-stencil8'\n | 'texture-compression-bc'\n | 'texture-compression-bc-sliced-3d'\n | 'texture-compression-etc2'\n | 'texture-compression-astc'\n | 'texture-compression-astc-sliced-3d'\n | 'timestamp-query'\n | 'indirect-first-instance'\n | 'shader-f16'\n | 'rg11b10ufloat-renderable' // Is the rg11b10ufloat texture format renderable?\n | 'bgra8unorm-storage' // Can the bgra8unorm texture format be used in storage buffers?\n | 'float32-filterable' // Is the float32 format filterable?\n | 'float32-blendable' // Is the float32 format blendable?\n | 'clip-distances'\n | 'dual-source-blending'\n | 'subgroups';\n// | 'depth-clamping' // removed from the WebGPU spec...\n// | 'pipeline-statistics-query' // removed from the WebGPU spec...\n\nexport type WebGLDeviceFeature =\n // webgl extension features\n | 'compilation-status-async-webgl' // Non-blocking shader compile/link status query available\n | 'provoking-vertex-webgl' // parameters.provokingVertex\n | 'polygon-mode-webgl' // parameters.polygonMode and parameters.polygonOffsetLine\n\n // GLSL extension features\n | 'shader-noperspective-interpolation-webgl' // Vertex outputs & fragment inputs can have a `noperspective` interpolation qualifier.\n | 'shader-conservative-depth-webgl' // GLSL `gl_FragDepth` qualifiers `depth_unchanged` etc can enable early depth test\n | 'shader-clip-cull-distance-webgl' // Makes gl_ClipDistance and gl_CullDistance available in shaders\n\n // texture rendering\n | 'float32-renderable-webgl'\n | 'float16-renderable-webgl'\n | 'rgb9e5ufloat-renderable-webgl'\n | 'snorm8-renderable-webgl'\n | 'norm16-webgl'\n | 'norm16-renderable-webgl'\n | 'snorm16-renderable-webgl'\n\n // texture filtering\n | 'float16-filterable-webgl'\n | 'texture-filterable-anisotropic-webgl'\n\n // texture storage bindings\n | 'bgra8unorm-storage'\n\n // texture blending\n | 'texture-blend-float-webgl';\n\ntype WebGLCompressedTextureFeatures =\n | 'texture-compression-bc5-webgl'\n | 'texture-compression-bc7-webgl'\n | 'texture-compression-etc1-webgl'\n | 'texture-compression-pvrtc-webgl'\n | 'texture-compression-atc-webgl';\n\n/** Texture format capabilities that have been checked against a specific device */\nexport type DeviceTextureFormatCapabilities = {\n format: TextureFormat;\n /** Can the format be created and sampled?*/\n create: boolean;\n /** Is the format renderable. */\n render: boolean;\n /** Is the format filterable. */\n filter: boolean;\n /** Is the format blendable. */\n blend: boolean;\n /** Is the format storeable. */\n store: boolean;\n};\n\n/** Device properties */\nexport type DeviceProps = {\n /** string id for debugging. Stored on the object, used in logging and set on underlying GPU objects when feasible. */\n id?: string;\n /** Properties for creating a default canvas context */\n createCanvasContext?: CanvasContextProps | true;\n /** Control which type of GPU is preferred on systems with both integrated and discrete GPU. Defaults to \"high-performance\" / discrete GPU. */\n powerPreference?: 'default' | 'high-performance' | 'low-power';\n /** Hints that device creation should fail if no hardware GPU is available (if the system performance is \"low\"). */\n failIfMajorPerformanceCaveat?: boolean;\n\n /** WebGL specific: Properties passed through to WebGL2RenderingContext creation: `canvas.getContext('webgl2', props.webgl)` */\n webgl?: WebGLContextProps;\n\n // CALLBACKS\n\n /** Error handler. If it returns a probe logger style function, it will be called at the site of the error to optimize console error links. */\n onError?: (error: Error, context?: unknown) => unknown;\n /** Called when the size of a CanvasContext's canvas changes */\n onResize?: (\n ctx: CanvasContext | PresentationContext,\n info: {oldPixelSize: [number, number]}\n ) => unknown;\n /** Called when the absolute position of a CanvasContext's canvas changes. Must set `CanvasContextProps.trackPosition: true` */\n onPositionChange?: (\n ctx: CanvasContext | PresentationContext,\n info: {oldPosition: [number, number]}\n ) => unknown;\n /** Called when the visibility of a CanvasContext's canvas changes */\n onVisibilityChange?: (ctx: CanvasContext | PresentationContext) => unknown;\n /** Called when the device pixel ratio of a CanvasContext's canvas changes */\n onDevicePixelRatioChange?: (\n ctx: CanvasContext | PresentationContext,\n info: {oldRatio: number}\n ) => unknown;\n\n // DEBUG SETTINGS\n\n /** Turn on implementation defined checks that slow down execution but help break where errors occur */\n debug?: boolean;\n /** Enable GPU timestamp collection without enabling all debug validation paths. */\n debugGPUTime?: boolean;\n /** Show shader source in browser? The default is `'error'`, meaning that logs are shown when shader compilation has errors */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n /** Renders a small version of updated Framebuffers into the primary canvas context. Can be set in console luma.log.set('debug-framebuffers', true) */\n debugFramebuffers?: boolean;\n /** Traces resource caching, reuse, and destroys in the PipelineFactory */\n debugFactories?: boolean;\n /** WebGL specific - Trace WebGL calls (instruments WebGL2RenderingContext at the expense of performance). Can be set in console luma.log.set('debug-webgl', true) */\n debugWebGL?: boolean;\n /** WebGL specific - Initialize the SpectorJS WebGL debugger. Can be set in console luma.log.set('debug-spectorjs', true) */\n debugSpectorJS?: boolean;\n /** WebGL specific - SpectorJS URL. Override if CDN is down or different SpectorJS version is desired. */\n debugSpectorJSUrl?: string;\n\n // EXPERIMENTAL SETTINGS - subject to change\n\n /** adapter.create() returns the existing Device if the provided canvas' WebGL context is already associated with a Device. */\n _reuseDevices?: boolean;\n /** WebGPU specific - Request a Device with the highest limits supported by platform. On WebGPU devices can be created with minimal limits. */\n _requestMaxLimits?: boolean;\n /** Disable specific features */\n _disabledFeatures?: Partial<Record<DeviceFeature, boolean>>;\n /** WebGL specific - Initialize all features on startup */\n _initializeFeatures?: boolean;\n /** Enable shader caching (via ShaderFactory) */\n _cacheShaders?: boolean;\n /**\n * Destroy cached shaders when they become unused.\n * Defaults to `false` so repeated create/destroy cycles can still reuse cached shaders.\n * Enable this if the application creates very large numbers of distinct shaders and needs cache eviction.\n */\n _destroyShaders?: boolean;\n /** Enable pipeline caching (via PipelineFactory) */\n _cachePipelines?: boolean;\n /** Enable sharing of backend render-pipeline implementations when caching is enabled. Currently used by WebGL. */\n _sharePipelines?: boolean;\n /**\n * Destroy cached pipelines when they become unused.\n * Defaults to `false` so repeated create/destroy cycles can still reuse cached pipelines.\n * Enable this if the application creates very large numbers of distinct pipelines and needs cache eviction.\n */\n _destroyPipelines?: boolean;\n\n /** @deprecated Internal, Do not use directly! Use `luma.attachDevice()` to attach to pre-created contexts/devices. */\n _handle?: unknown; // WebGL2RenderingContext | GPUDevice | null;\n};\n\ntype DeviceFactories = {\n bindGroupFactory?: unknown;\n};\n\n/** WebGL independent copy of WebGLContextAttributes */\ntype WebGLContextProps = {\n /** indicates if the canvas contains an alpha buffer. */\n alpha?: boolean;\n /** hints the user agent to reduce the latency by desynchronizing the canvas paint cycle from the event loop */\n desynchronized?: boolean;\n /** indicates whether or not to perform anti-aliasing. */\n antialias?: boolean;\n /** indicates that the render target has a stencil buffer of at least `8` bits. */\n stencil?: boolean;\n /** indicates that the drawing buffer has a depth buffer of at least 16 bits. */\n depth?: boolean;\n /** indicates if a context will be created if the system performance is low or if no hardware GPU is available. */\n failIfMajorPerformanceCaveat?: boolean;\n /** Selects GPU */\n powerPreference?: 'default' | 'high-performance' | 'low-power';\n /** page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. */\n premultipliedAlpha?: boolean;\n /** buffers will not be cleared and will preserve their values until cleared or overwritten by the author. */\n preserveDrawingBuffer?: boolean;\n};\n\n/**\n * Create and attach devices for a specific backend. Currently static methods on each device\n */\nexport interface DeviceFactory {\n // new (props: DeviceProps): Device; Constructor isn't used\n type: string;\n isSupported(): boolean;\n create(props: DeviceProps): Promise<Device>;\n attach?(handle: unknown): Device;\n}\n\n/**\n * WebGPU Device/WebGL context abstraction\n */\nexport abstract class Device {\n static defaultProps: Required<DeviceProps> = {\n id: null!,\n powerPreference: 'high-performance',\n failIfMajorPerformanceCaveat: false,\n createCanvasContext: undefined!,\n // WebGL specific\n webgl: {},\n\n // Callbacks\n // eslint-disable-next-line handle-callback-err\n onError: (error: Error, context: unknown) => {},\n onResize: (context: CanvasContext, info: {oldPixelSize: [number, number]}) => {\n const [width, height] = context.getDevicePixelSize();\n log.log(1, `${context} resized => ${width}x${height}px`)();\n },\n onPositionChange: (context: CanvasContext, info: {oldPosition: [number, number]}) => {\n const [left, top] = context.getPosition();\n log.log(1, `${context} repositioned => ${left},${top}`)();\n },\n onVisibilityChange: (context: CanvasContext) =>\n log.log(1, `${context} Visibility changed ${context.isVisible}`)(),\n onDevicePixelRatioChange: (context: CanvasContext, info: {oldRatio: number}) =>\n log.log(1, `${context} DPR changed ${info.oldRatio} => ${context.devicePixelRatio}`)(),\n\n // Debug flags\n debug: getDefaultDebugValue(),\n debugGPUTime: false,\n debugShaders: log.get('debug-shaders') || undefined!,\n debugFramebuffers: Boolean(log.get('debug-framebuffers')),\n debugFactories: Boolean(log.get('debug-factories')),\n debugWebGL: Boolean(log.get('debug-webgl')),\n debugSpectorJS: undefined!, // Note: log setting is queried by the spector.js code\n debugSpectorJSUrl: undefined!,\n\n // Experimental\n _reuseDevices: false,\n _requestMaxLimits: true,\n _cacheShaders: true,\n _destroyShaders: false,\n _cachePipelines: true,\n _sharePipelines: true,\n _destroyPipelines: false,\n // TODO - Change these after confirming things work as expected\n _initializeFeatures: true,\n _disabledFeatures: {\n 'compilation-status-async-webgl': true\n },\n\n // INTERNAL\n _handle: undefined!\n };\n\n get [Symbol.toStringTag](): string {\n return 'Device';\n }\n\n toString(): string {\n return `Device(${this.id})`;\n }\n\n /** id of this device, primarily for debugging */\n readonly id: string;\n /** type of this device */\n abstract readonly type: 'webgl' | 'webgpu' | 'null' | 'unknown';\n abstract readonly handle: unknown;\n abstract commandEncoder: CommandEncoder;\n\n /** A copy of the device props */\n readonly props: Required<DeviceProps>;\n /** Available for the application to store data on the device */\n userData: {[key: string]: unknown} = {};\n /** stats */\n readonly statsManager: StatsManager = lumaStats;\n /** Internal per-device factory storage */\n _factories: DeviceFactories = {};\n /** An abstract timestamp used for change tracking */\n timestamp: number = 0;\n\n /** True if this device has been reused during device creation (app has multiple references) */\n _reused: boolean = false;\n /** Used by other luma.gl modules to store data on the device */\n private _moduleData: Record<string, Record<string, unknown>> = {};\n\n // Capabilities\n\n /** Information about the device (vendor, versions etc) */\n abstract info: DeviceInfo;\n /** Optional capability discovery */\n abstract features: DeviceFeatures;\n /** WebGPU style device limits */\n abstract get limits(): DeviceLimits;\n\n // Texture helpers\n\n /** Optimal TextureFormat for displaying 8-bit depth, standard dynamic range content on this system. */\n abstract preferredColorFormat: 'rgba8unorm' | 'bgra8unorm';\n /** Default depth format used on this system */\n abstract preferredDepthFormat: 'depth16' | 'depth24plus' | 'depth32float';\n\n protected _textureCaps: Partial<Record<TextureFormat, DeviceTextureFormatCapabilities>> = {};\n /** Internal timestamp query set used when GPU timing collection is enabled for this device. */\n protected _debugGPUTimeQuery: QuerySet | null = null;\n\n constructor(props: DeviceProps) {\n this.props = {...Device.defaultProps, ...props};\n this.id = this.props.id || uid(this[Symbol.toStringTag].toLowerCase());\n }\n\n abstract destroy(): void;\n\n // TODO - just expose the shadertypes decoders?\n\n getVertexFormatInfo(format: VertexFormat): VertexFormatInfo {\n return vertexFormatDecoder.getVertexFormatInfo(format);\n }\n\n isVertexFormatSupported(format: VertexFormat): boolean {\n return true;\n }\n\n /** Returns information about a texture format, such as data type, channels, bits per channel, compression etc */\n getTextureFormatInfo(format: TextureFormat): TextureFormatInfo {\n return textureFormatDecoder.getInfo(format);\n }\n\n /** Determines what operations are supported on a texture format on this particular device (checks against supported device features) */\n getTextureFormatCapabilities(format: TextureFormat): DeviceTextureFormatCapabilities {\n let textureCaps = this._textureCaps[format];\n if (!textureCaps) {\n const capabilities = this._getDeviceTextureFormatCapabilities(format);\n textureCaps = this._getDeviceSpecificTextureFormatCapabilities(capabilities);\n this._textureCaps[format] = textureCaps;\n }\n return textureCaps;\n }\n\n /** Calculates the number of mip levels for a texture of width, height and in case of 3d textures only, depth */\n getMipLevelCount(width: number, height: number, depth3d: number = 1): number {\n const maxSize = Math.max(width, height, depth3d);\n return 1 + Math.floor(Math.log2(maxSize));\n }\n\n /** Check if data is an external image */\n isExternalImage(data: unknown): data is ExternalImage {\n return isExternalImage(data);\n }\n\n /** Get the size of an external image */\n getExternalImageSize(data: ExternalImage): {width: number; height: number} {\n return getExternalImageSize(data);\n }\n\n /** Check if device supports a specific texture format (creation and `nearest` sampling) */\n isTextureFormatSupported(format: TextureFormat): boolean {\n return this.getTextureFormatCapabilities(format).create;\n }\n\n /** Check if linear filtering (sampler interpolation) is supported for a specific texture format */\n isTextureFormatFilterable(format: TextureFormat): boolean {\n return this.getTextureFormatCapabilities(format).filter;\n }\n\n /** Check if device supports rendering to a framebuffer color attachment of a specific texture format */\n isTextureFormatRenderable(format: TextureFormat): boolean {\n return this.getTextureFormatCapabilities(format).render;\n }\n\n /** Check if a specific texture format is GPU compressed */\n isTextureFormatCompressed(format: TextureFormat): boolean {\n return textureFormatDecoder.isCompressed(format);\n }\n\n /** Returns the compressed texture formats that can be created and sampled on this device */\n getSupportedCompressedTextureFormats(): CompressedTextureFormat[] {\n const supportedFormats: CompressedTextureFormat[] = [];\n\n for (const format of Object.keys(getTextureFormatTable()) as TextureFormat[]) {\n if (this.isTextureFormatCompressed(format) && this.isTextureFormatSupported(format)) {\n supportedFormats.push(format as CompressedTextureFormat);\n }\n }\n\n return supportedFormats;\n }\n\n // DEBUG METHODS\n\n pushDebugGroup(groupLabel: string): void {\n this.commandEncoder.pushDebugGroup(groupLabel);\n }\n\n popDebugGroup(): void {\n this.commandEncoder?.popDebugGroup();\n }\n\n insertDebugMarker(markerLabel: string): void {\n this.commandEncoder?.insertDebugMarker(markerLabel);\n }\n\n // Device loss\n\n /** `true` if device is already lost */\n abstract get isLost(): boolean;\n\n /** Promise that resolves when device is lost */\n abstract readonly lost: Promise<{reason: 'destroyed'; message: string}>;\n\n /**\n * Trigger device loss.\n * @returns `true` if context loss could actually be triggered.\n * @note primarily intended for testing how application reacts to device loss\n */\n loseDevice(): boolean {\n return false;\n }\n\n /** A monotonic counter for tracking buffer and texture updates */\n incrementTimestamp(): number {\n return this.timestamp++;\n }\n\n /**\n * Reports Device errors in a way that optimizes for developer experience / debugging.\n * - Logs so that the console error links directly to the source code that generated the error.\n * - Includes the object that reported the error in the log message, even if the error is asynchronous.\n *\n * Conventions when calling reportError():\n * - Always call the returned function - to ensure error is logged, at the error site\n * - Follow with a call to device.debug() - to ensure that the debugger breaks at the error site\n *\n * @param error - the error to report. If needed, just create a new Error object with the appropriate message.\n * @param context - pass `this` as context, otherwise it may not be available in the debugger for async errors.\n * @returns the logger function returned by device.props.onError() so that it can be called from the error site.\n *\n * @example\n * device.reportError(new Error(...), this)();\n * device.debug();\n */\n reportError(error: Error, context: unknown, ...args: unknown[]): () => unknown {\n // Call the error handler\n const isHandled = this.props.onError(error, context);\n if (!isHandled) {\n const logArguments = formatErrorLogArguments(context, args);\n // Note: Returns a function that must be called: `device.reportError(...)()`\n return log.error(\n this.type === 'webgl' ? '%cWebGL' : '%cWebGPU',\n 'color: white; background: red; padding: 2px 6px; border-radius: 3px;',\n error.message,\n ...logArguments\n );\n }\n return () => {};\n }\n\n /** Break in the debugger - if device.props.debug is true */\n debug(): void {\n if (this.props.debug) {\n // @ts-ignore\n debugger; // eslint-disable-line\n } else {\n // TODO(ibgreen): Does not appear to be printed in the console\n const message = `\\\n'Type luma.log.set({debug: true}) in console to enable debug breakpoints',\nor create a device with the 'debug: true' prop.`;\n log.once(0, message)();\n }\n }\n\n // Canvas context\n\n /** Default / primary canvas context. Can be null as WebGPU devices can be created without a CanvasContext */\n abstract canvasContext: CanvasContext | null;\n\n /** Returns the default / primary canvas context. Throws an error if no canvas context is available (a WebGPU compute device) */\n getDefaultCanvasContext(): CanvasContext {\n if (!this.canvasContext) {\n throw new Error('Device has no default CanvasContext. See props.createCanvasContext');\n }\n return this.canvasContext;\n }\n\n /** Creates a new CanvasContext (WebGPU only) */\n abstract createCanvasContext(props?: CanvasContextProps): CanvasContext;\n\n /** Creates a presentation context for a destination canvas. WebGL requires the default canvas context to use an OffscreenCanvas. */\n abstract createPresentationContext(props?: PresentationContextProps): PresentationContext;\n\n /** Call after rendering a frame (necessary e.g. on WebGL OffscreenCanvas) */\n abstract submit(commandBuffer?: CommandBuffer): void;\n\n // Resource creation\n\n /** Create a buffer */\n abstract createBuffer(props: BufferProps | ArrayBuffer | ArrayBufferView): Buffer;\n\n /** Create a texture */\n abstract createTexture(props: TextureProps): Texture;\n\n /** Create a temporary texture view of a video source */\n abstract createExternalTexture(props: ExternalTextureProps): ExternalTexture;\n\n /** Create a sampler */\n abstract createSampler(props: SamplerProps): Sampler;\n\n /** Create a Framebuffer. Must have at least one attachment. */\n abstract createFramebuffer(props: FramebufferProps): Framebuffer;\n\n /** Create a shader */\n abstract createShader(props: ShaderProps): Shader;\n\n /** Create a render pipeline (aka program) */\n abstract createRenderPipeline(props: RenderPipelineProps): RenderPipeline;\n\n /** Create a compute pipeline (aka program). WebGPU only. */\n abstract createComputePipeline(props: ComputePipelineProps): ComputePipeline;\n\n /** Create a vertex array */\n abstract createVertexArray(props: VertexArrayProps): VertexArray;\n\n abstract createCommandEncoder(props?: CommandEncoderProps): CommandEncoder;\n\n /** Create a transform feedback (immutable set of output buffer bindings). WebGL only. */\n abstract createTransformFeedback(props: TransformFeedbackProps): TransformFeedback;\n\n abstract createQuerySet(props: QuerySetProps): QuerySet;\n\n /** Create a fence sync object */\n createFence(): Fence {\n throw new Error('createFence() not implemented');\n }\n\n /** Create a RenderPass using the default CommandEncoder */\n beginRenderPass(props?: RenderPassProps): RenderPass {\n return this.commandEncoder.beginRenderPass(props);\n }\n\n /** Create a ComputePass using the default CommandEncoder*/\n beginComputePass(props?: ComputePassProps): ComputePass {\n return this.commandEncoder.beginComputePass(props);\n }\n\n /**\n * Generate mipmaps for a WebGPU texture.\n * WebGPU textures must be created up front with the required mip count, usage flags, and a format that supports the chosen generation path.\n * WebGL uses `Texture.generateMipmapsWebGL()` directly because the backend manages mip generation on the texture object itself.\n */\n generateMipmapsWebGPU(_texture: Texture): void {\n throw new Error('not implemented');\n }\n\n /** Internal helper for creating a shareable WebGL render-pipeline implementation. */\n _createSharedRenderPipelineWebGL(_props: RenderPipelineProps): SharedRenderPipeline {\n throw new Error('_createSharedRenderPipelineWebGL() not implemented');\n }\n\n /** Internal WebGPU-only helper for retrieving the native bind-group layout for a pipeline group. */\n _createBindGroupLayoutWebGPU(\n _pipeline: RenderPipeline | ComputePipeline,\n _group: number\n ): unknown {\n throw new Error('_createBindGroupLayoutWebGPU() not implemented');\n }\n\n /** Internal WebGPU-only helper for creating a native bind group. */\n _createBindGroupWebGPU(\n _bindGroupLayout: unknown,\n _shaderLayout: ShaderLayout | ComputeShaderLayout,\n _bindings: Bindings,\n _group: number\n ): unknown {\n throw new Error('_createBindGroupWebGPU() not implemented');\n }\n\n /**\n * Internal helper that returns `true` when timestamp-query GPU timing should be\n * collected for this device.\n */\n _supportsDebugGPUTime(): boolean {\n return (\n this.features.has('timestamp-query') && Boolean(this.props.debug || this.props.debugGPUTime)\n );\n }\n\n /**\n * Internal helper that enables device-managed GPU timing collection on the\n * default command encoder. Reuses the existing query set if timing is already enabled.\n *\n * @param queryCount - Number of timestamp slots reserved for profiled passes.\n * @returns The device-managed timestamp QuerySet, or `null` when timing is not supported or could not be enabled.\n */\n _enableDebugGPUTime(queryCount: number = 256): QuerySet | null {\n if (!this._supportsDebugGPUTime()) {\n return null;\n }\n\n if (this._debugGPUTimeQuery) {\n return this._debugGPUTimeQuery;\n }\n\n try {\n this._debugGPUTimeQuery = this.createQuerySet({type: 'timestamp', count: queryCount});\n this.commandEncoder = this.createCommandEncoder({\n id: this.commandEncoder.props.id,\n timeProfilingQuerySet: this._debugGPUTimeQuery\n });\n } catch {\n this._debugGPUTimeQuery = null;\n }\n\n return this._debugGPUTimeQuery;\n }\n\n /**\n * Internal helper that disables device-managed GPU timing collection and restores\n * the default command encoder to an unprofiled state.\n */\n _disableDebugGPUTime(): void {\n if (!this._debugGPUTimeQuery) {\n return;\n }\n\n if (this.commandEncoder.getTimeProfilingQuerySet() === this._debugGPUTimeQuery) {\n this.commandEncoder = this.createCommandEncoder({\n id: this.commandEncoder.props.id\n });\n }\n\n this._debugGPUTimeQuery.destroy();\n this._debugGPUTimeQuery = null;\n }\n\n /** Internal helper that returns `true` when device-managed GPU timing is currently active. */\n _isDebugGPUTimeEnabled(): boolean {\n return this._debugGPUTimeQuery !== null;\n }\n\n /**\n * Determines what operations are supported on a texture format, checking against supported device features\n * Subclasses override to apply additional checks\n */\n protected abstract _getDeviceSpecificTextureFormatCapabilities(\n format: DeviceTextureFormatCapabilities\n ): DeviceTextureFormatCapabilities;\n\n // DEPRECATED METHODS\n\n /** @deprecated Use getDefaultCanvasContext() */\n getCanvasContext(): CanvasContext {\n return this.getDefaultCanvasContext();\n }\n\n // WebGL specific HACKS - enables app to remove webgl import\n // Use until we have a better way to handle these\n\n /** @deprecated - will be removed - should use command encoder */\n readPixelsToArrayWebGL(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n sourceAttachment?: number;\n target?: Uint8Array | Uint16Array | Float32Array;\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n ): Uint8Array | Uint16Array | Float32Array {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use command encoder */\n readPixelsToBufferWebGL(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n target?: Buffer; // A new Buffer object is created when not provided.\n targetByteOffset?: number; // byte offset in buffer object\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n ): Buffer {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */\n setParametersWebGL(parameters: any): void {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */\n getParametersWebGL(parameters: any): void {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */\n withParametersWebGL(parameters: any, func: any): any {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use clear arguments in RenderPass */\n clearWebGL(options?: {framebuffer?: Framebuffer; color?: any; depth?: any; stencil?: any}): void {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use for debugging only */\n resetWebGL(): void {\n throw new Error('not implemented');\n }\n\n // INTERNAL LUMA.GL METHODS\n\n getModuleData<ModuleDataT extends Record<string, unknown>>(moduleName: string): ModuleDataT {\n this._moduleData[moduleName] ||= {};\n return this._moduleData[moduleName] as ModuleDataT;\n }\n\n // INTERNAL HELPERS\n\n // IMPLEMENTATION\n\n /** Helper to get the canvas context props */\n static _getCanvasContextProps(props: DeviceProps): CanvasContextProps | undefined {\n return props.createCanvasContext === true ? {} : props.createCanvasContext;\n }\n\n protected _getDeviceTextureFormatCapabilities(\n format: TextureFormat\n ): DeviceTextureFormatCapabilities {\n const genericCapabilities = textureFormatDecoder.getCapabilities(format);\n\n // Check standard features\n const checkFeature = (feature: DeviceFeature | boolean | undefined) =>\n (typeof feature === 'string' ? this.features.has(feature) : feature) ?? true;\n\n const supported = checkFeature(genericCapabilities.create);\n return {\n format,\n create: supported,\n render: supported && checkFeature(genericCapabilities.render),\n filter: supported && checkFeature(genericCapabilities.filter),\n blend: supported && checkFeature(genericCapabilities.blend),\n store: supported && checkFeature(genericCapabilities.store)\n } as const satisfies DeviceTextureFormatCapabilities;\n }\n\n /** Subclasses use this to support .createBuffer() overloads */\n protected _normalizeBufferProps(props: BufferProps | ArrayBuffer | ArrayBufferView): BufferProps {\n if (props instanceof ArrayBuffer || ArrayBuffer.isView(props)) {\n props = {data: props};\n }\n\n // TODO(ibgreen) - fragile, as this is done before we merge with default options\n // inside the Buffer constructor\n\n const newProps = {...props};\n // Deduce indexType\n const usage = props.usage || 0;\n if (usage & Buffer.INDEX) {\n if (!props.indexType) {\n if (props.data instanceof Uint32Array) {\n newProps.indexType = 'uint32';\n } else if (props.data instanceof Uint16Array) {\n newProps.indexType = 'uint16';\n } else if (props.data instanceof Uint8Array) {\n // Convert uint8 to uint16 for WebGPU compatibility (WebGPU doesn't support uint8 indices)\n newProps.data = new Uint16Array(props.data);\n newProps.indexType = 'uint16';\n }\n }\n if (!newProps.indexType) {\n throw new Error('indices buffer content must be of type uint16 or uint32');\n }\n }\n\n return newProps;\n }\n}\n\n/**\n * Internal helper for resolving the default `debug` prop.\n * Precedence is: explicit log debug value first, then `NODE_ENV`, then `false`.\n */\nexport function _getDefaultDebugValue(logDebugValue: unknown, nodeEnv?: string): boolean {\n if (logDebugValue !== undefined && logDebugValue !== null) {\n return Boolean(logDebugValue);\n }\n\n if (nodeEnv !== undefined) {\n return nodeEnv !== 'production';\n }\n\n return false;\n}\n\nfunction getDefaultDebugValue(): boolean {\n return _getDefaultDebugValue(log.get('debug'), getNodeEnv());\n}\n\nfunction getNodeEnv(): string | undefined {\n const processObject = (\n globalThis as typeof globalThis & {\n process?: {env?: Record<string, string | undefined>};\n }\n ).process;\n if (!processObject?.env) {\n return undefined;\n }\n\n return processObject.env['NODE_ENV'];\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Log} from '@probe.gl/log';\nimport type {DeviceProps} from './device';\nimport {Device} from './device';\nimport {Adapter} from './adapter';\nimport {StatsManager, lumaStats} from '../utils/stats-manager';\nimport {log} from '../utils/log';\n\ndeclare global {\n // eslint-disable-next-line no-var\n var luma: Luma;\n}\n\nconst STARTUP_MESSAGE = 'set luma.log.level=1 (or higher) to trace rendering';\n\nconst ERROR_MESSAGE =\n 'No matching device found. Ensure `@luma.gl/webgl` and/or `@luma.gl/webgpu` modules are imported.';\n\n/** Properties for creating a new device */\nexport type CreateDeviceProps = {\n /** Selects the type of device. `best-available` uses webgpu if available, then webgl. */\n type?: 'webgl' | 'webgpu' | 'null' | 'unknown' | 'best-available';\n /** List of adapters. Will also search any pre-registered adapters */\n adapters?: Adapter[];\n /**\n * Whether to wait for page to be loaded so that CanvasContext's can access the DOM.\n * The browser only supports one 'load' event listener so it may be necessary for the application to set this to false to avoid conflicts.\n */\n waitForPageLoad?: boolean;\n} & DeviceProps;\n\n/** Properties for attaching an existing WebGL context or WebGPU device to a new luma Device */\nexport type AttachDeviceProps = {\n /** List of adapters. Will also search any pre-registered adapters */\n adapters?: Adapter[];\n} & DeviceProps;\n\n/**\n * Entry point to the luma.gl GPU abstraction\n * Register WebGPU and/or WebGL adapters (controls application bundle size)\n * Run-time selection of the first available Device\n */\nexport class Luma {\n static defaultProps: Required<CreateDeviceProps> = {\n ...Device.defaultProps,\n type: 'best-available',\n adapters: undefined!,\n waitForPageLoad: true\n };\n\n /** Global stats for all devices */\n readonly stats: StatsManager = lumaStats;\n\n /**\n * Global log\n *\n * Assign luma.log.level in console to control logging: \\\n * 0: none, 1: minimal, 2: verbose, 3: attribute/uniforms, 4: gl logs\n * luma.log.break[], set to gl funcs, luma.log.profile[] set to model names`;\n */\n readonly log: Log = log;\n\n /** Version of luma.gl */\n readonly VERSION: string =\n // Version detection using build plugin\n // @ts-expect-error no-undef\n typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'running from source';\n\n spector: unknown;\n\n protected preregisteredAdapters = new Map<string, Adapter>();\n\n constructor() {\n if (globalThis.luma) {\n if (globalThis.luma.VERSION !== this.VERSION) {\n log.error(`Found luma.gl ${globalThis.luma.VERSION} while initialzing ${this.VERSION}`)();\n log.error(`'yarn why @luma.gl/core' can help identify the source of the conflict`)();\n throw new Error(`luma.gl - multiple versions detected: see console log`);\n }\n\n log.error('This version of luma.gl has already been initialized')();\n }\n\n log.log(1, `${this.VERSION} - ${STARTUP_MESSAGE}`)();\n\n globalThis.luma = this;\n }\n\n /** Creates a device. Asynchronously. */\n async createDevice(props_: CreateDeviceProps = {}): Promise<Device> {\n const props: Required<CreateDeviceProps> = {...Luma.defaultProps, ...props_};\n\n const adapter = this.selectAdapter(props.type, props.adapters);\n if (!adapter) {\n throw new Error(ERROR_MESSAGE);\n }\n\n // Wait for page to load so that CanvasContext's can access the DOM.\n if (props.waitForPageLoad) {\n await adapter.pageLoaded;\n }\n\n return await adapter.create(props);\n }\n\n /**\n * Attach to an existing GPU API handle (WebGL2RenderingContext or GPUDevice).\n * @param handle Externally created WebGL context or WebGPU device\n */\n async attachDevice(handle: unknown, props: AttachDeviceProps): Promise<Device> {\n const type = this._getTypeFromHandle(handle, props.adapters);\n\n const adapter = type && this.selectAdapter(type, props.adapters);\n if (!adapter) {\n throw new Error(ERROR_MESSAGE);\n }\n\n return await adapter?.attach?.(handle, props);\n }\n\n /**\n * Global adapter registration.\n * @deprecated Use props.adapters instead\n */\n registerAdapters(adapters: Adapter[]): void {\n for (const deviceClass of adapters) {\n this.preregisteredAdapters.set(deviceClass.type, deviceClass);\n }\n }\n\n /** Get type strings for supported Devices */\n getSupportedAdapters(adapters: Adapter[] = []): string[] {\n const adapterMap = this._getAdapterMap(adapters);\n return Array.from(adapterMap)\n .map(([, adapter]) => adapter)\n .filter(adapter => adapter.isSupported?.())\n .map(adapter => adapter.type);\n }\n\n /** Get type strings for best available Device */\n getBestAvailableAdapterType(adapters: Adapter[] = []): 'webgpu' | 'webgl' | 'null' | null {\n const KNOWN_ADAPTERS: ('webgpu' | 'webgl' | 'null')[] = ['webgpu', 'webgl', 'null'];\n const adapterMap = this._getAdapterMap(adapters);\n for (const type of KNOWN_ADAPTERS) {\n if (adapterMap.get(type)?.isSupported?.()) {\n return type;\n }\n }\n return null;\n }\n\n /** Select adapter of type from registered adapters */\n selectAdapter(type: string, adapters: Adapter[] = []): Adapter | null {\n let selectedType: string | null = type;\n if (type === 'best-available') {\n selectedType = this.getBestAvailableAdapterType(adapters);\n }\n\n const adapterMap = this._getAdapterMap(adapters);\n return (selectedType && adapterMap.get(selectedType)) || null;\n }\n\n /**\n * Override `HTMLCanvasContext.getCanvas()` to always create WebGL2 contexts with additional WebGL1 compatibility.\n * Useful when attaching luma to a context from an external library does not support creating WebGL2 contexts.\n */\n enforceWebGL2(enforce: boolean = true, adapters: Adapter[] = []): void {\n const adapterMap = this._getAdapterMap(adapters);\n const webgl2Adapter = adapterMap.get('webgl');\n if (!webgl2Adapter) {\n log.warn('enforceWebGL2: webgl adapter not found')();\n }\n (webgl2Adapter as any)?.enforceWebGL2?.(enforce);\n }\n\n // DEPRECATED\n\n /** @deprecated */\n setDefaultDeviceProps(props: CreateDeviceProps): void {\n Object.assign(Luma.defaultProps, props);\n }\n\n // HELPERS\n\n /** Convert a list of adapters to a map */\n protected _getAdapterMap(adapters: Adapter[] = []): Map<string, Adapter> {\n const map = new Map(this.preregisteredAdapters);\n for (const adapter of adapters) {\n map.set(adapter.type, adapter);\n }\n return map;\n }\n\n /** Get type of a handle (for attachDevice) */\n protected _getTypeFromHandle(\n handle: unknown,\n adapters: Adapter[] = []\n ): 'webgpu' | 'webgl' | 'null' | null {\n // TODO - delegate handle identification to adapters\n\n // WebGL\n if (handle instanceof WebGL2RenderingContext) {\n return 'webgl';\n }\n\n if (typeof GPUDevice !== 'undefined' && handle instanceof GPUDevice) {\n return 'webgpu';\n }\n\n // TODO - WebGPU does not yet seem to have a stable in-browser API, so we \"sniff\" for members instead\n if ((handle as any)?.queue) {\n return 'webgpu';\n }\n\n // null\n if (handle === null) {\n return 'null';\n }\n\n if (handle instanceof WebGLRenderingContext) {\n log.warn('WebGL1 is not supported', handle)();\n } else {\n log.warn('Unknown handle type', handle)();\n }\n\n return null;\n }\n}\n\n/**\n * Entry point to the luma.gl GPU abstraction\n * Register WebGPU and/or WebGL adapters (controls application bundle size)\n * Run-time selection of the first available Device\n */\nexport const luma = new Luma();\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isBrowser} from '@probe.gl/env';\nimport {Device, DeviceProps} from './device';\n\n/**\n * Create and attach devices for a specific backend.\n */\nexport abstract class Adapter {\n // new (props: DeviceProps): Device; Constructor isn't used\n abstract type: string;\n /** Check if this backend is supported */\n abstract isSupported(): boolean;\n /** Check if the given handle is a valid device handle for this backend */\n abstract isDeviceHandle(handle: unknown): boolean;\n /** Create a new device for this backend */\n abstract create(props: DeviceProps): Promise<Device>;\n /** Attach a Device to a valid handle for this backend (GPUDevice, WebGL2RenderingContext etc) */\n abstract attach(handle: unknown, props: DeviceProps): Promise<Device>;\n\n /**\n * Page load promise\n * Resolves when the DOM is loaded.\n * @note Since are be limitations on number of `load` event listeners,\n * it is recommended avoid calling this accessor until actually needed.\n * I.e. we don't call it unless you know that you will be looking up a string in the DOM.\n */\n get pageLoaded(): Promise<void> {\n return getPageLoadPromise();\n }\n}\n\n// HELPER FUNCTIONS\n\nconst isPage: boolean = isBrowser() && typeof document !== 'undefined';\nconst isPageLoaded: () => boolean = () => isPage && document.readyState === 'complete';\nlet pageLoadPromise: Promise<void> | null = null;\n\n/** Returns a promise that resolves when the page is loaded */\nfunction getPageLoadPromise(): Promise<void> {\n if (!pageLoadPromise) {\n if (isPageLoaded() || typeof window === 'undefined') {\n pageLoadPromise = Promise.resolve();\n } else {\n pageLoadPromise = new Promise(resolve => window.addEventListener('load', () => resolve()));\n }\n }\n return pageLoadPromise;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isBrowser} from '@probe.gl/env';\nimport type {Device} from './device';\nimport type {CanvasContext} from './canvas-context';\nimport {CanvasObserver} from './canvas-observer';\nimport type {PresentationContext} from './presentation-context';\nimport type {Framebuffer} from './resources/framebuffer';\nimport type {TextureFormatDepthStencil} from '../shadertypes/texture-types/texture-formats';\nimport {uid} from '../utils/uid';\nimport {withResolvers} from '../utils/promise-utils';\nimport {assertDefined} from '../utils/assert';\n\n/** Properties for a CanvasContext */\nexport type CanvasContextProps = {\n /** Identifier, for debugging */\n id?: string;\n /** If a canvas not supplied, one will be created and added to the DOM. If a string, a canvas with that id will be looked up in the DOM */\n canvas?: HTMLCanvasElement | OffscreenCanvas | string | null;\n /** If new canvas is created, it will be created in the specified container, otherwise is appended as a child of document.body */\n container?: HTMLElement | string | null;\n /** Width in pixels of the canvas - used when creating a new canvas */\n width?: number;\n /** Height in pixels of the canvas - used when creating a new canvas */\n height?: number;\n /** Visibility (only used if new canvas is created). */\n visible?: boolean;\n /** Whether to size the drawing buffer to the pixel size during auto resize. If a number is provided it is used as a static pixel ratio */\n useDevicePixels?: boolean | number;\n /** Whether to track window resizes. */\n autoResize?: boolean;\n /** @see https://developer.mozilla.org/en-US/docs/Web/API/GPUCanvasContext/configure#alphamode */\n alphaMode?: 'opaque' | 'premultiplied';\n /** @see https://developer.mozilla.org/en-US/docs/Web/API/GPUCanvasContext/configure#colorspace */\n colorSpace?: 'srgb'; // GPUPredefinedColorSpace\n /** Whether to track position changes. Calls this.device.onPositionChange */\n trackPosition?: boolean;\n};\n\nexport type MutableCanvasContextProps = {\n /** Whether to size the drawing buffer to the pixel size during auto resize. If a number is provided it is used as a static pixel ratio */\n useDevicePixels?: boolean | number;\n};\n\n/**\n * Shared tracked-canvas lifecycle used by both renderable and presentation contexts.\n * - Creates a new canvas or looks up a canvas from the DOM\n * - Provides check for DOM loaded\n * @todo commit() @see https://github.com/w3ctag/design-reviews/issues/288\n * @todo transferControlToOffscreen: @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/transferControlToOffscreen\n */\nexport abstract class CanvasSurface {\n static isHTMLCanvas(canvas: unknown): canvas is HTMLCanvasElement {\n return typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement;\n }\n\n static isOffscreenCanvas(canvas: unknown): canvas is OffscreenCanvas {\n return typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas;\n }\n\n static defaultProps: Required<CanvasContextProps> = {\n id: undefined!,\n canvas: null,\n width: 800,\n height: 600,\n useDevicePixels: true,\n autoResize: true,\n container: null,\n visible: true,\n alphaMode: 'opaque',\n colorSpace: 'srgb',\n trackPosition: false\n };\n\n abstract readonly device: Device;\n abstract readonly handle: unknown;\n readonly id: string;\n\n readonly props: Required<CanvasContextProps>;\n readonly canvas: HTMLCanvasElement | OffscreenCanvas;\n /** Handle to HTML canvas */\n readonly htmlCanvas?: HTMLCanvasElement;\n /** Handle to wrapped OffScreenCanvas */\n readonly offscreenCanvas?: OffscreenCanvas;\n readonly type: 'html-canvas' | 'offscreen-canvas' | 'node';\n\n /** Promise that resolved once the resize observer has updated the pixel size */\n initialized: Promise<void>;\n isInitialized: boolean = false;\n\n /** Visibility is automatically updated (via an IntersectionObserver) */\n isVisible: boolean = true;\n\n /** Width of canvas in CSS units (tracked by a ResizeObserver) */\n cssWidth: number;\n /** Height of canvas in CSS units (tracked by a ResizeObserver) */\n cssHeight: number;\n\n /** Device pixel ratio. Automatically updated via media queries */\n devicePixelRatio: number;\n /** Exact width of canvas in physical pixels (tracked by a ResizeObserver) */\n devicePixelWidth: number;\n /** Exact height of canvas in physical pixels (tracked by a ResizeObserver) */\n devicePixelHeight: number;\n\n /** Width of drawing buffer: automatically tracks this.pixelWidth if props.autoResize is true */\n drawingBufferWidth: number;\n /** Height of drawing buffer: automatically tracks this.pixelHeight if props.autoResize is true */\n drawingBufferHeight: number;\n\n /** Resolves when the canvas is initialized, i.e. when the ResizeObserver has updated the pixel size */\n protected _initializedResolvers = withResolvers<void>();\n protected _canvasObserver: CanvasObserver;\n /** Position of the canvas in the document, updated by a timer */\n protected _position: [number, number] = [0, 0];\n /** Whether this canvas context has been destroyed */\n protected destroyed = false;\n /** Whether the drawing buffer size needs to be resized (deferred resizing to avoid flicker) */\n protected _needsDrawingBufferResize: boolean = true;\n\n abstract get [Symbol.toStringTag](): string;\n\n toString(): string {\n return `${this[Symbol.toStringTag]}(${this.id})`;\n }\n\n constructor(props?: CanvasContextProps) {\n this.props = {...CanvasSurface.defaultProps, ...props};\n props = this.props;\n\n this.initialized = this._initializedResolvers.promise;\n\n if (!isBrowser()) {\n this.canvas = {width: props.width || 1, height: props.height || 1} as OffscreenCanvas;\n } else if (!props.canvas) {\n this.canvas = createCanvasElement(props);\n } else if (typeof props.canvas === 'string') {\n this.canvas = getCanvasFromDOM(props.canvas);\n } else {\n this.canvas = props.canvas;\n }\n\n if (CanvasSurface.isHTMLCanvas(this.canvas)) {\n this.id = props.id || this.canvas.id;\n this.type = 'html-canvas';\n this.htmlCanvas = this.canvas;\n } else if (CanvasSurface.isOffscreenCanvas(this.canvas)) {\n this.id = props.id || 'offscreen-canvas';\n this.type = 'offscreen-canvas';\n this.offscreenCanvas = this.canvas;\n } else {\n this.id = props.id || 'node-canvas-context';\n this.type = 'node';\n }\n\n this.cssWidth = this.htmlCanvas?.clientWidth || this.canvas.width;\n this.cssHeight = this.htmlCanvas?.clientHeight || this.canvas.height;\n this.devicePixelWidth = this.canvas.width;\n this.devicePixelHeight = this.canvas.height;\n this.drawingBufferWidth = this.canvas.width;\n this.drawingBufferHeight = this.canvas.height;\n this.devicePixelRatio = globalThis.devicePixelRatio || 1;\n this._position = [0, 0];\n this._canvasObserver = new CanvasObserver({\n canvas: this.htmlCanvas,\n trackPosition: this.props.trackPosition,\n onResize: entries => this._handleResize(entries),\n onIntersection: entries => this._handleIntersection(entries),\n onDevicePixelRatioChange: () => this._observeDevicePixelRatio(),\n onPositionChange: () => this.updatePosition()\n });\n }\n\n destroy() {\n if (!this.destroyed) {\n this.destroyed = true;\n this._stopObservers();\n // @ts-expect-error Clear the device to make sure we don't access it after destruction.\n this.device = null;\n }\n }\n\n setProps(props: MutableCanvasContextProps): this {\n if ('useDevicePixels' in props) {\n this.props.useDevicePixels = props.useDevicePixels || false;\n this._updateDrawingBufferSize();\n }\n return this;\n }\n\n /** Returns a framebuffer with properly resized current 'swap chain' textures */\n getCurrentFramebuffer(options?: {\n depthStencilFormat?: TextureFormatDepthStencil | false;\n }): Framebuffer {\n this._resizeDrawingBufferIfNeeded();\n return this._getCurrentFramebuffer(options);\n }\n\n getCSSSize(): [number, number] {\n return [this.cssWidth, this.cssHeight];\n }\n\n getPosition() {\n return this._position;\n }\n\n getDevicePixelSize(): [number, number] {\n return [this.devicePixelWidth, this.devicePixelHeight];\n }\n\n getDrawingBufferSize(): [number, number] {\n return [this.drawingBufferWidth, this.drawingBufferHeight];\n }\n\n getMaxDrawingBufferSize(): [number, number] {\n const maxTextureDimension = this.device.limits.maxTextureDimension2D;\n return [maxTextureDimension, maxTextureDimension];\n }\n\n setDrawingBufferSize(width: number, height: number) {\n width = Math.floor(width);\n height = Math.floor(height);\n if (this.drawingBufferWidth === width && this.drawingBufferHeight === height) {\n return;\n }\n this.drawingBufferWidth = width;\n this.drawingBufferHeight = height;\n this._needsDrawingBufferResize = true;\n }\n\n getDevicePixelRatio(): number {\n const devicePixelRatio = typeof window !== 'undefined' && window.devicePixelRatio;\n return devicePixelRatio || 1;\n }\n\n cssToDevicePixels(\n cssPixel: [number, number],\n yInvert: boolean = true\n ): {\n x: number;\n y: number;\n width: number;\n height: number;\n } {\n const ratio = this.cssToDeviceRatio();\n const [width, height] = this.getDrawingBufferSize();\n return scalePixels(cssPixel, ratio, width, height, yInvert);\n }\n\n /** @deprecated - use .getDevicePixelSize() */\n getPixelSize() {\n return this.getDevicePixelSize();\n }\n\n /** @deprecated Use the current drawing buffer size for projection setup. */\n getAspect(): number {\n const [width, height] = this.getDrawingBufferSize();\n return width > 0 && height > 0 ? width / height : 1;\n }\n\n /** @deprecated Returns multiplier need to convert CSS size to Device size */\n cssToDeviceRatio(): number {\n try {\n const [drawingBufferWidth] = this.getDrawingBufferSize();\n const [cssWidth] = this.getCSSSize();\n return cssWidth ? drawingBufferWidth / cssWidth : 1;\n } catch {\n return 1;\n }\n }\n\n /** @deprecated Use canvasContext.setDrawingBufferSize() */\n resize(size: {width: number; height: number}): void {\n this.setDrawingBufferSize(size.width, size.height);\n }\n\n protected abstract _configureDevice(): void;\n\n protected abstract _getCurrentFramebuffer(options?: {\n depthStencilFormat?: TextureFormatDepthStencil | false;\n }): Framebuffer;\n\n protected _setAutoCreatedCanvasId(id: string) {\n if (this.htmlCanvas?.id === 'lumagl-auto-created-canvas') {\n this.htmlCanvas.id = id;\n }\n }\n\n /**\n * Starts DOM observation after the derived context and its device are fully initialized.\n *\n * `CanvasSurface` construction runs before subclasses can assign `this.device`, and the\n * default WebGL canvas context is created before `WebGLDevice` has initialized `limits`,\n * `features`, and the rest of its runtime state. Deferring observer startup avoids early\n * `ResizeObserver` and DPR callbacks running against a partially initialized device.\n */\n _startObservers(): void {\n if (this.destroyed) {\n return;\n }\n this._canvasObserver.start();\n }\n\n /**\n * Stops all DOM observation and timers associated with a canvas surface.\n *\n * This pairs with `_startObservers()` so teardown uses the same lifecycle whether a context is\n * explicitly destroyed, abandoned during device reuse, or temporarily has not started observing\n * yet. Centralizing shutdown here keeps resize/DPR/position watchers from surviving past the\n * lifetime of the owning device.\n */\n _stopObservers(): void {\n this._canvasObserver.stop();\n }\n\n protected _handleIntersection(entries: IntersectionObserverEntry[]) {\n if (this.destroyed) {\n return;\n }\n\n const entry = entries.find(entry_ => entry_.target === this.canvas);\n if (!entry) {\n return;\n }\n const isVisible = entry.isIntersecting;\n if (this.isVisible !== isVisible) {\n this.isVisible = isVisible;\n this.device.props.onVisibilityChange(this as CanvasContext | PresentationContext);\n }\n }\n\n protected _handleResize(entries: ResizeObserverEntry[]) {\n if (this.destroyed) {\n return;\n }\n\n const entry = entries.find(entry_ => entry_.target === this.canvas);\n if (!entry) {\n return;\n }\n\n const contentBoxSize = assertDefined(entry.contentBoxSize?.[0]);\n this.cssWidth = contentBoxSize.inlineSize;\n this.cssHeight = contentBoxSize.blockSize;\n\n const oldPixelSize = this.getDevicePixelSize();\n\n const devicePixelWidth =\n entry.devicePixelContentBoxSize?.[0]?.inlineSize ||\n contentBoxSize.inlineSize * devicePixelRatio;\n\n const devicePixelHeight =\n entry.devicePixelContentBoxSize?.[0]?.blockSize ||\n contentBoxSize.blockSize * devicePixelRatio;\n\n const [maxDevicePixelWidth, maxDevicePixelHeight] = this.getMaxDrawingBufferSize();\n this.devicePixelWidth = Math.max(1, Math.min(devicePixelWidth, maxDevicePixelWidth));\n this.devicePixelHeight = Math.max(1, Math.min(devicePixelHeight, maxDevicePixelHeight));\n\n this._updateDrawingBufferSize();\n\n this.device.props.onResize(this as CanvasContext | PresentationContext, {oldPixelSize});\n }\n\n protected _updateDrawingBufferSize() {\n if (this.props.autoResize) {\n if (typeof this.props.useDevicePixels === 'number') {\n const devicePixelRatio = this.props.useDevicePixels;\n this.setDrawingBufferSize(\n this.cssWidth * devicePixelRatio,\n this.cssHeight * devicePixelRatio\n );\n } else if (this.props.useDevicePixels) {\n this.setDrawingBufferSize(this.devicePixelWidth, this.devicePixelHeight);\n } else {\n this.setDrawingBufferSize(this.cssWidth, this.cssHeight);\n }\n }\n\n this._initializedResolvers.resolve();\n this.isInitialized = true;\n\n this.updatePosition();\n }\n\n _resizeDrawingBufferIfNeeded() {\n if (this._needsDrawingBufferResize) {\n this._needsDrawingBufferResize = false;\n const sizeChanged =\n this.drawingBufferWidth !== this.canvas.width ||\n this.drawingBufferHeight !== this.canvas.height;\n if (sizeChanged) {\n this.canvas.width = this.drawingBufferWidth;\n this.canvas.height = this.drawingBufferHeight;\n this._configureDevice();\n }\n }\n }\n\n _observeDevicePixelRatio() {\n if (this.destroyed || !this._canvasObserver.started) {\n return;\n }\n const oldRatio = this.devicePixelRatio;\n this.devicePixelRatio = window.devicePixelRatio;\n\n this.updatePosition();\n\n this.device.props.onDevicePixelRatioChange?.(this as CanvasContext | PresentationContext, {\n oldRatio\n });\n }\n\n updatePosition() {\n if (this.destroyed) {\n return;\n }\n const newRect = this.htmlCanvas?.getBoundingClientRect();\n if (newRect) {\n const position: [number, number] = [newRect.left, newRect.top];\n this._position ??= position;\n const positionChanged =\n position[0] !== this._position[0] || position[1] !== this._position[1];\n if (positionChanged) {\n const oldPosition = this._position;\n this._position = position;\n this.device.props.onPositionChange?.(this as CanvasContext | PresentationContext, {\n oldPosition\n });\n }\n }\n }\n}\n\nfunction getContainer(container: HTMLElement | string | null): HTMLElement {\n if (typeof container === 'string') {\n const element = document.getElementById(container);\n if (!element) {\n throw new Error(`${container} is not an HTML element`);\n }\n return element;\n }\n if (container) {\n return container;\n }\n return document.body;\n}\n\nfunction getCanvasFromDOM(canvasId: string): HTMLCanvasElement {\n const canvas = document.getElementById(canvasId);\n if (!CanvasSurface.isHTMLCanvas(canvas)) {\n throw new Error('Object is not a canvas element');\n }\n return canvas;\n}\n\nfunction createCanvasElement(props: CanvasContextProps) {\n const {width, height} = props;\n const newCanvas = document.createElement('canvas');\n newCanvas.id = uid('lumagl-auto-created-canvas');\n newCanvas.width = width || 1;\n newCanvas.height = height || 1;\n newCanvas.style.width = Number.isFinite(width) ? `${width}px` : '100%';\n newCanvas.style.height = Number.isFinite(height) ? `${height}px` : '100%';\n if (!props?.visible) {\n newCanvas.style.visibility = 'hidden';\n }\n const container = getContainer(props?.container || null);\n container.insertBefore(newCanvas, container.firstChild);\n\n return newCanvas;\n}\n\nfunction scalePixels(\n pixel: [number, number],\n ratio: number,\n width: number,\n height: number,\n yInvert: boolean\n): {\n x: number;\n y: number;\n width: number;\n height: number;\n} {\n const point = pixel;\n\n const x = scaleX(point[0], ratio, width);\n let y = scaleY(point[1], ratio, height, yInvert);\n\n let temporary = scaleX(point[0] + 1, ratio, width);\n const xHigh = temporary === width - 1 ? temporary : temporary - 1;\n\n temporary = scaleY(point[1] + 1, ratio, height, yInvert);\n let yHigh;\n if (yInvert) {\n temporary = temporary === 0 ? temporary : temporary + 1;\n yHigh = y;\n y = temporary;\n } else {\n yHigh = temporary === height - 1 ? temporary : temporary - 1;\n }\n return {\n x,\n y,\n width: Math.max(xHigh - x + 1, 1),\n height: Math.max(yHigh - y + 1, 1)\n };\n}\n\nfunction scaleX(x: number, ratio: number, width: number): number {\n return Math.min(Math.round(x * ratio), width - 1);\n}\n\nfunction scaleY(y: number, ratio: number, height: number, yInvert: boolean): number {\n return yInvert\n ? Math.max(0, height - 1 - Math.round(y * ratio))\n : Math.min(Math.round(y * ratio), height - 1);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\ntype CanvasObserverProps = {\n canvas?: HTMLCanvasElement;\n trackPosition: boolean;\n onResize: (entries: ResizeObserverEntry[]) => void;\n onIntersection: (entries: IntersectionObserverEntry[]) => void;\n onDevicePixelRatioChange: () => void;\n onPositionChange: () => void;\n};\n\n/**\n * Internal DOM observer orchestration for HTML canvas surfaces.\n *\n * CanvasSurface owns the tracked state and device callback dispatch. This helper only manages\n * browser observers, timers, and polling loops, then reports events through callbacks.\n */\nexport class CanvasObserver {\n readonly props: CanvasObserverProps;\n\n private _resizeObserver: ResizeObserver | undefined;\n private _intersectionObserver: IntersectionObserver | undefined;\n private _observeDevicePixelRatioTimeout: ReturnType<typeof setTimeout> | null = null;\n private _observeDevicePixelRatioMediaQuery: MediaQueryList | null = null;\n private readonly _handleDevicePixelRatioChange = () => this._refreshDevicePixelRatio();\n private _trackPositionInterval: ReturnType<typeof setInterval> | null = null;\n private _started = false;\n\n get started(): boolean {\n return this._started;\n }\n\n constructor(props: CanvasObserverProps) {\n this.props = props;\n }\n\n start(): void {\n if (this._started || !this.props.canvas) {\n return;\n }\n\n this._started = true;\n this._intersectionObserver ||= new IntersectionObserver(entries =>\n this.props.onIntersection(entries)\n );\n this._resizeObserver ||= new ResizeObserver(entries => this.props.onResize(entries));\n\n this._intersectionObserver.observe(this.props.canvas);\n try {\n this._resizeObserver.observe(this.props.canvas, {box: 'device-pixel-content-box'});\n } catch {\n this._resizeObserver.observe(this.props.canvas, {box: 'content-box'});\n }\n\n this._observeDevicePixelRatioTimeout = setTimeout(() => this._refreshDevicePixelRatio(), 0);\n\n if (this.props.trackPosition) {\n this._trackPosition();\n }\n }\n\n stop(): void {\n if (!this._started) {\n return;\n }\n\n this._started = false;\n\n if (this._observeDevicePixelRatioTimeout) {\n clearTimeout(this._observeDevicePixelRatioTimeout);\n this._observeDevicePixelRatioTimeout = null;\n }\n\n if (this._observeDevicePixelRatioMediaQuery) {\n this._observeDevicePixelRatioMediaQuery.removeEventListener(\n 'change',\n this._handleDevicePixelRatioChange\n );\n this._observeDevicePixelRatioMediaQuery = null;\n }\n\n if (this._trackPositionInterval) {\n clearInterval(this._trackPositionInterval);\n this._trackPositionInterval = null;\n }\n\n this._resizeObserver?.disconnect();\n this._intersectionObserver?.disconnect();\n }\n\n private _refreshDevicePixelRatio(): void {\n if (!this._started) {\n return;\n }\n\n this.props.onDevicePixelRatioChange();\n\n this._observeDevicePixelRatioMediaQuery?.removeEventListener(\n 'change',\n this._handleDevicePixelRatioChange\n );\n this._observeDevicePixelRatioMediaQuery = matchMedia(\n `(resolution: ${window.devicePixelRatio}dppx)`\n );\n this._observeDevicePixelRatioMediaQuery.addEventListener(\n 'change',\n this._handleDevicePixelRatioChange,\n {once: true}\n );\n }\n\n private _trackPosition(intervalMs: number = 100): void {\n if (this._trackPositionInterval) {\n return;\n }\n\n this._trackPositionInterval = setInterval(() => {\n if (!this._started) {\n if (this._trackPositionInterval) {\n clearInterval(this._trackPositionInterval);\n this._trackPositionInterval = null;\n }\n } else {\n this.props.onPositionChange();\n }\n }, intervalMs);\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// TODO - replace with Promise.withResolvers once we upgrade TS baseline\nexport function withResolvers<T>(): {\n promise: Promise<T>;\n resolve: (t: T) => void;\n reject: (error: Error) => void;\n} {\n let resolve: (t: T) => void;\n let reject: (error: Error) => void;\n const promise = new Promise<T>((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n // @ts-expect-error - in fact these are no used before initialized\n return {promise, resolve, reject};\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Throws if condition is true and narrows type */\nexport function assert(condition: unknown, message?: string): asserts condition {\n if (!condition) {\n const error = new Error(message ?? 'luma.gl assertion failed.');\n Error.captureStackTrace?.(error, assert);\n throw error;\n }\n}\n\n/** Throws if value is not defined, narrows type */\nexport function assertDefined<T>(value: T | undefined, message?: string): T {\n assert(value, message);\n return value;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type {CanvasContextProps, MutableCanvasContextProps} from './canvas-surface';\nimport {CanvasSurface} from './canvas-surface';\n\n/**\n * Manages a renderable backend canvas. Supports both HTML or offscreen canvas\n * and returns backend framebuffers sourced from the canvas itself.\n */\nexport abstract class CanvasContext extends CanvasSurface {\n static override defaultProps = CanvasSurface.defaultProps;\n\n abstract override readonly handle: unknown;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {CanvasSurface} from './canvas-surface';\n\nexport type {CanvasContextProps as PresentationContextProps} from './canvas-surface';\n\n/**\n * Tracks a destination canvas for presentation.\n * Backend implementations either borrow the default GPU-backed canvas (WebGL)\n * or render directly into the destination canvas (WebGPU).\n */\nexport abstract class PresentationContext extends CanvasSurface {\n abstract present(): void;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {CompareFunction} from '../types/parameters';\nimport {Resource, ResourceProps} from './resource';\n\n/** Edge values sampling mode */\nexport type SamplerAddressMode = 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n\n/** Sampler filtering mode */\nexport type SamplerFilterMode = 'nearest' | 'linear';\n\n/**\n * Properties for initializing a sampler\n */\nexport type SamplerProps = ResourceProps & {\n /** Comparison / shadow samplers are used with depth textures. See the `Sampler.compare` field */\n type?: 'color-sampler' | 'comparison-sampler';\n /** Edge value sampling in X direction */\n addressModeU?: 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n /** Edge value sampling in Y direction */\n addressModeV?: 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n /** Edge value sampling in Z direction */\n addressModeW?: 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n\n /** Magnification: the area of the fragment in texture space is smaller than a texel */\n magFilter?: 'nearest' | 'linear';\n /** Minification: the area of the fragment in texture space is larger than a texel */\n minFilter?: 'nearest' | 'linear';\n /** mipmapping: select between multiple mipmaps based on angle and size of the texture relative to the screen. */\n mipmapFilter?: 'none' | 'nearest' | 'linear';\n /** Affects the mipmap image selection */\n lodMinClamp?: number;\n /** Affects the mipmap image selection */\n lodMaxClamp?: number;\n /** Maximum number of samples that can be taken of the texture during any one texture fetch */\n maxAnisotropy?: number;\n /** How to compare reference values provided in shader shadow sampler calls with those pulled from the texture */\n compare?: CompareFunction;\n};\n\nexport type SamplerParameters = Omit<SamplerProps, keyof ResourceProps>;\n\n/** Immutable Sampler object */\nexport abstract class Sampler extends Resource<SamplerProps> {\n static override defaultProps: Required<SamplerProps> = {\n ...Resource.defaultProps,\n type: 'color-sampler',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge',\n addressModeW: 'clamp-to-edge',\n magFilter: 'nearest',\n minFilter: 'nearest',\n mipmapFilter: 'none',\n lodMinClamp: 0,\n lodMaxClamp: 32, // Per WebGPU spec\n compare: 'less-equal',\n maxAnisotropy: 1\n };\n\n override get [Symbol.toStringTag](): string {\n return 'Sampler';\n }\n\n constructor(device: Device, props: SamplerProps) {\n props = Sampler.normalizeProps(device, props);\n super(device, props, Sampler.defaultProps);\n }\n\n protected static normalizeProps(device: Device, props: SamplerProps): SamplerProps {\n return props;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {type TypedArray} from '@math.gl/types';\nimport {type Device} from '../device';\nimport {\n type TextureFormat,\n type TextureMemoryLayout,\n type TextureFormatInfo\n} from '../../shadertypes/texture-types/texture-formats';\nimport {type ExternalImage} from '../../shadertypes/image-types/image-types';\nimport {type TextureView, type TextureViewProps} from './texture-view';\nimport {Resource, type ResourceProps} from './resource';\nimport {Sampler, type SamplerProps} from './sampler';\nimport {Buffer} from './buffer';\nimport {log} from '../../utils/log';\nimport {textureFormatDecoder} from '../../shadertypes/texture-types/texture-format-decoder';\n\n/** Options for Texture.copyExternalImage */\nexport type CopyExternalImageOptions = {\n /** Image */\n image: ExternalImage;\n /** Copy from image x offset (default 0) */\n sourceX?: number;\n /** Copy from image y offset (default 0) */\n sourceY?: number;\n /** Copy area width (default 1) */\n width?: number;\n /** Copy area height (default 1) */\n height?: number;\n /** Copy depth, number of layers/depth slices(default 1) */\n depth?: number;\n /** Start copying into offset x (default 0) */\n x?: number;\n /** Start copying into offset y (default 0) */\n y?: number;\n /** Start copying into layer / depth slice z (default 0) */\n z?: number;\n /** Which mip-level to copy into (default 0) */\n mipLevel?: number;\n /** When copying into depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n /** Specific color space of image data */\n colorSpace?: 'srgb';\n /** load as premultiplied alpha */\n premultipliedAlpha?: boolean;\n /** Whether to flip the image vertically */\n flipY?: boolean;\n};\n\n/** Options for copyImageData */\nexport type CopyImageDataOptions = {\n /** Data to copy (array of bytes) */\n data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView;\n /** Offset into the data (in addition to any offset built-in to the ArrayBufferView) */\n byteOffset?: number;\n /** The stride, in bytes, between successive texel rows in the CPU source data. Tightly packed uploads can omit this. */\n bytesPerRow?: number;\n /** Number of rows that make up one image when uploading multiple layers or depth slices from CPU memory. */\n rowsPerImage?: number;\n /** Width to copy */\n width?: number;\n /** Height to copy */\n height?: number;\n /** Copy depth or number of layers */\n depthOrArrayLayers?: number;\n /** @deprecated Use `depthOrArrayLayers` */\n depth?: number;\n /** Start copying into offset x (default 0) */\n x?: number;\n /** Start copying into offset y (default 0) */\n y?: number;\n /** Start copying from depth layer z (default 0) */\n z?: number;\n /** Which mip-level to copy into (default 0) */\n mipLevel?: number;\n /** When copying into depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\nexport type TextureReadOptions = {\n /** Start reading from offset x (default 0) */\n x?: number;\n /** Start reading from offset y (default 0) */\n y?: number;\n /** Start reading from layer / depth slice z (default 0) */\n z?: number;\n /** Width of the region to read. Defaults to the mip width. */\n width?: number;\n /** Height of the region to read. Defaults to the mip height. */\n height?: number;\n /** Number of array layers or depth slices to read. Defaults to 1. */\n depthOrArrayLayers?: number;\n /** Which mip-level to read from (default 0) */\n mipLevel?: number;\n /** When reading from depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\nexport type TextureWriteOptions = {\n /** Offset into the source data or buffer, in bytes. */\n byteOffset?: number;\n /** The stride, in bytes, between successive texel rows in the source data or buffer. */\n bytesPerRow?: number;\n /** The number of rows that make up one image when writing multiple layers or slices. */\n rowsPerImage?: number;\n /** Start writing into offset x (default 0) */\n x?: number;\n /** Start writing into offset y (default 0) */\n y?: number;\n /** Start writing into layer / depth slice z (default 0) */\n z?: number;\n /** Width of the region to write. Defaults to the mip width. */\n width?: number;\n /** Height of the region to write. Defaults to the mip height. */\n height?: number;\n /** Number of array layers or depth slices to write. Defaults to 1, or the full mip depth for 3D textures. */\n depthOrArrayLayers?: number;\n /** Which mip-level to write into (default 0) */\n mipLevel?: number;\n /** When writing into depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\nconst BASE_DIMENSIONS = {\n '1d': '1d',\n '2d': '2d',\n '2d-array': '2d',\n cube: '2d',\n 'cube-array': '2d',\n '3d': '3d'\n} as const satisfies Record<string, '1d' | '2d' | '3d'>;\n\n/** Texture properties */\nexport type TextureProps = ResourceProps & {\n /** @deprecated Use DynamicTexture to create textures with data. */\n data?: ExternalImage | TypedArray | null;\n /** Dimension of this texture. Defaults to '2d' */\n dimension?: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** The format (bit layout) of the textures pixel data */\n format?: TextureFormat;\n /** Width in texels */\n width: number;\n /** Width in texels */\n height: number;\n /** Number of depth layers */\n depth?: number;\n /** How this texture will be used. Defaults to TEXTURE | COPY_DST | RENDER_ATTACHMENT */\n usage?: number;\n /** How many mip levels */\n mipLevels?: number;\n /** Multi sampling */\n samples?: number;\n\n /** Sampler (or SamplerProps) for the default sampler for this texture. Used if no sampler provided. Note that other samplers can still be used. */\n sampler?: Sampler | SamplerProps;\n /** Props for the default TextureView for this texture. Note that other views can still be created and used. */\n view?: TextureViewProps;\n};\n\n/**\n * Abstract Texture interface\n * Texture Object\n * https://gpuweb.github.io/gpuweb/#gputexture\n */\nexport abstract class Texture extends Resource<TextureProps> {\n /** The texture can be bound for use as a sampled texture in a shader */\n static SAMPLE = 0x04;\n /** The texture can be bound for use as a storage texture in a shader */\n static STORAGE = 0x08;\n /** The texture can be used as a color or depth/stencil attachment in a render pass */\n static RENDER = 0x10;\n /** The texture can be used as the source of a copy operation */\n static COPY_SRC = 0x01;\n /** he texture can be used as the destination of a copy or write operation */\n static COPY_DST = 0x02;\n\n /** @deprecated Use Texture.SAMPLE */\n static TEXTURE = 0x04;\n /** @deprecated Use Texture.RENDER */\n static RENDER_ATTACHMENT = 0x10;\n\n /** dimension of this texture */\n readonly dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** base dimension of this texture */\n readonly baseDimension: '1d' | '2d' | '3d';\n /** format of this texture */\n readonly format: TextureFormat;\n /** width in pixels of this texture */\n readonly width: number;\n /** height in pixels of this texture */\n readonly height: number;\n /** depth of this texture */\n readonly depth: number;\n /** mip levels in this texture */\n readonly mipLevels: number;\n /** sample count */\n readonly samples: number;\n /** Rows are multiples of this length, padded with extra bytes if needed */\n readonly byteAlignment: number;\n /** Default sampler for this texture */\n abstract sampler: Sampler;\n /** Default view for this texture */\n abstract view: TextureView;\n\n /** The ready promise is always resolved. It is provided for type compatibility with DynamicTexture. */\n readonly ready: Promise<Texture> = Promise.resolve(this);\n /** isReady is always true. It is provided for type compatibility with DynamicTexture. */\n readonly isReady: boolean = true;\n\n /** \"Time\" of last update. Monotonically increasing timestamp. TODO move to DynamicTexture? */\n updateTimestamp: number;\n\n override get [Symbol.toStringTag](): string {\n return 'Texture';\n }\n\n override toString(): string {\n return `Texture(${this.id},${this.format},${this.width}x${this.height})`;\n }\n\n /** Do not use directly. Create with device.createTexture() */\n constructor(device: Device, props: TextureProps, backendProps?: {byteAlignment?: number}) {\n props = Texture.normalizeProps(device, props);\n super(device, props, Texture.defaultProps);\n this.dimension = this.props.dimension;\n this.baseDimension = BASE_DIMENSIONS[this.dimension];\n this.format = this.props.format;\n\n // Size\n this.width = this.props.width;\n this.height = this.props.height;\n this.depth = this.props.depth;\n this.mipLevels = this.props.mipLevels;\n this.samples = this.props.samples || 1;\n\n if (this.dimension === 'cube') {\n this.depth = 6;\n }\n\n // Calculate size, if not provided\n if (this.props.width === undefined || this.props.height === undefined) {\n if (device.isExternalImage(props.data)) {\n const size = device.getExternalImageSize(props.data);\n this.width = size?.width || 1;\n this.height = size?.height || 1;\n } else {\n this.width = 1;\n this.height = 1;\n if (this.props.width === undefined || this.props.height === undefined) {\n log.warn(\n `${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`\n )();\n }\n }\n }\n\n this.byteAlignment = backendProps?.byteAlignment || 1;\n\n // TODO - perhaps this should be set on async write completion?\n this.updateTimestamp = device.incrementTimestamp();\n }\n\n /**\n * Create a new texture with the same parameters and optionally a different size\n * @note Textures are immutable and cannot be resized after creation, but we can create a similar texture with the same parameters but a new size.\n * @note Does not copy contents of the texture\n */\n clone(size?: {width: number; height: number}): Texture {\n return this.device.createTexture({...this.props, ...size});\n }\n\n /** Set sampler props associated with this texture */\n setSampler(sampler: Sampler | SamplerProps): void {\n this.sampler = sampler instanceof Sampler ? sampler : this.device.createSampler(sampler);\n }\n\n /** Create a texture view for this texture */\n abstract createView(props: TextureViewProps): TextureView;\n\n /** Copy an image (e.g an ImageBitmap) into the texture */\n abstract copyExternalImage(options: CopyExternalImageOptions): {width: number; height: number};\n\n /**\n * Copy raw image data (bytes) into the texture.\n *\n * @note Deprecated compatibility wrapper over {@link writeData}.\n * @note Uses the same layout defaults and alignment rules as {@link writeData}.\n * @note Tightly packed CPU uploads can omit `bytesPerRow` and `rowsPerImage`.\n * @note If the CPU source rows are padded, pass explicit `bytesPerRow` and `rowsPerImage`.\n * @deprecated Use writeData()\n */\n copyImageData(options: CopyImageDataOptions): void {\n const {data, depth, ...writeOptions} = options;\n this.writeData(data, {\n ...writeOptions,\n depthOrArrayLayers: writeOptions.depthOrArrayLayers ?? depth\n });\n }\n\n /**\n * Calculates the memory layout of the texture, required when reading and writing data.\n * @return the backend-aligned linear layout, in particular bytesPerRow which includes any required padding for buffer copy/read paths\n */\n computeMemoryLayout(options_: TextureReadOptions = {}): TextureMemoryLayout {\n const options = this._normalizeTextureReadOptions(options_);\n const {width = this.width, height = this.height, depthOrArrayLayers = this.depth} = options;\n const {format, byteAlignment} = this;\n\n // TODO - does the overriding above make sense?\n // return textureFormatDecoder.computeMemoryLayout(this);\n return textureFormatDecoder.computeMemoryLayout({\n format,\n width,\n height,\n depth: depthOrArrayLayers,\n byteAlignment\n });\n }\n\n /**\n * Read the contents of a texture into a GPU Buffer.\n * @returns A Buffer containing the texture data.\n *\n * @note The memory layout of the texture data is determined by the texture format and dimensions.\n * @note The application can call Texture.computeMemoryLayout() to compute the backend-aligned layout.\n * @note The application can call Buffer.readAsync() to read the returned buffer on the CPU.\n * @note The destination buffer must be supplied by the caller and must be large enough for the requested region.\n * @note On WebGPU this corresponds to a texture-to-buffer copy and uses buffer-copy alignment rules.\n * @note On WebGL, luma.gl emulates the same logical readback behavior.\n */\n readBuffer(options?: TextureReadOptions, buffer?: Buffer): Buffer {\n throw new Error('readBuffer not implemented');\n }\n\n /**\n * Reads data from a texture into an ArrayBuffer.\n * @returns An ArrayBuffer containing the texture data.\n *\n * @note The memory layout of the texture data is determined by the texture format and dimensions.\n * @note The application can call Texture.computeMemoryLayout() to compute the layout.\n * @deprecated Use Texture.readBuffer() with an explicit destination buffer, or DynamicTexture.readAsync() for convenience readback.\n */\n readDataAsync(options?: TextureReadOptions): Promise<ArrayBuffer> {\n throw new Error('readBuffer not implemented');\n }\n\n /**\n * Writes a GPU Buffer into a texture.\n *\n * @param buffer - Source GPU buffer.\n * @param options - Destination subresource, extent, and source layout options.\n * @note The memory layout of the texture data is determined by the texture format and dimensions.\n * @note The application can call Texture.computeMemoryLayout() to compute the backend-aligned layout.\n * @note On WebGPU this corresponds to a buffer-to-texture copy and uses buffer-copy alignment rules.\n * @note On WebGL, luma.gl emulates the same destination and layout semantics.\n */\n writeBuffer(buffer: Buffer, options?: TextureWriteOptions): void {\n throw new Error('readBuffer not implemented');\n }\n\n /**\n * Writes an array buffer into a texture.\n *\n * @param data - Source texel data.\n * @param options - Destination subresource, extent, and source layout options.\n * @note If `bytesPerRow` and `rowsPerImage` are omitted, luma.gl computes a tightly packed CPU-memory layout for the requested region.\n * @note On WebGPU this corresponds to `GPUQueue.writeTexture()` and does not implicitly pad rows to 256 bytes.\n * @note On WebGL, padded CPU data is supported via the same `bytesPerRow` and `rowsPerImage` options.\n */\n writeData(\n data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView,\n options?: TextureWriteOptions\n ): void {\n throw new Error('readBuffer not implemented');\n }\n\n // IMPLEMENTATION SPECIFIC\n\n /**\n * WebGL can read data synchronously.\n * @note While it is convenient, the performance penalty is very significant\n */\n readDataSyncWebGL(options?: TextureReadOptions): ArrayBuffer | ArrayBufferView {\n throw new Error('readDataSyncWebGL not available');\n }\n\n /** Generate mipmaps (WebGL only) */\n generateMipmapsWebGL(): void {\n throw new Error('generateMipmapsWebGL not available');\n }\n\n // HELPERS\n\n /** Ensure we have integer coordinates */\n protected static normalizeProps(device: Device, props: TextureProps): TextureProps {\n const newProps = {...props};\n\n // Ensure we have integer coordinates\n const {width, height} = newProps;\n if (typeof width === 'number') {\n newProps.width = Math.max(1, Math.ceil(width));\n }\n if (typeof height === 'number') {\n newProps.height = Math.max(1, Math.ceil(height));\n }\n return newProps;\n }\n\n /** Initialize texture with supplied props */\n // eslint-disable-next-line max-statements\n _initializeData(data: TextureProps['data']): void {\n // Store opts for accessors\n\n if (this.device.isExternalImage(data)) {\n this.copyExternalImage({\n image: data,\n width: this.width,\n height: this.height,\n depth: this.depth,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all',\n colorSpace: 'srgb',\n premultipliedAlpha: false,\n flipY: false\n });\n } else if (data) {\n this.copyImageData({\n data,\n // width: this.width,\n // height: this.height,\n // depth: this.depth,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all'\n });\n }\n }\n\n _normalizeCopyImageDataOptions(options_: CopyImageDataOptions): Required<CopyImageDataOptions> {\n const {data, depth, ...writeOptions} = options_;\n const options = this._normalizeTextureWriteOptions({\n ...writeOptions,\n depthOrArrayLayers: writeOptions.depthOrArrayLayers ?? depth\n });\n return {data, depth: options.depthOrArrayLayers, ...options};\n }\n\n _normalizeCopyExternalImageOptions(\n options_: CopyExternalImageOptions\n ): Required<CopyExternalImageOptions> {\n const optionsWithoutUndefined = Texture._omitUndefined(options_);\n const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const size = this.device.getExternalImageSize(options_.image);\n const options = {\n ...Texture.defaultCopyExternalImageOptions,\n ...mipLevelSize,\n ...size,\n ...optionsWithoutUndefined\n };\n // WebGL will error if we try to copy outside the bounds of the texture\n options.width = Math.min(options.width, mipLevelSize.width - options.x);\n options.height = Math.min(options.height, mipLevelSize.height - options.y);\n options.depth = Math.min(options.depth, mipLevelSize.depthOrArrayLayers - options.z);\n return options;\n }\n\n _normalizeTextureReadOptions(options_: TextureReadOptions): Required<TextureReadOptions> {\n const optionsWithoutUndefined = Texture._omitUndefined(options_);\n const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const options = {\n ...Texture.defaultTextureReadOptions,\n ...mipLevelSize,\n ...optionsWithoutUndefined\n };\n // WebGL will error if we try to copy outside the bounds of the texture\n options.width = Math.min(options.width, mipLevelSize.width - options.x);\n options.height = Math.min(options.height, mipLevelSize.height - options.y);\n options.depthOrArrayLayers = Math.min(\n options.depthOrArrayLayers,\n mipLevelSize.depthOrArrayLayers - options.z\n );\n return options;\n }\n\n /**\n * Normalizes a texture read request and validates the color-only readback contract used by the\n * current texture read APIs. Supported dimensions are `2d`, `cube`, `cube-array`,\n * `2d-array`, and `3d`.\n *\n * @throws if the texture format, aspect, or dimension is not supported by the first-pass\n * color-read implementation.\n */\n protected _getSupportedColorReadOptions(\n options_: TextureReadOptions\n ): Required<TextureReadOptions> {\n const options = this._normalizeTextureReadOptions(options_);\n const formatInfo = textureFormatDecoder.getInfo(this.format);\n\n this._validateColorReadAspect(options);\n this._validateColorReadFormat(formatInfo);\n\n switch (this.dimension) {\n case '2d':\n case 'cube':\n case 'cube-array':\n case '2d-array':\n case '3d':\n return options;\n\n default:\n throw new Error(`${this} color readback does not support ${this.dimension} textures`);\n }\n }\n\n /** Validates that a read request targets the full color aspect of the texture. */\n protected _validateColorReadAspect(options: Required<TextureReadOptions>): void {\n if (options.aspect !== 'all') {\n throw new Error(`${this} color readback only supports aspect 'all'`);\n }\n }\n\n /** Validates that a read request targets an uncompressed color-renderable texture format. */\n protected _validateColorReadFormat(formatInfo: TextureFormatInfo): void {\n if (formatInfo.compressed) {\n throw new Error(\n `${this} color readback does not support compressed formats (${this.format})`\n );\n }\n\n switch (formatInfo.attachment) {\n case 'color':\n return;\n\n case 'depth':\n throw new Error(`${this} color readback does not support depth formats (${this.format})`);\n\n case 'stencil':\n throw new Error(`${this} color readback does not support stencil formats (${this.format})`);\n\n case 'depth-stencil':\n throw new Error(\n `${this} color readback does not support depth-stencil formats (${this.format})`\n );\n\n default:\n throw new Error(`${this} color readback does not support format ${this.format}`);\n }\n }\n\n _normalizeTextureWriteOptions(options_: TextureWriteOptions): Required<TextureWriteOptions> {\n const optionsWithoutUndefined = Texture._omitUndefined(options_);\n const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const options = {\n ...Texture.defaultTextureWriteOptions,\n ...mipLevelSize,\n ...optionsWithoutUndefined\n };\n\n options.width = Math.min(options.width, mipLevelSize.width - options.x);\n options.height = Math.min(options.height, mipLevelSize.height - options.y);\n options.depthOrArrayLayers = Math.min(\n options.depthOrArrayLayers,\n mipLevelSize.depthOrArrayLayers - options.z\n );\n\n const layout = textureFormatDecoder.computeMemoryLayout({\n format: this.format,\n width: options.width,\n height: options.height,\n depth: options.depthOrArrayLayers,\n byteAlignment: this.byteAlignment\n });\n\n const minimumBytesPerRow = layout.bytesPerPixel * options.width;\n options.bytesPerRow = optionsWithoutUndefined.bytesPerRow ?? layout.bytesPerRow;\n options.rowsPerImage = optionsWithoutUndefined.rowsPerImage ?? options.height;\n\n if (options.bytesPerRow < minimumBytesPerRow) {\n throw new Error(\n `bytesPerRow (${options.bytesPerRow}) must be at least ${minimumBytesPerRow} for ${this.format}`\n );\n }\n if (options.rowsPerImage < options.height) {\n throw new Error(\n `rowsPerImage (${options.rowsPerImage}) must be at least ${options.height} for ${this.format}`\n );\n }\n\n const bytesPerPixel = this.device.getTextureFormatInfo(this.format).bytesPerPixel;\n if (bytesPerPixel && options.bytesPerRow % bytesPerPixel !== 0) {\n throw new Error(\n `bytesPerRow (${options.bytesPerRow}) must be a multiple of bytesPerPixel (${bytesPerPixel}) for ${this.format}`\n );\n }\n\n return options;\n }\n\n protected _getMipLevelSize(\n mipLevel: number\n ): Required<Pick<TextureReadOptions, 'width' | 'height' | 'depthOrArrayLayers'>> {\n const width = Math.max(1, this.width >> mipLevel);\n const height = this.baseDimension === '1d' ? 1 : Math.max(1, this.height >> mipLevel);\n const depthOrArrayLayers =\n this.dimension === '3d' ? Math.max(1, this.depth >> mipLevel) : this.depth;\n\n return {width, height, depthOrArrayLayers};\n }\n\n protected getAllocatedByteLength(): number {\n let allocatedByteLength = 0;\n\n for (let mipLevel = 0; mipLevel < this.mipLevels; mipLevel++) {\n const {width, height, depthOrArrayLayers} = this._getMipLevelSize(mipLevel);\n allocatedByteLength += textureFormatDecoder.computeMemoryLayout({\n format: this.format,\n width,\n height,\n depth: depthOrArrayLayers,\n byteAlignment: 1\n }).byteLength;\n }\n\n return allocatedByteLength * this.samples;\n }\n\n protected static _omitUndefined<T extends object>(options: T): Partial<T> {\n return Object.fromEntries(\n Object.entries(options).filter(([, value]) => value !== undefined)\n ) as Partial<T>;\n }\n\n static override defaultProps: Required<TextureProps> = {\n ...Resource.defaultProps,\n data: null,\n dimension: '2d',\n format: 'rgba8unorm',\n usage: Texture.SAMPLE | Texture.RENDER | Texture.COPY_DST,\n width: undefined!,\n height: undefined!,\n depth: 1,\n mipLevels: 1,\n samples: undefined!,\n sampler: {},\n view: undefined!\n };\n\n protected static defaultCopyDataOptions: Required<CopyImageDataOptions> = {\n data: undefined!,\n byteOffset: 0,\n bytesPerRow: undefined!,\n rowsPerImage: undefined!,\n width: undefined!,\n height: undefined!,\n depthOrArrayLayers: undefined!,\n depth: 1,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all'\n };\n\n /** Default options */\n protected static defaultCopyExternalImageOptions: Required<CopyExternalImageOptions> = {\n image: undefined!,\n sourceX: 0,\n sourceY: 0,\n width: undefined!,\n height: undefined!,\n depth: 1,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all',\n colorSpace: 'srgb',\n premultipliedAlpha: false,\n flipY: false\n };\n\n protected static defaultTextureReadOptions: Required<TextureReadOptions> = {\n x: 0,\n y: 0,\n z: 0,\n width: undefined!,\n height: undefined!,\n depthOrArrayLayers: 1,\n mipLevel: 0,\n aspect: 'all'\n };\n\n protected static defaultTextureWriteOptions: Required<TextureWriteOptions> = {\n byteOffset: 0,\n bytesPerRow: undefined!,\n rowsPerImage: undefined!,\n x: 0,\n y: 0,\n z: 0,\n width: undefined!,\n height: undefined!,\n depthOrArrayLayers: 1,\n mipLevel: 0,\n aspect: 'all'\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {Texture} from './texture';\nimport type {TextureFormat} from '../../shadertypes/texture-types/texture-formats';\nimport {Resource, ResourceProps} from './resource';\n\n/** Properties for initializing a texture view */\nexport type TextureViewProps = ResourceProps & {\n /** The format of the texture view. Must be either the format of the texture or one of the viewFormats specified during its creation. */\n format?: TextureFormat;\n /** The dimension to view the texture as. */\n dimension?: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** Which aspect(s) of the texture are accessible to the texture view. default \"all\"*/\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n /** The first (most detailed) mipmap level accessible to the texture view. default 0*/\n baseMipLevel?: number;\n /** How many mipmap levels, starting with baseMipLevel, are accessible to the texture view. */\n mipLevelCount: number;\n /** The index of the first array layer accessible to the texture view. default 0 */\n baseArrayLayer?: number;\n /** How many array layers, starting with baseArrayLayer, are accessible to the texture view. */\n arrayLayerCount: number;\n};\n\n/** Immutable TextureView object */\nexport abstract class TextureView extends Resource<TextureViewProps> {\n abstract texture: Texture;\n\n override get [Symbol.toStringTag](): string {\n return 'TextureView';\n }\n\n /** Should not be constructed directly. Use `texture.createView(props)` */\n constructor(device: Device, props: TextureViewProps & {texture: Texture}) {\n super(device, props, TextureView.defaultProps);\n }\n\n static override defaultProps: Required<TextureViewProps> = {\n ...Resource.defaultProps,\n format: undefined!,\n dimension: undefined!,\n aspect: 'all',\n baseMipLevel: 0,\n mipLevelCount: undefined!,\n baseArrayLayer: 0,\n arrayLayerCount: undefined!\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\nexport type ExternalTextureProps = ResourceProps & {\n source: HTMLVideoElement; // | null;\n colorSpace?: 'srgb';\n};\nexport abstract class ExternalTexture extends Resource<ExternalTextureProps> {\n override get [Symbol.toStringTag](): string {\n return 'ExternalTexture';\n }\n\n constructor(device: Device, props: ExternalTextureProps) {\n super(device, props, ExternalTexture.defaultProps);\n }\n\n static override defaultProps: Required<ExternalTextureProps> = {\n ...Resource.defaultProps,\n source: undefined!,\n colorSpace: 'srgb'\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CompilerMessage} from '../adapter/types/compiler-message';\n\n/** @returns annotated errors or warnings */\nexport function formatCompilerLog(\n shaderLog: readonly CompilerMessage[],\n source: string,\n options?: {\n /** Include source code in the log. Either just the lines before issues or all source code */\n showSourceCode?: 'no' | 'issues' | 'all';\n html?: boolean;\n }\n): string {\n let formattedLog = '';\n const lines = source.split(/\\r?\\n/);\n const log = shaderLog.slice().sort((a, b) => a.lineNum - b.lineNum);\n\n switch (options?.showSourceCode || 'no') {\n case 'all':\n // Parse the error - note: browser and driver dependent\n let currentMessageIndex = 0;\n for (let lineNum = 1; lineNum <= lines.length; lineNum++) {\n const line = lines[lineNum - 1];\n const currentMessage = log[currentMessageIndex];\n if (line && currentMessage) {\n formattedLog += getNumberedLine(line, lineNum, options);\n }\n while (log.length > currentMessageIndex && currentMessage.lineNum === lineNum) {\n const message = log[currentMessageIndex++];\n if (message) {\n formattedLog += formatCompilerMessage(message, lines, message.lineNum, {\n ...options,\n inlineSource: false\n });\n }\n }\n }\n // Print any remaining messages\n while (log.length > currentMessageIndex) {\n const message = log[currentMessageIndex++];\n if (message) {\n formattedLog += formatCompilerMessage(message, [], 0, {\n ...options,\n inlineSource: false\n });\n }\n }\n return formattedLog;\n\n case 'issues':\n case 'no':\n // Parse the error - note: browser and driver dependent\n for (const message of shaderLog) {\n formattedLog += formatCompilerMessage(message, lines, message.lineNum, {\n inlineSource: options?.showSourceCode !== 'no'\n });\n }\n return formattedLog;\n }\n}\n\n// Helpers\n\n/** Format one message */\nfunction formatCompilerMessage(\n message: CompilerMessage,\n lines: readonly string[],\n lineNum: number,\n options: {\n inlineSource?: boolean;\n html?: boolean;\n }\n): string {\n if (options?.inlineSource) {\n const numberedLines = getNumberedLines(lines, lineNum);\n // If we got error position on line add a `^^^` indicator on next line\n const positionIndicator = message.linePos > 0 ? `${' '.repeat(message.linePos + 5)}^^^\\n` : '';\n return `\n${numberedLines}${positionIndicator}${message.type.toUpperCase()}: ${message.message}\n\n`;\n }\n const color = message.type === 'error' ? 'red' : 'orange';\n return options?.html\n ? `<div class='luma-compiler-log-${message.type}' style=\"color:${color};\"><b> ${message.type.toUpperCase()}: ${\n message.message\n }</b></div>`\n : `${message.type.toUpperCase()}: ${message.message}`;\n}\n\nfunction getNumberedLines(\n lines: readonly string[],\n lineNum: number,\n options?: {html?: boolean}\n): string {\n let numberedLines = '';\n for (let lineIndex = lineNum - 2; lineIndex <= lineNum; lineIndex++) {\n const sourceLine = lines[lineIndex - 1];\n if (sourceLine !== undefined) {\n numberedLines += getNumberedLine(sourceLine, lineNum, options);\n }\n }\n return numberedLines;\n}\n\nfunction getNumberedLine(line: string, lineNum: number, options?: {html?: boolean}): string {\n const escapedLine = options?.html ? escapeHTML(line) : line;\n return `${padLeft(String(lineNum), 4)}: ${escapedLine}${options?.html ? '<br/>' : '\\n'}`;\n}\n\n/**\n * Pads a string with a number of spaces (space characters) to the left\n * @param {String} string - string to pad\n * @param {Number} digits - number of spaces to add\n * @return {String} string - The padded string\n */\nfunction padLeft(string: string, paddedLength: number): string {\n let result = '';\n for (let i = string.length; i < paddedLength; ++i) {\n result += ' ';\n }\n return result + string;\n}\n\nfunction escapeHTML(unsafe: string): string {\n return unsafe\n .replaceAll('&', '&amp;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;')\n .replaceAll('\"', '&quot;')\n .replaceAll(\"'\", '&#039;');\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n// import { log } from '../../utils/log';\nimport {uid} from '../../utils/uid';\nimport {CompilerMessage} from '../types/compiler-message';\nimport {formatCompilerLog} from '../../adapter-utils/format-compiler-log';\n\n/**\n * Properties for a Shader\n */\nexport type ShaderProps = ResourceProps & {\n /** Shader language (defaults to auto) */\n language?: 'glsl' | 'wgsl' | 'auto';\n /** Which stage are we compiling? Required for GLSL. Ignored for WGSL. */\n stage?: 'vertex' | 'fragment' | 'compute';\n /** Shader source code */\n source: string;\n /** Optional shader source map (WebGPU only) */\n sourceMap?: string | null;\n /** Optional shader entry point (WebGPU only) */\n entryPoint?: string;\n /** Show shader source in browser? Overrides the device.props.debugShaders setting */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n};\n\n/**\n * Immutable Shader object\n * In WebGPU the handle can be copied between threads\n */\nexport abstract class Shader extends Resource<ShaderProps> {\n override get [Symbol.toStringTag](): string {\n return 'Shader';\n }\n\n /** The stage of this shader */\n readonly stage: 'vertex' | 'fragment' | 'compute';\n /** The source code of this shader */\n readonly source: string;\n /** The compilation status of the shader. 'pending' if compilation is asynchronous, and on production */\n compilationStatus: 'pending' | 'success' | 'error' = 'pending';\n\n /** Create a new Shader instance */\n constructor(device: Device, props: ShaderProps) {\n props = {...props, debugShaders: props.debugShaders || device.props.debugShaders || 'errors'};\n super(device, {id: getShaderIdFromProps(props), ...props}, Shader.defaultProps);\n this.stage = this.props.stage;\n this.source = this.props.source;\n }\n\n abstract get asyncCompilationStatus(): Promise<'pending' | 'success' | 'error'>;\n\n /** Get compiler log asynchronously */\n abstract getCompilationInfo(): Promise<readonly CompilerMessage[]>;\n\n /** Get compiler log synchronously (WebGL only) */\n getCompilationInfoSync(): readonly CompilerMessage[] | null {\n return null;\n }\n\n /** Get translated shader source in host platform's native language (HLSL, GLSL, and even GLSL ES), if available */\n getTranslatedSource(): string | null {\n return null;\n }\n\n // PORTABLE HELPERS\n\n /** In browser logging of errors */\n async debugShader(): Promise<void> {\n const trigger = this.props.debugShaders;\n switch (trigger) {\n case 'never':\n return;\n case 'errors':\n // On WebGL - Don't extract the log unless errors\n if (this.compilationStatus === 'success') {\n return;\n }\n break;\n case 'warnings':\n case 'always':\n break;\n }\n\n const messages = await this.getCompilationInfo();\n if (trigger === 'warnings' && messages?.length === 0) {\n return;\n }\n this._displayShaderLog(messages, this.id);\n }\n\n // PRIVATE\n\n /**\n * In-browser UI logging of errors\n * TODO - this HTML formatting code should not be in Device, should be pluggable\n */\n protected _displayShaderLog(messages: readonly CompilerMessage[], shaderId: string): void {\n // Return if under Node.js / incomplete `document` polyfills\n if (typeof document === 'undefined' || !document?.createElement) {\n return;\n }\n\n const shaderName: string = shaderId; // getShaderName(this.source) || ;\n const shaderTitle: string = `${this.stage} shader \"${shaderName}\"`;\n const htmlLog = formatCompilerLog(messages, this.source, {showSourceCode: 'all', html: true});\n // Show translated source if available\n const translatedSource = this.getTranslatedSource();\n\n const container = document.createElement('div');\n container.innerHTML = `\\\n<h1>Compilation error in ${shaderTitle}</h1>\n<div style=\"display:flex;position:fixed;top:10px;right:20px;gap:2px;\">\n<button id=\"copy\">Copy source</button><br/>\n<button id=\"close\">Close</button>\n</div>\n<code><pre>${htmlLog}</pre></code>`;\n if (translatedSource) {\n container.innerHTML += `<br /><h1>Translated Source</h1><br /><br /><code><pre>${translatedSource}</pre></code>`;\n }\n container.style.top = '0';\n container.style.left = '0';\n container.style.background = 'white';\n container.style.position = 'fixed';\n container.style.zIndex = '9999';\n container.style.maxWidth = '100vw';\n container.style.maxHeight = '100vh';\n container.style.overflowY = 'auto';\n document.body.appendChild(container);\n const error = container.querySelector('.luma-compiler-log-error');\n error?.scrollIntoView();\n (container.querySelector('button#close') as HTMLButtonElement).onclick = () => {\n container.remove();\n };\n (container.querySelector('button#copy') as HTMLButtonElement).onclick = () => {\n navigator.clipboard.writeText(this.source);\n };\n }\n\n static override defaultProps: Required<ShaderProps> = {\n ...Resource.defaultProps,\n language: 'auto',\n stage: undefined!,\n source: '',\n sourceMap: null,\n entryPoint: 'main',\n debugShaders: undefined!\n };\n}\n\n// HELPERS\n\n/** Deduce an id, from shader source, or supplied id, or shader type */\nfunction getShaderIdFromProps(props: ShaderProps): string {\n return getShaderName(props.source) || props.id || uid(`unnamed ${props.stage}-shader`);\n}\n\n/** Extracts GLSLIFY style naming of shaders: `#define SHADER_NAME ...` */\nfunction getShaderName(shader: string, defaultName: string = 'unnamed'): string {\n const SHADER_NAME_REGEXP = /#define[\\s*]SHADER_NAME[\\s*]([A-Za-z0-9_-]+)[\\s*]/;\n const match = SHADER_NAME_REGEXP.exec(shader);\n return match?.[1] ?? defaultName;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n TextureFormatColor,\n TextureFormatDepthStencil,\n TextureFormat\n} from '../../shadertypes/texture-types/texture-formats';\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\nimport {Texture} from './texture';\nimport {TextureView} from './texture-view';\nimport {log} from '../../utils/log';\n\nexport type FramebufferProps = ResourceProps & {\n width?: number;\n height?: number;\n colorAttachments?: (TextureView | Texture | TextureFormatColor)[];\n depthStencilAttachment?: (TextureView | Texture | TextureFormatDepthStencil) | null;\n};\n\n/**\n * Create new textures with correct size for all attachments.\n * @note resize() destroys existing textures (if size has changed).\n */\nexport abstract class Framebuffer extends Resource<FramebufferProps> {\n override get [Symbol.toStringTag](): string {\n return 'Framebuffer';\n }\n\n /** Width of all attachments in this framebuffer */\n width: number;\n /** Height of all attachments in this framebuffer */\n height: number;\n /** Color attachments */\n abstract colorAttachments: TextureView[];\n /** Depth-stencil attachment, if provided */\n abstract depthStencilAttachment: TextureView | null;\n\n constructor(device: Device, props: FramebufferProps = {}) {\n super(device, props, Framebuffer.defaultProps);\n this.width = this.props.width;\n this.height = this.props.height;\n }\n\n /**\n * Create a copy of this framebuffer with new attached textures, with same props but of the specified size.\n * @note Does not copy contents of the attached textures.\n */\n clone(size?: {width: number; height: number}): Framebuffer {\n const colorAttachments = this.colorAttachments.map(colorAttachment =>\n colorAttachment.texture.clone(size)\n );\n\n const depthStencilAttachment =\n this.depthStencilAttachment && this.depthStencilAttachment.texture.clone(size);\n\n return this.device.createFramebuffer({\n ...this.props,\n ...size,\n colorAttachments,\n depthStencilAttachment\n });\n }\n\n /**\n * Resizes all attachments\n * @note resize() destroys existing textures (if size has changed).\n * @deprecated Use framebuffer.clone()\n */\n resize(size: {width: number; height: number}): void;\n resize(size: [width: number, height: number]): void;\n resize(): void;\n resize(size?: {width: number; height: number} | [width: number, height: number]): void {\n let updateSize: boolean = !size;\n if (size) {\n const [width, height] = Array.isArray(size) ? size : [size.width, size.height];\n updateSize = updateSize || height !== this.height || width !== this.width;\n this.width = width;\n this.height = height;\n }\n if (updateSize) {\n log.log(2, `Resizing framebuffer ${this.id} to ${this.width}x${this.height}`)();\n this.resizeAttachments(this.width, this.height);\n }\n }\n\n /** Auto creates any textures */\n protected autoCreateAttachmentTextures(): void {\n if (this.props.colorAttachments.length === 0 && !this.props.depthStencilAttachment) {\n throw new Error('Framebuffer has noattachments');\n }\n\n this.colorAttachments = this.props.colorAttachments.map((attachment, index) => {\n if (typeof attachment === 'string') {\n const texture = this.createColorTexture(attachment, index);\n this.attachResource(texture);\n return texture.view;\n }\n if (attachment instanceof Texture) {\n return attachment.view;\n }\n return attachment;\n });\n\n const attachment = this.props.depthStencilAttachment;\n if (attachment) {\n if (typeof attachment === 'string') {\n const texture = this.createDepthStencilTexture(attachment);\n this.attachResource(texture);\n this.depthStencilAttachment = texture.view;\n } else if (attachment instanceof Texture) {\n this.depthStencilAttachment = attachment.view;\n } else {\n this.depthStencilAttachment = attachment;\n }\n }\n }\n\n /** Create a color texture */\n protected createColorTexture(format: TextureFormat, index: number): Texture {\n return this.device.createTexture({\n id: `${this.id}-color-attachment-${index}`,\n usage: Texture.RENDER_ATTACHMENT,\n format,\n width: this.width,\n height: this.height,\n // TODO deprecated? - luma.gl v8 compatibility\n sampler: {\n magFilter: 'linear',\n minFilter: 'linear'\n }\n });\n }\n\n /** Create depth stencil texture */\n protected createDepthStencilTexture(format: TextureFormat): Texture {\n return this.device.createTexture({\n id: `${this.id}-depth-stencil-attachment`,\n usage: Texture.RENDER_ATTACHMENT,\n format,\n width: this.width,\n height: this.height\n });\n }\n\n /**\n * Default implementation of resize\n * Creates new textures with correct size for all attachments.\n * and destroys existing textures if owned\n */\n protected resizeAttachments(width: number, height: number): void {\n this.colorAttachments.forEach((colorAttachment, i) => {\n const resizedTexture = colorAttachment.texture.clone({\n width,\n height\n });\n this.destroyAttachedResource(colorAttachment);\n this.colorAttachments[i] = resizedTexture.view;\n this.attachResource(resizedTexture.view);\n });\n\n if (this.depthStencilAttachment) {\n const resizedTexture = this.depthStencilAttachment.texture.clone({\n width,\n height\n });\n this.destroyAttachedResource(this.depthStencilAttachment);\n this.depthStencilAttachment = resizedTexture.view;\n this.attachResource(resizedTexture);\n }\n\n this.updateAttachments();\n }\n\n /** Implementation is expected to update any underlying binding (WebGL framebuffer attachment) */\n protected abstract updateAttachments(): void;\n\n static override defaultProps: Required<FramebufferProps> = {\n ...Resource.defaultProps,\n width: 1,\n height: 1,\n colorAttachments: [], // ['rgba8unorm'],\n depthStencilAttachment: null // 'depth24plus-stencil8'\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {PrimitiveTopology, RenderPipelineParameters} from '../types/parameters';\nimport type {ShaderLayout, Bindings, BindingsByGroup} from '../types/shader-layout';\nimport type {BufferLayout} from '../types/buffer-layout';\nimport type {\n TextureFormatColor,\n TextureFormatDepthStencil\n} from '@luma.gl/core/shadertypes/texture-types/texture-formats';\nimport type {Shader} from './shader';\nimport type {SharedRenderPipeline} from './shared-render-pipeline';\nimport type {RenderPass} from './render-pass';\nimport {Resource, ResourceProps} from './resource';\nimport {VertexArray} from './vertex-array';\nimport {TransformFeedback} from './transform-feedback';\n\nexport type RenderPipelineProps = ResourceProps & {\n // Shaders and shader layout\n\n /** Compiled vertex shader */\n vs?: Shader | null;\n /** Name of vertex shader stage main function (defaults to 'main'). WGSL only */\n vertexEntryPoint?: string; //\n /** Constant values to apply to compiled vertex shader. Do not require re-compilation. (WGSL only) */\n vsConstants?: Record<string, number>; // WGSL only\n /** Compiled fragment shader */\n fs?: Shader | null;\n /** Name of fragment shader stage main function (defaults to 'main'). WGSL only */\n fragmentEntryPoint?: string; // WGSL only\n /** Constant values to apply to compiled fragment shader. Do not require re-compilation. (WGSL only) */\n fsConstants?: Record<string, number>;\n\n /** Describes the attributes and bindings exposed by the pipeline shader(s). */\n shaderLayout?: ShaderLayout | null;\n /** Describes the buffers accepted by this pipeline and how they are mapped to shader attributes. */\n bufferLayout?: BufferLayout[]; // Record<string, Omit<BufferLayout, 'name'>\n\n /** Determines how vertices are read from the 'vertex' attributes */\n topology?: PrimitiveTopology;\n\n // color attachment information (needed on WebGPU)\n\n /** Color attachments expected by this pipeline. Defaults to [device.preferredColorFormat]. Array needs not be contiguous. */\n colorAttachmentFormats?: (TextureFormatColor | null)[];\n /** Depth attachment expected by this pipeline. Defaults to device.preferredDepthFormat, if depthWriteEnables parameter is set */\n depthStencilAttachmentFormat?: TextureFormatDepthStencil;\n\n /** Parameters that are controlled by pipeline */\n parameters?: RenderPipelineParameters;\n\n /** Transform feedback varyings captured when linking a WebGL render pipeline. WebGL only. */\n varyings?: string[];\n /** Transform feedback buffer mode used when linking a WebGL render pipeline. WebGL only. */\n bufferMode?: number;\n\n /** Some applications intentionally supply unused attributes and bindings, and want to disable warnings */\n disableWarnings?: boolean;\n\n /** Internal hook for backend-specific shared pipeline implementations. */\n _sharedRenderPipeline?: SharedRenderPipeline;\n\n // Dynamic bindings (TODO - pipelines should be immutable, move to RenderPass)\n /** Buffers, Textures, Samplers for the shader bindings */\n bindings?: Bindings;\n /** Bindings grouped by bind-group index */\n bindGroups?: BindingsByGroup;\n};\n\n/**\n * A compiled and linked shader program\n */\nexport abstract class RenderPipeline extends Resource<RenderPipelineProps> {\n override get [Symbol.toStringTag](): string {\n return 'RenderPipeline';\n }\n\n abstract readonly vs: Shader;\n abstract readonly fs: Shader | null;\n\n /** The merged layout */\n shaderLayout: ShaderLayout;\n /** Buffer map describing buffer interleaving etc */\n readonly bufferLayout: BufferLayout[];\n /** The linking status of the pipeline. 'pending' if linking is asynchronous, and on production */\n linkStatus: 'pending' | 'success' | 'error' = 'pending';\n /** The hash of the pipeline */\n hash: string = '';\n /** Optional shared backend implementation */\n sharedRenderPipeline: SharedRenderPipeline | null = null;\n\n /** Whether shader or pipeline compilation/linking is still in progress */\n get isPending(): boolean {\n return (\n this.linkStatus === 'pending' ||\n this.vs.compilationStatus === 'pending' ||\n this.fs?.compilationStatus === 'pending'\n );\n }\n\n /** Whether shader or pipeline compilation/linking has failed */\n get isErrored(): boolean {\n return (\n this.linkStatus === 'error' ||\n this.vs.compilationStatus === 'error' ||\n this.fs?.compilationStatus === 'error'\n );\n }\n\n constructor(device: Device, props: RenderPipelineProps) {\n super(device, props, RenderPipeline.defaultProps);\n this.shaderLayout = this.props.shaderLayout!;\n this.bufferLayout = this.props.bufferLayout || [];\n this.sharedRenderPipeline = this.props._sharedRenderPipeline || null;\n }\n\n /** Draw call. Returns false if the draw call was aborted (due to resources still initializing) */\n abstract draw(options: {\n /** Render pass to draw into (targeting screen or framebuffer) */\n renderPass?: RenderPass;\n /** Parameters to be set during draw call. Note that most parameters can only be overridden in WebGL. */\n parameters?: RenderPipelineParameters;\n /** Topology. Note can only be overridden in WebGL. */\n topology?: PrimitiveTopology;\n /** vertex attributes */\n vertexArray: VertexArray;\n /** Use instanced rendering? */\n isInstanced?: boolean;\n /** Number of \"rows\" in 'instance' buffers */\n instanceCount?: number;\n /** Number of \"rows\" in 'vertex' buffers */\n vertexCount?: number;\n /** Number of \"rows\" in index buffer */\n indexCount?: number;\n /** First vertex to draw from */\n firstVertex?: number;\n /** First index to draw from */\n firstIndex?: number;\n /** First instance to draw from */\n firstInstance?: number;\n baseVertex?: number;\n /** Transform feedback. WebGL only. */\n transformFeedback?: TransformFeedback;\n /** Bindings applied for this draw (textures, samplers, uniform buffers) */\n bindings?: Bindings;\n /** Bindings grouped by bind-group index */\n bindGroups?: BindingsByGroup;\n /** Optional stable cache keys for backend bind-group reuse */\n _bindGroupCacheKeys?: Partial<Record<number, object>>;\n /** WebGL-only uniforms */\n uniforms?: Record<string, unknown>;\n }): boolean;\n\n static override defaultProps: Required<RenderPipelineProps> = {\n ...Resource.defaultProps,\n\n vs: null,\n vertexEntryPoint: 'vertexMain',\n vsConstants: {},\n\n fs: null,\n fragmentEntryPoint: 'fragmentMain',\n fsConstants: {},\n\n shaderLayout: null,\n bufferLayout: [],\n topology: 'triangle-list',\n\n colorAttachmentFormats: undefined!,\n depthStencilAttachmentFormat: undefined!,\n\n parameters: {},\n varyings: undefined!,\n bufferMode: undefined!,\n disableWarnings: false,\n _sharedRenderPipeline: undefined!,\n bindings: undefined!,\n bindGroups: undefined!\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {Shader} from './shader';\nimport {Resource, type ResourceProps} from './resource';\n\nexport type SharedRenderPipelineProps = ResourceProps & {\n handle?: unknown;\n vs: Shader;\n fs: Shader;\n varyings?: string[];\n bufferMode?: number;\n};\n\n/**\n * Internal base class for backend-specific shared render-pipeline implementations.\n * Backends may use this to share expensive linked/program state across multiple\n * `RenderPipeline` wrappers.\n */\nexport abstract class SharedRenderPipeline extends Resource<SharedRenderPipelineProps> {\n override get [Symbol.toStringTag](): string {\n return 'SharedRenderPipeline';\n }\n\n abstract override readonly device: Device;\n abstract override readonly handle: unknown;\n\n constructor(device: Device, props: SharedRenderPipelineProps) {\n super(device, props, {\n ...Resource.defaultProps,\n handle: undefined!,\n vs: undefined!,\n fs: undefined!,\n varyings: undefined!,\n bufferMode: undefined!\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Resource, ResourceProps} from './resource';\nimport type {ComputeShaderLayout, Bindings, BindingsByGroup} from '../types/shader-layout';\nimport type {Device} from '../device';\nimport type {Shader} from './shader';\n\n/**\n * Properties for a compute pipeline\n */\nexport type ComputePipelineProps = ResourceProps & {\n handle?: unknown;\n /** Compiled shader object */\n shader: Shader;\n /** The entry point, defaults to main */\n entryPoint?: string;\n /** These are WGSL constant values - different from GLSL defines in that shader does not need to be recompiled */\n constants?: Record<string, number>;\n /** Describes the attributes and bindings exposed by the pipeline shader(s). */\n shaderLayout?: ComputeShaderLayout | null;\n};\n\n/**\n * A compiled and linked shader program for compute\n */\nexport abstract class ComputePipeline extends Resource<ComputePipelineProps> {\n override get [Symbol.toStringTag](): string {\n return 'ComputePipeline';\n }\n\n hash: string = '';\n /** The merged shader layout */\n shaderLayout: ComputeShaderLayout;\n\n constructor(device: Device, props: ComputePipelineProps) {\n super(device, props, ComputePipeline.defaultProps);\n this.shaderLayout = props.shaderLayout!;\n }\n\n /**\n * @todo Use renderpass.setBindings() ?\n * @todo Do we want to expose BindGroups in the API and remove this?\n */\n abstract setBindings(bindings: Bindings | BindingsByGroup): void;\n\n static override defaultProps: Required<ComputePipelineProps> = {\n ...Resource.defaultProps,\n shader: undefined!,\n entryPoint: undefined!,\n constants: {},\n shaderLayout: undefined!\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../adapter/device';\nimport {ComputePipeline, type ComputePipelineProps} from '../adapter/resources/compute-pipeline';\nimport {RenderPipeline, type RenderPipelineProps} from '../adapter/resources/render-pipeline';\nimport {Resource} from '../adapter/resources/resource';\nimport type {SharedRenderPipeline} from '../adapter/resources/shared-render-pipeline';\nimport {log} from '../utils/log';\nimport {uid} from '../utils/uid';\nimport type {CoreModuleState} from './core-module-state';\n\nexport type PipelineFactoryProps = RenderPipelineProps;\n\ntype CacheItem<ResourceT extends Resource<any>> = {resource: ResourceT; useCount: number};\n\n/**\n * Efficiently creates / caches pipelines\n */\nexport class PipelineFactory {\n static defaultProps: Required<PipelineFactoryProps> = {...RenderPipeline.defaultProps};\n\n /** Get the singleton default pipeline factory for the specified device */\n static getDefaultPipelineFactory(device: Device): PipelineFactory {\n const moduleData = device.getModuleData<CoreModuleState>('@luma.gl/core');\n moduleData.defaultPipelineFactory ||= new PipelineFactory(device);\n return moduleData.defaultPipelineFactory;\n }\n\n readonly device: Device;\n\n private _hashCounter: number = 0;\n private readonly _hashes: Record<string, number> = {};\n private readonly _renderPipelineCache: Record<string, CacheItem<RenderPipeline>> = {};\n private readonly _computePipelineCache: Record<string, CacheItem<ComputePipeline>> = {};\n private readonly _sharedRenderPipelineCache: Record<string, CacheItem<SharedRenderPipeline>> = {};\n\n get [Symbol.toStringTag](): string {\n return 'PipelineFactory';\n }\n\n toString(): string {\n return `PipelineFactory(${this.device.id})`;\n }\n\n constructor(device: Device) {\n this.device = device;\n }\n\n /**\n * WebGL has two cache layers with different priorities:\n * - `_sharedRenderPipelineCache` owns `WEBGLSharedRenderPipeline` / `WebGLProgram` reuse.\n * - `_renderPipelineCache` owns `RenderPipeline` wrapper reuse.\n *\n * Shared WebGL program reuse is the hard requirement. Wrapper reuse is beneficial,\n * but wrapper cache misses are acceptable if that keeps the cache logic simple and\n * prevents incorrect cache hits.\n *\n * In particular, wrapper hash logic must never force program creation or linked-program\n * introspection just to decide whether a shared WebGL program can be reused.\n */\n /** Return a RenderPipeline matching supplied props. Reuses an equivalent pipeline if already created. */\n createRenderPipeline(props: RenderPipelineProps): RenderPipeline {\n if (!this.device.props._cachePipelines) {\n return this.device.createRenderPipeline(props);\n }\n\n const allProps: Required<RenderPipelineProps> = {...RenderPipeline.defaultProps, ...props};\n\n const cache = this._renderPipelineCache;\n const hash = this._hashRenderPipeline(allProps);\n\n let pipeline: RenderPipeline = cache[hash]?.resource;\n if (!pipeline) {\n const sharedRenderPipeline =\n this.device.type === 'webgl' && this.device.props._sharePipelines\n ? this.createSharedRenderPipeline(allProps)\n : undefined;\n pipeline = this.device.createRenderPipeline({\n ...allProps,\n id: allProps.id ? `${allProps.id}-cached` : uid('unnamed-cached'),\n _sharedRenderPipeline: sharedRenderPipeline\n });\n pipeline.hash = hash;\n cache[hash] = {resource: pipeline, useCount: 1};\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} created, count=${cache[hash].useCount}`)();\n }\n } else {\n cache[hash].useCount++;\n if (this.device.props.debugFactories) {\n log.log(\n 3,\n `${this}: ${cache[hash].resource} reused, count=${cache[hash].useCount}, (id=${props.id})`\n )();\n }\n }\n\n return pipeline;\n }\n\n /** Return a ComputePipeline matching supplied props. Reuses an equivalent pipeline if already created. */\n createComputePipeline(props: ComputePipelineProps): ComputePipeline {\n if (!this.device.props._cachePipelines) {\n return this.device.createComputePipeline(props);\n }\n\n const allProps: Required<ComputePipelineProps> = {...ComputePipeline.defaultProps, ...props};\n\n const cache = this._computePipelineCache;\n const hash = this._hashComputePipeline(allProps);\n\n let pipeline: ComputePipeline = cache[hash]?.resource;\n if (!pipeline) {\n pipeline = this.device.createComputePipeline({\n ...allProps,\n id: allProps.id ? `${allProps.id}-cached` : undefined\n });\n pipeline.hash = hash;\n cache[hash] = {resource: pipeline, useCount: 1};\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} created, count=${cache[hash].useCount}`)();\n }\n } else {\n cache[hash].useCount++;\n if (this.device.props.debugFactories) {\n log.log(\n 3,\n `${this}: ${cache[hash].resource} reused, count=${cache[hash].useCount}, (id=${props.id})`\n )();\n }\n }\n\n return pipeline;\n }\n\n release(pipeline: RenderPipeline | ComputePipeline): void {\n if (!this.device.props._cachePipelines) {\n pipeline.destroy();\n return;\n }\n\n const cache = this._getCache(pipeline);\n const hash = pipeline.hash;\n\n cache[hash].useCount--;\n if (cache[hash].useCount === 0) {\n this._destroyPipeline(pipeline);\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} released and destroyed`)();\n }\n } else if (cache[hash].useCount < 0) {\n log.error(`${this}: ${pipeline} released, useCount < 0, resetting`)();\n cache[hash].useCount = 0;\n } else if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} released, count=${cache[hash].useCount}`)();\n }\n }\n\n createSharedRenderPipeline(props: RenderPipelineProps): SharedRenderPipeline {\n const sharedPipelineHash = this._hashSharedRenderPipeline(props);\n let sharedCacheItem = this._sharedRenderPipelineCache[sharedPipelineHash];\n if (!sharedCacheItem) {\n const sharedRenderPipeline = this.device._createSharedRenderPipelineWebGL(props);\n sharedCacheItem = {resource: sharedRenderPipeline, useCount: 0};\n this._sharedRenderPipelineCache[sharedPipelineHash] = sharedCacheItem;\n }\n sharedCacheItem.useCount++;\n return sharedCacheItem.resource;\n }\n\n releaseSharedRenderPipeline(pipeline: RenderPipeline): void {\n if (!pipeline.sharedRenderPipeline) {\n return;\n }\n\n const sharedPipelineHash = this._hashSharedRenderPipeline(pipeline.sharedRenderPipeline.props);\n const sharedCacheItem = this._sharedRenderPipelineCache[sharedPipelineHash];\n if (!sharedCacheItem) {\n return;\n }\n\n sharedCacheItem.useCount--;\n if (sharedCacheItem.useCount === 0) {\n sharedCacheItem.resource.destroy();\n delete this._sharedRenderPipelineCache[sharedPipelineHash];\n }\n }\n\n // PRIVATE\n\n /** Destroy a cached pipeline, removing it from the cache if configured to do so. */\n private _destroyPipeline(pipeline: RenderPipeline | ComputePipeline): boolean {\n const cache = this._getCache(pipeline);\n\n if (!this.device.props._destroyPipelines) {\n return false;\n }\n\n delete cache[pipeline.hash];\n pipeline.destroy();\n if (pipeline instanceof RenderPipeline) {\n this.releaseSharedRenderPipeline(pipeline);\n }\n return true;\n }\n\n /** Get the appropriate cache for the type of pipeline */\n private _getCache(\n pipeline: RenderPipeline | ComputePipeline\n ): Record<string, CacheItem<RenderPipeline>> | Record<string, CacheItem<ComputePipeline>> {\n let cache:\n | Record<string, CacheItem<RenderPipeline>>\n | Record<string, CacheItem<ComputePipeline>>\n | undefined;\n if (pipeline instanceof ComputePipeline) {\n cache = this._computePipelineCache;\n }\n if (pipeline instanceof RenderPipeline) {\n cache = this._renderPipelineCache;\n }\n if (!cache) {\n throw new Error(`${this}`);\n }\n if (!cache[pipeline.hash]) {\n throw new Error(`${this}: ${pipeline} matched incorrect entry`);\n }\n return cache;\n }\n\n /** Calculate a hash based on all the inputs for a compute pipeline */\n private _hashComputePipeline(props: ComputePipelineProps): string {\n const {type} = this.device;\n const shaderHash = this._getHash(props.shader.source);\n const shaderLayoutHash = this._getHash(JSON.stringify(props.shaderLayout));\n return `${type}/C/${shaderHash}SL${shaderLayoutHash}`;\n }\n\n /** Calculate a hash based on all the inputs for a render pipeline */\n private _hashRenderPipeline(props: RenderPipelineProps): string {\n // Backend-specific hashing requirements:\n // - WebGPU hash keys must include every immutable descriptor-shaping input that can\n // change the created `GPURenderPipeline`, including attachment formats.\n // - WebGL hash keys only govern wrapper reuse. They must remain compatible with\n // shared-program reuse and must not depend on linked-program introspection just\n // to decide whether a shared `WebGLProgram` can be reused.\n //\n // General exclusions:\n // - `id`, `handle`: resource identity / caller-supplied handles, not cache shape\n // - `bindings`: mutable per-pipeline compatibility state\n // - `disableWarnings`: logging only, no rendering impact\n // - `vsConstants`, `fsConstants`: currently unused by pipeline creation\n const vsHash = props.vs ? this._getHash(props.vs.source) : 0;\n const fsHash = props.fs ? this._getHash(props.fs.source) : 0;\n const varyingHash = this._getWebGLVaryingHash(props);\n const shaderLayoutHash = this._getHash(JSON.stringify(props.shaderLayout));\n const bufferLayoutHash = this._getHash(JSON.stringify(props.bufferLayout));\n\n const {type} = this.device;\n switch (type) {\n case 'webgl':\n // WebGL wrappers preserve default topology and parameter semantics for direct\n // callers, even though the underlying linked program may be shared separately.\n // Future WebGL-only additions here must not turn wrapper reuse into a prerequisite\n // for shared `WebGLProgram` reuse.\n const webglParameterHash = this._getHash(JSON.stringify(props.parameters));\n return `${type}/R/${vsHash}/${fsHash}V${varyingHash}T${props.topology}P${webglParameterHash}SL${shaderLayoutHash}BL${bufferLayoutHash}`;\n\n case 'webgpu':\n default:\n // On WebGPU we need to rebuild the pipeline if topology, entry points,\n // shader/layout data, parameters, bufferLayout or attachment formats change.\n // Attachment formats must stay in the key so screen and offscreen passes do not\n // accidentally alias the same cached `GPURenderPipeline`.\n const entryPointHash = this._getHash(\n JSON.stringify({\n vertexEntryPoint: props.vertexEntryPoint,\n fragmentEntryPoint: props.fragmentEntryPoint\n })\n );\n const parameterHash = this._getHash(JSON.stringify(props.parameters));\n const attachmentHash = this._getWebGPUAttachmentHash(props);\n // TODO - Can json.stringify() generate different strings for equivalent objects if order of params is different?\n // create a deepHash() to deduplicate?\n return `${type}/R/${vsHash}/${fsHash}V${varyingHash}T${props.topology}EP${entryPointHash}P${parameterHash}SL${shaderLayoutHash}BL${bufferLayoutHash}A${attachmentHash}`;\n }\n }\n\n // This is the only gate for shared `WebGLProgram` reuse.\n // Only include inputs that affect program linking or transform-feedback linkage.\n // Wrapper-only concerns such as topology, parameters, attachment formats and layout\n // overrides must not be added here.\n private _hashSharedRenderPipeline(props: RenderPipelineProps): string {\n const vsHash = props.vs ? this._getHash(props.vs.source) : 0;\n const fsHash = props.fs ? this._getHash(props.fs.source) : 0;\n const varyingHash = this._getWebGLVaryingHash(props);\n return `webgl/S/${vsHash}/${fsHash}V${varyingHash}`;\n }\n\n private _getHash(key: string): number {\n if (this._hashes[key] === undefined) {\n this._hashes[key] = this._hashCounter++;\n }\n return this._hashes[key];\n }\n\n private _getWebGLVaryingHash(props: RenderPipelineProps): number {\n const {varyings = [], bufferMode = null} = props;\n return this._getHash(JSON.stringify({varyings, bufferMode}));\n }\n\n private _getWebGPUAttachmentHash(props: RenderPipelineProps): number {\n const colorAttachmentFormats = props.colorAttachmentFormats ?? [\n this.device.preferredColorFormat\n ];\n const depthStencilAttachmentFormat = props.parameters?.depthWriteEnabled\n ? props.depthStencilAttachmentFormat || this.device.preferredDepthFormat\n : null;\n\n return this._getHash(\n JSON.stringify({\n colorAttachmentFormats,\n depthStencilAttachmentFormat\n })\n );\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../adapter/device';\nimport {Shader, type ShaderProps} from '../adapter/resources/shader';\nimport {log} from '../utils/log';\nimport type {CoreModuleState} from './core-module-state';\n\ntype CacheItem = {resource: Shader; useCount: number};\n\n/** Manages a cached pool of Shaders for reuse. */\nexport class ShaderFactory {\n static readonly defaultProps: Required<ShaderProps> = {...Shader.defaultProps};\n\n /** Returns the default ShaderFactory for the given {@link Device}, creating one if necessary. */\n static getDefaultShaderFactory(device: Device): ShaderFactory {\n const moduleData = device.getModuleData<CoreModuleState>('@luma.gl/core');\n moduleData.defaultShaderFactory ||= new ShaderFactory(device);\n return moduleData.defaultShaderFactory;\n }\n\n public readonly device: Device;\n\n private readonly _cache: Record<string, CacheItem> = {};\n\n get [Symbol.toStringTag](): string {\n return 'ShaderFactory';\n }\n\n toString(): string {\n return `${this[Symbol.toStringTag]}(${this.device.id})`;\n }\n\n /** @internal */\n constructor(device: Device) {\n this.device = device;\n }\n\n /** Requests a {@link Shader} from the cache, creating a new Shader only if necessary. */\n createShader(props: ShaderProps): Shader {\n if (!this.device.props._cacheShaders) {\n return this.device.createShader(props);\n }\n\n const key = this._hashShader(props);\n\n let cacheEntry = this._cache[key];\n if (!cacheEntry) {\n const resource = this.device.createShader({\n ...props,\n id: props.id ? `${props.id}-cached` : undefined\n });\n this._cache[key] = cacheEntry = {resource, useCount: 1};\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: Created new shader ${resource.id}`)();\n }\n } else {\n cacheEntry.useCount++;\n if (this.device.props.debugFactories) {\n log.log(\n 3,\n `${this}: Reusing shader ${cacheEntry.resource.id} count=${cacheEntry.useCount}`\n )();\n }\n }\n\n return cacheEntry.resource;\n }\n\n /** Releases a previously-requested {@link Shader}, destroying it if no users remain. */\n release(shader: Shader): void {\n if (!this.device.props._cacheShaders) {\n shader.destroy();\n return;\n }\n\n const key = this._hashShader(shader);\n const cacheEntry = this._cache[key];\n if (cacheEntry) {\n cacheEntry.useCount--;\n if (cacheEntry.useCount === 0) {\n if (this.device.props._destroyShaders) {\n delete this._cache[key];\n cacheEntry.resource.destroy();\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: Releasing shader ${shader.id}, destroyed`)();\n }\n }\n } else if (cacheEntry.useCount < 0) {\n throw new Error(`ShaderFactory: Shader ${shader.id} released too many times`);\n } else if (this.device.props.debugFactories) {\n log.log(3, `${this}: Releasing shader ${shader.id} count=${cacheEntry.useCount}`)();\n }\n }\n }\n\n // PRIVATE\n\n protected _hashShader(value: Shader | ShaderProps): string {\n return `${value.stage}:${value.source}`;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n BindingDeclaration,\n Bindings,\n BindingsByGroup,\n ComputeShaderLayout,\n ShaderLayout\n} from '../adapter/types/shader-layout';\nimport {log} from '../utils/log';\n\ntype AnyShaderLayout = Pick<ShaderLayout | ComputeShaderLayout, 'bindings'>;\n\nexport function getShaderLayoutBinding(\n shaderLayout: AnyShaderLayout,\n bindingName: string,\n options?: {ignoreWarnings?: boolean}\n): BindingDeclaration | null {\n const bindingLayout = shaderLayout.bindings.find(\n binding =>\n binding.name === bindingName ||\n `${binding.name.toLocaleLowerCase()}uniforms` === bindingName.toLocaleLowerCase()\n );\n\n if (!bindingLayout && !options?.ignoreWarnings) {\n log.warn(`Binding ${bindingName} not set: Not found in shader layout.`)();\n }\n\n return bindingLayout || null;\n}\n\nexport function normalizeBindingsByGroup(\n shaderLayout: AnyShaderLayout,\n bindingsOrBindGroups?: Bindings | BindingsByGroup\n): BindingsByGroup {\n if (!bindingsOrBindGroups) {\n return {};\n }\n\n if (areBindingsGrouped(bindingsOrBindGroups)) {\n const bindGroups = bindingsOrBindGroups as BindingsByGroup;\n return Object.fromEntries(\n Object.entries(bindGroups).map(([group, bindings]) => [Number(group), {...bindings}])\n ) as BindingsByGroup;\n }\n\n const bindGroups: BindingsByGroup = {};\n for (const [bindingName, binding] of Object.entries(bindingsOrBindGroups as Bindings)) {\n const bindingLayout = getShaderLayoutBinding(shaderLayout, bindingName);\n const group = bindingLayout?.group ?? 0;\n bindGroups[group] ||= {};\n bindGroups[group][bindingName] = binding;\n }\n\n return bindGroups;\n}\n\nexport function flattenBindingsByGroup(bindGroups: BindingsByGroup): Bindings {\n const bindings: Bindings = {};\n for (const groupBindings of Object.values(bindGroups)) {\n Object.assign(bindings, groupBindings);\n }\n return bindings;\n}\n\nfunction areBindingsGrouped(bindingsOrBindGroups: Bindings | BindingsByGroup): boolean {\n const keys = Object.keys(bindingsOrBindGroups);\n return keys.length > 0 && keys.every(key => /^\\d+$/.test(key));\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n Bindings,\n BindingsByGroup,\n ComputeShaderLayout,\n ShaderLayout\n} from '../adapter/types/shader-layout';\nimport type {Device} from '../adapter/device';\nimport type {ComputePipeline} from '../adapter/resources/compute-pipeline';\nimport type {RenderPipeline} from '../adapter/resources/render-pipeline';\nimport {normalizeBindingsByGroup} from '../adapter-utils/bind-groups';\n\ntype AnyPipeline = RenderPipeline | ComputePipeline;\ntype AnyShaderLayout = ShaderLayout | ComputeShaderLayout;\ntype BindGroupCacheKeys = Partial<Record<number, object>>;\ntype BindGroupMap = Partial<Record<number, unknown>>;\ntype LayoutCache = Partial<Record<number, object>>;\ntype LayoutBindGroupCache = {\n bindGroupsBySource: WeakMap<object, unknown | null>;\n emptyBindGroup?: unknown;\n};\n\nexport class BindGroupFactory {\n readonly device: Device;\n\n private readonly _layoutCacheByPipeline: WeakMap<AnyPipeline, LayoutCache> = new WeakMap();\n private readonly _bindGroupCacheByLayout: WeakMap<object, LayoutBindGroupCache> = new WeakMap();\n\n constructor(device: Device) {\n this.device = device;\n }\n\n getBindGroups(\n pipeline: AnyPipeline,\n bindings?: Bindings | BindingsByGroup,\n bindGroupCacheKeys?: BindGroupCacheKeys\n ): BindGroupMap {\n if (this.device.type !== 'webgpu' || pipeline.shaderLayout.bindings.length === 0) {\n return {};\n }\n\n const bindingsByGroup = normalizeBindingsByGroup(pipeline.shaderLayout, bindings);\n const resolvedBindGroups: BindGroupMap = {};\n\n for (const group of getBindGroupIndicesUpToMax(pipeline.shaderLayout.bindings)) {\n const groupBindings = bindingsByGroup[group];\n const bindGroupLayout = this._getBindGroupLayout(pipeline, group);\n\n if (!groupBindings || Object.keys(groupBindings).length === 0) {\n if (!hasBindingsInGroup(pipeline.shaderLayout.bindings, group)) {\n resolvedBindGroups[group] = this._getEmptyBindGroup(\n bindGroupLayout,\n pipeline.shaderLayout,\n group\n );\n }\n continue;\n }\n\n const bindGroupCacheKey = bindGroupCacheKeys?.[group];\n if (bindGroupCacheKey) {\n const layoutCache = this._getLayoutBindGroupCache(bindGroupLayout);\n if (layoutCache.bindGroupsBySource.has(bindGroupCacheKey)) {\n resolvedBindGroups[group] = layoutCache.bindGroupsBySource.get(bindGroupCacheKey) || null;\n continue;\n }\n\n const bindGroup = this.device._createBindGroupWebGPU(\n bindGroupLayout,\n pipeline.shaderLayout,\n groupBindings,\n group\n );\n layoutCache.bindGroupsBySource.set(bindGroupCacheKey, bindGroup);\n resolvedBindGroups[group] = bindGroup;\n } else {\n resolvedBindGroups[group] = this.device._createBindGroupWebGPU(\n bindGroupLayout,\n pipeline.shaderLayout,\n groupBindings,\n group\n );\n }\n }\n\n return resolvedBindGroups;\n }\n\n private _getBindGroupLayout(pipeline: AnyPipeline, group: number): object {\n let layoutCache = this._layoutCacheByPipeline.get(pipeline);\n if (!layoutCache) {\n layoutCache = {};\n this._layoutCacheByPipeline.set(pipeline, layoutCache);\n }\n\n layoutCache[group] ||= this.device._createBindGroupLayoutWebGPU(pipeline, group) as object;\n return layoutCache[group];\n }\n\n private _getEmptyBindGroup(\n bindGroupLayout: object,\n shaderLayout: AnyShaderLayout,\n group: number\n ): unknown {\n const layoutCache = this._getLayoutBindGroupCache(bindGroupLayout);\n layoutCache.emptyBindGroup ||=\n this.device._createBindGroupWebGPU(bindGroupLayout, shaderLayout, {}, group) || null;\n return layoutCache.emptyBindGroup;\n }\n\n private _getLayoutBindGroupCache(bindGroupLayout: object): LayoutBindGroupCache {\n let layoutCache = this._bindGroupCacheByLayout.get(bindGroupLayout);\n if (!layoutCache) {\n layoutCache = {bindGroupsBySource: new WeakMap()};\n this._bindGroupCacheByLayout.set(bindGroupLayout, layoutCache);\n }\n return layoutCache;\n }\n}\n\nexport function _getDefaultBindGroupFactory(device: Device): BindGroupFactory {\n device._factories.bindGroupFactory ||= new BindGroupFactory(device);\n return device._factories.bindGroupFactory as BindGroupFactory;\n}\n\nfunction getBindGroupIndicesUpToMax(bindings: AnyShaderLayout['bindings']): number[] {\n const maxGroup = bindings.reduce(\n (highestGroup, binding) => Math.max(highestGroup, binding.group),\n -1\n );\n return Array.from({length: maxGroup + 1}, (_, group) => group);\n}\n\nfunction hasBindingsInGroup(bindings: AnyShaderLayout['bindings'], group: number): boolean {\n return bindings.some(binding => binding.group === group);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumberArray4, TypedArray} from '@math.gl/types';\nimport type {Device} from '../device';\nimport type {RenderPassParameters} from '../types/parameters';\n// import {Binding} from '../types/shader-layout';\nimport {Resource, ResourceProps} from './resource';\nimport {Framebuffer} from './framebuffer';\nimport {QuerySet} from './query-set';\n\n/**\n * Properties for a RenderPass instance is a required parameter to all draw calls.\n */\nexport type RenderPassProps = ResourceProps & {\n /** Framebuffer specifies which textures to render into. Default gets framebuffer from canvas context. */\n framebuffer?: Framebuffer | null;\n /** Control viewport, scissor rect, blend constant and stencil ref */\n parameters?: RenderPassParameters;\n\n // TODO - API needs to be able to control multiple render targets\n\n /** Clear value for color attachment, or false to preserve the previous value */\n clearColor?: NumberArray4 | TypedArray | false;\n /** Experimental: Clear color values for multiple color attachments. Must specify typed arrays. props.clearColor will be ignored. */\n clearColors?: (TypedArray | false)[];\n /** Clear value for depth attachment (true === `1`), or false to preserve the previous value. Must be between 0.0 (near) and 1.0 (far), inclusive. */\n clearDepth?: number | false;\n /** Clear value for stencil attachment (true === `0`), or false to preserve the previous value. Converted to the type and number of LSBs as the number of bits in the stencil aspect */\n clearStencil?: number | false;\n\n /** Indicates that the depth component is read only. */\n depthReadOnly?: boolean;\n /** Indicates that the stencil component is read only. */\n stencilReadOnly?: boolean;\n\n /** Whether to disable / discard the output of the rasterizer */\n discard?: boolean;\n\n /** QuerySet to write begin/end timestamps to */\n occlusionQuerySet?: QuerySet;\n /** QuerySet to write begin/end timestamps to */\n timestampQuerySet?: QuerySet;\n /** QuerySet index to write begin timestamp to. No timestamp is written if not provided. */\n beginTimestampIndex?: number;\n /** QuerySet index to write end timestamp to. No timestamp is written if not provided. */\n endTimestampIndex?: number;\n};\n\n/**\n * A RenderPass instance is a required parameter to all draw calls.\n *\n * It holds a combination of\n * - render targets (specified via a framebuffer)\n * - clear colors, read/write, discard information for the framebuffer attachments\n * - a couple of mutable parameters ()\n */\nexport abstract class RenderPass extends Resource<RenderPassProps> {\n /** TODO - should be [0, 0, 0, 0], update once deck.gl tests run clean */\n static defaultClearColor: [number, number, number, number] = [0, 0, 0, 1];\n /** Depth 1.0 represents the far plance */\n static defaultClearDepth = 1;\n /** Clears all stencil bits */\n static defaultClearStencil = 0;\n\n override get [Symbol.toStringTag](): string {\n return 'RenderPass';\n }\n\n constructor(device: Device, props: RenderPassProps) {\n props = RenderPass.normalizeProps(device, props);\n super(device, props, RenderPass.defaultProps);\n }\n\n /** Call when rendering is done in this pass. */\n abstract end(): void;\n\n /** A few parameters can be changed at any time (viewport, scissorRect, blendColor, stencilReference) */\n abstract setParameters(parameters: RenderPassParameters): void;\n\n // executeBundles(bundles: Iterable<GPURenderBundle>): void;\n\n /** Being an occlusion query. Value will be stored in the occlusionQuerySet at the index. Occlusion queries cannot be nested. */\n abstract beginOcclusionQuery(queryIndex: number): void;\n /** End an occlusion query. Stores result in the index specified in beginOcclusionQuery. */\n abstract endOcclusionQuery(): void;\n\n /** Begins a labeled debug group containing subsequent commands */\n abstract pushDebugGroup(groupLabel: string): void;\n /** Ends the labeled debug group most recently started by pushDebugGroup() */\n abstract popDebugGroup(): void;\n /** Marks a point in a stream of commands with a label */\n abstract insertDebugMarker(markerLabel: string): void;\n\n protected static normalizeProps(device: Device, props: RenderPassProps): RenderPassProps {\n return props;\n }\n\n /** Default properties for RenderPass */\n static override defaultProps: Required<RenderPassProps> = {\n ...Resource.defaultProps,\n framebuffer: null,\n parameters: undefined!,\n clearColor: RenderPass.defaultClearColor,\n clearColors: undefined!,\n clearDepth: RenderPass.defaultClearDepth,\n clearStencil: RenderPass.defaultClearStencil,\n depthReadOnly: false,\n stencilReadOnly: false,\n discard: false,\n\n occlusionQuerySet: undefined!,\n timestampQuerySet: undefined!,\n beginTimestampIndex: undefined!,\n endTimestampIndex: undefined!\n };\n}\n\n// TODO - Can we align WebGL implementation with WebGPU API?\n// In WebGPU the following methods are on the renderpass instead of the renderpipeline\n// luma.gl keeps them on the pipeline for now, but that has some issues.\n\n// abstract setPipeline(pipeline: RenderPipeline): void {}\n// abstract setIndexBuffer()\n// abstract setVertexBuffer(slot: number, buffer: Buffer, offset: number): void;\n// abstract setBindings(bindings: Record<string, Binding>): void;\n// abstract setParameters(parameters: RenderPassParameters);\n// abstract draw(options: {\n// abstract drawIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): void;\n// abstract drawIndexedIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): void;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Resource, ResourceProps} from './resource';\nimport {ComputePipeline} from './compute-pipeline';\nimport type {Device} from '../device';\nimport {Buffer} from './buffer';\nimport {QuerySet} from './query-set';\n\nexport type ComputePassProps = ResourceProps & {\n /** QuerySet to write beging/end timestamps to */\n timestampQuerySet?: QuerySet;\n /** QuerySet index to write begin timestamp to. No timestamp is written if not provided. */\n beginTimestampIndex?: number;\n /** QuerySet index to write end timestamp to. No timestamp is written if not provided. */\n endTimestampIndex?: number;\n};\n\nexport abstract class ComputePass extends Resource<ComputePassProps> {\n constructor(device: Device, props: ComputePassProps) {\n super(device, props, ComputePass.defaultProps);\n }\n\n abstract override destroy(): void;\n\n abstract end(): void;\n\n abstract setPipeline(pipeline: ComputePipeline): void;\n\n /** Sets an array of bindings (uniform buffers, samplers, textures, ...) */\n // abstract setBindings(bindings: Binding[]): void;\n\n /**\n * Dispatch work to be performed with the current ComputePipeline.\n * @param x X dimension of the grid of workgroups to dispatch.\n * @param y Y dimension of the grid of workgroups to dispatch.\n * @param z Z dimension of the grid of workgroups to dispatch.\n */\n abstract dispatch(x: number, y?: number, z?: number): void;\n\n /**\n * Dispatch work to be performed with the current ComputePipeline.\n * @param indirectBuffer buffer must be a tightly packed block of three 32-bit unsigned integer values (12 bytes total), given in the same order as the arguments for dispatch()\n * @param indirectOffset\n */\n abstract dispatchIndirect(indirectBuffer: Buffer, indirectOffset?: number): void;\n\n /** Begins a labeled debug group containing subsequent commands */\n abstract pushDebugGroup(groupLabel: string): void;\n /** Ends the labeled debug group most recently started by pushDebugGroup() */\n abstract popDebugGroup(): void;\n /** Marks a point in a stream of commands with a label */\n abstract insertDebugMarker(markerLabel: string): void;\n\n static override defaultProps: Required<ComputePassProps> = {\n ...Resource.defaultProps,\n timestampQuerySet: undefined!,\n beginTimestampIndex: undefined!,\n endTimestampIndex: undefined!\n };\n\n override get [Symbol.toStringTag](): string {\n return 'ComputePass';\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// import type {TypedArray} from '@math.gl/types';\nimport {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\nimport {QuerySet} from './query-set';\nimport {Buffer} from './buffer';\nimport {Texture} from './texture';\nimport type {RenderPass, RenderPassProps} from './render-pass';\nimport type {ComputePass, ComputePassProps} from './compute-pass';\nimport type {CommandBuffer, CommandBufferProps} from './command-buffer';\n\n// WEBGPU COMMAND ENCODER OPERATIONS\n\nexport type CopyBufferToBufferOptions = {\n sourceBuffer: Buffer;\n sourceOffset?: number;\n destinationBuffer: Buffer;\n destinationOffset?: number;\n size: number;\n};\n\nexport type CopyBufferToTextureOptions = {\n sourceBuffer: Buffer;\n byteOffset?: number;\n destinationTexture: Texture;\n mipLevel?: number; // = 0;\n origin?: [number, number, number];\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n bytesPerRow: number;\n rowsPerImage: number;\n size: [number, number, number];\n};\n\nexport type CopyTextureToBufferOptions = {\n /** Texture to copy to/from. */\n sourceTexture: Texture;\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n mipLevel?: number;\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to/from.\n * Together with `copySize`, defines the full copy sub-region.\n */\n /** Defines which aspects of the texture to copy to/from. */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n\n /** Width to copy */\n width?: number;\n height?: number;\n depthOrArrayLayers?: number;\n origin?: [number, number, number];\n\n /** Destination buffer */\n destinationBuffer: Buffer;\n /** Offset, in bytes, from the beginning of the buffer to the start of the image data (default 0) */\n byteOffset?: number;\n /**\n * The stride, in bytes, between the beginning of each block row and the subsequent block row.\n * Required if there are multiple block rows (i.e. the copy height or depth is more than one block).\n */\n bytesPerRow?: number;\n /**\n * Number of block rows per single image of the texture.\n * rowsPerImage &times; bytesPerRow is the stride, in bytes, between the beginning of each image of data and the subsequent image.\n * Required if there are multiple images (i.e. the copy depth is more than one).\n */\n rowsPerImage?: number;\n};\n\nexport type CopyTextureToTextureOptions = {\n /** Texture to copy to/from. */\n sourceTexture: Texture;\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n mipLevel?: number;\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy from. */\n origin?: [number, number, number];\n /** Defines which aspects of the {@link GPUImageCopyTexture#texture} to copy to/from. */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n\n /** Texture to copy to/from. */\n destinationTexture: Texture;\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n destinationMipLevel?: number;\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to. */\n destinationOrigin?: [number, number, number];\n /** Defines which aspects of the {@link GPUImageCopyTexture#texture} to copy to/from. */\n destinationAspect?: 'all' | 'stencil-only' | 'depth-only';\n\n /** Width to copy */\n width?: number;\n height?: number;\n depthOrArrayLayers?: number;\n};\n\n// ADDITIONAL COMMAND ENCODER OPERATIONS DEFINED BY LUMA.GL\n\n/** Options for clearing a texture mip level */\nexport type ClearTextureOptions = {\n /** Texture to Clear. */\n texture: Texture;\n /** Mip-map level of the texture clear. (Default 0) */\n mipLevel?: number;\n /** Defines which aspects of the Texture to clear. */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\n// export type WriteBufferOptions = {\n// buffer: Buffer;\n// bufferOffset?: number;\n// data: BufferSource;\n// dataOffset?: number;\n// size?: number;\n// };\n\n// export type TextureWriteOptions = {\n// destination: Texture;\n// mipLevel?: number; // = 0;\n// origin?: [number, number, number] | number[];\n// aspect?: 'all' | 'stencil-only' | 'depth-only';\n// data: BufferSource;\n// // dataLayout;\n// offset: number;\n// bytesPerRow: number;\n// rowsPerImage: number;\n// size: [number, number, number] | number[];\n// };\n\nexport type CommandEncoderProps = ResourceProps & {\n measureExecutionTime?: boolean;\n timeProfilingQuerySet?: QuerySet | null;\n};\n\ntype PassWithTimestamps = {\n timestampQuerySet?: QuerySet;\n beginTimestampIndex?: number;\n endTimestampIndex?: number;\n};\n\n/**\n * Records commands onto a single backend command encoder and can finish them into one command\n * buffer. Resource helpers invoked through a CommandEncoder must record onto that encoder rather\n * than allocating hidden encoders or submitting work eagerly.\n */\nexport abstract class CommandEncoder extends Resource<CommandEncoderProps> {\n override get [Symbol.toStringTag](): string {\n return 'CommandEncoder';\n }\n\n protected _timeProfilingQuerySet: QuerySet | null = null;\n protected _timeProfilingSlotCount: number = 0;\n _gpuTimeMs?: number;\n\n constructor(device: Device, props: CommandEncoderProps) {\n super(device, props, CommandEncoder.defaultProps);\n this._timeProfilingQuerySet = props.timeProfilingQuerySet ?? null;\n this._timeProfilingSlotCount = 0;\n this._gpuTimeMs = undefined;\n }\n\n /** Completes recording of the commands sequence */\n abstract finish(props?: CommandBufferProps): CommandBuffer;\n\n /** Create a RenderPass using the default CommandEncoder */\n abstract beginRenderPass(props?: RenderPassProps): RenderPass;\n\n /** Create a ComputePass using the default CommandEncoder*/\n abstract beginComputePass(props?: ComputePassProps): ComputePass;\n\n /** Add a command that that copies data from a sub-region of a Buffer to a sub-region of another Buffer. */\n abstract copyBufferToBuffer(options: CopyBufferToBufferOptions): void;\n\n /** Add a command that copies data from a sub-region of a GPUBuffer to a sub-region of one or multiple continuous texture subresources. */\n abstract copyBufferToTexture(options: CopyBufferToTextureOptions): void;\n\n /** Add a command that copies data from a sub-region of one or multiple continuous texture subresources to a sub-region of a Buffer. */\n abstract copyTextureToBuffer(options: CopyTextureToBufferOptions): void;\n\n /** Add a command that copies data from a sub-region of one or multiple contiguous texture subresources to another sub-region of one or multiple continuous texture subresources. */\n abstract copyTextureToTexture(options: CopyTextureToTextureOptions): void;\n\n /** Add a command that clears a texture mip level. */\n // abstract clearTexture(options: ClearTextureOptions): void;\n\n // abstract readTexture(options: TextureReadOptions): Promise<TypedArray>;\n\n /** Reads results from a query set into a GPU buffer. Values are 64 bits so byteLength must be querySet.props.count * 8 */\n abstract resolveQuerySet(\n querySet: QuerySet,\n destination: Buffer,\n options?: {\n firstQuery?: number;\n queryCount?: number;\n destinationOffset?: number;\n }\n ): void;\n\n /**\n * Reads all resolved timestamp pairs on the current profiler query set and caches the sum\n * as milliseconds on this encoder.\n */\n async resolveTimeProfilingQuerySet(): Promise<void> {\n this._gpuTimeMs = undefined;\n\n if (!this._timeProfilingQuerySet) {\n return;\n }\n\n const pairCount = Math.floor(this._timeProfilingSlotCount / 2);\n if (pairCount <= 0) {\n return;\n }\n\n const queryCount = pairCount * 2;\n const results = await this._timeProfilingQuerySet.readResults({\n firstQuery: 0,\n queryCount\n });\n\n let totalDurationNanoseconds = 0n;\n for (let queryIndex = 0; queryIndex < queryCount; queryIndex += 2) {\n totalDurationNanoseconds += results[queryIndex + 1] - results[queryIndex];\n }\n\n this._gpuTimeMs = Number(totalDurationNanoseconds) / 1e6;\n }\n\n /** Returns the number of query slots consumed by automatic pass profiling on this encoder. */\n getTimeProfilingSlotCount(): number {\n return this._timeProfilingSlotCount;\n }\n\n getTimeProfilingQuerySet(): QuerySet | null {\n return this._timeProfilingQuerySet;\n }\n\n /** Internal helper for auto-assigning timestamp slots to render/compute passes on this encoder. */\n protected _applyTimeProfilingToPassProps<P extends PassWithTimestamps>(props?: P): P {\n const passProps = (props || {}) as P;\n\n if (!this._supportsTimestampQueries() || !this._timeProfilingQuerySet) {\n return passProps;\n }\n\n if (\n passProps.timestampQuerySet !== undefined ||\n passProps.beginTimestampIndex !== undefined ||\n passProps.endTimestampIndex !== undefined\n ) {\n return passProps;\n }\n\n const beginTimestampIndex = this._timeProfilingSlotCount;\n if (beginTimestampIndex + 1 >= this._timeProfilingQuerySet.props.count) {\n return passProps;\n }\n\n this._timeProfilingSlotCount += 2;\n\n return {\n ...passProps,\n timestampQuerySet: this._timeProfilingQuerySet,\n beginTimestampIndex,\n endTimestampIndex: beginTimestampIndex + 1\n };\n }\n\n protected _supportsTimestampQueries(): boolean {\n return this.device.features.has('timestamp-query');\n }\n\n /** Begins a labeled debug group containing subsequent commands */\n abstract pushDebugGroup(groupLabel: string): void;\n /** Ends the labeled debug group most recently started by pushDebugGroup() */\n abstract popDebugGroup(): void;\n /** Marks a point in a stream of commands with a label */\n abstract insertDebugMarker(markerLabel: string): void;\n\n // TODO - luma.gl has these on the device, should we align with WebGPU API?\n // beginRenderPass(GPURenderPassDescriptor descriptor): GPURenderPassEncoder;\n // beginComputePass(optional GPUComputePassDescriptor descriptor = {}): GPUComputePassEncoder;\n\n static override defaultProps: Required<CommandEncoderProps> = {\n ...Resource.defaultProps,\n measureExecutionTime: undefined!,\n timeProfilingQuerySet: undefined!\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\n// interface Queue {\n// submit(commandBuffers);\n\n// // onSubmittedWorkDone(): Promise<undefined>;\n\n// writeBuffer(options: WriteBufferOptions): void;\n// writeTexture(options: TextureWriteOptions): void;\n\n// // copyExternalImageToTexture(\n// // GPUImageCopyExternalImage source,\n// // GPUImageCopyTextureTagged destination,\n// // GPUExtent3D copySize\n// // ): void;\n// }\n\nexport type CommandBufferProps = ResourceProps & {};\n\n/**\n * Represents the finished contents of exactly one CommandEncoder. Backends may store native\n * command buffers or replayable command lists internally, but submission must preserve the same\n * recorded command ordering.\n */\nexport abstract class CommandBuffer extends Resource<CommandBufferProps> {\n override get [Symbol.toStringTag](): string {\n return 'CommandBuffer';\n }\n\n constructor(device: Device, props: CommandBufferProps) {\n super(device, props, CommandBuffer.defaultProps);\n }\n\n static override defaultProps: Required<CommandBufferProps> = {\n ...Resource.defaultProps\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {type PrimitiveDataType} from '../data-types/data-types';\nimport {\n type VariableShaderType,\n type AttributeShaderType,\n type VariableShaderTypeAlias,\n type AttributeShaderTypeAlias\n} from './shader-types';\n\n/** Information extracted from a VariableShaderType constant */\nexport type VariableShaderTypeInfo = {\n type: PrimitiveDataType;\n components: number;\n};\n\n/** Information extracted from a AttributeShaderType constant */\nexport type AttributeShaderTypeInfo = {\n /** WGSL-style primitive data type, f32, i32, u32 */\n primitiveType: PrimitiveDataType;\n /** Whether this is a normalized integer (that must be used as float) */\n components: 1 | 2 | 3 | 4;\n /** Length in bytes of the data for one vertex */\n byteLength?: number;\n /** Whether this is for integer or float vert */\n integer: boolean;\n /** Whether this data type is signed */\n signed: boolean;\n};\n\n/** Split a uniform type string into type and components */\nexport function getVariableShaderTypeInfo(\n format: VariableShaderType | VariableShaderTypeAlias\n): VariableShaderTypeInfo {\n const resolvedFormat = resolveVariableShaderTypeAlias(format);\n const decoded = UNIFORM_FORMATS[resolvedFormat];\n if (!decoded) {\n throw new Error(`Unsupported variable shader type: ${format}`);\n }\n return decoded;\n}\n\n/** Decodes a vertex type, returning byte length and flags (integer, signed, normalized) */\nexport function getAttributeShaderTypeInfo(\n attributeType: AttributeShaderType | AttributeShaderTypeAlias\n): AttributeShaderTypeInfo {\n const resolvedAttributeType = resolveAttributeShaderTypeAlias(attributeType);\n const decoded = TYPE_INFO[resolvedAttributeType];\n if (!decoded) {\n throw new Error(`Unsupported attribute shader type: ${attributeType}`);\n }\n const [primitiveType, components] = decoded;\n const integer: boolean = primitiveType === 'i32' || primitiveType === 'u32';\n const signed: boolean = primitiveType !== 'u32';\n\n const byteLength = PRIMITIVE_TYPE_SIZES[primitiveType] * components;\n return {\n primitiveType,\n components,\n byteLength,\n integer,\n signed\n };\n}\n\nexport class ShaderTypeDecoder {\n getVariableShaderTypeInfo(\n format: VariableShaderType | VariableShaderTypeAlias\n ): VariableShaderTypeInfo {\n return getVariableShaderTypeInfo(format);\n }\n\n getAttributeShaderTypeInfo(\n attributeType: AttributeShaderType | AttributeShaderTypeAlias\n ): AttributeShaderTypeInfo {\n return getAttributeShaderTypeInfo(attributeType);\n }\n\n makeShaderAttributeType(\n primitiveType: PrimitiveDataType,\n components: 1 | 2 | 3 | 4\n ): AttributeShaderType {\n return makeShaderAttributeType(primitiveType, components);\n }\n\n resolveAttributeShaderTypeAlias(\n alias: AttributeShaderTypeAlias | AttributeShaderType\n ): AttributeShaderType {\n return resolveAttributeShaderTypeAlias(alias);\n }\n\n resolveVariableShaderTypeAlias(\n alias: VariableShaderTypeAlias | VariableShaderType\n ): VariableShaderType {\n return resolveVariableShaderTypeAlias(alias);\n }\n}\n\nexport function makeShaderAttributeType(\n primitiveType: PrimitiveDataType,\n components: 1 | 2 | 3 | 4\n): AttributeShaderType {\n return components === 1 ? primitiveType : `vec${components}<${primitiveType}>`;\n}\n\nexport function resolveAttributeShaderTypeAlias(\n alias: AttributeShaderTypeAlias | AttributeShaderType\n): AttributeShaderType {\n return WGSL_ATTRIBUTE_TYPE_ALIAS_MAP[alias as AttributeShaderTypeAlias] || alias;\n}\n\nexport function resolveVariableShaderTypeAlias(\n alias: VariableShaderTypeAlias | VariableShaderType\n): VariableShaderType {\n return WGSL_VARIABLE_TYPE_ALIAS_MAP[alias as VariableShaderTypeAlias] || alias;\n}\n\n/** Decoder for luma.gl shader types */\nexport const shaderTypeDecoder = new ShaderTypeDecoder();\n\n// TABLES\n\nconst PRIMITIVE_TYPE_SIZES: Record<PrimitiveDataType, 2 | 4> = {\n f32: 4,\n f16: 2,\n i32: 4,\n u32: 4\n // 'bool-webgl': 4,\n};\n\n/** All valid shader attribute types. A table guarantees exhaustive list and fast execution */\nconst TYPE_INFO: Record<AttributeShaderType, [PrimitiveDataType, components: 1 | 2 | 3 | 4]> = {\n f32: ['f32', 1],\n 'vec2<f32>': ['f32', 2],\n 'vec3<f32>': ['f32', 3],\n 'vec4<f32>': ['f32', 4],\n f16: ['f16', 1],\n 'vec2<f16>': ['f16', 2],\n 'vec3<f16>': ['f16', 3],\n 'vec4<f16>': ['f16', 4],\n i32: ['i32', 1],\n 'vec2<i32>': ['i32', 2],\n 'vec3<i32>': ['i32', 3],\n 'vec4<i32>': ['i32', 4],\n u32: ['u32', 1],\n 'vec2<u32>': ['u32', 2],\n 'vec3<u32>': ['u32', 3],\n 'vec4<u32>': ['u32', 4]\n};\n\n/** @todo These tables are quite big, consider parsing type strings instead */\nconst UNIFORM_FORMATS: Record<VariableShaderType, {type: PrimitiveDataType; components: number}> = {\n f32: {type: 'f32', components: 1},\n f16: {type: 'f16', components: 1},\n i32: {type: 'i32', components: 1},\n u32: {type: 'u32', components: 1},\n // 'bool-webgl': {type: 'bool-webgl', components: 1},\n 'vec2<f32>': {type: 'f32', components: 2},\n 'vec3<f32>': {type: 'f32', components: 3},\n 'vec4<f32>': {type: 'f32', components: 4},\n 'vec2<f16>': {type: 'f16', components: 2},\n 'vec3<f16>': {type: 'f16', components: 3},\n 'vec4<f16>': {type: 'f16', components: 4},\n 'vec2<i32>': {type: 'i32', components: 2},\n 'vec3<i32>': {type: 'i32', components: 3},\n 'vec4<i32>': {type: 'i32', components: 4},\n 'vec2<u32>': {type: 'u32', components: 2},\n 'vec3<u32>': {type: 'u32', components: 3},\n 'vec4<u32>': {type: 'u32', components: 4},\n\n 'mat2x2<f32>': {type: 'f32', components: 4},\n 'mat2x3<f32>': {type: 'f32', components: 6},\n 'mat2x4<f32>': {type: 'f32', components: 8},\n 'mat3x2<f32>': {type: 'f32', components: 6},\n 'mat3x3<f32>': {type: 'f32', components: 9},\n 'mat3x4<f32>': {type: 'f32', components: 12},\n 'mat4x2<f32>': {type: 'f32', components: 8},\n 'mat4x3<f32>': {type: 'f32', components: 12},\n 'mat4x4<f32>': {type: 'f32', components: 16},\n\n 'mat2x2<f16>': {type: 'f16', components: 4},\n 'mat2x3<f16>': {type: 'f16', components: 6},\n 'mat2x4<f16>': {type: 'f16', components: 8},\n 'mat3x2<f16>': {type: 'f16', components: 6},\n 'mat3x3<f16>': {type: 'f16', components: 9},\n 'mat3x4<f16>': {type: 'f16', components: 12},\n 'mat4x2<f16>': {type: 'f16', components: 8},\n 'mat4x3<f16>': {type: 'f16', components: 12},\n 'mat4x4<f16>': {type: 'f16', components: 16},\n\n 'mat2x2<i32>': {type: 'i32', components: 4},\n 'mat2x3<i32>': {type: 'i32', components: 6},\n 'mat2x4<i32>': {type: 'i32', components: 8},\n 'mat3x2<i32>': {type: 'i32', components: 6},\n 'mat3x3<i32>': {type: 'i32', components: 9},\n 'mat3x4<i32>': {type: 'i32', components: 12},\n 'mat4x2<i32>': {type: 'i32', components: 8},\n 'mat4x3<i32>': {type: 'i32', components: 12},\n 'mat4x4<i32>': {type: 'i32', components: 16},\n\n 'mat2x2<u32>': {type: 'u32', components: 4},\n 'mat2x3<u32>': {type: 'u32', components: 6},\n 'mat2x4<u32>': {type: 'u32', components: 8},\n 'mat3x2<u32>': {type: 'u32', components: 6},\n 'mat3x3<u32>': {type: 'u32', components: 9},\n 'mat3x4<u32>': {type: 'u32', components: 12},\n 'mat4x2<u32>': {type: 'u32', components: 8},\n 'mat4x3<u32>': {type: 'u32', components: 12},\n 'mat4x4<u32>': {type: 'u32', components: 16}\n};\n\n/** Predeclared aliases @see https://www.w3.org/TR/WGSL/#vector-types */\nexport const WGSL_ATTRIBUTE_TYPE_ALIAS_MAP: Record<AttributeShaderTypeAlias, AttributeShaderType> =\n {\n vec2i: 'vec2<i32>',\n vec3i: 'vec3<i32>',\n vec4i: 'vec4<i32>',\n vec2u: 'vec2<u32>',\n vec3u: 'vec3<u32>',\n vec4u: 'vec4<u32>',\n vec2f: 'vec2<f32>',\n vec3f: 'vec3<f32>',\n vec4f: 'vec4<f32>',\n // Requires the f16 extension.\n vec2h: 'vec2<f16>',\n vec3h: 'vec3<f16>',\n vec4h: 'vec4<f16>'\n };\n\n/** @todo These tables are quite big, consider parsing alias strings instead */\nexport const WGSL_VARIABLE_TYPE_ALIAS_MAP: Record<VariableShaderTypeAlias, VariableShaderType> = {\n vec2i: 'vec2<i32>',\n vec3i: 'vec3<i32>',\n vec4i: 'vec4<i32>',\n vec2u: 'vec2<u32>',\n vec3u: 'vec3<u32>',\n vec4u: 'vec4<u32>',\n vec2f: 'vec2<f32>',\n vec3f: 'vec3<f32>',\n vec4f: 'vec4<f32>',\n vec2h: 'vec2<f16>',\n vec3h: 'vec3<f16>',\n vec4h: 'vec4<f16>',\n mat2x2f: 'mat2x2<f32>',\n mat2x3f: 'mat2x3<f32>',\n mat2x4f: 'mat2x4<f32>',\n mat3x2f: 'mat3x2<f32>',\n mat3x3f: 'mat3x3<f32>',\n mat3x4f: 'mat3x4<f32>',\n mat4x2f: 'mat4x2<f32>',\n mat4x3f: 'mat4x3<f32>',\n mat4x4f: 'mat4x4<f32>',\n\n mat2x2i: 'mat2x2<i32>',\n mat2x3i: 'mat2x3<i32>',\n mat2x4i: 'mat2x4<i32>',\n mat3x2i: 'mat3x2<i32>',\n mat3x3i: 'mat3x3<i32>',\n mat3x4i: 'mat3x4<i32>',\n mat4x2i: 'mat4x2<i32>',\n mat4x3i: 'mat4x3<i32>',\n mat4x4i: 'mat4x4<i32>',\n\n mat2x2u: 'mat2x2<u32>',\n mat2x3u: 'mat2x3<u32>',\n mat2x4u: 'mat2x4<u32>',\n mat3x2u: 'mat3x2<u32>',\n mat3x3u: 'mat3x3<u32>',\n mat3x4u: 'mat3x4<u32>',\n mat4x2u: 'mat4x2<u32>',\n mat4x3u: 'mat4x3<u32>',\n mat4x4u: 'mat4x4<u32>',\n\n mat2x2h: 'mat2x2<f16>',\n mat2x3h: 'mat2x3<f16>',\n mat2x4h: 'mat2x4<f16>',\n mat3x2h: 'mat3x2<f16>',\n mat3x3h: 'mat3x3<f16>',\n mat3x4h: 'mat3x4<f16>',\n mat4x2h: 'mat4x2<f16>',\n mat4x3h: 'mat4x3<f16>',\n mat4x4h: 'mat4x4<f16>'\n};\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log} from '../utils/log';\nimport type {PrimitiveDataType, NormalizedDataType} from '../shadertypes/data-types/data-types';\nimport type {AttributeShaderType} from '../shadertypes/shader-types/shader-types';\nimport type {VertexFormat} from '../shadertypes/vertex-types/vertex-formats';\nimport {shaderTypeDecoder} from '../shadertypes/shader-types/shader-type-decoder';\nimport {vertexFormatDecoder} from '../shadertypes/vertex-types/vertex-format-decoder';\nimport type {ShaderLayout, AttributeDeclaration} from '../adapter/types/shader-layout';\nimport type {BufferLayout} from '../adapter/types/buffer-layout';\n\n/** Resolved info for a buffer / attribute combination to help backend configure it correctly */\nexport type AttributeInfo = {\n /** Attribute name */\n attributeName: string;\n /** Location in shader */\n location: number;\n /** Type / precision used in shader (buffer values may be converted) */\n shaderType: AttributeShaderType;\n /** Calculations are done in this type in the shader's attribute declaration */\n primitiveType: PrimitiveDataType;\n /** Components refer to the number of components in the shader's attribute declaration */\n shaderComponents: 1 | 2 | 3 | 4;\n /** It is the shader attribute declaration that determines whether GPU will process as integer or float */\n integer: boolean;\n\n /** BufferName */\n bufferName: string;\n /** Format of buffer data */\n vertexFormat: VertexFormat;\n /** Memory data type refers to the data type in the buffer */\n bufferDataType: NormalizedDataType;\n /** Components refer to the number of components in the buffer's vertex format */\n bufferComponents: 1 | 2 | 3 | 4;\n /** Normalization is encoded in the buffer layout's vertex format... */\n normalized: boolean;\n\n /** If not specified, the step mode is inferred from the attribute name in the shader (contains string instance) */\n stepMode: 'vertex' | 'instance';\n\n /** The byteOffset is encoded in or calculated from the buffer layout */\n byteOffset: number;\n /** The byteStride is encoded in or calculated from the buffer layout */\n byteStride: number;\n};\n\ntype BufferAttributeInfo = {\n attributeName: string;\n bufferName: string;\n stepMode?: 'vertex' | 'instance';\n vertexFormat: VertexFormat;\n byteOffset: number;\n byteStride: number;\n};\n\n/**\n * Map from \"attribute names\" to \"resolved attribute infos\"\n * containing information about both buffer layouts and shader attribute declarations\n */\nexport function getAttributeInfosFromLayouts(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[]\n): Record<string, AttributeInfo> {\n const attributeInfos: Record<string, AttributeInfo> = {};\n for (const attribute of shaderLayout.attributes) {\n const attributeInfo = getAttributeInfoFromLayouts(shaderLayout, bufferLayout, attribute.name);\n if (attributeInfo) {\n attributeInfos[attribute.name] = attributeInfo;\n }\n }\n return attributeInfos;\n}\n\n/**\n * Array indexed by \"location\" holding \"resolved attribute infos\"\n */\nexport function getAttributeInfosByLocation(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[],\n maxVertexAttributes: number = 16\n): AttributeInfo[] {\n const attributeInfos = getAttributeInfosFromLayouts(shaderLayout, bufferLayout);\n const locationInfos: AttributeInfo[] = new Array(maxVertexAttributes).fill(null);\n for (const attributeInfo of Object.values(attributeInfos)) {\n locationInfos[attributeInfo.location] = attributeInfo;\n }\n return locationInfos;\n}\n\n/**\n * Get the combined information from a shader layout and a buffer layout for a specific attribute\n */\nfunction getAttributeInfoFromLayouts(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[],\n name: string\n): AttributeInfo | null {\n const shaderDeclaration = getAttributeFromShaderLayout(shaderLayout, name);\n const bufferMapping: BufferAttributeInfo | null = getAttributeFromBufferLayout(\n bufferLayout,\n name\n );\n\n // TODO should no longer happen\n if (!shaderDeclaration) {\n // || !bufferMapping\n return null;\n }\n\n const attributeTypeInfo = shaderTypeDecoder.getAttributeShaderTypeInfo(shaderDeclaration.type);\n const defaultVertexFormat = vertexFormatDecoder.getCompatibleVertexFormat(attributeTypeInfo);\n const vertexFormat = bufferMapping?.vertexFormat || defaultVertexFormat;\n const vertexFormatInfo = vertexFormatDecoder.getVertexFormatInfo(vertexFormat);\n\n return {\n attributeName: bufferMapping?.attributeName || shaderDeclaration.name,\n bufferName: bufferMapping?.bufferName || shaderDeclaration.name,\n location: shaderDeclaration.location,\n shaderType: shaderDeclaration.type,\n primitiveType: attributeTypeInfo.primitiveType,\n shaderComponents: attributeTypeInfo.components,\n vertexFormat,\n bufferDataType: vertexFormatInfo.type,\n bufferComponents: vertexFormatInfo.components,\n // normalized is a property of the buffer's vertex format\n normalized: vertexFormatInfo.normalized,\n // integer is a property of the shader declaration\n integer: attributeTypeInfo.integer,\n stepMode: bufferMapping?.stepMode || shaderDeclaration.stepMode || 'vertex',\n byteOffset: bufferMapping?.byteOffset || 0,\n byteStride: bufferMapping?.byteStride || 0\n };\n}\n\nfunction getAttributeFromShaderLayout(\n shaderLayout: ShaderLayout,\n name: string\n): AttributeDeclaration | null {\n const attribute = shaderLayout.attributes.find(attr => attr.name === name);\n if (!attribute) {\n log.warn(`shader layout attribute \"${name}\" not present in shader`);\n }\n return attribute || null;\n}\n\nfunction getAttributeFromBufferLayout(\n bufferLayouts: BufferLayout[],\n name: string\n): BufferAttributeInfo | null {\n // Check that bufferLayouts are valid (each either has format or attribute)\n checkBufferLayouts(bufferLayouts);\n\n let bufferLayoutInfo = getAttributeFromShortHand(bufferLayouts, name);\n if (bufferLayoutInfo) {\n return bufferLayoutInfo;\n }\n\n bufferLayoutInfo = getAttributeFromAttributesList(bufferLayouts, name);\n if (bufferLayoutInfo) {\n return bufferLayoutInfo;\n }\n\n // Didn't find...\n log.warn(`layout for attribute \"${name}\" not present in buffer layout`);\n return null;\n}\n\n/** Check that bufferLayouts are valid (each either has format or attribute) */\nfunction checkBufferLayouts(bufferLayouts: BufferLayout[]) {\n for (const bufferLayout of bufferLayouts) {\n if (\n (bufferLayout.attributes && bufferLayout.format) ||\n (!bufferLayout.attributes && !bufferLayout.format)\n ) {\n log.warn(`BufferLayout ${name} must have either 'attributes' or 'format' field`);\n }\n }\n}\n\n/** Get attribute from format shorthand if specified */\nfunction getAttributeFromShortHand(\n bufferLayouts: BufferLayout[],\n name: string\n): BufferAttributeInfo | null {\n for (const bufferLayout of bufferLayouts) {\n if (bufferLayout.format && bufferLayout.name === name) {\n return {\n attributeName: bufferLayout.name,\n bufferName: name,\n stepMode: bufferLayout.stepMode,\n vertexFormat: bufferLayout.format,\n // If offset is needed, use `attributes` field.\n byteOffset: 0,\n byteStride: bufferLayout.byteStride || 0\n };\n }\n }\n return null;\n}\n\n/**\n * Search attribute mappings (e.g. interleaved attributes) for buffer mapping.\n * Not the name of the buffer might be the same as one of the interleaved attributes.\n */\nfunction getAttributeFromAttributesList(\n bufferLayouts: BufferLayout[],\n name: string\n): BufferAttributeInfo | null {\n for (const bufferLayout of bufferLayouts) {\n let byteStride: number | undefined = bufferLayout.byteStride;\n\n // Calculate a default byte stride if not provided\n if (typeof bufferLayout.byteStride !== 'number') {\n for (const attributeMapping of bufferLayout.attributes || []) {\n const info = vertexFormatDecoder.getVertexFormatInfo(attributeMapping.format);\n // @ts-ignore\n byteStride += info.byteLength;\n }\n }\n\n const attributeMapping = bufferLayout.attributes?.find(mapping => mapping.attribute === name);\n if (attributeMapping) {\n return {\n attributeName: attributeMapping.attribute,\n bufferName: bufferLayout.name,\n stepMode: bufferLayout.stepMode,\n vertexFormat: attributeMapping.format,\n byteOffset: attributeMapping.byteOffset,\n // @ts-ignore\n byteStride\n };\n }\n }\n\n return null;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '../../types';\nimport {\n AttributeInfo,\n getAttributeInfosByLocation\n} from '../../adapter-utils/get-attribute-from-layouts';\nimport type {Device} from '../device';\nimport type {Buffer} from './buffer';\nimport type {RenderPass} from './render-pass';\nimport {Resource, ResourceProps} from './resource';\nimport {ShaderLayout} from '../types/shader-layout';\nimport {BufferLayout} from '../types/buffer-layout';\n\n/** Properties for initializing a VertexArray */\nexport type VertexArrayProps = ResourceProps & {\n shaderLayout: ShaderLayout;\n bufferLayout: BufferLayout[];\n};\n\n/**\n * Stores attribute bindings.\n * Makes it easy to share a render pipeline and use separate vertex arrays.\n * @note On WebGL, VertexArray allows non-constant bindings to be performed in advance\n * reducing the number of WebGL calls per draw call.\n * @note On WebGPU this is just a convenience class that collects the bindings.\n */\nexport abstract class VertexArray extends Resource<VertexArrayProps> {\n static override defaultProps: Required<VertexArrayProps> = {\n ...Resource.defaultProps,\n shaderLayout: undefined!,\n bufferLayout: []\n };\n\n override get [Symbol.toStringTag](): string {\n return 'VertexArray';\n }\n\n /** Max number of vertex attributes */\n readonly maxVertexAttributes: number;\n /** Attribute infos indexed by location - TODO only needed by webgl module? */\n protected readonly attributeInfos: AttributeInfo[];\n\n /** Index buffer */\n indexBuffer: Buffer | null = null;\n /** Attributes indexed by buffer slot */\n attributes: (Buffer | TypedArray | null)[];\n\n constructor(device: Device, props: VertexArrayProps) {\n super(device, props, VertexArray.defaultProps);\n this.maxVertexAttributes = device.limits.maxVertexAttributes;\n this.attributes = new Array(this.maxVertexAttributes).fill(null);\n this.attributeInfos = getAttributeInfosByLocation(\n props.shaderLayout,\n props.bufferLayout,\n this.maxVertexAttributes\n );\n }\n\n /** Set attributes (stored on pipeline and set before each call) */\n abstract setIndexBuffer(indices: Buffer | null): void;\n /** Set attributes (stored on pipeline and set before each call) */\n abstract setBuffer(bufferSlot: number, buffer: Buffer | null): void;\n\n abstract bindBeforeRender(renderPass: RenderPass): void;\n abstract unbindAfterRender(renderPass: RenderPass): void;\n\n // DEPRECATED METHODS\n\n /** @deprecated Set constant attributes (WebGL only) */\n setConstantWebGL(location: number, value: TypedArray | null): void {\n this.device.reportError(new Error('constant attributes not supported'), this)();\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {PrimitiveTopology} from '../types/parameters';\nimport {ShaderLayout} from '../types/shader-layout';\nimport type {Buffer} from './buffer';\nimport {Resource, ResourceProps} from './resource';\n\n/** For bindRange */\nexport type BufferRange = {\n buffer: Buffer;\n byteOffset?: number;\n byteLength?: number;\n};\n\n/** Configures a set of output buffers for pipeline (WebGL only) */\nexport type TransformFeedbackProps = ResourceProps & {\n /** Layout of shader (for varyings) */\n layout: ShaderLayout;\n /** Buffer bindings (for varyings) */\n buffers: Record<string, Buffer | BufferRange>;\n};\n\n/** Holds a set of output buffers for pipeline (WebGL only) */\nexport abstract class TransformFeedback extends Resource<TransformFeedbackProps> {\n static override defaultProps: Required<TransformFeedbackProps> = {\n ...Resource.defaultProps,\n layout: undefined!,\n buffers: {}\n };\n\n get [Symbol.toStringTag](): string {\n return 'TransformFeedback';\n }\n\n constructor(device: Device, props: TransformFeedbackProps) {\n super(device, props, TransformFeedback.defaultProps);\n }\n\n abstract begin(topology?: PrimitiveTopology): void;\n abstract end(): void;\n\n abstract setBuffers(buffers: Record<string, Buffer | BufferRange>): void;\n abstract setBuffer(locationOrName: string | number, bufferOrRange: Buffer | BufferRange): void;\n abstract getBuffer(locationOrName: string | number): Buffer | BufferRange | null;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\n/**\n * Properties for creating a QuerySet\n * - 'timestamp' - query the GPU timestamp counter at the start and end of render passes\n * timestamp queries are available if the 'timestamp-query' feature is present.\n * - 'occlusion' - query the number of fragment samples that pass all per-fragment tests for a set of drawing commands\n * including scissor, sample mask, alpha to coverage, stencil, and depth tests\n */\nexport type QuerySetProps = ResourceProps & {\n /**\n * The type of query set\n * occlusion - query the number of fragment samples that pass all the per-fragment tests for a set of drawing commands, including scissor, sample mask, alpha to coverage, stencil, and depth tests\n * timestamp - query the GPU timestamp counter. Timestamp queries are available if the\n * `timestamp-query` feature is present.\n */\n type: 'occlusion' | 'timestamp';\n /** The number of queries managed by the query set */\n count: number;\n};\n\n/** Immutable QuerySet object */\nexport abstract class QuerySet extends Resource<QuerySetProps> {\n get [Symbol.toStringTag](): string {\n return 'QuerySet';\n }\n\n constructor(device: Device, props: QuerySetProps) {\n super(device, props, QuerySet.defaultProps);\n }\n\n static override defaultProps: Required<QuerySetProps> = {\n ...Resource.defaultProps,\n type: undefined!,\n count: undefined!\n };\n\n /**\n * Returns true if the requested result has been captured and can be read without blocking.\n * Backends may implement this conservatively.\n */\n abstract isResultAvailable(queryIndex?: number): boolean;\n\n /** Reads query results as 64-bit values. */\n abstract readResults(options?: {firstQuery?: number; queryCount?: number}): Promise<bigint[]>;\n\n /**\n * Reads a timestamp duration in milliseconds between a begin and end query index.\n * Portable duration profiling requires adjacent indices that identify one logical pair.\n */\n abstract readTimestampDuration(beginIndex: number, endIndex: number): Promise<number>;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, type ResourceProps} from './resource';\n\nexport type FenceProps = ResourceProps;\n\n/** Synchronization primitive that resolves when GPU work is completed */\nexport abstract class Fence extends Resource<FenceProps> {\n static override defaultProps: Required<FenceProps> = {\n ...Resource.defaultProps\n };\n\n override get [Symbol.toStringTag](): string {\n return 'Fence';\n }\n\n /** Promise that resolves when the fence is signaled */\n abstract readonly signaled: Promise<void>;\n\n constructor(device: Device, props: FenceProps = {}) {\n super(device, props, Fence.defaultProps);\n }\n\n /** Destroy the fence and release any resources */\n abstract override destroy(): void;\n\n /** Check if the fence has been signaled */\n abstract isSignaled(): boolean;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../device';\nimport {ShaderLayout} from '../types/shader-layout';\nimport {Resource, ResourceProps} from './resource';\n\nexport type PipelineLayoutProps = ResourceProps & {\n shaderLayout: ShaderLayout;\n};\n\n/** Immutable PipelineLayout object */\nexport abstract class PipelineLayout extends Resource<PipelineLayoutProps> {\n get [Symbol.toStringTag](): string {\n return 'PipelineLayout';\n }\n\n constructor(device: Device, props: PipelineLayoutProps) {\n super(device, props, PipelineLayout.defaultProps);\n }\n\n static override defaultProps: Required<PipelineLayoutProps> = {\n ...Resource.defaultProps,\n shaderLayout: {\n attributes: [],\n bindings: []\n }\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray, TypedArrayConstructor} from '../../types';\nimport {PrimitiveDataType, SignedDataType, NormalizedDataType, DataTypeInfo} from './data-types';\n\n/**\n * Gets info about a data type constant (signed or normalized)\n * @returns underlying primitive / signed types, byte length, normalization, integer, signed flags\n */\nexport function getDataTypeInfo(type: NormalizedDataType): DataTypeInfo {\n const normalized: boolean = type.includes('norm');\n const integer: boolean = !normalized && !type.startsWith('float');\n const signed: boolean = type.startsWith('s');\n const typeInfo = NORMALIZED_TYPE_MAP[type];\n const [signedType, primitiveType, byteLength] = typeInfo || ['uint8 ', 'i32', 1];\n return {\n signedType,\n primitiveType,\n byteLength,\n normalized,\n integer,\n signed\n };\n}\n\n/** Build a vertex format from a signed data type and a component */\nexport function getNormalizedDataType(signedDataType: SignedDataType): NormalizedDataType {\n const dataType: NormalizedDataType = signedDataType;\n // prettier-ignore\n switch (dataType) {\n case 'uint8': return 'unorm8';\n case 'sint8': return 'snorm8';\n case 'uint16': return 'unorm16';\n case 'sint16': return 'snorm16';\n default: return dataType;\n }\n}\n\n/** Align offset to 1, 2 or 4 elements (4, 8 or 16 bytes) */\nexport function alignTo(size: number, count: number): number {\n // prettier-ignore\n switch (count) {\n case 1: return size; // Pad upwards to even multiple of 2\n case 2: return size + (size % 2); // Pad upwards to even multiple of 2\n default: return size + ((4 - (size % 4)) % 4); // Pad upwards to even multiple of 4\n }\n}\n\n/** Returns the VariableShaderType that corresponds to a typed array */\nexport function getDataType(arrayOrType: TypedArray | TypedArrayConstructor): SignedDataType {\n const Constructor = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;\n if (Constructor === Uint8ClampedArray) {\n return 'uint8';\n }\n const info = Object.values(NORMALIZED_TYPE_MAP).find(entry => Constructor === entry[4]);\n if (!info) {\n throw new Error(Constructor.name);\n }\n return info[0];\n}\n\n/** Returns the TypedArray that corresponds to a shader data type */\nexport function getTypedArrayConstructor(type: NormalizedDataType): TypedArrayConstructor {\n const [, , , , Constructor] = NORMALIZED_TYPE_MAP[type];\n return Constructor;\n}\n\nconst NORMALIZED_TYPE_MAP: Record<\n NormalizedDataType,\n [\n SignedDataType,\n PrimitiveDataType,\n bytes: 1 | 2 | 4,\n normalized: boolean,\n arrayConstructor: TypedArrayConstructor\n ]\n> = {\n uint8: ['uint8', 'u32', 1, false, Uint8Array],\n sint8: ['sint8', 'i32', 1, false, Int8Array],\n unorm8: ['uint8', 'f32', 1, true, Uint8Array],\n snorm8: ['sint8', 'f32', 1, true, Int8Array],\n uint16: ['uint16', 'u32', 2, false, Uint16Array],\n sint16: ['sint16', 'i32', 2, false, Int16Array],\n unorm16: ['uint16', 'u32', 2, true, Uint16Array],\n snorm16: ['sint16', 'i32', 2, true, Int16Array],\n float16: ['float16', 'f16', 2, false, Uint16Array],\n float32: ['float32', 'f32', 4, false, Float32Array],\n uint32: ['uint32', 'u32', 4, false, Uint32Array],\n sint32: ['sint32', 'i32', 4, false, Int32Array]\n};\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '../types';\n\nlet arrayBuffer: ArrayBuffer;\n\nexport function getScratchArrayBuffer(byteLength: number): ArrayBuffer {\n if (!arrayBuffer || arrayBuffer.byteLength < byteLength) {\n arrayBuffer = new ArrayBuffer(byteLength);\n }\n return arrayBuffer;\n}\n\nexport function getScratchArray(Type: any, length: number): TypedArray {\n const scratchArrayBuffer = getScratchArrayBuffer(Type.BYTES_PER_ELEMENT * length);\n return new Type(scratchArrayBuffer, 0, length); // arrayBuffer, byteOffset, length (in elements)\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray, NumberArray} from '../types';\n\n/**\n * Check is an array is a typed array\n * @param value value to be tested\n * @returns input as TypedArray, or null\n * @todo this should be provided by @math.gl/types\n */\nexport function isTypedArray(value: unknown): value is TypedArray {\n return ArrayBuffer.isView(value) && !(value instanceof DataView);\n}\n\n/**\n * Check is an array is a numeric array (typed array or array of numbers)\n * @param value value to be tested\n * @returns input as NumberArray, or null\n * @todo this should be provided by @math.gl/types\n */\nexport function isNumberArray(value: unknown): value is NumberArray {\n if (Array.isArray(value)) {\n return value.length === 0 || typeof value[0] === 'number';\n }\n return isTypedArray(value);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {PrimitiveDataType} from '../shadertypes/data-types/data-types';\nimport type {\n CompositeShaderType,\n VariableShaderType\n} from '../shadertypes/shader-types/shader-types';\nimport {alignTo} from '../shadertypes/data-types/decode-data-types';\nimport {\n getVariableShaderTypeInfo,\n resolveVariableShaderTypeAlias\n} from '../shadertypes/shader-types/shader-type-decoder';\n\nimport type {CompositeUniformValue, UniformValue} from '../adapter/types/uniforms';\nimport {getScratchArrayBuffer} from '../utils/array-utils-flat';\nimport {isNumberArray} from '../utils/is-array';\nimport {log} from '../utils/log';\n\ntype UniformLayoutEntry = {\n offset: number;\n size: number;\n components: number;\n columns: number;\n rows: number;\n shaderType: VariableShaderType;\n type: PrimitiveDataType;\n};\n\nexport type UniformValues = Record<string, CompositeUniformValue>;\n\n/**\n * Smallest buffer size that can be used for uniform buffers.\n * TODO - does this depend on device?\n */\nconst minBufferSize: number = 1024;\n\n/**\n * Std140 layout for uniform buffers\n * Supports manual listing of uniforms\n */\nexport class UniformBufferLayout {\n readonly layout: Record<string, UniformLayoutEntry> = {};\n readonly uniformTypes: Record<string, CompositeShaderType>;\n\n /** number of bytes needed for buffer allocation */\n readonly byteLength: number;\n\n /** Create a new UniformBufferLayout given a map of attributes. */\n constructor(uniformTypes: Readonly<Record<string, CompositeShaderType>>) {\n this.uniformTypes = {...uniformTypes};\n\n let size = 0;\n\n for (const [key, uniformType] of Object.entries(this.uniformTypes)) {\n size = this._addToLayout(key, uniformType, size);\n }\n\n size = alignTo(size, 4);\n this.byteLength = Math.max(size * 4, minBufferSize);\n }\n\n /** Does this layout have a field with specified name */\n has(name: string) {\n return Boolean(this.layout[name]);\n }\n\n /** Get offset and size for a field with specified name */\n get(name: string): {offset: number; size: number} | undefined {\n const layout = this.layout[name];\n return layout;\n }\n\n /** Flatten nested uniform values into leaf-path values understood by UniformBlock. */\n getFlatUniformValues(uniformValues: Readonly<UniformValues>): Record<string, UniformValue> {\n const flattenedUniformValues: Record<string, UniformValue> = {};\n\n for (const [name, value] of Object.entries(uniformValues)) {\n const uniformType = this.uniformTypes[name];\n if (uniformType) {\n this._flattenCompositeValue(flattenedUniformValues, name, uniformType, value);\n } else if (this.layout[name]) {\n flattenedUniformValues[name] = value as UniformValue;\n }\n }\n\n return flattenedUniformValues;\n }\n\n /** Get the data for the complete buffer */\n getData(uniformValues: Readonly<UniformValues>): Uint8Array {\n const buffer = getScratchArrayBuffer(this.byteLength);\n new Uint8Array(buffer, 0, this.byteLength).fill(0);\n const typedArrays = {\n i32: new Int32Array(buffer),\n u32: new Uint32Array(buffer),\n f32: new Float32Array(buffer),\n f16: new Uint16Array(buffer)\n };\n\n const flattenedUniformValues = this.getFlatUniformValues(uniformValues);\n for (const [name, value] of Object.entries(flattenedUniformValues)) {\n this._writeLeafValue(typedArrays, name, value);\n }\n\n return new Uint8Array(buffer, 0, this.byteLength);\n }\n\n // Recursively add a uniform to the layout\n private _addToLayout(name: string, type: CompositeShaderType, offset: number): number {\n if (typeof type === 'string') {\n const info = getLeafLayoutInfo(type);\n const alignedOffset = alignTo(offset, info.alignment);\n this.layout[name] = {\n offset: alignedOffset,\n ...info\n };\n return alignedOffset + info.size;\n }\n\n if (Array.isArray(type)) {\n if (Array.isArray(type[0])) {\n throw new Error(`Nested arrays are not supported for ${name}`);\n }\n\n const elementType = type[0] as CompositeShaderType;\n const length = type[1] as number;\n const stride = alignTo(getTypeSize(elementType), 4);\n const arrayOffset = alignTo(offset, 4);\n\n for (let i = 0; i < length; i++) {\n this._addToLayout(`${name}[${i}]`, elementType, arrayOffset + i * stride);\n }\n return arrayOffset + stride * length;\n }\n\n if (isCompositeShaderTypeStruct(type)) {\n let structOffset = alignTo(offset, 4);\n for (const [memberName, memberType] of Object.entries(type)) {\n structOffset = this._addToLayout(`${name}.${memberName}`, memberType, structOffset);\n }\n return alignTo(structOffset, 4);\n }\n\n throw new Error(`Unsupported CompositeShaderType for ${name}`);\n }\n\n private _flattenCompositeValue(\n flattenedUniformValues: Record<string, UniformValue>,\n baseName: string,\n uniformType: CompositeShaderType,\n value: CompositeUniformValue | undefined\n ): void {\n if (value === undefined) {\n return;\n }\n\n if (typeof uniformType === 'string' || this.layout[baseName]) {\n flattenedUniformValues[baseName] = value as UniformValue;\n return;\n }\n\n if (Array.isArray(uniformType)) {\n const elementType = uniformType[0] as CompositeShaderType;\n const length = uniformType[1] as number;\n\n if (Array.isArray(elementType)) {\n throw new Error(`Nested arrays are not supported for ${baseName}`);\n }\n\n if (typeof elementType === 'string' && isNumberArray(value)) {\n this._flattenPackedArray(flattenedUniformValues, baseName, elementType, length, value);\n return;\n }\n\n if (!Array.isArray(value)) {\n log.warn(`Unsupported uniform array value for ${baseName}:`, value)();\n return;\n }\n\n for (let index = 0; index < Math.min(value.length, length); index++) {\n const elementValue = value[index];\n if (elementValue === undefined) {\n continue;\n }\n\n this._flattenCompositeValue(\n flattenedUniformValues,\n `${baseName}[${index}]`,\n elementType,\n elementValue\n );\n }\n return;\n }\n\n if (isCompositeShaderTypeStruct(uniformType) && isCompositeUniformObject(value)) {\n for (const [key, subValue] of Object.entries(value)) {\n if (subValue === undefined) {\n continue;\n }\n\n const nestedName = `${baseName}.${key}`;\n this._flattenCompositeValue(flattenedUniformValues, nestedName, uniformType[key], subValue);\n }\n return;\n }\n\n log.warn(`Unsupported uniform value for ${baseName}:`, value)();\n }\n\n private _flattenPackedArray(\n flattenedUniformValues: Record<string, UniformValue>,\n baseName: string,\n elementType: VariableShaderType,\n length: number,\n value: UniformValue\n ): void {\n const numericValue = value as Readonly<ArrayLike<number>>;\n const elementLayout = getLeafLayoutInfo(elementType);\n const packedElementLength = elementLayout.components;\n\n for (let index = 0; index < length; index++) {\n const start = index * packedElementLength;\n if (start >= numericValue.length) {\n break;\n }\n\n if (packedElementLength === 1) {\n flattenedUniformValues[`${baseName}[${index}]`] = Number(numericValue[start]);\n } else {\n flattenedUniformValues[`${baseName}[${index}]`] = sliceNumericArray(\n value,\n start,\n start + packedElementLength\n ) as UniformValue;\n }\n }\n }\n\n private _writeLeafValue(\n typedArrays: Record<string, any>,\n name: string,\n value: UniformValue\n ): void {\n const layout = this.layout[name];\n if (!layout) {\n log.warn(`Uniform ${name} not found in layout`)();\n return;\n }\n\n const {type, components, columns, rows, offset} = layout;\n const array = typedArrays[type];\n\n if (components === 1) {\n array[offset] = Number(value);\n return;\n }\n\n const sourceValue = value as Readonly<ArrayLike<number>>;\n\n if (columns === 1) {\n for (let componentIndex = 0; componentIndex < components; componentIndex++) {\n array[offset + componentIndex] = Number(sourceValue[componentIndex] ?? 0);\n }\n return;\n }\n\n let sourceIndex = 0;\n for (let columnIndex = 0; columnIndex < columns; columnIndex++) {\n const columnOffset = offset + columnIndex * 4;\n for (let rowIndex = 0; rowIndex < rows; rowIndex++) {\n array[columnOffset + rowIndex] = Number(sourceValue[sourceIndex++] ?? 0);\n }\n }\n }\n}\n\nfunction getTypeSize(type: CompositeShaderType): number {\n if (typeof type === 'string') {\n return getLeafLayoutInfo(type).size;\n }\n\n if (Array.isArray(type)) {\n const elementType = type[0] as CompositeShaderType;\n const length = type[1] as number;\n\n if (Array.isArray(elementType)) {\n throw new Error('Nested arrays are not supported');\n }\n\n return alignTo(getTypeSize(elementType), 4) * length;\n }\n\n let size = 0;\n for (const memberType of Object.values(type)) {\n const compositeMemberType = memberType as CompositeShaderType;\n size = alignTo(size, getTypeAlignment(compositeMemberType));\n size += getTypeSize(compositeMemberType);\n }\n\n return alignTo(size, 4);\n}\n\nfunction getTypeAlignment(type: CompositeShaderType): 1 | 2 | 4 {\n if (typeof type === 'string') {\n return getLeafLayoutInfo(type).alignment;\n }\n\n if (Array.isArray(type)) {\n return 4;\n }\n\n return 4;\n}\n\nfunction getLeafLayoutInfo(\n type: VariableShaderType\n): Omit<UniformLayoutEntry, 'offset'> & {alignment: 1 | 2 | 4} {\n const resolvedType = resolveVariableShaderTypeAlias(type);\n const decodedType = getVariableShaderTypeInfo(resolvedType);\n const matrixMatch = /^mat(\\d)x(\\d)<.+>$/.exec(resolvedType);\n\n if (matrixMatch) {\n const columns = Number(matrixMatch[1]);\n const rows = Number(matrixMatch[2]);\n\n return {\n alignment: 4,\n size: columns * 4,\n components: columns * rows,\n columns,\n rows,\n shaderType: resolvedType,\n type: decodedType.type\n };\n }\n\n const vectorMatch = /^vec(\\d)<.+>$/.exec(resolvedType);\n if (vectorMatch) {\n const components = Number(vectorMatch[1]) as 2 | 3 | 4;\n return {\n alignment: components === 2 ? 2 : 4,\n size: components === 3 ? 4 : components,\n components,\n columns: 1,\n rows: components,\n shaderType: resolvedType,\n type: decodedType.type\n };\n }\n\n return {\n alignment: 1,\n size: 1,\n components: 1,\n columns: 1,\n rows: 1,\n shaderType: resolvedType,\n type: decodedType.type\n };\n}\n\nfunction isCompositeShaderTypeStruct(\n value: CompositeShaderType\n): value is Record<string, CompositeShaderType> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isCompositeUniformObject(\n value: CompositeUniformValue\n): value is Record<string, CompositeUniformValue | undefined> {\n return (\n Boolean(value) &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !ArrayBuffer.isView(value)\n );\n}\n\nfunction sliceNumericArray(value: UniformValue, start: number, end: number): number[] {\n return Array.prototype.slice.call(value, start, end) as number[];\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isNumberArray} from './is-array';\n\nconst MAX_ELEMENTWISE_ARRAY_COMPARE_LENGTH = 128;\n\n/** Test if two arrays are deep equal, with a small-array length limit that defaults to 16 */\nexport function arrayEqual(a: unknown, b: unknown, limit: number = 16) {\n if (a === b) {\n return true;\n }\n\n const arrayA = a;\n const arrayB = b;\n if (!isNumberArray(arrayA) || !isNumberArray(arrayB)) {\n return false;\n }\n\n if (arrayA.length !== arrayB.length) {\n return false;\n }\n\n const maxCompareLength = Math.min(limit, MAX_ELEMENTWISE_ARRAY_COMPARE_LENGTH);\n if (arrayA.length > maxCompareLength) {\n return false;\n }\n\n for (let i = 0; i < arrayA.length; ++i) {\n if (arrayB[i] !== arrayA[i]) {\n return false;\n }\n }\n\n return true;\n}\n\n/** Copy a value */\nexport function arrayCopy<T>(a: T): T {\n if (isNumberArray(a)) {\n return a.slice() as T;\n }\n return a;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {VariableShaderType} from '../shadertypes/shader-types/shader-types';\nimport type {UniformValue} from '../adapter/types/uniforms';\nimport {\n ShaderLayout,\n UniformInfo,\n UniformBufferBindingLayout\n} from '../adapter/types/shader-layout';\nimport {arrayEqual, arrayCopy} from '../utils/array-equal';\n\n/**\n * A uniform block holds values of the of uniform values for one uniform block / buffer.\n * It also does some book keeping on what has changed, to minimize unnecessary writes to uniform buffers.\n */\nexport class UniformBlock<\n TUniforms extends Record<string, UniformValue> = Record<string, UniformValue>\n> {\n name: string;\n\n uniforms: Record<keyof TUniforms, UniformValue> = {} as Record<keyof TUniforms, UniformValue>;\n modifiedUniforms: Record<keyof TUniforms, boolean> = {} as Record<keyof TUniforms, boolean>;\n modified: boolean = true;\n\n readonly bindingLayout: Record<string, UniformInfo> = {};\n needsRedraw: string | false = 'initialized';\n\n constructor(props?: {\n name?: string;\n shaderLayout?: ShaderLayout;\n uniformTypes?: Record<keyof TUniforms, Record<string, VariableShaderType>>;\n }) {\n this.name = props?.name || 'unnamed';\n\n // TODO - Extract uniform layout from the shaderLayout object\n if (props?.name && props?.shaderLayout) {\n const binding = props?.shaderLayout.bindings?.find(\n binding_ => binding_.type === 'uniform' && binding_.name === props?.name\n );\n if (!binding) {\n throw new Error(props?.name);\n }\n\n const uniformBlock = binding as UniformBufferBindingLayout;\n for (const uniform of uniformBlock.uniforms || []) {\n this.bindingLayout[uniform.name] = uniform;\n }\n }\n }\n\n /** Set a map of uniforms */\n setUniforms(uniforms: Partial<TUniforms>): void {\n for (const [key, value] of Object.entries(uniforms)) {\n this._setUniform(key, value);\n if (!this.needsRedraw) {\n this.setNeedsRedraw(`${this.name}.${key}=${value}`);\n }\n }\n }\n\n setNeedsRedraw(reason: string): void {\n this.needsRedraw = this.needsRedraw || reason;\n }\n\n /** Returns all uniforms */\n getAllUniforms(): Record<string, UniformValue> {\n // @ts-expect-error\n this.modifiedUniforms = {};\n this.needsRedraw = false;\n return (this.uniforms || {}) as Record<string, UniformValue>;\n }\n\n /** Set a single uniform */\n private _setUniform(key: keyof TUniforms, value: UniformValue) {\n if (arrayEqual(this.uniforms[key], value)) {\n return;\n }\n this.uniforms[key] = arrayCopy(value);\n this.modifiedUniforms[key] = true;\n this.modified = true;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CompositeShaderType} from '../shadertypes/shader-types/shader-types';\nimport type {CompositeUniformValue} from '../adapter/types/uniforms';\nimport type {Device} from '../adapter/device';\nimport {Buffer} from '../adapter/resources/buffer';\nimport {log} from '../utils/log';\nimport {UniformBlock} from './uniform-block';\nimport {UniformBufferLayout} from './uniform-buffer-layout';\n\n/**\n * A uniform store holds a uniform values for one or more uniform blocks,\n * - It can generate binary data for any uniform buffer\n * - It can manage a uniform buffer for each block\n * - It can update managed uniform buffers with a single call\n * - It performs some book keeping on what has changed to minimize unnecessary writes to uniform buffers.\n */\nexport class UniformStore<\n TPropGroups extends Record<string, Record<string, unknown>> = Record<\n string,\n Record<string, unknown>\n >\n> {\n /** Stores the uniform values for each uniform block */\n uniformBlocks = new Map<keyof TPropGroups, UniformBlock>();\n /** Can generate data for a uniform buffer for each block from data */\n uniformBufferLayouts = new Map<keyof TPropGroups, UniformBufferLayout>();\n /** Actual buffer for the blocks */\n uniformBuffers = new Map<keyof TPropGroups, Buffer>();\n\n /**\n * Create a new UniformStore instance\n * @param blocks\n */\n constructor(\n blocks: Record<\n keyof TPropGroups,\n {\n uniformTypes?: Record<string, CompositeShaderType>;\n defaultProps?: Record<string, unknown>;\n defaultUniforms?: Record<string, CompositeUniformValue>;\n }\n >\n ) {\n for (const [bufferName, block] of Object.entries(blocks)) {\n const uniformBufferName = bufferName as keyof TPropGroups;\n\n // Create a layout object to help us generate correctly formatted binary uniform buffers\n const uniformBufferLayout = new UniformBufferLayout(block.uniformTypes ?? {});\n this.uniformBufferLayouts.set(uniformBufferName, uniformBufferLayout);\n\n // Create a Uniform block to store the uniforms for each buffer.\n const uniformBlock = new UniformBlock({name: bufferName});\n uniformBlock.setUniforms(\n uniformBufferLayout.getFlatUniformValues(block.defaultUniforms || {})\n );\n this.uniformBlocks.set(uniformBufferName, uniformBlock);\n }\n }\n\n /** Destroy any managed uniform buffers */\n destroy(): void {\n for (const uniformBuffer of this.uniformBuffers.values()) {\n uniformBuffer.destroy();\n }\n }\n\n /**\n * Set uniforms\n * Makes all properties partial\n */\n setUniforms(\n uniforms: Partial<{[group in keyof TPropGroups]: Partial<TPropGroups[group]>}>\n ): void {\n for (const [blockName, uniformValues] of Object.entries(uniforms)) {\n const uniformBufferName = blockName as keyof TPropGroups;\n const uniformBufferLayout = this.uniformBufferLayouts.get(uniformBufferName);\n const flattenedUniforms = uniformBufferLayout?.getFlatUniformValues(\n (uniformValues || {}) as Record<string, CompositeUniformValue>\n );\n this.uniformBlocks.get(uniformBufferName)?.setUniforms(flattenedUniforms || {});\n // We leverage logging in updateUniformBuffers(), even though slightly less efficient\n // this.updateUniformBuffer(blockName);\n }\n\n this.updateUniformBuffers();\n }\n\n /** Get the required minimum length of the uniform buffer */\n getUniformBufferByteLength(uniformBufferName: keyof TPropGroups): number {\n return this.uniformBufferLayouts.get(uniformBufferName)?.byteLength || 0;\n }\n\n /** Get formatted binary memory that can be uploaded to a buffer */\n getUniformBufferData(uniformBufferName: keyof TPropGroups): Uint8Array {\n const uniformValues = this.uniformBlocks.get(uniformBufferName)?.getAllUniforms() || {};\n // @ts-ignore\n return this.uniformBufferLayouts.get(uniformBufferName)?.getData(uniformValues);\n }\n\n /**\n * Creates an unmanaged uniform buffer (umnanaged means that application is responsible for destroying it)\n * The new buffer is initialized with current / supplied values\n */\n createUniformBuffer(\n device: Device,\n uniformBufferName: keyof TPropGroups,\n uniforms?: Partial<{[group in keyof TPropGroups]: Partial<TPropGroups[group]>}>\n ): Buffer {\n if (uniforms) {\n this.setUniforms(uniforms);\n }\n const byteLength = this.getUniformBufferByteLength(uniformBufferName);\n const uniformBuffer = device.createBuffer({\n usage: Buffer.UNIFORM | Buffer.COPY_DST,\n byteLength\n });\n // Note that this clears the needs redraw flag\n const uniformBufferData = this.getUniformBufferData(uniformBufferName);\n uniformBuffer.write(uniformBufferData);\n return uniformBuffer;\n }\n\n /** Get the managed uniform buffer. \"managed\" resources are destroyed when the uniformStore is destroyed. */\n getManagedUniformBuffer(device: Device, uniformBufferName: keyof TPropGroups): Buffer {\n if (!this.uniformBuffers.get(uniformBufferName)) {\n const byteLength = this.getUniformBufferByteLength(uniformBufferName);\n const uniformBuffer = device.createBuffer({\n usage: Buffer.UNIFORM | Buffer.COPY_DST,\n byteLength\n });\n this.uniformBuffers.set(uniformBufferName, uniformBuffer);\n }\n // this.updateUniformBuffers();\n // @ts-ignore\n return this.uniformBuffers.get(uniformBufferName);\n }\n\n /** Updates all uniform buffers where values have changed */\n updateUniformBuffers(): false | string {\n let reason: false | string = false;\n for (const uniformBufferName of this.uniformBlocks.keys()) {\n const bufferReason = this.updateUniformBuffer(uniformBufferName);\n reason ||= bufferReason;\n }\n if (reason) {\n log.log(3, `UniformStore.updateUniformBuffers(): ${reason}`)();\n }\n return reason;\n }\n\n /** Update one uniform buffer. Only updates if values have changed */\n updateUniformBuffer(uniformBufferName: keyof TPropGroups): false | string {\n const uniformBlock = this.uniformBlocks.get(uniformBufferName);\n let uniformBuffer = this.uniformBuffers.get(uniformBufferName);\n\n let reason: false | string = false;\n if (uniformBuffer && uniformBlock?.needsRedraw) {\n reason ||= uniformBlock.needsRedraw;\n // This clears the needs redraw flag\n const uniformBufferData = this.getUniformBufferData(uniformBufferName);\n\n uniformBuffer = this.uniformBuffers.get(uniformBufferName);\n uniformBuffer?.write(uniformBufferData);\n\n // logging - TODO - don't query the values unnecessarily\n const uniformValues = this.uniformBlocks.get(uniformBufferName)?.getAllUniforms();\n log.log(\n 4,\n `Writing to uniform buffer ${String(uniformBufferName)}`,\n uniformBufferData,\n uniformValues\n )();\n }\n return reason;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray} from '@math.gl/types';\nimport {type TextureFormat, type TextureMemoryLayout} from './texture-formats';\nimport {textureFormatDecoder} from './texture-format-decoder';\n\nexport function getTextureImageView<T extends TextureFormat>(\n arrayBuffer: ArrayBuffer,\n memoryLayout: TextureMemoryLayout,\n format: T,\n image = 0\n) {\n const formatInfo = textureFormatDecoder.getInfo(format);\n const bytesPerComponent = formatInfo.bytesPerPixel / formatInfo.components;\n const {bytesPerImage} = memoryLayout;\n const offset = bytesPerImage * image;\n const totalPixels = memoryLayout.bytesPerImage / bytesPerComponent;\n\n switch (format) {\n case 'rgba8unorm':\n case 'bgra8unorm':\n case 'rgba8uint':\n return new Uint8Array(arrayBuffer, offset, totalPixels);\n case 'r8unorm':\n return new Uint8Array(arrayBuffer, offset, totalPixels);\n case 'r16uint':\n case 'rgba16uint':\n return new Uint16Array(arrayBuffer, offset, totalPixels);\n case 'r32uint':\n case 'rgba32uint':\n return new Uint32Array(arrayBuffer, offset, totalPixels);\n case 'r32float':\n return new Float32Array(arrayBuffer, offset, totalPixels);\n case 'rgba16float':\n return new Uint16Array(arrayBuffer, offset, totalPixels); // 4 channels\n case 'rgba32float':\n return new Float32Array(arrayBuffer, offset, totalPixels);\n default:\n throw new Error(`Unsupported format: ${format}`);\n }\n}\n\nexport function setTextureImageData<T extends TextureFormat>(\n arrayBuffer: ArrayBuffer,\n memoryLayout: TextureMemoryLayout,\n format: T,\n data: TypedArray,\n image = 0\n): void {\n const offset = 0; // memoryLayout.bytesPerImage * image;\n\n const totalPixels = memoryLayout.bytesPerImage / memoryLayout.bytesPerPixel;\n const subArray = data.subarray(0, totalPixels);\n\n const typedArray = getTextureImageView(arrayBuffer, memoryLayout, format, image);\n\n typedArray.set(subArray, offset);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type ImageData = {\n /** Offset into the data (in addition to any offset built-in to the ArrayBufferView) */\n byteOffset?: number;\n /** The stride, in bytes, between the beginning of each texel block row and the subsequent texel block row. Required if there are multiple texel block rows (i.e. the copy height or depth is more than one block). */\n bytesPerRow?: number;\n /** Number or rows per image (needed if multiple images are being set) */\n rowsPerImage?: number;\n /** Bits per channel */\n bitsPerChannel: [number, number, number, number];\n};\n\nexport type PixelData = {\n arrayBuffer: ArrayBuffer;\n width: number;\n height: number;\n /** Bytes per pixel */\n bytesPerPixel: number;\n bytesPerRow: number;\n bitsPerChannel: [number, number, number, number];\n};\n\n/**\n * Extracts a single RGBA pixel value from PixelData at the given (x, y) coordinate.\n *\n * The pixel's data is assumed to be packed according to pixelData.bitsPerChannel.\n * The pixel data for a given row is padded to pixelData.bytesPerRow.\n *\n * @param pixelData - The metadata and data for the pixel buffer.\n * @param x - The x coordinate (0-based).\n * @param y - The y coordinate (0-based).\n * @returns A tuple [r, g, b, a] where each channel is the extracted numeric value.\n *\n* @example\n\nAssume you obtained an ArrayBuffer from copyTextureToBuffer and have the following metadata:\n\n const pixelData: PixelData = {\n bitsPerChannel: [5, 6, 5, 0], // For example, a 16-bit RGB565 format (no alpha)\n width: 800,\n height: 600,\n bytesPerPixel: 2, // 16 bits per pixel\n bytesPerRow: 1600, // Assuming no extra padding\n arrayBuffer: myTextureBuffer, // Obtained from copyTextureToBuffer\n };\n\nYou can then extract the pixel at (x, y) like so:\n\n const rgba = extractPixel(pixelData, x, y);\n console.log(\"Extracted RGBA:\", rgba);\n\nFor RGBA formats where all channels are present (e.g. [8, 8, 8, 8]), the function will extract a 4-channel pixel value.\n*/\n\nexport function readPixel(\n pixelData: PixelData,\n x: number,\n y: number,\n bitsPerChannel: [number, number, number, number]\n): [number, number, number, number] {\n if (x < 0 || x >= pixelData.width || y < 0 || y >= pixelData.height) {\n throw new Error('Coordinates out of bounds.');\n }\n\n // Compute the byte offset of the pixel in the buffer.\n const byteOffset = y * pixelData.bytesPerRow + x * pixelData.bytesPerPixel;\n\n // Create a Uint8Array view for this pixel's bytes.\n // We only need to view pixelData.bytesPerPixel bytes.\n const pixelDataView = new DataView(pixelData.arrayBuffer, byteOffset, pixelData.bytesPerPixel);\n\n let bitOffsetWithinPixel = 0;\n const channels: number[] = [];\n\n // Extract each of the four channels.\n for (let i = 0; i < 4; i++) {\n const bits = bitsPerChannel[i] ?? 0;\n // If a channel's bit width is zero or negative, consider it not present.\n if (bits <= 0) {\n channels.push(0);\n } else {\n const channelValue = readBitsFromDataView(pixelDataView, bitOffsetWithinPixel, bits);\n channels.push(channelValue);\n bitOffsetWithinPixel += bits;\n }\n }\n\n return [channels[0] ?? 0, channels[1] ?? 0, channels[2] ?? 0, channels[3] ?? 0];\n}\n\n/**\n * Encodes an RGBA pixel into a DataView at a given bit offset according to a specified bit layout.\n *\n * The channels are written sequentially in the order R, G, B, A. For each channel, the number\n * of bits is taken from the bitsPerChannel array. Channel values are masked to fit within the specified width.\n *\n * @param dataView - The DataView into which the pixel will be encoded.\n * @param bitOffset - The bit offset in the DataView where the pixel should be written.\n * @param bitsPerChannel - A tuple specifying the number of bits for each channel: [R, G, B, A].\n * @param pixel - A tuple [r, g, b, a] containing the channel values (as numbers).\n *\n * @example\n\nAssume you want to encode a pixel into a packed format where:\n - Red uses 5 bits\n - Green uses 6 bits\n - Blue uses 5 bits\n - Alpha is not used (0 bits)\nAnd the pixel format is packed into 16 bits total.\n\nYou might have:\n const bitsPerChannel: [number, number, number, number] = [5, 6, 5, 0];\n const pixel: [number, number, number, number] = [15, 31, 15, 0]; // Example values\n const buffer = new ArrayBuffer(2); // 16 bits = 2 bytes\n const dataView = new DataView(buffer);\n\nNow encode the pixel at bit offset 0:\n encodePixel(dataView, 0, bitsPerChannel, pixel);\n\nThe dataView now contains the 16-bit packed pixel value in big-endian order.\n*/\nexport function writePixel(\n dataView: DataView,\n bitOffset: number,\n bitsPerChannel: [number, number, number, number],\n pixel: [number, number, number, number]\n): void {\n let currentBitOffset = bitOffset;\n for (let channel = 0; channel < 4; channel++) {\n const bits = bitsPerChannel[channel] ?? 0;\n // Clamp the channel value to the maximum allowed by the bit width.\n const maxValue = (1 << bits) - 1;\n const channelValue = (pixel[channel] ?? 0) & maxValue;\n writeBitsToDataView(dataView, currentBitOffset, bits, channelValue);\n currentBitOffset += bits;\n }\n}\n\n/**\n * Reads a specified number of bits from a DataView starting at a given bit offset.\n *\n * For channels with a bit width of 8, 16, or 32 bits and when the bitOffset is byte-aligned,\n * this function uses DataView methods for fast extraction.\n *\n * Bits are assumed to be stored in big-endian order (i.e. the most-significant bit is at position 7 in each byte).\n *\n * @param dataView - The DataView containing the data.\n * @param bitOffset - The offset (in bits) within the data from which to start reading.\n * @param bitCount - The number of bits to read (supported range: 1 to 32).\n * @returns The extracted value as a number.\n */\nexport function readBitsFromDataView(\n dataView: DataView,\n bitOffset: number,\n bitCount: number\n): number {\n // Check if we can optimize when bitOffset is byte-aligned.\n if (bitOffset % 8 === 0) {\n const byteOffset = bitOffset / 8;\n if (bitCount === 8 && byteOffset + 1 <= dataView.byteLength) {\n return dataView.getUint8(byteOffset);\n } else if (bitCount === 16 && byteOffset + 2 <= dataView.byteLength) {\n // false for big-endian reading.\n return dataView.getUint16(byteOffset, false);\n } else if (bitCount === 32 && byteOffset + 4 <= dataView.byteLength) {\n return dataView.getUint32(byteOffset, false);\n }\n }\n\n // Fallback: bit-level extraction for non-aligned or non-standard bit widths.\n let value = 0;\n for (let i = 0; i < bitCount; i++) {\n const overallBitIndex = bitOffset + i;\n const byteIndex = Math.floor(overallBitIndex / 8);\n const bitIndex = overallBitIndex % 8;\n // Read the byte and extract the bit at position (7 - bitIndex).\n const byteValue = dataView.getUint8(byteIndex);\n const bit = (byteValue >> (7 - bitIndex)) & 1;\n value = (value << 1) | bit;\n }\n return value;\n}\n\n/**\n * Writes a specified number of bits from a value into a DataView at a given bit offset.\n *\n * For channels with a bit width of 8, 16, or 32 bits and when the bit offset is byte-aligned,\n * this function uses DataView methods for fast writing.\n *\n * Bits are assumed to be stored in big-endian order (i.e. the most-significant bit is at position 7 in each byte).\n *\n * @param dataView - The DataView to write into.\n * @param bitOffset - The bit offset at which to begin writing.\n * @param bitCount - The number of bits to write (supported range: 1 to 32).\n * @param value - The numeric value whose lower bitCount bits will be written.\n */\nexport function writeBitsToDataView(\n dataView: DataView,\n bitOffset: number,\n bitCount: number,\n value: number\n): void {\n // If the bitOffset is byte-aligned, we may optimize for common bit widths.\n if (bitOffset % 8 === 0) {\n const byteOffset = bitOffset / 8;\n if (bitCount === 8 && byteOffset + 1 <= dataView.byteLength) {\n dataView.setUint8(byteOffset, value & 0xff);\n return;\n } else if (bitCount === 16 && byteOffset + 2 <= dataView.byteLength) {\n dataView.setUint16(byteOffset, value & 0xffff, false); // big-endian\n return;\n } else if (bitCount === 32 && byteOffset + 4 <= dataView.byteLength) {\n dataView.setUint32(byteOffset, value, false); // big-endian\n return;\n }\n }\n\n // Fallback: write bit-by-bit.\n for (let i = 0; i < bitCount; i++) {\n const overallBitIndex = bitOffset + i;\n const byteIndex = Math.floor(overallBitIndex / 8);\n const bitIndex = overallBitIndex % 8;\n const mask = 1 << (7 - bitIndex);\n // Extract the i-th bit from value (starting from the most-significant bit)\n const bitValue = (value >> (bitCount - 1 - i)) & 1;\n // Read the current byte.\n let currentByte = dataView.getUint8(byteIndex);\n // Clear the target bit.\n currentByte &= ~mask;\n // Set the target bit if bitValue is 1.\n if (bitValue) {\n currentByte |= mask;\n }\n dataView.setUint8(byteIndex, currentByte);\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;gBAAAA;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACIA,mBAA0B;AAE1B,IAAM,4BAA4B;AAClC,IAAM,iCAAiC;EACrC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAEF,IAAM,sBAAsB,oBAAI,QAAO;AAIvC,IAAM,8BAA8B,oBAAI,QAAO;AAKzC,IAAO,eAAP,MAAmB;EACvB,QAAQ,oBAAI,IAAG;EAEf,SAASC,OAAY;AACnB,WAAO,KAAK,IAAIA,KAAI;EACtB;EAEA,IAAIA,OAAY;AACd,QAAI,CAAC,KAAK,MAAM,IAAIA,KAAI,GAAG;AACzB,WAAK,MAAM,IAAIA,OAAM,IAAI,mBAAM,EAAC,IAAIA,MAAI,CAAC,CAAC;IAC5C;AAEA,UAAM,QAAQ,KAAK,MAAM,IAAIA,KAAI;AACjC,QAAIA,UAAS,2BAA2B;AACtC,sBAAgB,OAAO,8BAA8B;IACvD;AAEA,WAAO;EACT;;AAIK,IAAM,YAA0B,IAAI,aAAY;AAEvD,SAAS,gBAAgB,OAAc,kBAAmC;AACxE,QAAM,WAAW,MAAM;AACvB,MAAI,mBAAmB;AACvB,aAAW,YAAY,kBAAkB;A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nE,aAAO,SAAS,UAAU,YAAY,KAAK;IAC7C;EACF;AAGA,MAAI,QAAQ;AACZ,WAAS,IAAI,GAAG,IAAI,UAAU,KAAK;AACjC,UAAM,kBAAkB,YAAY;AACpC,UAAM,YAAY,KAAK,MAAM,kBAAkB,CAAC;AAChD,UAAM,WAAW,kBAAkB;AAEnC,UAAM,YAAY,SAAS,SAAS,SAAS;AAC7C,UAAM,MAAO,aAAc,IAAI,WAAa;AAC5C,YAAS,SAAS,IAAK;EACzB;AACA,SAAO;AACT;AAeM,SAAU,oBACd,UACA,WACA,UACA,OAAa;AAGb,MAAI,YAAY,MAAM,GAAG;AACvB,UAAM,aAAa,YAAY;AAC/B,QAAI,aAAa,KAAK,aAAa,KAAK,SAAS,YAAY;AAC3D,eAAS,SAAS,YAAY,QAAQ,GAAI;AAC1C;IACF,WAAW,aAAa,MAAM,aAAa,KAAK,SAAS,YAAY;AACnE,eAAS,UAAU,YAAY,QAAQ,OAAQ,KAAK;AACpD;IACF,WAAW,aAAa,MAAM,aAAa,KAAK,SAAS,YAAY;AACnE,eAAS,UAAU,YAAY,OAAO,KAAK;AAC3C;IACF;EACF;AAGA,WAAS,IAAI,GAAG,IAAI,UAAU,KAAK;AACjC,UAAM,kBAAkB,YAAY;AACpC,UAAM,YAAY,KAAK,MAAM,kBAAkB,CAAC;AAChD,UAAM,WAAW,kBAAkB;AACnC,UAAM,OAAO,KAAM,IAAI;AAEvB,UAAM,WAAY,SAAU,WAAW,IAAI,IAAM;AAEjD,QAAI,cAAc,SAAS,SAAS,SAAS;AAE7C,mBAAe,CAAC;AAEhB,QAAI,UAAU;AACZ,qBAAe;IACjB;AACA,aAAS,SAAS,WAAW,WAAW;EAC1C;AACF;",
6
- "names": ["Buffer", "name", "GPU_TIME_AND_MEMORY_STATS", "ORDERED_STATS_CACHE", "ORDERED_STAT_NAME_SET_CACHE", "initializeStats", "name", "arrayBuffer", "Buffer", "Buffer", "import_env", "devicePixelRatio", "log", "attachment", "bindGroups", "name", "attributeMapping", "NORMALIZED_TYPE_MAP", "name", "Buffer", "arrayBuffer"]
3
+ "sources": ["../src/index.ts", "../src/utils/stats-manager.ts", "../src/utils/log.ts", "../src/utils/uid.ts", "../src/adapter/resources/resource.ts", "../src/adapter/resources/buffer.ts", "../src/shadertypes/data-types/data-type-decoder.ts", "../src/shadertypes/vertex-types/vertex-format-decoder.ts", "../src/shadertypes/texture-types/texture-format-table.ts", "../src/shadertypes/texture-types/texture-format-decoder.ts", "../src/shadertypes/image-types/image-types.ts", "../src/adapter/device.ts", "../src/adapter/luma.ts", "../src/adapter/adapter.ts", "../src/adapter/canvas-surface.ts", "../src/adapter/canvas-observer.ts", "../src/utils/promise-utils.ts", "../src/utils/assert.ts", "../src/adapter/canvas-context.ts", "../src/adapter/presentation-context.ts", "../src/adapter/resources/sampler.ts", "../src/adapter/resources/texture.ts", "../src/adapter/resources/texture-view.ts", "../src/adapter/resources/external-texture.ts", "../src/adapter-utils/format-compiler-log.ts", "../src/adapter/resources/shader.ts", "../src/adapter/resources/framebuffer.ts", "../src/adapter/resources/render-pipeline.ts", "../src/adapter/resources/shared-render-pipeline.ts", "../src/adapter/resources/compute-pipeline.ts", "../src/factories/pipeline-factory.ts", "../src/factories/shader-factory.ts", "../src/adapter-utils/bind-groups.ts", "../src/factories/bind-group-factory.ts", "../src/adapter/resources/render-pass.ts", "../src/adapter/resources/compute-pass.ts", "../src/adapter/resources/command-encoder.ts", "../src/adapter/resources/command-buffer.ts", "../src/shadertypes/shader-types/shader-type-decoder.ts", "../src/adapter-utils/get-attribute-from-layouts.ts", "../src/adapter/resources/vertex-array.ts", "../src/adapter/resources/transform-feedback.ts", "../src/adapter/resources/query-set.ts", "../src/adapter/resources/fence.ts", "../src/adapter/resources/pipeline-layout.ts", "../src/shadertypes/data-types/decode-data-types.ts", "../src/shadertypes/shader-types/shader-block-layout.ts", "../src/utils/array-utils-flat.ts", "../src/utils/is-array.ts", "../src/portable/shader-block-writer.ts", "../src/utils/array-equal.ts", "../src/portable/uniform-block.ts", "../src/portable/uniform-store.ts", "../src/shadertypes/texture-types/texture-layout.ts", "../src/shadertypes/texture-types/pixel-utils.ts"],
4
+ "sourcesContent": ["// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// MAIN API ACCESS POINT\nexport type {AttachDeviceProps, CreateDeviceProps} from './adapter/luma';\nexport {luma} from './adapter/luma';\n\n// ADAPTER (DEVICE AND GPU RESOURCE INTERFACES)\nexport {Adapter} from './adapter/adapter';\n\nexport type {\n DeviceProps,\n DeviceInfo,\n DeviceFeature,\n DeviceTextureFormatCapabilities\n} from './adapter/device';\nexport {Device, DeviceFeatures, DeviceLimits} from './adapter/device';\n\nexport type {CanvasContextProps} from './adapter/canvas-context';\nexport {CanvasContext} from './adapter/canvas-context';\nexport type {PresentationContextProps} from './adapter/presentation-context';\nexport {PresentationContext} from './adapter/presentation-context';\n\n// GPU RESOURCES\nexport {Resource, type ResourceProps} from './adapter/resources/resource';\n\nexport {Buffer, type BufferProps, type BufferMapCallback} from './adapter/resources/buffer';\n\nexport {Texture, type TextureProps} from './adapter/resources/texture';\n\nexport {TextureView, type TextureViewProps} from './adapter/resources/texture-view';\n\nexport type {ExternalTextureProps} from './adapter/resources/external-texture';\nexport {ExternalTexture} from './adapter/resources/external-texture';\n\nexport type {ShaderProps} from './adapter/resources/shader';\nexport {Shader} from './adapter/resources/shader';\n\nexport type {SamplerProps, SamplerParameters} from './adapter/resources/sampler';\nexport {Sampler} from './adapter/resources/sampler';\n\nexport type {FramebufferProps} from './adapter/resources/framebuffer';\nexport {Framebuffer} from './adapter/resources/framebuffer';\n\nexport type {RenderPipelineProps} from './adapter/resources/render-pipeline';\nexport {RenderPipeline} from './adapter/resources/render-pipeline';\nexport {\n SharedRenderPipeline,\n type SharedRenderPipelineProps\n} from './adapter/resources/shared-render-pipeline';\nexport type {PipelineFactoryProps} from './factories/pipeline-factory';\nexport {PipelineFactory} from './factories/pipeline-factory';\nexport {ShaderFactory} from './factories/shader-factory';\nexport {_getDefaultBindGroupFactory} from './factories/bind-group-factory';\n\nexport type {RenderPassProps} from './adapter/resources/render-pass';\nexport {RenderPass} from './adapter/resources/render-pass';\n\nexport type {ComputePipelineProps} from './adapter/resources/compute-pipeline';\nexport {ComputePipeline} from './adapter/resources/compute-pipeline';\n\nexport type {ComputePassProps} from './adapter/resources/compute-pass';\nexport {ComputePass} from './adapter/resources/compute-pass';\n\nexport type {CommandEncoderProps} from './adapter/resources/command-encoder';\nexport {CommandEncoder} from './adapter/resources/command-encoder';\n\nexport type {CommandBufferProps} from './adapter/resources/command-buffer';\nexport {CommandBuffer} from './adapter/resources/command-buffer';\n\nexport type {VertexArrayProps} from './adapter/resources/vertex-array';\nexport {VertexArray} from './adapter/resources/vertex-array';\n\nexport type {TransformFeedbackProps, BufferRange} from './adapter/resources/transform-feedback';\nexport {TransformFeedback} from './adapter/resources/transform-feedback';\n\nexport type {QuerySetProps} from './adapter/resources/query-set';\nexport {QuerySet} from './adapter/resources/query-set';\n\nexport {Fence, type FenceProps} from './adapter/resources/fence';\n\nexport type {PipelineLayoutProps} from './adapter/resources/pipeline-layout';\nexport {PipelineLayout} from './adapter/resources/pipeline-layout';\n\n// PORTABLE API - UNIFORM BUFFERS\nexport {\n makeShaderBlockLayout,\n type ShaderBlockLayout,\n type ShaderBlockLayoutEntry,\n type ShaderBlockLayoutOptions\n} from './shadertypes/shader-types/shader-block-layout';\nexport {ShaderBlockWriter} from './portable/shader-block-writer';\nexport {UniformBlock} from './portable/uniform-block';\nexport {UniformStore} from './portable/uniform-store';\n// TEXTURE TYPES\n\n// API TYPES\nexport type {CompilerMessage} from './adapter/types/compiler-message';\n\nexport type {ExternalImage} from './shadertypes/image-types/image-types';\n\nexport {\n type CopyExternalImageOptions,\n type CopyImageDataOptions,\n type TextureReadOptions,\n type TextureWriteOptions\n} from './adapter/resources/texture';\n\nexport type {Parameters, PrimitiveTopology, IndexFormat} from './adapter/types/parameters';\n\nexport type {\n CullMode,\n FrontFace,\n RasterizationParameters,\n CompareFunction,\n StencilOperation,\n DepthStencilParameters,\n BlendFactor,\n BlendOperation,\n ColorParameters,\n MultisampleParameters,\n RenderPassParameters,\n RenderPipelineParameters,\n PolygonMode,\n ProvokingVertex\n} from './adapter/types/parameters';\n\nexport type {ColorAttachment, DepthStencilAttachment} from './adapter/types/attachments';\n\nexport type {\n ShaderLayout,\n ComputeShaderLayout,\n AttributeDeclaration,\n BindingDeclaration,\n Binding,\n Bindings,\n BindingsByGroup,\n UniformBufferBindingLayout,\n StorageBufferBindingLayout,\n TextureBindingLayout,\n SamplerBindingLayout,\n StorageTextureBindingLayout\n} from './adapter/types/shader-layout';\nexport type {BufferLayout, BufferAttributeLayout} from './adapter/types/buffer-layout';\nexport type {\n // Deprecated, todo\n AttributeBinding,\n UniformBinding,\n UniformBlockBinding,\n VaryingBinding\n} from './adapter/types/shader-layout';\n\nexport type {UniformValue} from './adapter/types/uniforms';\nexport type {\n CompositeUniformValue,\n CompositeUniformValueArray,\n CompositeUniformValueStruct\n} from './adapter/types/uniforms';\n\n// TYPED ARRAY TYPES\n\nexport type {\n NumberArray,\n TypedArray,\n TypedArrayConstructor,\n BigTypedArray,\n BigTypedArrayConstructor\n} from './types';\n\n// GPU TYPE UTILS - BASIC DATA TYPES\n\nexport {\n type PrimitiveDataType,\n type SignedDataType,\n type NormalizedDataType,\n type DataTypeInfo,\n type PrimitiveDataTypeT,\n type SignedDataTypeT,\n type TypedArrayConstructorT,\n type NormalizedTypedArrayConstructorT\n} from './shadertypes/data-types/data-types';\nexport {dataTypeDecoder} from './shadertypes/data-types/data-type-decoder';\nexport {getTypedArrayConstructor} from './shadertypes/data-types/decode-data-types';\n\nexport {\n type AttributeShaderTypeT,\n type AttributeShaderType,\n type ArrayShaderType,\n type CompositeShaderType,\n type StructShaderType,\n type VariableShaderTypeT,\n type VariableShaderType\n} from './shadertypes/shader-types/shader-types';\nexport {\n shaderTypeDecoder,\n getAttributeShaderTypeInfo,\n getVariableShaderTypeInfo,\n type AttributeShaderTypeInfo\n} from './shadertypes/shader-types/shader-type-decoder';\n\n// GPU TYPE UTILS - VERTEX ARRAYs\n\nexport {\n type VertexFormat,\n type VertexFormatDataTypeT\n} from './shadertypes/vertex-types/vertex-formats';\n\nexport {vertexFormatDecoder} from './shadertypes/vertex-types/vertex-format-decoder';\n\n// GPU TYPE UTILS - Texture Formats\n\nexport {\n type TextureFormat,\n type TextureFormatColor,\n type TextureFormatDepthStencil,\n type CompressedTextureFormat,\n type TextureCompression,\n type TextureFormatInfo,\n type TextureFormatCapabilities,\n type TextureMemoryLayout\n} from './shadertypes/texture-types/texture-formats';\nexport {type TextureFormatDataTypeT} from './shadertypes/texture-types/texture-format-generics';\n\nexport {\n type TextureFormatDecoder,\n textureFormatDecoder\n} from './shadertypes/texture-types/texture-format-decoder';\n\nexport {getTextureImageView, setTextureImageData} from './shadertypes/texture-types/texture-layout';\nexport {type PixelData, readPixel, writePixel} from './shadertypes/texture-types/pixel-utils';\n\nexport {isExternalImage, getExternalImageSize} from './shadertypes/image-types/image-types';\n\n// GENERAL EXPORTS - FOR APPLICATIONS\n\nexport type {StatsManager} from './utils/stats-manager'; // TODO - should this be moved to probe.gl?\n\n// ADAPTER UTILS - for implementing Device adapters (@luma.gl/webgl and @luma.gl/webgpu)\n\nexport type {\n CopyBufferToBufferOptions,\n CopyBufferToTextureOptions,\n CopyTextureToBufferOptions,\n CopyTextureToTextureOptions\n} from './adapter/resources/command-encoder';\n\n// INTERNAL UTILS - for use in other luma.gl modules only\nexport {log} from './utils/log';\nexport {\n getShaderLayoutBinding,\n normalizeBindingsByGroup,\n flattenBindingsByGroup\n} from './adapter-utils/bind-groups';\nexport {assert, assertDefined} from './utils/assert';\nexport {getScratchArray} from './utils/array-utils-flat';\nexport type {AttributeInfo} from './adapter-utils/get-attribute-from-layouts';\nexport {getAttributeInfosFromLayouts} from './adapter-utils/get-attribute-from-layouts';\n\n// TEST EXPORTS\nexport {\n getTextureFormatDefinition as _getTextureFormatDefinition,\n getTextureFormatTable as _getTextureFormatTable\n} from './shadertypes/texture-types/texture-format-table';\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Stat, Stats} from '@probe.gl/stats';\n\nconst GPU_TIME_AND_MEMORY_STATS = 'GPU Time and Memory';\nconst GPU_TIME_AND_MEMORY_STAT_ORDER = [\n 'Adapter',\n 'GPU',\n 'GPU Type',\n 'GPU Backend',\n 'Frame Rate',\n 'CPU Time',\n 'GPU Time',\n 'GPU Memory',\n 'Buffer Memory',\n 'Texture Memory',\n 'Referenced Buffer Memory',\n 'Referenced Texture Memory',\n 'Swap Chain Texture'\n] as const;\nconst ORDERED_STATS_CACHE = new WeakMap<\n Stats,\n {orderedStatNames: readonly string[]; statCount: number}\n>();\nconst ORDERED_STAT_NAME_SET_CACHE = new WeakMap<readonly string[], Set<string>>();\n\n/**\n * Helper class managing a collection of probe.gl stats objects\n */\nexport class StatsManager {\n stats = new Map();\n\n getStats(name: string): Stats {\n return this.get(name);\n }\n\n get(name: string): Stats {\n if (!this.stats.has(name)) {\n this.stats.set(name, new Stats({id: name}));\n }\n\n const stats = this.stats.get(name);\n if (name === GPU_TIME_AND_MEMORY_STATS) {\n initializeStats(stats, GPU_TIME_AND_MEMORY_STAT_ORDER);\n }\n\n return stats;\n }\n}\n\n/** Global stats for all luma.gl devices */\nexport const lumaStats: StatsManager = new StatsManager();\n\nfunction initializeStats(stats: Stats, orderedStatNames: readonly string[]): void {\n const statsMap = stats.stats;\n let addedOrderedStat = false;\n for (const statName of orderedStatNames) {\n if (!statsMap[statName]) {\n stats.get(statName);\n addedOrderedStat = true;\n }\n }\n\n const statCount = Object.keys(statsMap).length;\n const cachedStats = ORDERED_STATS_CACHE.get(stats);\n if (\n !addedOrderedStat &&\n cachedStats?.orderedStatNames === orderedStatNames &&\n cachedStats.statCount === statCount\n ) {\n return;\n }\n\n const reorderedStats: Record<string, Stat> = {};\n let orderedStatNamesSet = ORDERED_STAT_NAME_SET_CACHE.get(orderedStatNames);\n if (!orderedStatNamesSet) {\n orderedStatNamesSet = new Set(orderedStatNames);\n ORDERED_STAT_NAME_SET_CACHE.set(orderedStatNames, orderedStatNamesSet);\n }\n\n for (const statName of orderedStatNames) {\n if (statsMap[statName]) {\n reorderedStats[statName] = statsMap[statName];\n }\n }\n\n for (const [statName, stat] of Object.entries(statsMap)) {\n if (!orderedStatNamesSet.has(statName)) {\n reorderedStats[statName] = stat;\n }\n }\n\n for (const statName of Object.keys(statsMap)) {\n delete statsMap[statName];\n }\n\n Object.assign(statsMap, reorderedStats);\n ORDERED_STATS_CACHE.set(stats, {orderedStatNames, statCount});\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Log} from '@probe.gl/log';\n\n/** Global log instance */\nexport const log: Log = new Log({id: 'luma.gl'});\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nconst uidCounters: Record<string, number> = {};\n\n/**\n * Returns a UID.\n * @param id= - Identifier base name\n * @return uid\n **/\nexport function uid(id: string = 'id'): string {\n uidCounters[id] = uidCounters[id] || 1;\n const count = uidCounters[id]++;\n return `${id}-${count}`;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {Stat, Stats} from '@probe.gl/stats';\nimport {uid} from '../../utils/uid';\n\nconst CPU_HOTSPOT_PROFILER_MODULE = 'cpu-hotspot-profiler';\nconst RESOURCE_COUNTS_STATS = 'GPU Resource Counts';\nconst LEGACY_RESOURCE_COUNTS_STATS = 'Resource Counts';\nconst GPU_TIME_AND_MEMORY_STATS = 'GPU Time and Memory';\nconst BASE_RESOURCE_COUNT_ORDER = [\n 'Resources',\n 'Buffers',\n 'Textures',\n 'Samplers',\n 'TextureViews',\n 'Framebuffers',\n 'QuerySets',\n 'Shaders',\n 'RenderPipelines',\n 'ComputePipelines',\n 'PipelineLayouts',\n 'VertexArrays',\n 'RenderPasss',\n 'ComputePasss',\n 'CommandEncoders',\n 'CommandBuffers'\n] as const;\nconst WEBGL_RESOURCE_COUNT_ORDER = [\n 'Resources',\n 'Buffers',\n 'Textures',\n 'Samplers',\n 'TextureViews',\n 'Framebuffers',\n 'QuerySets',\n 'Shaders',\n 'RenderPipelines',\n 'SharedRenderPipelines',\n 'ComputePipelines',\n 'PipelineLayouts',\n 'VertexArrays',\n 'RenderPasss',\n 'ComputePasss',\n 'CommandEncoders',\n 'CommandBuffers'\n] as const;\nconst BASE_RESOURCE_COUNT_STAT_ORDER = BASE_RESOURCE_COUNT_ORDER.flatMap(resourceType => [\n `${resourceType} Created`,\n `${resourceType} Active`\n]);\nconst WEBGL_RESOURCE_COUNT_STAT_ORDER = WEBGL_RESOURCE_COUNT_ORDER.flatMap(resourceType => [\n `${resourceType} Created`,\n `${resourceType} Active`\n]);\nconst ORDERED_STATS_CACHE = new WeakMap<\n Stats,\n {orderedStatNames: readonly string[]; statCount: number}\n>();\nconst ORDERED_STAT_NAME_SET_CACHE = new WeakMap<readonly string[], Set<string>>();\n\ntype CpuHotspotProfiler = {\n enabled?: boolean;\n activeDefaultFramebufferAcquireDepth?: number;\n statsBookkeepingTimeMs?: number;\n statsBookkeepingCalls?: number;\n transientCanvasResourceCreates?: number;\n transientCanvasTextureCreates?: number;\n transientCanvasTextureViewCreates?: number;\n transientCanvasSamplerCreates?: number;\n transientCanvasFramebufferCreates?: number;\n};\n\nexport type ResourceProps = {\n /** Name of resource, mainly for debugging purposes. A unique name will be assigned if not provided */\n id?: string;\n /** Handle for the underlying resources (WebGL object or WebGPU handle) */\n handle?: any;\n /** User provided data stored on this resource */\n userData?: {[key: string]: any};\n};\n\n/**\n * Base class for GPU (WebGPU/WebGL) Resources\n */\nexport abstract class Resource<Props extends ResourceProps> {\n /** Default properties for resource */\n static defaultProps: Required<ResourceProps> = {\n id: 'undefined',\n handle: undefined,\n userData: undefined!\n };\n\n abstract get [Symbol.toStringTag](): string;\n\n toString(): string {\n return `${this[Symbol.toStringTag] || this.constructor.name}:\"${this.id}\"`;\n }\n\n /** props.id, for debugging. */\n id: string;\n /** The props that this resource was created with */\n readonly props: Required<Props>;\n /** User data object, reserved for the application */\n readonly userData: Record<string, unknown> = {};\n /** The device that this resource is associated with */\n abstract readonly device: Device;\n /** The handle for the underlying resource, e.g. WebGL object or WebGPU handle */\n abstract readonly handle: unknown;\n /** The device that this resource is associated with - TODO can we remove this dup? */\n private _device: Device;\n\n /** Whether this resource has been destroyed */\n destroyed: boolean = false;\n /** For resources that allocate GPU memory */\n private allocatedBytes: number = 0;\n /** Stats bucket currently holding the tracked allocation */\n private allocatedBytesName: string | null = null;\n /** Attached resources will be destroyed when this resource is destroyed. Tracks auto-created \"sub\" resources. */\n private _attachedResources = new Set<Resource<ResourceProps>>();\n\n /**\n * Create a new Resource. Called from Subclass\n */\n constructor(device: Device, props: Props, defaultProps: Required<Props>) {\n if (!device) {\n throw new Error('no device');\n }\n this._device = device;\n this.props = selectivelyMerge<Props>(props, defaultProps);\n\n const id =\n this.props.id !== 'undefined' ? (this.props.id as string) : uid(this[Symbol.toStringTag]);\n this.props.id = id;\n this.id = id;\n this.userData = this.props.userData || {};\n\n this.addStats();\n }\n\n /**\n * destroy can be called on any resource to release it before it is garbage collected.\n */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyResource();\n }\n\n /** @deprecated Use destroy() */\n delete(): this {\n this.destroy();\n return this;\n }\n\n /**\n * Combines a map of user props and default props, only including props from defaultProps\n * @returns returns a map of overridden default props\n */\n getProps(): object {\n return this.props;\n }\n\n // ATTACHED RESOURCES\n\n /**\n * Attaches a resource. Attached resources are auto destroyed when this resource is destroyed\n * Called automatically when sub resources are auto created but can be called by application\n */\n attachResource(resource: Resource<ResourceProps>): void {\n this._attachedResources.add(resource);\n }\n\n /**\n * Detach an attached resource. The resource will no longer be auto-destroyed when this resource is destroyed.\n */\n detachResource(resource: Resource<ResourceProps>): void {\n this._attachedResources.delete(resource);\n }\n\n /**\n * Destroys a resource (only if owned), and removes from the owned (auto-destroy) list for this resource.\n */\n destroyAttachedResource(resource: Resource<ResourceProps>): void {\n if (this._attachedResources.delete(resource)) {\n resource.destroy();\n }\n }\n\n /** Destroy all owned resources. Make sure the resources are no longer needed before calling. */\n destroyAttachedResources(): void {\n for (const resource of this._attachedResources) {\n resource.destroy();\n }\n // don't remove while we are iterating\n this._attachedResources = new Set<Resource<ResourceProps>>();\n }\n\n // PROTECTED METHODS\n\n /** Perform all destroy steps. Can be called by derived resources when overriding destroy() */\n protected destroyResource(): void {\n if (this.destroyed) {\n return;\n }\n this.destroyAttachedResources();\n this.removeStats();\n this.destroyed = true;\n }\n\n /** Called by .destroy() to track object destruction. Subclass must call if overriding destroy() */\n protected removeStats(): void {\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const statsObjects = [\n this._device.statsManager.getStats(RESOURCE_COUNTS_STATS),\n this._device.statsManager.getStats(LEGACY_RESOURCE_COUNTS_STATS)\n ];\n const orderedStatNames = getResourceCountStatOrder(this._device);\n for (const stats of statsObjects) {\n initializeStats(stats, orderedStatNames);\n }\n const name = this.getStatsName();\n for (const stats of statsObjects) {\n stats.get('Resources Active').decrementCount();\n stats.get(`${name}s Active`).decrementCount();\n }\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n }\n\n /** Called by subclass to track memory allocations */\n protected trackAllocatedMemory(bytes: number, name = this.getStatsName()): void {\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const stats = this._device.statsManager.getStats(GPU_TIME_AND_MEMORY_STATS);\n\n if (this.allocatedBytes > 0 && this.allocatedBytesName) {\n stats.get('GPU Memory').subtractCount(this.allocatedBytes);\n stats.get(`${this.allocatedBytesName} Memory`).subtractCount(this.allocatedBytes);\n }\n\n stats.get('GPU Memory').addCount(bytes);\n stats.get(`${name} Memory`).addCount(bytes);\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n this.allocatedBytes = bytes;\n this.allocatedBytesName = name;\n }\n\n /** Called by subclass to track handle-backed memory allocations separately from owned allocations */\n protected trackReferencedMemory(bytes: number, name = this.getStatsName()): void {\n this.trackAllocatedMemory(bytes, `Referenced ${name}`);\n }\n\n /** Called by subclass to track memory deallocations */\n protected trackDeallocatedMemory(name = this.getStatsName()): void {\n if (this.allocatedBytes === 0) {\n this.allocatedBytesName = null;\n return;\n }\n\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const stats = this._device.statsManager.getStats(GPU_TIME_AND_MEMORY_STATS);\n stats.get('GPU Memory').subtractCount(this.allocatedBytes);\n stats.get(`${this.allocatedBytesName || name} Memory`).subtractCount(this.allocatedBytes);\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n this.allocatedBytes = 0;\n this.allocatedBytesName = null;\n }\n\n /** Called by subclass to deallocate handle-backed memory tracked via trackReferencedMemory() */\n protected trackDeallocatedReferencedMemory(name = this.getStatsName()): void {\n this.trackDeallocatedMemory(`Referenced ${name}`);\n }\n\n /** Called by resource constructor to track object creation */\n private addStats(): void {\n const name = this.getStatsName();\n const profiler = getCpuHotspotProfiler(this._device);\n const startTime = profiler ? getTimestamp() : 0;\n const statsObjects = [\n this._device.statsManager.getStats(RESOURCE_COUNTS_STATS),\n this._device.statsManager.getStats(LEGACY_RESOURCE_COUNTS_STATS)\n ];\n const orderedStatNames = getResourceCountStatOrder(this._device);\n for (const stats of statsObjects) {\n initializeStats(stats, orderedStatNames);\n }\n for (const stats of statsObjects) {\n stats.get('Resources Created').incrementCount();\n stats.get('Resources Active').incrementCount();\n stats.get(`${name}s Created`).incrementCount();\n stats.get(`${name}s Active`).incrementCount();\n }\n if (profiler) {\n profiler.statsBookkeepingCalls = (profiler.statsBookkeepingCalls || 0) + 1;\n profiler.statsBookkeepingTimeMs =\n (profiler.statsBookkeepingTimeMs || 0) + (getTimestamp() - startTime);\n }\n recordTransientCanvasResourceCreate(this._device, name);\n }\n\n /** Canonical resource name used for stats buckets. */\n protected getStatsName(): string {\n return getCanonicalResourceName(this);\n }\n}\n\n/**\n * Combines a map of user props and default props, only including props from defaultProps\n * @param props\n * @param defaultProps\n * @returns returns a map of overridden default props\n */\nfunction selectivelyMerge<Props>(props: Props, defaultProps: Required<Props>): Required<Props> {\n const mergedProps = {...defaultProps};\n for (const key in props) {\n if (props[key] !== undefined) {\n mergedProps[key] = props[key];\n }\n }\n return mergedProps;\n}\n\nfunction initializeStats(stats: Stats, orderedStatNames: readonly string[]): void {\n const statsMap = stats.stats;\n let addedOrderedStat = false;\n for (const statName of orderedStatNames) {\n if (!statsMap[statName]) {\n stats.get(statName);\n addedOrderedStat = true;\n }\n }\n\n const statCount = Object.keys(statsMap).length;\n const cachedStats = ORDERED_STATS_CACHE.get(stats);\n if (\n !addedOrderedStat &&\n cachedStats?.orderedStatNames === orderedStatNames &&\n cachedStats.statCount === statCount\n ) {\n return;\n }\n\n const reorderedStats: Record<string, Stat> = {};\n let orderedStatNamesSet = ORDERED_STAT_NAME_SET_CACHE.get(orderedStatNames);\n if (!orderedStatNamesSet) {\n orderedStatNamesSet = new Set(orderedStatNames);\n ORDERED_STAT_NAME_SET_CACHE.set(orderedStatNames, orderedStatNamesSet);\n }\n\n for (const statName of orderedStatNames) {\n if (statsMap[statName]) {\n reorderedStats[statName] = statsMap[statName];\n }\n }\n\n for (const [statName, stat] of Object.entries(statsMap)) {\n if (!orderedStatNamesSet.has(statName)) {\n reorderedStats[statName] = stat;\n }\n }\n\n for (const statName of Object.keys(statsMap)) {\n delete statsMap[statName];\n }\n\n Object.assign(statsMap, reorderedStats);\n ORDERED_STATS_CACHE.set(stats, {orderedStatNames, statCount});\n}\n\nfunction getResourceCountStatOrder(device: Device): readonly string[] {\n return device.type === 'webgl' ? WEBGL_RESOURCE_COUNT_STAT_ORDER : BASE_RESOURCE_COUNT_STAT_ORDER;\n}\n\nfunction getCpuHotspotProfiler(device: Device): CpuHotspotProfiler | null {\n const profiler = device.userData[CPU_HOTSPOT_PROFILER_MODULE] as CpuHotspotProfiler | undefined;\n return profiler?.enabled ? profiler : null;\n}\n\nfunction getTimestamp(): number {\n return globalThis.performance?.now?.() ?? Date.now();\n}\n\nfunction recordTransientCanvasResourceCreate(device: Device, name: string): void {\n const profiler = getCpuHotspotProfiler(device);\n if (!profiler || !profiler.activeDefaultFramebufferAcquireDepth) {\n return;\n }\n\n profiler.transientCanvasResourceCreates = (profiler.transientCanvasResourceCreates || 0) + 1;\n\n switch (name) {\n case 'Texture':\n profiler.transientCanvasTextureCreates = (profiler.transientCanvasTextureCreates || 0) + 1;\n break;\n case 'TextureView':\n profiler.transientCanvasTextureViewCreates =\n (profiler.transientCanvasTextureViewCreates || 0) + 1;\n break;\n case 'Sampler':\n profiler.transientCanvasSamplerCreates = (profiler.transientCanvasSamplerCreates || 0) + 1;\n break;\n case 'Framebuffer':\n profiler.transientCanvasFramebufferCreates =\n (profiler.transientCanvasFramebufferCreates || 0) + 1;\n break;\n default:\n break;\n }\n}\n\nfunction getCanonicalResourceName(resource: Resource<any>): string {\n let prototype = Object.getPrototypeOf(resource);\n\n while (prototype) {\n const parentPrototype = Object.getPrototypeOf(prototype);\n if (!parentPrototype || parentPrototype === Resource.prototype) {\n return (\n getPrototypeToStringTag(prototype) ||\n resource[Symbol.toStringTag] ||\n resource.constructor.name\n );\n }\n prototype = parentPrototype;\n }\n\n return resource[Symbol.toStringTag] || resource.constructor.name;\n}\n\nfunction getPrototypeToStringTag(prototype: object): string | null {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag);\n if (typeof descriptor?.get === 'function') {\n return descriptor.get.call(prototype);\n }\n if (typeof descriptor?.value === 'string') {\n return descriptor.value;\n }\n return null;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\n/** Callback for Buffer.mapAndReadAsync */\nexport type BufferMapCallback<T> = (arrayBuffer: ArrayBuffer, lifetime: 'mapped' | 'copied') => T;\n\nexport type BufferProps = ResourceProps & {\n /** Supply a handle to connect to an existing device-specific buffer */\n handle?: WebGLBuffer;\n /** Specifies how this buffer can be used */\n usage?: number;\n /** Length in bytes of memory to be allocated. If not specified, `byteLength` of `props.data` will be used. */\n byteLength?: number;\n /** Byte offset into the newly created Buffer to store data at */\n byteOffset?: number;\n /** If props.usage includes Buffer.INDEX. Note: uint8 indices are automatically converted to uint16 for WebGPU compatibility */\n indexType?: 'uint8' | 'uint16' | 'uint32';\n /** Data to initialize the buffer with. */\n data?: ArrayBuffer | ArrayBufferView | null;\n /** Callback to initialize data without copy */\n onMapped?: BufferMapCallback<void>;\n};\n\n/** Abstract GPU buffer */\nexport abstract class Buffer extends Resource<BufferProps> {\n /** Index buffer */\n static INDEX = 0x0010;\n /** Vertex buffer */\n static VERTEX = 0x0020;\n /** Uniform buffer */\n static UNIFORM = 0x0040;\n /** Storage buffer */\n static STORAGE = 0x0080;\n static INDIRECT = 0x0100;\n static QUERY_RESOLVE = 0x0200;\n\n // Usage Flags\n static MAP_READ = 0x01;\n static MAP_WRITE = 0x02;\n static COPY_SRC = 0x0004;\n static COPY_DST = 0x0008;\n\n override get [Symbol.toStringTag](): string {\n return 'Buffer';\n }\n\n /** The usage with which this buffer was created */\n readonly usage: number;\n /** For index buffers, whether indices are 8, 16 or 32 bit. Note: uint8 indices are automatically converted to uint16 for WebGPU compatibility */\n readonly indexType?: 'uint8' | 'uint16' | 'uint32';\n /** Length of buffer in bytes */\n abstract byteLength: number;\n /** \"Time\" of last update, can be used to check if redraw is needed */\n updateTimestamp: number;\n\n constructor(device: Device, props: BufferProps) {\n const deducedProps = {...props};\n\n // Deduce indexType\n if ((props.usage || 0) & Buffer.INDEX && !props.indexType) {\n if (props.data instanceof Uint32Array) {\n deducedProps.indexType = 'uint32';\n } else if (props.data instanceof Uint16Array) {\n deducedProps.indexType = 'uint16';\n } else if (props.data instanceof Uint8Array) {\n deducedProps.indexType = 'uint8';\n }\n }\n\n // Remove data from props before storing, we don't want to hold on to a big chunk of memory\n delete deducedProps.data;\n\n super(device, deducedProps, Buffer.defaultProps);\n\n this.usage = deducedProps.usage || 0;\n this.indexType = deducedProps.indexType;\n\n // TODO - perhaps this should be set on async write completion?\n this.updateTimestamp = device.incrementTimestamp();\n }\n\n /**\n * Create a copy of this Buffer with new byteLength, with same props but of the specified size.\n * @note Does not copy contents of the cloned Buffer.\n */\n clone(props: {byteLength: number}): Buffer {\n return this.device.createBuffer({...this.props, ...props});\n }\n\n /** Write data to buffer */\n abstract write(\n data: ArrayBufferLike | ArrayBufferView | SharedArrayBuffer,\n byteOffset?: number\n ): void;\n\n abstract mapAndWriteAsync(\n onMapped: BufferMapCallback<void | Promise<void>>,\n byteOffset?: number,\n byteLength?: number\n ): Promise<void>;\n\n /** Reads data asynchronously, returns a copy of the buffer data */\n abstract readAsync(byteOffset?: number, byteLength?: number): Promise<Uint8Array>;\n\n /** Maps buffer data to CPU memory. Mapped memory is only accessible in the callback */\n abstract mapAndReadAsync<T>(\n onMapped: BufferMapCallback<T>,\n byteOffset?: number,\n byteLength?: number\n ): Promise<T>;\n\n /** Read data synchronously. @note WebGL2 only */\n abstract readSyncWebGL(byteOffset?: number, byteLength?: number): Uint8Array;\n\n // PROTECTED METHODS (INTENDED FOR USE BY OTHER FRAMEWORK CODE ONLY)\n\n /** Max amount of debug data saved. Two vec4's */\n static DEBUG_DATA_MAX_LENGTH = 32;\n\n /** A partial CPU-side copy of the data in this buffer, for debugging purposes */\n debugData: ArrayBuffer = new ArrayBuffer(0);\n\n /** This doesn't handle partial non-zero offset updates correctly */\n protected _setDebugData(\n data: ArrayBufferView | ArrayBufferLike | null,\n _byteOffset: number,\n byteLength: number\n ): void {\n let arrayBufferView: ArrayBufferView | null = null;\n let arrayBuffer: ArrayBufferLike | null;\n if (ArrayBuffer.isView(data)) {\n arrayBufferView = data;\n arrayBuffer = data.buffer;\n } else {\n arrayBuffer = data;\n }\n const debugDataLength = Math.min(\n data ? data.byteLength : byteLength,\n Buffer.DEBUG_DATA_MAX_LENGTH\n );\n if (arrayBuffer === null) {\n this.debugData = new ArrayBuffer(debugDataLength);\n } else {\n const sourceByteOffset = Math.min(arrayBufferView?.byteOffset || 0, arrayBuffer.byteLength);\n const availableByteLength = Math.max(0, arrayBuffer.byteLength - sourceByteOffset);\n const copyByteLength = Math.min(debugDataLength, availableByteLength);\n this.debugData = new Uint8Array(arrayBuffer, sourceByteOffset, copyByteLength).slice().buffer;\n }\n }\n\n static override defaultProps: Required<BufferProps> = {\n ...Resource.defaultProps,\n usage: 0, // Buffer.COPY_DST | Buffer.COPY_SRC\n byteLength: 0,\n byteOffset: 0,\n data: null,\n indexType: 'uint16',\n onMapped: undefined!\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray, TypedArrayConstructor} from '../../types';\nimport {\n PrimitiveDataType,\n SignedDataType,\n NormalizedDataType,\n DataTypeInfo,\n TypedArrayConstructorT\n} from './data-types';\n\nexport class DataTypeDecoder {\n /**\n * Gets info about a data type constant (signed or normalized)\n * @returns underlying primitive / signed types, byte length, normalization, integer, signed flags\n */\n getDataTypeInfo<T extends NormalizedDataType = NormalizedDataType>(type: T): DataTypeInfo<T> {\n const [signedType, primitiveType, byteLength] = NORMALIZED_TYPE_MAP[type];\n const normalized: boolean = type.includes('norm');\n const integer: boolean = !normalized && !type.startsWith('float');\n const signed: boolean = type.startsWith('s');\n return {\n signedType: signedType as DataTypeInfo<T>['signedType'],\n primitiveType: primitiveType as DataTypeInfo<T>['primitiveType'],\n byteLength: byteLength as DataTypeInfo<T>['byteLength'],\n normalized: normalized as DataTypeInfo<T>['normalized'],\n integer: integer as DataTypeInfo<T>['integer'],\n signed: signed as DataTypeInfo<T>['signed']\n // TODO - add webglOnly flag\n };\n }\n\n /** Build a vertex format from a signed data type and a component */\n getNormalizedDataType(signedDataType: SignedDataType): NormalizedDataType {\n const dataType: NormalizedDataType = signedDataType;\n // biome-ignore format: preserve layout\n switch (dataType) {\n case 'uint8': return 'unorm8';\n case 'sint8': return 'snorm8';\n case 'uint16': return 'unorm16';\n case 'sint16': return 'snorm16';\n default: return dataType;\n }\n }\n\n /** Align offset to 1, 2 or 4 elements (4, 8 or 16 bytes) */\n alignTo(size: number, count: number): number {\n // biome-ignore format: preserve layout\n switch (count) {\n case 1: return size; // Pad upwards to even multiple of 2\n case 2: return size + (size % 2); // Pad upwards to even multiple of 2\n default: return size + ((4 - (size % 4)) % 4); // Pad upwards to even multiple of 4\n }\n }\n\n /** Returns the VariableShaderType that corresponds to a typed array */\n getDataType(arrayOrType: TypedArray | TypedArrayConstructor): SignedDataType {\n const Constructor = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;\n if (Constructor === Uint8ClampedArray) {\n return 'uint8';\n }\n const info = Object.values(NORMALIZED_TYPE_MAP).find(entry => Constructor === entry[4]);\n if (!info) {\n throw new Error(Constructor.name);\n }\n return info[0];\n }\n\n /** Returns the TypedArray that corresponds to a shader data type */\n getTypedArrayConstructor<T extends NormalizedDataType>(\n type: NormalizedDataType\n ): TypedArrayConstructorT<T> {\n const [, , , , Constructor] = NORMALIZED_TYPE_MAP[type];\n return Constructor as unknown as TypedArrayConstructorT<T>;\n }\n}\n\n/** Entry point for decoding luma.gl data types */\nexport const dataTypeDecoder = new DataTypeDecoder();\n\nconst NORMALIZED_TYPE_MAP = {\n uint8: ['uint8', 'u32', 1, false, Uint8Array],\n sint8: ['sint8', 'i32', 1, false, Int8Array],\n unorm8: ['uint8', 'f32', 1, true, Uint8Array],\n snorm8: ['sint8', 'f32', 1, true, Int8Array],\n uint16: ['uint16', 'u32', 2, false, Uint16Array],\n sint16: ['sint16', 'i32', 2, false, Int16Array],\n unorm16: ['uint16', 'u32', 2, true, Uint16Array],\n snorm16: ['sint16', 'i32', 2, true, Int16Array],\n float16: ['float16', 'f16', 2, false, Uint16Array],\n float32: ['float32', 'f32', 4, false, Float32Array],\n uint32: ['uint32', 'u32', 4, false, Uint32Array],\n sint32: ['sint32', 'i32', 4, false, Int32Array]\n} satisfies Record<\n NormalizedDataType,\n [\n SignedDataType,\n PrimitiveDataType,\n bytes: 1 | 2 | 4,\n normalized: boolean,\n arrayConstructor: TypedArrayConstructor\n ]\n>;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '../../types';\nimport type {NormalizedDataType, PrimitiveDataType, SignedDataType} from '../data-types/data-types';\nimport type {VertexFormat, VertexFormatInfo} from './vertex-formats';\nimport {dataTypeDecoder} from '../data-types/data-type-decoder';\n\nexport class VertexFormatDecoder {\n /**\n * Decodes a vertex format, returning type, components, byte length and flags (integer, signed, normalized)\n */\n getVertexFormatInfo<T extends VertexFormat = VertexFormat>(format: T): VertexFormatInfo<T> {\n // Strip the -webgl ending if present\n let webglOnly: boolean | undefined;\n if (format.endsWith('-webgl')) {\n format.replace('-webgl', '');\n webglOnly = true;\n }\n // split components from type\n const [type_, count] = format.split('x');\n const type = type_ as NormalizedDataType;\n const components = (count ? parseInt(count) : 1) as 1 | 2 | 3 | 4;\n // decode the type\n const decodedType = dataTypeDecoder.getDataTypeInfo(type);\n const result: VertexFormatInfo = {\n type,\n components,\n byteLength: decodedType.byteLength * components,\n integer: decodedType.integer,\n signed: decodedType.signed,\n normalized: decodedType.normalized\n };\n if (webglOnly) {\n result.webglOnly = true;\n }\n return result;\n }\n\n /** Build a vertex format from a signed data type and a component */\n makeVertexFormat(\n signedDataType: SignedDataType,\n components: 1 | 2 | 3 | 4,\n normalized?: boolean\n ): VertexFormat {\n const dataType: NormalizedDataType = normalized\n ? dataTypeDecoder.getNormalizedDataType(signedDataType)\n : signedDataType;\n\n switch (dataType) {\n // Special cases for WebGL-only x3 formats that WebGPU does not support.\n case 'unorm8':\n if (components === 1) {\n return 'unorm8';\n }\n if (components === 3) {\n return 'unorm8x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'snorm8':\n if (components === 1) {\n return 'snorm8';\n }\n if (components === 3) {\n return 'snorm8x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'uint8':\n case 'sint8':\n // WebGPU 8 bit formats must be aligned to 16 bit boundaries.\n if (components === 1 || components === 3) {\n throw new Error(`size: ${components}`);\n }\n return `${dataType}x${components}`;\n\n case 'uint16':\n if (components === 1) {\n return 'uint16';\n }\n if (components === 3) {\n return 'uint16x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'sint16':\n if (components === 1) {\n return 'sint16';\n }\n if (components === 3) {\n return 'sint16x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'unorm16':\n if (components === 1) {\n return 'unorm16';\n }\n if (components === 3) {\n return 'unorm16x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'snorm16':\n if (components === 1) {\n return 'snorm16';\n }\n if (components === 3) {\n return 'snorm16x3-webgl';\n }\n return `${dataType}x${components}`;\n\n case 'float16':\n // WebGPU 16 bit formats must be aligned to 32 bit boundaries\n if (components === 1 || components === 3) {\n throw new Error(`size: ${components}`);\n }\n return `${dataType}x${components}`;\n\n default:\n return components === 1 ? dataType : `${dataType}x${components}`;\n }\n }\n\n /** Get the vertex format for an attribute with TypedArray and size */\n getVertexFormatFromAttribute(\n typedArray: TypedArray,\n size: number,\n normalized?: boolean\n ): VertexFormat {\n if (!size || size > 4) {\n throw new Error(`size ${size}`);\n }\n\n const components = size as 1 | 2 | 3 | 4;\n const signedDataType = dataTypeDecoder.getDataType(typedArray);\n return this.makeVertexFormat(signedDataType, components, normalized);\n }\n\n /**\n * Return a \"default\" vertex format for a certain shader data type\n * The simplest vertex format that matches the shader attribute's data type\n */\n\n getCompatibleVertexFormat(opts: {\n primitiveType: PrimitiveDataType;\n components: 1 | 2 | 3 | 4;\n }): VertexFormat {\n let vertexType: NormalizedDataType;\n switch (opts.primitiveType) {\n case 'f32':\n vertexType = 'float32';\n break;\n case 'i32':\n vertexType = 'sint32';\n break;\n case 'u32':\n vertexType = 'uint32';\n break;\n case 'f16':\n return opts.components <= 2 ? 'float16x2' : 'float16x4';\n }\n\n // TODO logic does not work for float16\n if (opts.components === 1) {\n return vertexType;\n }\n return `${vertexType}x${opts.components}`;\n }\n}\n\n/** Decoder for luma.gl vertex types */\nexport const vertexFormatDecoder = new VertexFormatDecoder();\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {\n TextureFormat,\n TextureFormatColorUncompressed,\n TextureFormatDepthStencil,\n TextureFeature,\n TextureFormatInfo,\n TextureFormatCompressed\n} from './texture-formats';\n/* eslint-disable camelcase */\n\n// Define local device feature strings to optimize minification\nconst texture_compression_bc: TextureFeature = 'texture-compression-bc';\nconst texture_compression_astc: TextureFeature = 'texture-compression-astc';\nconst texture_compression_etc2: TextureFeature = 'texture-compression-etc2';\nconst texture_compression_etc1_webgl: TextureFeature = 'texture-compression-etc1-webgl';\nconst texture_compression_pvrtc_webgl: TextureFeature = 'texture-compression-pvrtc-webgl';\nconst texture_compression_atc_webgl: TextureFeature = 'texture-compression-atc-webgl';\n\nconst float32_renderable: TextureFeature = 'float32-renderable-webgl';\nconst float16_renderable: TextureFeature = 'float16-renderable-webgl';\nconst rgb9e5ufloat_renderable: TextureFeature = 'rgb9e5ufloat-renderable-webgl';\nconst snorm8_renderable: TextureFeature = 'snorm8-renderable-webgl';\nconst norm16_webgl: TextureFeature = 'norm16-webgl';\nconst norm16_renderable: TextureFeature = 'norm16-renderable-webgl';\nconst snorm16_renderable: TextureFeature = 'snorm16-renderable-webgl';\n\nconst float32_filterable: TextureFeature = 'float32-filterable';\nconst float16_filterable: TextureFeature = 'float16-filterable-webgl';\n\n/** https://www.w3.org/TR/webgpu/#texture-format-caps */\n\n/** Internal type representing texture capabilities */\ntype TextureFormatDefinition = Partial<TextureFormatInfo> & {\n /** for compressed texture formats */\n f?: TextureFeature;\n /** renderable if feature is present. false means the spec does not support this format */\n render?: TextureFeature | false;\n /** filterable if feature is present. false means the spec does not support this format */\n filter?: TextureFeature | false;\n blend?: TextureFeature | false;\n store?: TextureFeature | false;\n\n /** (bytes per pixel), for memory usage calculations. */\n b?: number;\n /** channels */\n c?: number;\n bpp?: number;\n /** packed */\n p?: number;\n\n /** If not supported on WebGPU */\n wgpu?: false;\n};\n\nexport function getTextureFormatDefinition(format: TextureFormat): TextureFormatDefinition {\n const info = TEXTURE_FORMAT_TABLE[format];\n if (!info) {\n throw new Error(`Unsupported texture format ${format}`);\n }\n return info;\n}\n\nexport function getTextureFormatTable(): Readonly<Record<TextureFormat, TextureFormatDefinition>> {\n return TEXTURE_FORMAT_TABLE;\n}\n\n// biome-ignore format: preserve layout\nconst TEXTURE_FORMAT_COLOR_DEPTH_TABLE: Readonly<Record<TextureFormatColorUncompressed | TextureFormatDepthStencil, TextureFormatDefinition>> = {\n // 8-bit formats\n 'r8unorm': {},\n 'rg8unorm': {},\n 'rgb8unorm-webgl': {},\n 'rgba8unorm': {},\n 'rgba8unorm-srgb': {},\n\n 'r8snorm': {render: snorm8_renderable},\n 'rg8snorm': {render: snorm8_renderable},\n 'rgb8snorm-webgl': {},\n 'rgba8snorm': {render: snorm8_renderable},\n\n 'r8uint': {},\n 'rg8uint': {},\n 'rgba8uint': {},\n\n 'r8sint': {},\n 'rg8sint': {},\n 'rgba8sint': {},\n\n 'bgra8unorm': {},\n 'bgra8unorm-srgb': {},\n\n\n 'r16unorm': {f: norm16_webgl, render: norm16_renderable},\n 'rg16unorm': {f: norm16_webgl, render: norm16_renderable},\n 'rgb16unorm-webgl': {f: norm16_webgl, render: false}, // rgb not renderable\n 'rgba16unorm': {f: norm16_webgl, render: norm16_renderable},\n\n 'r16snorm': {f: norm16_webgl, render: snorm16_renderable},\n 'rg16snorm': {f: norm16_webgl, render: snorm16_renderable},\n 'rgb16snorm-webgl': {f: norm16_webgl, render: false}, // rgb not renderable\n 'rgba16snorm': {f: norm16_webgl, render: snorm16_renderable},\n\n 'r16uint': {},\n 'rg16uint': {},\n 'rgba16uint': {},\n\n 'r16sint': {},\n 'rg16sint': {},\n 'rgba16sint': {},\n\n 'r16float': {render: float16_renderable, filter: 'float16-filterable-webgl'},\n 'rg16float': {render: float16_renderable, filter: float16_filterable},\n 'rgba16float': {render: float16_renderable, filter: float16_filterable},\n\n 'r32uint': {},\n 'rg32uint': {},\n 'rgba32uint': {},\n\n 'r32sint': {},\n 'rg32sint': {},\n 'rgba32sint': {},\n\n 'r32float': {render: float32_renderable, filter: float32_filterable},\n 'rg32float': {render: false, filter: float32_filterable},\n 'rgb32float-webgl': {render: float32_renderable, filter: float32_filterable},\n 'rgba32float': {render: float32_renderable, filter: float32_filterable},\n\n // Packed 16-bit formats\n 'rgba4unorm-webgl': {channels: 'rgba', bitsPerChannel: [4, 4, 4, 4], packed: true},\n 'rgb565unorm-webgl': {channels: 'rgb', bitsPerChannel: [5, 6, 5, 0], packed: true},\n 'rgb5a1unorm-webgl': {channels: 'rgba', bitsPerChannel: [5, 5, 5, 1], packed: true},\n\n // Packed 32 bit formats\n 'rgb9e5ufloat': {channels: 'rgb', packed: true, render: rgb9e5ufloat_renderable}, // , filter: true},\n 'rg11b10ufloat': {channels: 'rgb', bitsPerChannel: [11, 11, 10, 0], packed: true, p: 1,render: float32_renderable},\n 'rgb10a2unorm': {channels: 'rgba', bitsPerChannel: [10, 10, 10, 2], packed: true, p: 1},\n 'rgb10a2uint': {channels: 'rgba', bitsPerChannel: [10, 10, 10, 2], packed: true, p: 1},\n\n // Depth/stencil Formats\n \n // Depth and stencil formats\n stencil8: {attachment: 'stencil', bitsPerChannel: [8, 0, 0, 0], dataType: 'uint8'},\n 'depth16unorm': {attachment: 'depth', bitsPerChannel: [16, 0, 0, 0], dataType: 'uint16'},\n 'depth24plus': {attachment: 'depth', bitsPerChannel: [24, 0, 0, 0], dataType: 'uint32'},\n 'depth32float': {attachment: 'depth', bitsPerChannel: [32, 0, 0, 0], dataType: 'float32'},\n // The depth component of the \"depth24plus\" and \"depth24plus-stencil8\" formats may be implemented as either a 24-bit depth value or a \"depth32float\" value.\n 'depth24plus-stencil8': {attachment: 'depth-stencil', bitsPerChannel: [24, 8, 0, 0], packed: true},\n // \"depth32float-stencil8\" feature\n 'depth32float-stencil8': {attachment: 'depth-stencil', bitsPerChannel: [32, 8, 0, 0], packed: true},\n};\n\n// biome-ignore format: preserve layout\nconst TEXTURE_FORMAT_COMPRESSED_TABLE: Readonly<Record<TextureFormatCompressed, TextureFormatDefinition>> = {\n\n // BC compressed formats: check device.features.has(\"texture-compression-bc\");\n\n 'bc1-rgb-unorm-webgl': {f: texture_compression_bc},\n 'bc1-rgb-unorm-srgb-webgl': {f: texture_compression_bc},\n\n 'bc1-rgba-unorm': {f: texture_compression_bc},\n 'bc1-rgba-unorm-srgb': {f: texture_compression_bc},\n 'bc2-rgba-unorm': {f: texture_compression_bc},\n 'bc2-rgba-unorm-srgb': {f: texture_compression_bc},\n 'bc3-rgba-unorm': {f: texture_compression_bc},\n 'bc3-rgba-unorm-srgb': {f: texture_compression_bc},\n 'bc4-r-unorm': {f: texture_compression_bc},\n 'bc4-r-snorm': {f: texture_compression_bc},\n 'bc5-rg-unorm': {f: texture_compression_bc},\n 'bc5-rg-snorm': {f: texture_compression_bc},\n 'bc6h-rgb-ufloat': {f: texture_compression_bc},\n 'bc6h-rgb-float': {f: texture_compression_bc},\n 'bc7-rgba-unorm': {f: texture_compression_bc},\n 'bc7-rgba-unorm-srgb': {f: texture_compression_bc},\n\n // WEBGL_compressed_texture_etc: device.features.has(\"texture-compression-etc2\")\n // Note: Supposedly guaranteed availability compressed formats in WebGL2, but through CPU decompression\n\n 'etc2-rgb8unorm': {f: texture_compression_etc2},\n 'etc2-rgb8unorm-srgb': {f: texture_compression_etc2},\n 'etc2-rgb8a1unorm': {f: texture_compression_etc2},\n 'etc2-rgb8a1unorm-srgb': {f: texture_compression_etc2},\n 'etc2-rgba8unorm': {f: texture_compression_etc2},\n 'etc2-rgba8unorm-srgb': {f: texture_compression_etc2},\n\n 'eac-r11unorm': {f: texture_compression_etc2},\n 'eac-r11snorm': {f: texture_compression_etc2},\n 'eac-rg11unorm': {f: texture_compression_etc2},\n 'eac-rg11snorm': {f: texture_compression_etc2},\n\n // X_ASTC compressed formats: device.features.has(\"texture-compression-astc\")\n\n 'astc-4x4-unorm': {f: texture_compression_astc},\n 'astc-4x4-unorm-srgb': {f: texture_compression_astc},\n 'astc-5x4-unorm': {f: texture_compression_astc},\n 'astc-5x4-unorm-srgb': {f: texture_compression_astc},\n 'astc-5x5-unorm': {f: texture_compression_astc},\n 'astc-5x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-6x5-unorm': {f: texture_compression_astc},\n 'astc-6x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-6x6-unorm': {f: texture_compression_astc},\n 'astc-6x6-unorm-srgb': {f: texture_compression_astc},\n 'astc-8x5-unorm': {f: texture_compression_astc},\n 'astc-8x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-8x6-unorm': {f: texture_compression_astc},\n 'astc-8x6-unorm-srgb': {f: texture_compression_astc},\n 'astc-8x8-unorm': {f: texture_compression_astc},\n 'astc-8x8-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x5-unorm': {f: texture_compression_astc},\n 'astc-10x5-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x6-unorm': {f: texture_compression_astc},\n 'astc-10x6-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x8-unorm': {f: texture_compression_astc},\n 'astc-10x8-unorm-srgb': {f: texture_compression_astc},\n 'astc-10x10-unorm': {f: texture_compression_astc},\n 'astc-10x10-unorm-srgb': {f: texture_compression_astc},\n 'astc-12x10-unorm': {f: texture_compression_astc},\n 'astc-12x10-unorm-srgb': {f: texture_compression_astc},\n 'astc-12x12-unorm': {f: texture_compression_astc},\n 'astc-12x12-unorm-srgb': {f: texture_compression_astc},\n\n // WEBGL_compressed_texture_pvrtc\n\n 'pvrtc-rgb4unorm-webgl': {f: texture_compression_pvrtc_webgl},\n 'pvrtc-rgba4unorm-webgl': {f: texture_compression_pvrtc_webgl},\n 'pvrtc-rgb2unorm-webgl': {f: texture_compression_pvrtc_webgl},\n 'pvrtc-rgba2unorm-webgl': {f: texture_compression_pvrtc_webgl},\n\n // WEBGL_compressed_texture_etc1\n\n 'etc1-rbg-unorm-webgl': {f: texture_compression_etc1_webgl},\n\n // WEBGL_compressed_texture_atc\n\n 'atc-rgb-unorm-webgl': {f: texture_compression_atc_webgl},\n 'atc-rgba-unorm-webgl': {f: texture_compression_atc_webgl},\n 'atc-rgbai-unorm-webgl': {f: texture_compression_atc_webgl}\n};\n\nexport const TEXTURE_FORMAT_TABLE: Readonly<Record<TextureFormat, TextureFormatDefinition>> = {\n ...TEXTURE_FORMAT_COLOR_DEPTH_TABLE,\n ...TEXTURE_FORMAT_COMPRESSED_TABLE\n};\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NormalizedDataType} from '../data-types/data-types';\nimport {dataTypeDecoder} from '../data-types/data-type-decoder';\nimport type {\n TextureFormat,\n TextureFormatCompressed,\n TextureFormatInfo,\n TextureFormatCapabilities,\n TextureFormatColor,\n TextureMemoryLayout,\n TextureFormatDepthStencil\n} from './texture-formats';\nimport {getTextureFormatDefinition} from './texture-format-table';\n\nconst RGB_FORMAT_REGEX = /^(r|rg|rgb|rgba|bgra)([0-9]*)([a-z]*)(-srgb)?(-webgl)?$/;\nconst COLOR_FORMAT_PREFIXES = ['rgb', 'rgba', 'bgra'];\nconst DEPTH_FORMAT_PREFIXES = ['depth', 'stencil'];\n// biome-ignore format: preserve layout\nconst COMPRESSED_TEXTURE_FORMAT_PREFIXES = [\n 'bc1', 'bc2', 'bc3', 'bc4', 'bc5', 'bc6', 'bc7', 'etc1', 'etc2', 'eac', 'atc', 'astc', 'pvrtc'\n];\n\n// HELPERS - MEMORY LAYOUT\n\n/** Options to calculate a texture layout */\nexport type TextureMemoryLayoutOptions = {\n /** Number of bytes per pixel */\n format: TextureFormat;\n /** Width of the texture in pixels */\n width: number;\n /** Height of the texture in pixels */\n height: number;\n /** Number of images in the texture */\n depth: number;\n /** Alignment of each row */\n byteAlignment: number;\n};\n\n/** Class that helps applications work with texture formats */\nexport class TextureFormatDecoder {\n /** Checks if a texture format is color */\n isColor(format: TextureFormat): format is TextureFormatColor {\n return COLOR_FORMAT_PREFIXES.some(prefix => format.startsWith(prefix));\n }\n\n /** Checks if a texture format is depth or stencil */\n isDepthStencil(format: TextureFormat): format is TextureFormatDepthStencil {\n return DEPTH_FORMAT_PREFIXES.some(prefix => format.startsWith(prefix));\n }\n\n /** Checks if a texture format is compressed */\n isCompressed(format: TextureFormat): format is TextureFormatCompressed {\n return COMPRESSED_TEXTURE_FORMAT_PREFIXES.some(prefix => format.startsWith(prefix));\n }\n\n /** Returns information about a texture format, e.g. attachment type, components, byte length and flags (integer, signed, normalized) */\n getInfo(format: TextureFormat): TextureFormatInfo {\n return getTextureFormatInfo(format);\n }\n\n /** \"static\" capabilities of a texture format. @note Needs to be adjusted against current device */\n getCapabilities(format: TextureFormat): TextureFormatCapabilities {\n return getTextureFormatCapabilities(format);\n }\n\n /** Computes the memory layout for a texture, in particular including row byte alignment */\n computeMemoryLayout(opts: TextureMemoryLayoutOptions): TextureMemoryLayout {\n return computeTextureMemoryLayout(opts);\n }\n}\n\n/** Decoder for luma.gl texture types */\nexport const textureFormatDecoder = new TextureFormatDecoder();\n\n// HELPERS - MEMORY LAYOUT\n\n/** Get the memory layout of a texture */\nfunction computeTextureMemoryLayout({\n format,\n width,\n height,\n depth,\n byteAlignment\n}: TextureMemoryLayoutOptions): TextureMemoryLayout {\n const formatInfo = textureFormatDecoder.getInfo(format);\n const {\n bytesPerPixel,\n bytesPerBlock = bytesPerPixel,\n blockWidth = 1,\n blockHeight = 1,\n compressed = false\n } = formatInfo;\n const blockColumns = compressed ? Math.ceil(width / blockWidth) : width;\n const blockRows = compressed ? Math.ceil(height / blockHeight) : height;\n // byteAlignment comes from the backend/call site. WebGPU buffer copies use 256, queue.writeTexture uses 1.\n const unpaddedBytesPerRow = blockColumns * bytesPerBlock;\n const bytesPerRow = Math.ceil(unpaddedBytesPerRow / byteAlignment) * byteAlignment;\n const rowsPerImage = blockRows;\n const byteLength = bytesPerRow * rowsPerImage * depth;\n\n return {\n bytesPerPixel,\n bytesPerRow,\n rowsPerImage,\n depthOrArrayLayers: depth,\n bytesPerImage: bytesPerRow * rowsPerImage,\n byteLength\n };\n}\n\n// HELPERS - CAPABILITIES\n\nfunction getTextureFormatCapabilities(format: TextureFormat): TextureFormatCapabilities {\n const info = getTextureFormatDefinition(format);\n\n const formatCapabilities: Required<TextureFormatCapabilities> = {\n format,\n create: info.f ?? true,\n render: info.render ?? true,\n filter: info.filter ?? true,\n blend: info.blend ?? true,\n store: info.store ?? true\n };\n\n const formatInfo = getTextureFormatInfo(format);\n const isDepthStencil = format.startsWith('depth') || format.startsWith('stencil');\n const isSigned = formatInfo?.signed;\n const isInteger = formatInfo?.integer;\n const isWebGLSpecific = formatInfo?.webgl;\n const isCompressed = Boolean(formatInfo?.compressed);\n\n // Only uncompressed color formats can be used as color-renderable attachments.\n formatCapabilities.render &&= !isDepthStencil && !isCompressed;\n // signed and integer formats are not filterable\n formatCapabilities.filter &&= !isDepthStencil && !isSigned && !isInteger && !isWebGLSpecific;\n\n return formatCapabilities;\n}\n\n// HELPER - FORMAT INFO\n\n/**\n * Decodes a texture format, returning e.g. attatchment type, components, byte length and flags (integer, signed, normalized)\n */\nexport function getTextureFormatInfo(format: TextureFormat): TextureFormatInfo {\n let formatInfo: TextureFormatInfo = getTextureFormatInfoUsingTable(format);\n\n if (textureFormatDecoder.isCompressed(format)) {\n formatInfo.channels = 'rgb';\n formatInfo.components = 3;\n formatInfo.bytesPerPixel = 1;\n formatInfo.srgb = false;\n formatInfo.compressed = true;\n formatInfo.bytesPerBlock = getCompressedTextureBlockByteLength(format);\n\n const blockSize = getCompressedTextureBlockSize(format);\n if (blockSize) {\n formatInfo.blockWidth = blockSize.blockWidth;\n formatInfo.blockHeight = blockSize.blockHeight;\n }\n }\n\n // Fill in missing information that can be derived from the format string\n const matches = !formatInfo.packed ? RGB_FORMAT_REGEX.exec(format as string) : null;\n if (matches) {\n const [, channels, length, type, srgb, suffix] = matches;\n const dataType = `${type}${length}` as NormalizedDataType;\n const decodedType = dataTypeDecoder.getDataTypeInfo(dataType);\n const bits = decodedType.byteLength * 8;\n const components = (channels?.length ?? 1) as 1 | 2 | 3 | 4;\n const bitsPerChannel: [number, number, number, number] = [\n bits,\n components >= 2 ? bits : 0,\n components >= 3 ? bits : 0,\n components >= 4 ? bits : 0\n ];\n\n formatInfo = {\n format,\n attachment: formatInfo.attachment,\n dataType: decodedType.signedType,\n components,\n channels: channels as 'r' | 'rg' | 'rgb' | 'rgba',\n integer: decodedType.integer,\n signed: decodedType.signed,\n normalized: decodedType.normalized,\n bitsPerChannel,\n bytesPerPixel: decodedType.byteLength * components,\n packed: formatInfo.packed,\n srgb: formatInfo.srgb\n };\n\n if (suffix === '-webgl') {\n formatInfo.webgl = true;\n }\n // dataType - overwritten by decodedType\n if (srgb === '-srgb') {\n formatInfo.srgb = true;\n }\n }\n\n if (format.endsWith('-webgl')) {\n formatInfo.webgl = true;\n }\n if (format.endsWith('-srgb')) {\n formatInfo.srgb = true;\n }\n\n return formatInfo;\n}\n\n/** Decode texture format info from the table */\nfunction getTextureFormatInfoUsingTable(format: TextureFormat): TextureFormatInfo {\n const info = getTextureFormatDefinition(format);\n\n const bytesPerPixel = info.bytesPerPixel || 1;\n const bitsPerChannel = info.bitsPerChannel || [8, 8, 8, 8];\n delete info.bitsPerChannel;\n delete info.bytesPerPixel;\n delete info.f;\n delete info.render;\n delete info.filter;\n delete info.blend;\n delete info.store;\n\n const formatInfo: TextureFormatInfo = {\n ...info,\n format,\n attachment: info.attachment || 'color',\n channels: info.channels || 'r',\n components: (info.components || info.channels?.length || 1) as 1 | 2 | 3 | 4,\n bytesPerPixel,\n bitsPerChannel,\n dataType: info.dataType || 'uint8',\n srgb: info.srgb ?? false,\n packed: info.packed ?? false,\n webgl: info.webgl ?? false,\n integer: info.integer ?? false,\n signed: info.signed ?? false,\n normalized: info.normalized ?? false,\n compressed: info.compressed ?? false\n };\n\n return formatInfo;\n}\n\n/** Parses ASTC block widths from format string */\nfunction getCompressedTextureBlockSize(\n format: TextureFormatCompressed\n): {blockWidth: number; blockHeight: number} | null {\n const REGEX = /.*-(\\d+)x(\\d+)-.*/;\n const matches = REGEX.exec(format as string);\n if (matches) {\n const [, blockWidth, blockHeight] = matches;\n return {blockWidth: Number(blockWidth), blockHeight: Number(blockHeight)};\n }\n\n if (\n format.startsWith('bc') ||\n format.startsWith('etc1') ||\n format.startsWith('etc2') ||\n format.startsWith('eac') ||\n format.startsWith('atc')\n ) {\n return {blockWidth: 4, blockHeight: 4};\n }\n\n if (format.startsWith('pvrtc-rgb4') || format.startsWith('pvrtc-rgba4')) {\n return {blockWidth: 4, blockHeight: 4};\n }\n\n if (format.startsWith('pvrtc-rgb2') || format.startsWith('pvrtc-rgba2')) {\n return {blockWidth: 8, blockHeight: 4};\n }\n\n return null;\n}\n\nfunction getCompressedTextureBlockByteLength(format: TextureFormatCompressed): number {\n if (\n format.startsWith('bc1') ||\n format.startsWith('bc4') ||\n format.startsWith('etc1') ||\n format.startsWith('etc2-rgb8') ||\n format.startsWith('etc2-rgb8a1') ||\n format.startsWith('eac-r11') ||\n format === 'atc-rgb-unorm-webgl'\n ) {\n return 8;\n }\n\n if (\n format.startsWith('bc2') ||\n format.startsWith('bc3') ||\n format.startsWith('bc5') ||\n format.startsWith('bc6h') ||\n format.startsWith('bc7') ||\n format.startsWith('etc2-rgba8') ||\n format.startsWith('eac-rg11') ||\n format.startsWith('astc') ||\n format === 'atc-rgba-unorm-webgl' ||\n format === 'atc-rgbai-unorm-webgl'\n ) {\n return 16;\n }\n\n if (format.startsWith('pvrtc')) {\n return 8;\n }\n\n return 16;\n}\n\n/*\n'r8unorm':\t{s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n'r8snorm':\t{s: \"float\"}, // \t\t\u2713\t\t},\n'r8uint':\t{s: \"uint\"}, // \t\u2713\t\u2713\t\t},\n'r8sint':\t{s: \"sint\"}, // \t\u2713\t\u2713\t\t},\n'rg8unorm':\t{s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n'rg8snorm':\t{s: \"float\"}, // \t\t\u2713\t\t},\n'rg8uint':\t{s: \"uint\"}, // \t\u2713\t\u2713\t\t},\n'rg8sint':\t{s: \"sint\"}, // \t\u2713\t\u2713\t\t},\n'rgba8unorm':\t{s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t\u2713},\n'rgba8unorm-srgb': {s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n'rgba8snorm':\t{s: \"float\"}, // \t\t\u2713\t\t\u2713},\n'rgba8uint':\t{s: \"uint\"}, // \t\u2713\t\u2713\t\t\u2713},\n'rgba8sint':\t{s: \"sint\"}, // \t\u2713\t\u2713\t\t\u2713},\n'bgra8unorm':\t{s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n'bgra8unorm-srgb': {s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n// 16-bit per component\t\t\t\t\t\n'r16uint': {s: \"uint\"}, // \t\u2713\t\u2713\t\t},\n'r16sint': {s: \"sint\"}, // \t\u2713\t\u2713\t\t},\n'r16float': {s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n'rg16uint': {s: \"uint\"}, // \t\u2713\t\u2713\t\t},\n'rg16sint': {s: \"sint\"}, // \t\u2713\t\u2713\t\t},\n'rg16float': {s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t},\n'rgba16uint': {s: \"uint\"}, // \t\u2713\t\u2713\t\t\u2713},\n'rgba16sint': {s: \"sint\"}, // \t\u2713\t\u2713\t\t\u2713},\n'rgba16float': {s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t\u2713},\n// 32-bit per component\t\t\t\t\t\n'r32uint': {s: \"uint\"}, // \t\u2713\t\t\t\u2713},\n'r32sint': {s: \"sint\"}, // \t\u2713\t\t\t\u2713},\n'r32float': {\"unfilterable-float\"\t\u2713\t\u2713\t\t\u2713},\n'rg32uint': {s: \"uint\"}, // \t\u2713\t\t\t\u2713},\n'rg32sint': {s: \"sint\"}, // \t\u2713\t\t\t\u2713},\n'rg32float': {\"unfilterable-float\"\t\u2713\t\t\t\u2713},\n'rgba32uint': {s: \"uint\"}, // \t\u2713\t\t\t\u2713},\n'rgba32sint': {s: \"sint\"}, // \t\u2713\t\t\t\u2713},\n'rgba32float': {\"unfilterable-float\"\t\u2713\t\t\t\u2713},\n// mixed component width\t\t\t\t\t\n'rgb10a2unorm': {s: \"float\"}, // \t\u2713\t\u2713\t\u2713\t}\n'rg11b10ufloat': {s: \"float\"}, // \t\t\u2713\t\t}\n// Format\tBytes per texel\tAspect\tGPUTextureSampleType\tValid image copy source\tValid image copy destination\n'stencil8': {1 \u2212 4\tstencil\t\"uint\"\t\u2713}\n'depth16unorm': {2\tdepth\t\"depth\"\t\u2713}\n'depth24plus': {4\tdepth\t\"depth\"\t\u2717}\n'depth24plus': {stencil8\t4 \u2212 8\tdepth\t\"depth\"\t\u2717}\n'stencil': {s: \"uint\"}, // \t\u2713}\n'depth32float': {4\tdepth\t\"depth\"\t\u2713\t\u2717}\n'depth24unorm': {stencil8\t4\tdepth\t\"depth\"\t\u2717}\n'stencil': {s: \"uint\"}, // \t\u2713}\n'depth32float': {stencil8}\n\n// Format\tBytes per block\tGPUTextureSampleType\tBlock Size\tFeature\n'rgb9e5ufloat': {c: 4, s: \"float\",\tbpp: 4/(1*1)},\n\n'bc1-rgba-unorm': {c: 4. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc1-rgba-unorm-srgb': {c: 4. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc2-rgba-unorm': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc2-rgba-unorm-srgb': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc3-rgba-unorm': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc3-rgba-unorm-srgb': {c: 4. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc4-r-unorm': {c: 1. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc4-r-snorm': {c: 1. s: \"float\", bpp: 8/(4 * 4) f: 'texture-compression-bc'},\n'bc5-rg-unorm': {c: 2. s: \"float\", bpp: 16/(4 * 4) f: 'texture-compression-bc'},\n'bc5-rg-snorm': { },\n'bc6h-rgb-ufloat': {\t16 },\n'bc6h-rgb-float': { },\n'bc7-rgba-unorm': {\t16 },\n'bc7-rgba-unorm-srgb': { },\n\n'etc2-rgb8unorm': {\t8\t\"float\"\t4 \u00D7 4\ttexture-compression-etc2 },\n'etc2-rgb8unorm-srgb': { },\n'etc2-rgb8a1unorm': {\t8 },\n'etc2-rgb8a1unorm-srgb': { },\n'etc2-rgba8unorm': {\t16 },\n'etc2-rgba8unorm-srgb': { },\n\n'eac-r11unorm': {\t8 },\n'eac-r11snorm': { },\n'eac-rg11unorm': {\t16 },\n'eac-rg11snorm': { },\n\n'astc-4x4-unorm': {\t16\t\"float\"\t4 \u00D7 4\ttexture-compression-astc },\n'astc-4x4-unorm-srgb': { },\n'astc-5x4-unorm': {\t16\t5 \u00D7 4 },\n'astc-5x4-unorm-srgb': { },\n'astc-5x5-unorm': {\t16\t5 \u00D7 5 },\n'astc-5x5-unorm-srgb': { },\n'astc-6x5-unorm': {\t16\t6 \u00D7 5 },\n'astc-6x5-unorm-srgb': { },\n'astc-6x6-unorm': {\t16\t6 \u00D7 6 },\n'astc-6x6-unorm-srgb': { },\n'astc-8x5-unorm': {\t16\t8 \u00D7 5 },\n'astc-8x5-unorm-srgb': { },\n'astc-8x6-unorm': {\t16\t8 \u00D7 6 },\n'astc-8x6-unorm-srgb': { },\n'astc-8x8-unorm': {\t16\t8 \u00D7 8 },\n'astc-8x8-unorm-srgb': { },\n'astc-10x5-unorm': {\t16\t10 \u00D7 5 },\n'astc-10x5-unorm-srgb': { },\n'astc-10x6-unorm': {\t16\t10 \u00D7 6 },\n'astc-10x6-unorm-srgb': { },\n'astc-10x8-unorm': {\t16\t10 \u00D7 8 },\n'astc-10x8-unorm-srgb': { },\n'astc-10x10-unorm': {\t16\t10 \u00D7 10 },\n'astc-10x10-unorm-srgb': { },\n'astc-12x10-unorm': {\t16\t12 \u00D7 10 },\n'astc-12x10-unorm-srgb': { },\n'astc-12x12-unorm': {\t16 },\n*/\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/**\n * Built-in data types that can be used to initialize textures\n * @note ImageData can be used for contiguous 8 bit data via Uint8ClampedArray\n */\nexport type ExternalImage =\n | ImageBitmap\n | ImageData\n | HTMLImageElement\n | HTMLVideoElement\n | VideoFrame\n | HTMLCanvasElement\n | OffscreenCanvas;\n\n/** Check if data is an external image */\nexport function isExternalImage(data: unknown): data is ExternalImage {\n return (\n (typeof ImageData !== 'undefined' && data instanceof ImageData) ||\n (typeof ImageBitmap !== 'undefined' && data instanceof ImageBitmap) ||\n (typeof HTMLImageElement !== 'undefined' && data instanceof HTMLImageElement) ||\n (typeof HTMLVideoElement !== 'undefined' && data instanceof HTMLVideoElement) ||\n (typeof VideoFrame !== 'undefined' && data instanceof VideoFrame) ||\n (typeof HTMLCanvasElement !== 'undefined' && data instanceof HTMLCanvasElement) ||\n (typeof OffscreenCanvas !== 'undefined' && data instanceof OffscreenCanvas)\n );\n}\n\n/** Determine size (width and height) of provided image data */\nexport function getExternalImageSize(data: ExternalImage): {width: number; height: number} {\n if (\n (typeof ImageData !== 'undefined' && data instanceof ImageData) ||\n (typeof ImageBitmap !== 'undefined' && data instanceof ImageBitmap) ||\n (typeof HTMLCanvasElement !== 'undefined' && data instanceof HTMLCanvasElement) ||\n (typeof OffscreenCanvas !== 'undefined' && data instanceof OffscreenCanvas)\n ) {\n return {width: data.width, height: data.height};\n }\n if (typeof HTMLImageElement !== 'undefined' && data instanceof HTMLImageElement) {\n return {width: data.naturalWidth, height: data.naturalHeight};\n }\n if (typeof HTMLVideoElement !== 'undefined' && data instanceof HTMLVideoElement) {\n return {width: data.videoWidth, height: data.videoHeight};\n }\n if (typeof VideoFrame !== 'undefined' && data instanceof VideoFrame) {\n // TODO: is this the right choice for width and height?\n return {width: data.displayWidth, height: data.displayHeight};\n }\n throw new Error('Unknown image type');\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {StatsManager, lumaStats} from '../utils/stats-manager';\nimport {log} from '../utils/log';\nimport {uid} from '../utils/uid';\nimport type {VertexFormat, VertexFormatInfo} from '../shadertypes/vertex-types/vertex-formats';\nimport type {\n TextureFormat,\n TextureFormatInfo,\n CompressedTextureFormat\n} from '../shadertypes/texture-types/texture-formats';\nimport type {CanvasContext, CanvasContextProps} from './canvas-context';\nimport type {PresentationContext, PresentationContextProps} from './presentation-context';\nimport type {BufferProps} from './resources/buffer';\nimport {Buffer} from './resources/buffer';\nimport type {RenderPipeline, RenderPipelineProps} from './resources/render-pipeline';\nimport type {SharedRenderPipeline} from './resources/shared-render-pipeline';\nimport type {ComputePipeline, ComputePipelineProps} from './resources/compute-pipeline';\nimport type {Sampler, SamplerProps} from './resources/sampler';\nimport type {Shader, ShaderProps} from './resources/shader';\nimport type {Texture, TextureProps} from './resources/texture';\nimport type {ExternalTexture, ExternalTextureProps} from './resources/external-texture';\nimport type {Framebuffer, FramebufferProps} from './resources/framebuffer';\nimport type {RenderPass, RenderPassProps} from './resources/render-pass';\nimport type {ComputePass, ComputePassProps} from './resources/compute-pass';\nimport type {CommandEncoder, CommandEncoderProps} from './resources/command-encoder';\nimport type {CommandBuffer} from './resources/command-buffer';\nimport type {VertexArray, VertexArrayProps} from './resources/vertex-array';\nimport type {TransformFeedback, TransformFeedbackProps} from './resources/transform-feedback';\nimport type {QuerySet, QuerySetProps} from './resources/query-set';\nimport type {Fence} from './resources/fence';\nimport type {Bindings, ComputeShaderLayout, ShaderLayout} from './types/shader-layout';\n\nimport {vertexFormatDecoder} from '../shadertypes/vertex-types/vertex-format-decoder';\nimport {textureFormatDecoder} from '../shadertypes/texture-types/texture-format-decoder';\nimport type {ExternalImage} from '../shadertypes/image-types/image-types';\nimport {isExternalImage, getExternalImageSize} from '../shadertypes/image-types/image-types';\nimport {getTextureFormatTable} from '../shadertypes/texture-types/texture-format-table';\n\n/**\n * Identifies the GPU vendor and driver.\n * @note Chrome WebGPU does not provide much information, though more can be enabled with\n * @see https://developer.chrome.com/blog/new-in-webgpu-120#adapter_information_updates\n * chrome://flags/#enable-webgpu-developer-features\n */\nexport type DeviceInfo = {\n /** Type of device */\n type: 'webgl' | 'webgpu' | 'null' | 'unknown';\n /** Vendor (name of GPU vendor, Apple, nVidia etc */\n vendor: string;\n /** Renderer (usually driver name) */\n renderer: string;\n /** version of driver */\n version: string;\n /** family of GPU */\n gpu: 'nvidia' | 'amd' | 'intel' | 'apple' | 'software' | 'unknown';\n /** Type of GPU () */\n gpuType: 'discrete' | 'integrated' | 'cpu' | 'unknown';\n /** GPU architecture */\n gpuArchitecture?: string; // 'common-3' on Apple\n /** GPU driver backend. Can sometimes be sniffed */\n gpuBackend?: 'opengl' | 'opengles' | 'metal' | 'd3d11' | 'd3d12' | 'vulkan' | 'unknown';\n /** If this is a fallback adapter */\n fallback?: boolean;\n /** Shader language supported by device.createShader() */\n shadingLanguage: 'wgsl' | 'glsl';\n /** Highest supported shader language version: GLSL 3.00 = 300, WGSL 1.00 = 100 */\n shadingLanguageVersion: number;\n};\n\n/** Limits for a device (max supported sizes of resources, max number of bindings etc) */\nexport abstract class DeviceLimits {\n /** max number of TextureDimension1D */\n abstract maxTextureDimension1D: number;\n /** max number of TextureDimension2D */\n abstract maxTextureDimension2D: number;\n /** max number of TextureDimension3D */\n abstract maxTextureDimension3D: number;\n /** max number of TextureArrayLayers */\n abstract maxTextureArrayLayers: number;\n /** max number of BindGroups */\n abstract maxBindGroups: number;\n /** max number of DynamicUniformBuffers per PipelineLayout */\n abstract maxDynamicUniformBuffersPerPipelineLayout: number;\n /** max number of DynamicStorageBuffers per PipelineLayout */\n abstract maxDynamicStorageBuffersPerPipelineLayout: number;\n /** max number of SampledTextures per ShaderStage */\n abstract maxSampledTexturesPerShaderStage: number;\n /** max number of Samplers per ShaderStage */\n abstract maxSamplersPerShaderStage: number;\n /** max number of StorageBuffers per ShaderStage */\n abstract maxStorageBuffersPerShaderStage: number;\n /** max number of StorageTextures per ShaderStage */\n abstract maxStorageTexturesPerShaderStage: number;\n /** max number of UniformBuffers per ShaderStage */\n abstract maxUniformBuffersPerShaderStage: number;\n /** max number of UniformBufferBindingSize */\n abstract maxUniformBufferBindingSize: number;\n /** max number of StorageBufferBindingSize */\n abstract maxStorageBufferBindingSize: number;\n /** min UniformBufferOffsetAlignment */\n abstract minUniformBufferOffsetAlignment: number;\n /** min StorageBufferOffsetAlignment */\n abstract minStorageBufferOffsetAlignment: number;\n /** max number of VertexBuffers */\n abstract maxVertexBuffers: number;\n /** max number of VertexAttributes */\n abstract maxVertexAttributes: number;\n /** max number of VertexBufferArrayStride */\n abstract maxVertexBufferArrayStride: number;\n /** max number of InterStageShaderComponents */\n abstract maxInterStageShaderVariables: number;\n /** max number of ComputeWorkgroupStorageSize */\n abstract maxComputeWorkgroupStorageSize: number;\n /** max number of ComputeInvocations per Workgroup */\n abstract maxComputeInvocationsPerWorkgroup: number;\n /** max ComputeWorkgroupSizeX */\n abstract maxComputeWorkgroupSizeX: number;\n /** max ComputeWorkgroupSizeY */\n abstract maxComputeWorkgroupSizeY: number;\n /** max ComputeWorkgroupSizeZ */\n abstract maxComputeWorkgroupSizeZ: number;\n /** max ComputeWorkgroupsPerDimension */\n abstract maxComputeWorkgroupsPerDimension: number;\n}\n\nfunction formatErrorLogArguments(context: unknown, args: unknown[]): unknown[] {\n const formattedContext = formatErrorLogValue(context);\n const formattedArgs = args.map(formatErrorLogValue).filter(arg => arg !== undefined);\n return [formattedContext, ...formattedArgs].filter(arg => arg !== undefined);\n}\n\nfunction formatErrorLogValue(value: unknown): unknown {\n if (value === undefined) {\n return undefined;\n }\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return value;\n }\n if (value instanceof Error) {\n return value.message;\n }\n if (Array.isArray(value)) {\n return value.map(formatErrorLogValue);\n }\n if (typeof value === 'object') {\n if (hasCustomToString(value)) {\n const stringValue = String(value);\n if (stringValue !== '[object Object]') {\n return stringValue;\n }\n }\n\n if (looksLikeGPUCompilationMessage(value)) {\n return formatGPUCompilationMessage(value);\n }\n\n return value.constructor?.name || 'Object';\n }\n\n return String(value);\n}\n\nfunction hasCustomToString(value: object): boolean {\n return (\n 'toString' in value &&\n typeof value.toString === 'function' &&\n value.toString !== Object.prototype.toString\n );\n}\n\nfunction looksLikeGPUCompilationMessage(value: object): value is {\n message?: unknown;\n type?: unknown;\n lineNum?: unknown;\n linePos?: unknown;\n} {\n return 'message' in value && 'type' in value;\n}\n\nfunction formatGPUCompilationMessage(value: {\n message?: unknown;\n type?: unknown;\n lineNum?: unknown;\n linePos?: unknown;\n}): string {\n const type = typeof value.type === 'string' ? value.type : 'message';\n const message = typeof value.message === 'string' ? value.message : '';\n const lineNum = typeof value.lineNum === 'number' ? value.lineNum : null;\n const linePos = typeof value.linePos === 'number' ? value.linePos : null;\n const location =\n lineNum !== null && linePos !== null\n ? ` @ ${lineNum}:${linePos}`\n : lineNum !== null\n ? ` @ ${lineNum}`\n : '';\n return `${type}${location}: ${message}`.trim();\n}\n\n/** Set-like class for features (lets apps check for WebGL / WebGPU extensions) */\nexport class DeviceFeatures {\n protected features: Set<DeviceFeature>;\n protected disabledFeatures?: Partial<Record<DeviceFeature, boolean>>;\n\n constructor(\n features: DeviceFeature[] = [],\n disabledFeatures: Partial<Record<DeviceFeature, boolean>>\n ) {\n this.features = new Set<DeviceFeature>(features);\n this.disabledFeatures = disabledFeatures || {};\n }\n\n *[Symbol.iterator](): IterableIterator<DeviceFeature> {\n yield* this.features;\n }\n\n has(feature: DeviceFeature): boolean {\n return !this.disabledFeatures?.[feature] && this.features.has(feature);\n }\n}\n\n/** Device feature names */\nexport type DeviceFeature =\n | WebGPUDeviceFeature\n | WebGLDeviceFeature\n | WebGLCompressedTextureFeatures;\n// | ChromeExperimentalFeatures\n\n/** Chrome-specific extensions. Expected to eventually become standard features. */\n// export type ChromeExperimentalFeatures = ;\n\nexport type WebGPUDeviceFeature =\n | 'depth-clip-control'\n | 'depth32float-stencil8'\n | 'texture-compression-bc'\n | 'texture-compression-bc-sliced-3d'\n | 'texture-compression-etc2'\n | 'texture-compression-astc'\n | 'texture-compression-astc-sliced-3d'\n | 'timestamp-query'\n | 'indirect-first-instance'\n | 'shader-f16'\n | 'rg11b10ufloat-renderable' // Is the rg11b10ufloat texture format renderable?\n | 'bgra8unorm-storage' // Can the bgra8unorm texture format be used in storage buffers?\n | 'float32-filterable' // Is the float32 format filterable?\n | 'float32-blendable' // Is the float32 format blendable?\n | 'clip-distances'\n | 'dual-source-blending'\n | 'subgroups';\n// | 'depth-clamping' // removed from the WebGPU spec...\n// | 'pipeline-statistics-query' // removed from the WebGPU spec...\n\nexport type WebGLDeviceFeature =\n // webgl extension features\n | 'compilation-status-async-webgl' // Non-blocking shader compile/link status query available\n | 'provoking-vertex-webgl' // parameters.provokingVertex\n | 'polygon-mode-webgl' // parameters.polygonMode and parameters.polygonOffsetLine\n\n // GLSL extension features\n | 'shader-noperspective-interpolation-webgl' // Vertex outputs & fragment inputs can have a `noperspective` interpolation qualifier.\n | 'shader-conservative-depth-webgl' // GLSL `gl_FragDepth` qualifiers `depth_unchanged` etc can enable early depth test\n | 'shader-clip-cull-distance-webgl' // Makes gl_ClipDistance and gl_CullDistance available in shaders\n\n // texture rendering\n | 'float32-renderable-webgl'\n | 'float16-renderable-webgl'\n | 'rgb9e5ufloat-renderable-webgl'\n | 'snorm8-renderable-webgl'\n | 'norm16-webgl'\n | 'norm16-renderable-webgl'\n | 'snorm16-renderable-webgl'\n\n // texture filtering\n | 'float16-filterable-webgl'\n | 'texture-filterable-anisotropic-webgl'\n\n // texture storage bindings\n | 'bgra8unorm-storage'\n\n // texture blending\n | 'texture-blend-float-webgl';\n\ntype WebGLCompressedTextureFeatures =\n | 'texture-compression-bc5-webgl'\n | 'texture-compression-bc7-webgl'\n | 'texture-compression-etc1-webgl'\n | 'texture-compression-pvrtc-webgl'\n | 'texture-compression-atc-webgl';\n\n/** Texture format capabilities that have been checked against a specific device */\nexport type DeviceTextureFormatCapabilities = {\n format: TextureFormat;\n /** Can the format be created and sampled?*/\n create: boolean;\n /** Is the format renderable. */\n render: boolean;\n /** Is the format filterable. */\n filter: boolean;\n /** Is the format blendable. */\n blend: boolean;\n /** Is the format storeable. */\n store: boolean;\n};\n\n/** Device properties */\nexport type DeviceProps = {\n /** string id for debugging. Stored on the object, used in logging and set on underlying GPU objects when feasible. */\n id?: string;\n /** Properties for creating a default canvas context */\n createCanvasContext?: CanvasContextProps | true;\n /** Control which type of GPU is preferred on systems with both integrated and discrete GPU. Defaults to \"high-performance\" / discrete GPU. */\n powerPreference?: 'default' | 'high-performance' | 'low-power';\n /** Hints that device creation should fail if no hardware GPU is available (if the system performance is \"low\"). */\n failIfMajorPerformanceCaveat?: boolean;\n\n /** WebGL specific: Properties passed through to WebGL2RenderingContext creation: `canvas.getContext('webgl2', props.webgl)` */\n webgl?: WebGLContextProps;\n\n // CALLBACKS\n\n /** Error handler. If it returns a probe logger style function, it will be called at the site of the error to optimize console error links. */\n onError?: (error: Error, context?: unknown) => unknown;\n /** Called when the size of a CanvasContext's canvas changes */\n onResize?: (\n ctx: CanvasContext | PresentationContext,\n info: {oldPixelSize: [number, number]}\n ) => unknown;\n /** Called when the absolute position of a CanvasContext's canvas changes. Must set `CanvasContextProps.trackPosition: true` */\n onPositionChange?: (\n ctx: CanvasContext | PresentationContext,\n info: {oldPosition: [number, number]}\n ) => unknown;\n /** Called when the visibility of a CanvasContext's canvas changes */\n onVisibilityChange?: (ctx: CanvasContext | PresentationContext) => unknown;\n /** Called when the device pixel ratio of a CanvasContext's canvas changes */\n onDevicePixelRatioChange?: (\n ctx: CanvasContext | PresentationContext,\n info: {oldRatio: number}\n ) => unknown;\n\n // DEBUG SETTINGS\n\n /** Turn on implementation defined checks that slow down execution but help break where errors occur */\n debug?: boolean;\n /** Enable GPU timestamp collection without enabling all debug validation paths. */\n debugGPUTime?: boolean;\n /** Show shader source in browser? The default is `'error'`, meaning that logs are shown when shader compilation has errors */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n /** Renders a small version of updated Framebuffers into the primary canvas context. Can be set in console luma.log.set('debug-framebuffers', true) */\n debugFramebuffers?: boolean;\n /** Traces resource caching, reuse, and destroys in the PipelineFactory */\n debugFactories?: boolean;\n /** WebGL specific - Trace WebGL calls (instruments WebGL2RenderingContext at the expense of performance). Can be set in console luma.log.set('debug-webgl', true) */\n debugWebGL?: boolean;\n /** WebGL specific - Initialize the SpectorJS WebGL debugger. Can be set in console luma.log.set('debug-spectorjs', true) */\n debugSpectorJS?: boolean;\n /** WebGL specific - SpectorJS URL. Override if CDN is down or different SpectorJS version is desired. */\n debugSpectorJSUrl?: string;\n\n // EXPERIMENTAL SETTINGS - subject to change\n\n /** adapter.create() returns the existing Device if the provided canvas' WebGL context is already associated with a Device. */\n _reuseDevices?: boolean;\n /** WebGPU specific - Request a Device with the highest limits supported by platform. On WebGPU devices can be created with minimal limits. */\n _requestMaxLimits?: boolean;\n /** Disable specific features */\n _disabledFeatures?: Partial<Record<DeviceFeature, boolean>>;\n /** WebGL specific - Initialize all features on startup */\n _initializeFeatures?: boolean;\n /** Enable shader caching (via ShaderFactory) */\n _cacheShaders?: boolean;\n /**\n * Destroy cached shaders when they become unused.\n * Defaults to `false` so repeated create/destroy cycles can still reuse cached shaders.\n * Enable this if the application creates very large numbers of distinct shaders and needs cache eviction.\n */\n _destroyShaders?: boolean;\n /** Enable pipeline caching (via PipelineFactory) */\n _cachePipelines?: boolean;\n /** Enable sharing of backend render-pipeline implementations when caching is enabled. Currently used by WebGL. */\n _sharePipelines?: boolean;\n /**\n * Destroy cached pipelines when they become unused.\n * Defaults to `false` so repeated create/destroy cycles can still reuse cached pipelines.\n * Enable this if the application creates very large numbers of distinct pipelines and needs cache eviction.\n */\n _destroyPipelines?: boolean;\n\n /** @deprecated Internal, Do not use directly! Use `luma.attachDevice()` to attach to pre-created contexts/devices. */\n _handle?: unknown; // WebGL2RenderingContext | GPUDevice | null;\n};\n\ntype DeviceFactories = {\n bindGroupFactory?: unknown;\n};\n\n/** WebGL independent copy of WebGLContextAttributes */\ntype WebGLContextProps = {\n /** indicates if the canvas contains an alpha buffer. */\n alpha?: boolean;\n /** hints the user agent to reduce the latency by desynchronizing the canvas paint cycle from the event loop */\n desynchronized?: boolean;\n /** indicates whether or not to perform anti-aliasing. */\n antialias?: boolean;\n /** indicates that the render target has a stencil buffer of at least `8` bits. */\n stencil?: boolean;\n /** indicates that the drawing buffer has a depth buffer of at least 16 bits. */\n depth?: boolean;\n /** indicates if a context will be created if the system performance is low or if no hardware GPU is available. */\n failIfMajorPerformanceCaveat?: boolean;\n /** Selects GPU */\n powerPreference?: 'default' | 'high-performance' | 'low-power';\n /** page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. */\n premultipliedAlpha?: boolean;\n /** buffers will not be cleared and will preserve their values until cleared or overwritten by the author. */\n preserveDrawingBuffer?: boolean;\n};\n\n/**\n * Create and attach devices for a specific backend. Currently static methods on each device\n */\nexport interface DeviceFactory {\n // new (props: DeviceProps): Device; Constructor isn't used\n type: string;\n isSupported(): boolean;\n create(props: DeviceProps): Promise<Device>;\n attach?(handle: unknown): Device;\n}\n\n/**\n * WebGPU Device/WebGL context abstraction\n */\nexport abstract class Device {\n static defaultProps: Required<DeviceProps> = {\n id: null!,\n powerPreference: 'high-performance',\n failIfMajorPerformanceCaveat: false,\n createCanvasContext: undefined!,\n // WebGL specific\n webgl: {},\n\n // Callbacks\n // eslint-disable-next-line handle-callback-err\n onError: (error: Error, context: unknown) => {},\n onResize: (context: CanvasContext, info: {oldPixelSize: [number, number]}) => {\n const [width, height] = context.getDevicePixelSize();\n log.log(1, `${context} resized => ${width}x${height}px`)();\n },\n onPositionChange: (context: CanvasContext, info: {oldPosition: [number, number]}) => {\n const [left, top] = context.getPosition();\n log.log(1, `${context} repositioned => ${left},${top}`)();\n },\n onVisibilityChange: (context: CanvasContext) =>\n log.log(1, `${context} Visibility changed ${context.isVisible}`)(),\n onDevicePixelRatioChange: (context: CanvasContext, info: {oldRatio: number}) =>\n log.log(1, `${context} DPR changed ${info.oldRatio} => ${context.devicePixelRatio}`)(),\n\n // Debug flags\n debug: getDefaultDebugValue(),\n debugGPUTime: false,\n debugShaders: log.get('debug-shaders') || undefined!,\n debugFramebuffers: Boolean(log.get('debug-framebuffers')),\n debugFactories: Boolean(log.get('debug-factories')),\n debugWebGL: Boolean(log.get('debug-webgl')),\n debugSpectorJS: undefined!, // Note: log setting is queried by the spector.js code\n debugSpectorJSUrl: undefined!,\n\n // Experimental\n _reuseDevices: false,\n _requestMaxLimits: true,\n _cacheShaders: true,\n _destroyShaders: false,\n _cachePipelines: true,\n _sharePipelines: true,\n _destroyPipelines: false,\n // TODO - Change these after confirming things work as expected\n _initializeFeatures: true,\n _disabledFeatures: {\n 'compilation-status-async-webgl': true\n },\n\n // INTERNAL\n _handle: undefined!\n };\n\n get [Symbol.toStringTag](): string {\n return 'Device';\n }\n\n toString(): string {\n return `Device(${this.id})`;\n }\n\n /** id of this device, primarily for debugging */\n readonly id: string;\n /** type of this device */\n abstract readonly type: 'webgl' | 'webgpu' | 'null' | 'unknown';\n abstract readonly handle: unknown;\n abstract commandEncoder: CommandEncoder;\n\n /** A copy of the device props */\n readonly props: Required<DeviceProps>;\n /** Available for the application to store data on the device */\n userData: {[key: string]: unknown} = {};\n /** stats */\n readonly statsManager: StatsManager = lumaStats;\n /** Internal per-device factory storage */\n _factories: DeviceFactories = {};\n /** An abstract timestamp used for change tracking */\n timestamp: number = 0;\n\n /** True if this device has been reused during device creation (app has multiple references) */\n _reused: boolean = false;\n /** Used by other luma.gl modules to store data on the device */\n private _moduleData: Record<string, Record<string, unknown>> = {};\n\n // Capabilities\n\n /** Information about the device (vendor, versions etc) */\n abstract info: DeviceInfo;\n /** Optional capability discovery */\n abstract features: DeviceFeatures;\n /** WebGPU style device limits */\n abstract get limits(): DeviceLimits;\n\n // Texture helpers\n\n /** Optimal TextureFormat for displaying 8-bit depth, standard dynamic range content on this system. */\n abstract preferredColorFormat: 'rgba8unorm' | 'bgra8unorm';\n /** Default depth format used on this system */\n abstract preferredDepthFormat: 'depth16' | 'depth24plus' | 'depth32float';\n\n protected _textureCaps: Partial<Record<TextureFormat, DeviceTextureFormatCapabilities>> = {};\n /** Internal timestamp query set used when GPU timing collection is enabled for this device. */\n protected _debugGPUTimeQuery: QuerySet | null = null;\n\n constructor(props: DeviceProps) {\n this.props = {...Device.defaultProps, ...props};\n this.id = this.props.id || uid(this[Symbol.toStringTag].toLowerCase());\n }\n\n abstract destroy(): void;\n\n // TODO - just expose the shadertypes decoders?\n\n getVertexFormatInfo(format: VertexFormat): VertexFormatInfo {\n return vertexFormatDecoder.getVertexFormatInfo(format);\n }\n\n isVertexFormatSupported(format: VertexFormat): boolean {\n return true;\n }\n\n /** Returns information about a texture format, such as data type, channels, bits per channel, compression etc */\n getTextureFormatInfo(format: TextureFormat): TextureFormatInfo {\n return textureFormatDecoder.getInfo(format);\n }\n\n /** Determines what operations are supported on a texture format on this particular device (checks against supported device features) */\n getTextureFormatCapabilities(format: TextureFormat): DeviceTextureFormatCapabilities {\n let textureCaps = this._textureCaps[format];\n if (!textureCaps) {\n const capabilities = this._getDeviceTextureFormatCapabilities(format);\n textureCaps = this._getDeviceSpecificTextureFormatCapabilities(capabilities);\n this._textureCaps[format] = textureCaps;\n }\n return textureCaps;\n }\n\n /** Calculates the number of mip levels for a texture of width, height and in case of 3d textures only, depth */\n getMipLevelCount(width: number, height: number, depth3d: number = 1): number {\n const maxSize = Math.max(width, height, depth3d);\n return 1 + Math.floor(Math.log2(maxSize));\n }\n\n /** Check if data is an external image */\n isExternalImage(data: unknown): data is ExternalImage {\n return isExternalImage(data);\n }\n\n /** Get the size of an external image */\n getExternalImageSize(data: ExternalImage): {width: number; height: number} {\n return getExternalImageSize(data);\n }\n\n /** Check if device supports a specific texture format (creation and `nearest` sampling) */\n isTextureFormatSupported(format: TextureFormat): boolean {\n return this.getTextureFormatCapabilities(format).create;\n }\n\n /** Check if linear filtering (sampler interpolation) is supported for a specific texture format */\n isTextureFormatFilterable(format: TextureFormat): boolean {\n return this.getTextureFormatCapabilities(format).filter;\n }\n\n /** Check if device supports rendering to a framebuffer color attachment of a specific texture format */\n isTextureFormatRenderable(format: TextureFormat): boolean {\n return this.getTextureFormatCapabilities(format).render;\n }\n\n /** Check if a specific texture format is GPU compressed */\n isTextureFormatCompressed(format: TextureFormat): boolean {\n return textureFormatDecoder.isCompressed(format);\n }\n\n /** Returns the compressed texture formats that can be created and sampled on this device */\n getSupportedCompressedTextureFormats(): CompressedTextureFormat[] {\n const supportedFormats: CompressedTextureFormat[] = [];\n\n for (const format of Object.keys(getTextureFormatTable()) as TextureFormat[]) {\n if (this.isTextureFormatCompressed(format) && this.isTextureFormatSupported(format)) {\n supportedFormats.push(format as CompressedTextureFormat);\n }\n }\n\n return supportedFormats;\n }\n\n // DEBUG METHODS\n\n pushDebugGroup(groupLabel: string): void {\n this.commandEncoder.pushDebugGroup(groupLabel);\n }\n\n popDebugGroup(): void {\n this.commandEncoder?.popDebugGroup();\n }\n\n insertDebugMarker(markerLabel: string): void {\n this.commandEncoder?.insertDebugMarker(markerLabel);\n }\n\n // Device loss\n\n /** `true` if device is already lost */\n abstract get isLost(): boolean;\n\n /** Promise that resolves when device is lost */\n abstract readonly lost: Promise<{reason: 'destroyed'; message: string}>;\n\n /**\n * Trigger device loss.\n * @returns `true` if context loss could actually be triggered.\n * @note primarily intended for testing how application reacts to device loss\n */\n loseDevice(): boolean {\n return false;\n }\n\n /** A monotonic counter for tracking buffer and texture updates */\n incrementTimestamp(): number {\n return this.timestamp++;\n }\n\n /**\n * Reports Device errors in a way that optimizes for developer experience / debugging.\n * - Logs so that the console error links directly to the source code that generated the error.\n * - Includes the object that reported the error in the log message, even if the error is asynchronous.\n *\n * Conventions when calling reportError():\n * - Always call the returned function - to ensure error is logged, at the error site\n * - Follow with a call to device.debug() - to ensure that the debugger breaks at the error site\n *\n * @param error - the error to report. If needed, just create a new Error object with the appropriate message.\n * @param context - pass `this` as context, otherwise it may not be available in the debugger for async errors.\n * @returns the logger function returned by device.props.onError() so that it can be called from the error site.\n *\n * @example\n * device.reportError(new Error(...), this)();\n * device.debug();\n */\n reportError(error: Error, context: unknown, ...args: unknown[]): () => unknown {\n // Call the error handler\n const isHandled = this.props.onError(error, context);\n if (!isHandled) {\n const logArguments = formatErrorLogArguments(context, args);\n // Note: Returns a function that must be called: `device.reportError(...)()`\n return log.error(\n this.type === 'webgl' ? '%cWebGL' : '%cWebGPU',\n 'color: white; background: red; padding: 2px 6px; border-radius: 3px;',\n error.message,\n ...logArguments\n );\n }\n return () => {};\n }\n\n /** Break in the debugger - if device.props.debug is true */\n debug(): void {\n if (this.props.debug) {\n // @ts-ignore\n // biome-ignore lint/suspicious/noDebugger: explicit debug break when device debugging is enabled.\n debugger;\n } else {\n // TODO(ibgreen): Does not appear to be printed in the console\n const message = `\\\n'Type luma.log.set({debug: true}) in console to enable debug breakpoints',\nor create a device with the 'debug: true' prop.`;\n log.once(0, message)();\n }\n }\n\n // Canvas context\n\n /** Default / primary canvas context. Can be null as WebGPU devices can be created without a CanvasContext */\n abstract canvasContext: CanvasContext | null;\n\n /** Returns the default / primary canvas context. Throws an error if no canvas context is available (a WebGPU compute device) */\n getDefaultCanvasContext(): CanvasContext {\n if (!this.canvasContext) {\n throw new Error('Device has no default CanvasContext. See props.createCanvasContext');\n }\n return this.canvasContext;\n }\n\n /** Creates a new CanvasContext (WebGPU only) */\n abstract createCanvasContext(props?: CanvasContextProps): CanvasContext;\n\n /** Creates a presentation context for a destination canvas. WebGL requires the default canvas context to use an OffscreenCanvas. */\n abstract createPresentationContext(props?: PresentationContextProps): PresentationContext;\n\n /** Call after rendering a frame (necessary e.g. on WebGL OffscreenCanvas) */\n abstract submit(commandBuffer?: CommandBuffer): void;\n\n // Resource creation\n\n /** Create a buffer */\n abstract createBuffer(props: BufferProps | ArrayBuffer | ArrayBufferView): Buffer;\n\n /** Create a texture */\n abstract createTexture(props: TextureProps): Texture;\n\n /** Create a temporary texture view of a video source */\n abstract createExternalTexture(props: ExternalTextureProps): ExternalTexture;\n\n /** Create a sampler */\n abstract createSampler(props: SamplerProps): Sampler;\n\n /** Create a Framebuffer. Must have at least one attachment. */\n abstract createFramebuffer(props: FramebufferProps): Framebuffer;\n\n /** Create a shader */\n abstract createShader(props: ShaderProps): Shader;\n\n /** Create a render pipeline (aka program) */\n abstract createRenderPipeline(props: RenderPipelineProps): RenderPipeline;\n\n /** Create a compute pipeline (aka program). WebGPU only. */\n abstract createComputePipeline(props: ComputePipelineProps): ComputePipeline;\n\n /** Create a vertex array */\n abstract createVertexArray(props: VertexArrayProps): VertexArray;\n\n abstract createCommandEncoder(props?: CommandEncoderProps): CommandEncoder;\n\n /** Create a transform feedback (immutable set of output buffer bindings). WebGL only. */\n abstract createTransformFeedback(props: TransformFeedbackProps): TransformFeedback;\n\n abstract createQuerySet(props: QuerySetProps): QuerySet;\n\n /** Create a fence sync object */\n createFence(): Fence {\n throw new Error('createFence() not implemented');\n }\n\n /** Create a RenderPass using the default CommandEncoder */\n beginRenderPass(props?: RenderPassProps): RenderPass {\n return this.commandEncoder.beginRenderPass(props);\n }\n\n /** Create a ComputePass using the default CommandEncoder*/\n beginComputePass(props?: ComputePassProps): ComputePass {\n return this.commandEncoder.beginComputePass(props);\n }\n\n /**\n * Generate mipmaps for a WebGPU texture.\n * WebGPU textures must be created up front with the required mip count, usage flags, and a format that supports the chosen generation path.\n * WebGL uses `Texture.generateMipmapsWebGL()` directly because the backend manages mip generation on the texture object itself.\n */\n generateMipmapsWebGPU(_texture: Texture): void {\n throw new Error('not implemented');\n }\n\n /** Internal helper for creating a shareable WebGL render-pipeline implementation. */\n _createSharedRenderPipelineWebGL(_props: RenderPipelineProps): SharedRenderPipeline {\n throw new Error('_createSharedRenderPipelineWebGL() not implemented');\n }\n\n /** Internal WebGPU-only helper for retrieving the native bind-group layout for a pipeline group. */\n _createBindGroupLayoutWebGPU(\n _pipeline: RenderPipeline | ComputePipeline,\n _group: number\n ): unknown {\n throw new Error('_createBindGroupLayoutWebGPU() not implemented');\n }\n\n /** Internal WebGPU-only helper for creating a native bind group. */\n _createBindGroupWebGPU(\n _bindGroupLayout: unknown,\n _shaderLayout: ShaderLayout | ComputeShaderLayout,\n _bindings: Bindings,\n _group: number,\n _label?: string\n ): unknown {\n throw new Error('_createBindGroupWebGPU() not implemented');\n }\n\n /**\n * Internal helper that returns `true` when timestamp-query GPU timing should be\n * collected for this device.\n */\n _supportsDebugGPUTime(): boolean {\n return (\n this.features.has('timestamp-query') && Boolean(this.props.debug || this.props.debugGPUTime)\n );\n }\n\n /**\n * Internal helper that enables device-managed GPU timing collection on the\n * default command encoder. Reuses the existing query set if timing is already enabled.\n *\n * @param queryCount - Number of timestamp slots reserved for profiled passes.\n * @returns The device-managed timestamp QuerySet, or `null` when timing is not supported or could not be enabled.\n */\n _enableDebugGPUTime(queryCount: number = 256): QuerySet | null {\n if (!this._supportsDebugGPUTime()) {\n return null;\n }\n\n if (this._debugGPUTimeQuery) {\n return this._debugGPUTimeQuery;\n }\n\n try {\n this._debugGPUTimeQuery = this.createQuerySet({type: 'timestamp', count: queryCount});\n this.commandEncoder = this.createCommandEncoder({\n id: this.commandEncoder.props.id,\n timeProfilingQuerySet: this._debugGPUTimeQuery\n });\n } catch {\n this._debugGPUTimeQuery = null;\n }\n\n return this._debugGPUTimeQuery;\n }\n\n /**\n * Internal helper that disables device-managed GPU timing collection and restores\n * the default command encoder to an unprofiled state.\n */\n _disableDebugGPUTime(): void {\n if (!this._debugGPUTimeQuery) {\n return;\n }\n\n if (this.commandEncoder.getTimeProfilingQuerySet() === this._debugGPUTimeQuery) {\n this.commandEncoder = this.createCommandEncoder({\n id: this.commandEncoder.props.id\n });\n }\n\n this._debugGPUTimeQuery.destroy();\n this._debugGPUTimeQuery = null;\n }\n\n /** Internal helper that returns `true` when device-managed GPU timing is currently active. */\n _isDebugGPUTimeEnabled(): boolean {\n return this._debugGPUTimeQuery !== null;\n }\n\n /**\n * Determines what operations are supported on a texture format, checking against supported device features\n * Subclasses override to apply additional checks\n */\n protected abstract _getDeviceSpecificTextureFormatCapabilities(\n format: DeviceTextureFormatCapabilities\n ): DeviceTextureFormatCapabilities;\n\n // DEPRECATED METHODS\n\n /** @deprecated Use getDefaultCanvasContext() */\n getCanvasContext(): CanvasContext {\n return this.getDefaultCanvasContext();\n }\n\n // WebGL specific HACKS - enables app to remove webgl import\n // Use until we have a better way to handle these\n\n /** @deprecated - will be removed - should use command encoder */\n readPixelsToArrayWebGL(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n sourceAttachment?: number;\n target?: Uint8Array | Uint16Array | Float32Array;\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n ): Uint8Array | Uint16Array | Float32Array {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use command encoder */\n readPixelsToBufferWebGL(\n source: Framebuffer | Texture,\n options?: {\n sourceX?: number;\n sourceY?: number;\n sourceFormat?: number;\n target?: Buffer; // A new Buffer object is created when not provided.\n targetByteOffset?: number; // byte offset in buffer object\n // following parameters are auto deduced if not provided\n sourceWidth?: number;\n sourceHeight?: number;\n sourceType?: number;\n }\n ): Buffer {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */\n setParametersWebGL(parameters: any): void {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */\n getParametersWebGL(parameters: any): void {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use WebGPU parameters (pipeline) */\n withParametersWebGL(parameters: any, func: any): any {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use clear arguments in RenderPass */\n clearWebGL(options?: {framebuffer?: Framebuffer; color?: any; depth?: any; stencil?: any}): void {\n throw new Error('not implemented');\n }\n\n /** @deprecated - will be removed - should use for debugging only */\n resetWebGL(): void {\n throw new Error('not implemented');\n }\n\n // INTERNAL LUMA.GL METHODS\n\n getModuleData<ModuleDataT extends Record<string, unknown>>(moduleName: string): ModuleDataT {\n this._moduleData[moduleName] ||= {};\n return this._moduleData[moduleName] as ModuleDataT;\n }\n\n // INTERNAL HELPERS\n\n // IMPLEMENTATION\n\n /** Helper to get the canvas context props */\n static _getCanvasContextProps(props: DeviceProps): CanvasContextProps | undefined {\n return props.createCanvasContext === true ? {} : props.createCanvasContext;\n }\n\n protected _getDeviceTextureFormatCapabilities(\n format: TextureFormat\n ): DeviceTextureFormatCapabilities {\n const genericCapabilities = textureFormatDecoder.getCapabilities(format);\n\n // Check standard features\n const checkFeature = (feature: DeviceFeature | boolean | undefined) =>\n (typeof feature === 'string' ? this.features.has(feature) : feature) ?? true;\n\n const supported = checkFeature(genericCapabilities.create);\n return {\n format,\n create: supported,\n render: supported && checkFeature(genericCapabilities.render),\n filter: supported && checkFeature(genericCapabilities.filter),\n blend: supported && checkFeature(genericCapabilities.blend),\n store: supported && checkFeature(genericCapabilities.store)\n } as const satisfies DeviceTextureFormatCapabilities;\n }\n\n /** Subclasses use this to support .createBuffer() overloads */\n protected _normalizeBufferProps(props: BufferProps | ArrayBuffer | ArrayBufferView): BufferProps {\n if (props instanceof ArrayBuffer || ArrayBuffer.isView(props)) {\n props = {data: props};\n }\n\n // TODO(ibgreen) - fragile, as this is done before we merge with default options\n // inside the Buffer constructor\n\n const newProps = {...props};\n // Deduce indexType\n const usage = props.usage || 0;\n if (usage & Buffer.INDEX) {\n if (!props.indexType) {\n if (props.data instanceof Uint32Array) {\n newProps.indexType = 'uint32';\n } else if (props.data instanceof Uint16Array) {\n newProps.indexType = 'uint16';\n } else if (props.data instanceof Uint8Array) {\n // Convert uint8 to uint16 for WebGPU compatibility (WebGPU doesn't support uint8 indices)\n newProps.data = new Uint16Array(props.data);\n newProps.indexType = 'uint16';\n }\n }\n if (!newProps.indexType) {\n throw new Error('indices buffer content must be of type uint16 or uint32');\n }\n }\n\n return newProps;\n }\n}\n\n/**\n * Internal helper for resolving the default `debug` prop.\n * Precedence is: explicit log debug value first, then `NODE_ENV`, then `false`.\n */\nexport function _getDefaultDebugValue(logDebugValue: unknown, nodeEnv?: string): boolean {\n if (logDebugValue !== undefined && logDebugValue !== null) {\n return Boolean(logDebugValue);\n }\n\n if (nodeEnv !== undefined) {\n return nodeEnv !== 'production';\n }\n\n return false;\n}\n\nfunction getDefaultDebugValue(): boolean {\n return _getDefaultDebugValue(log.get('debug'), getNodeEnv());\n}\n\nfunction getNodeEnv(): string | undefined {\n const processObject = (\n globalThis as typeof globalThis & {\n process?: {env?: Record<string, string | undefined>};\n }\n ).process;\n if (!processObject?.env) {\n return undefined;\n }\n\n return processObject.env['NODE_ENV'];\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Log} from '@probe.gl/log';\nimport type {DeviceProps} from './device';\nimport {Device} from './device';\nimport {Adapter} from './adapter';\nimport {StatsManager, lumaStats} from '../utils/stats-manager';\nimport {log} from '../utils/log';\n\ndeclare global {\n // eslint-disable-next-line no-var\n var luma: Luma;\n}\n\nconst STARTUP_MESSAGE = 'set luma.log.level=1 (or higher) to trace rendering';\n\nconst ERROR_MESSAGE =\n 'No matching device found. Ensure `@luma.gl/webgl` and/or `@luma.gl/webgpu` modules are imported.';\n\n/** Properties for creating a new device */\nexport type CreateDeviceProps = {\n /** Selects the type of device. `best-available` uses webgpu if available, then webgl. */\n type?: 'webgl' | 'webgpu' | 'null' | 'unknown' | 'best-available';\n /** List of adapters. Will also search any pre-registered adapters */\n adapters?: Adapter[];\n /**\n * Whether to wait for page to be loaded so that CanvasContext's can access the DOM.\n * The browser only supports one 'load' event listener so it may be necessary for the application to set this to false to avoid conflicts.\n */\n waitForPageLoad?: boolean;\n} & DeviceProps;\n\n/** Properties for attaching an existing WebGL context or WebGPU device to a new luma Device */\nexport type AttachDeviceProps = {\n /** List of adapters. Will also search any pre-registered adapters */\n adapters?: Adapter[];\n} & DeviceProps;\n\n/**\n * Entry point to the luma.gl GPU abstraction\n * Register WebGPU and/or WebGL adapters (controls application bundle size)\n * Run-time selection of the first available Device\n */\nexport class Luma {\n static defaultProps: Required<CreateDeviceProps> = {\n ...Device.defaultProps,\n type: 'best-available',\n adapters: undefined!,\n waitForPageLoad: true\n };\n\n /** Global stats for all devices */\n readonly stats: StatsManager = lumaStats;\n\n /**\n * Global log\n *\n * Assign luma.log.level in console to control logging: \\\n * 0: none, 1: minimal, 2: verbose, 3: attribute/uniforms, 4: gl logs\n * luma.log.break[], set to gl funcs, luma.log.profile[] set to model names`;\n */\n readonly log: Log = log;\n\n /** Version of luma.gl */\n readonly VERSION: string =\n // Version detection using build plugin\n // @ts-expect-error no-undef\n typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'running from source';\n\n spector: unknown;\n\n protected preregisteredAdapters = new Map<string, Adapter>();\n\n constructor() {\n if (globalThis.luma) {\n if (globalThis.luma.VERSION !== this.VERSION) {\n log.error(`Found luma.gl ${globalThis.luma.VERSION} while initialzing ${this.VERSION}`)();\n log.error(`'yarn why @luma.gl/core' can help identify the source of the conflict`)();\n throw new Error(`luma.gl - multiple versions detected: see console log`);\n }\n\n log.error('This version of luma.gl has already been initialized')();\n }\n\n log.log(1, `${this.VERSION} - ${STARTUP_MESSAGE}`)();\n\n globalThis.luma = this;\n }\n\n /** Creates a device. Asynchronously. */\n async createDevice(props_: CreateDeviceProps = {}): Promise<Device> {\n const props: Required<CreateDeviceProps> = {...Luma.defaultProps, ...props_};\n\n const adapter = this.selectAdapter(props.type, props.adapters);\n if (!adapter) {\n throw new Error(ERROR_MESSAGE);\n }\n\n // Wait for page to load so that CanvasContext's can access the DOM.\n if (props.waitForPageLoad) {\n await adapter.pageLoaded;\n }\n\n return await adapter.create(props);\n }\n\n /**\n * Attach to an existing GPU API handle (WebGL2RenderingContext or GPUDevice).\n * @param handle Externally created WebGL context or WebGPU device\n */\n async attachDevice(handle: unknown, props: AttachDeviceProps): Promise<Device> {\n const type = this._getTypeFromHandle(handle, props.adapters);\n\n const adapter = type && this.selectAdapter(type, props.adapters);\n if (!adapter) {\n throw new Error(ERROR_MESSAGE);\n }\n\n return await adapter?.attach?.(handle, props);\n }\n\n /**\n * Global adapter registration.\n * @deprecated Use props.adapters instead\n */\n registerAdapters(adapters: Adapter[]): void {\n for (const deviceClass of adapters) {\n this.preregisteredAdapters.set(deviceClass.type, deviceClass);\n }\n }\n\n /** Get type strings for supported Devices */\n getSupportedAdapters(adapters: Adapter[] = []): string[] {\n const adapterMap = this._getAdapterMap(adapters);\n return Array.from(adapterMap)\n .map(([, adapter]) => adapter)\n .filter(adapter => adapter.isSupported?.())\n .map(adapter => adapter.type);\n }\n\n /** Get type strings for best available Device */\n getBestAvailableAdapterType(adapters: Adapter[] = []): 'webgpu' | 'webgl' | 'null' | null {\n const KNOWN_ADAPTERS: ('webgpu' | 'webgl' | 'null')[] = ['webgpu', 'webgl', 'null'];\n const adapterMap = this._getAdapterMap(adapters);\n for (const type of KNOWN_ADAPTERS) {\n if (adapterMap.get(type)?.isSupported?.()) {\n return type;\n }\n }\n return null;\n }\n\n /** Select adapter of type from registered adapters */\n selectAdapter(type: string, adapters: Adapter[] = []): Adapter | null {\n let selectedType: string | null = type;\n if (type === 'best-available') {\n selectedType = this.getBestAvailableAdapterType(adapters);\n }\n\n const adapterMap = this._getAdapterMap(adapters);\n return (selectedType && adapterMap.get(selectedType)) || null;\n }\n\n /**\n * Override `HTMLCanvasContext.getCanvas()` to always create WebGL2 contexts with additional WebGL1 compatibility.\n * Useful when attaching luma to a context from an external library does not support creating WebGL2 contexts.\n */\n enforceWebGL2(enforce: boolean = true, adapters: Adapter[] = []): void {\n const adapterMap = this._getAdapterMap(adapters);\n const webgl2Adapter = adapterMap.get('webgl');\n if (!webgl2Adapter) {\n log.warn('enforceWebGL2: webgl adapter not found')();\n }\n (webgl2Adapter as any)?.enforceWebGL2?.(enforce);\n }\n\n // DEPRECATED\n\n /** @deprecated */\n setDefaultDeviceProps(props: CreateDeviceProps): void {\n Object.assign(Luma.defaultProps, props);\n }\n\n // HELPERS\n\n /** Convert a list of adapters to a map */\n protected _getAdapterMap(adapters: Adapter[] = []): Map<string, Adapter> {\n const map = new Map(this.preregisteredAdapters);\n for (const adapter of adapters) {\n map.set(adapter.type, adapter);\n }\n return map;\n }\n\n /** Get type of a handle (for attachDevice) */\n protected _getTypeFromHandle(\n handle: unknown,\n adapters: Adapter[] = []\n ): 'webgpu' | 'webgl' | 'null' | null {\n // TODO - delegate handle identification to adapters\n\n // WebGL\n if (handle instanceof WebGL2RenderingContext) {\n return 'webgl';\n }\n\n if (typeof GPUDevice !== 'undefined' && handle instanceof GPUDevice) {\n return 'webgpu';\n }\n\n // TODO - WebGPU does not yet seem to have a stable in-browser API, so we \"sniff\" for members instead\n if ((handle as any)?.queue) {\n return 'webgpu';\n }\n\n // null\n if (handle === null) {\n return 'null';\n }\n\n if (handle instanceof WebGLRenderingContext) {\n log.warn('WebGL1 is not supported', handle)();\n } else {\n log.warn('Unknown handle type', handle)();\n }\n\n return null;\n }\n}\n\n/**\n * Entry point to the luma.gl GPU abstraction\n * Register WebGPU and/or WebGL adapters (controls application bundle size)\n * Run-time selection of the first available Device\n */\n// biome-ignore lint/suspicious/noRedeclare: the exported singleton intentionally mirrors the global debug handle.\nexport const luma = new Luma();\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isBrowser} from '@probe.gl/env';\nimport {Device, DeviceProps} from './device';\n\n/**\n * Create and attach devices for a specific backend.\n */\nexport abstract class Adapter {\n // new (props: DeviceProps): Device; Constructor isn't used\n abstract type: string;\n /** Check if this backend is supported */\n abstract isSupported(): boolean;\n /** Check if the given handle is a valid device handle for this backend */\n abstract isDeviceHandle(handle: unknown): boolean;\n /** Create a new device for this backend */\n abstract create(props: DeviceProps): Promise<Device>;\n /** Attach a Device to a valid handle for this backend (GPUDevice, WebGL2RenderingContext etc) */\n abstract attach(handle: unknown, props: DeviceProps): Promise<Device>;\n\n /**\n * Page load promise\n * Resolves when the DOM is loaded.\n * @note Since are be limitations on number of `load` event listeners,\n * it is recommended avoid calling this accessor until actually needed.\n * I.e. we don't call it unless you know that you will be looking up a string in the DOM.\n */\n get pageLoaded(): Promise<void> {\n return getPageLoadPromise();\n }\n}\n\n// HELPER FUNCTIONS\n\nconst isPage: boolean = isBrowser() && typeof document !== 'undefined';\nconst isPageLoaded: () => boolean = () => isPage && document.readyState === 'complete';\nlet pageLoadPromise: Promise<void> | null = null;\n\n/** Returns a promise that resolves when the page is loaded */\nfunction getPageLoadPromise(): Promise<void> {\n if (!pageLoadPromise) {\n if (isPageLoaded() || typeof window === 'undefined') {\n pageLoadPromise = Promise.resolve();\n } else {\n pageLoadPromise = new Promise(resolve => window.addEventListener('load', () => resolve()));\n }\n }\n return pageLoadPromise;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isBrowser} from '@probe.gl/env';\nimport type {Device} from './device';\nimport type {CanvasContext} from './canvas-context';\nimport {CanvasObserver} from './canvas-observer';\nimport type {PresentationContext} from './presentation-context';\nimport type {Framebuffer} from './resources/framebuffer';\nimport type {TextureFormatDepthStencil} from '../shadertypes/texture-types/texture-formats';\nimport {uid} from '../utils/uid';\nimport {withResolvers} from '../utils/promise-utils';\nimport {assertDefined} from '../utils/assert';\n\n/** Properties for a CanvasContext */\nexport type CanvasContextProps = {\n /** Identifier, for debugging */\n id?: string;\n /** If a canvas not supplied, one will be created and added to the DOM. If a string, a canvas with that id will be looked up in the DOM */\n canvas?: HTMLCanvasElement | OffscreenCanvas | string | null;\n /** If new canvas is created, it will be created in the specified container, otherwise is appended as a child of document.body */\n container?: HTMLElement | string | null;\n /** Width in pixels of the canvas - used when creating a new canvas */\n width?: number;\n /** Height in pixels of the canvas - used when creating a new canvas */\n height?: number;\n /** Visibility (only used if new canvas is created). */\n visible?: boolean;\n /** Whether to size the drawing buffer to the pixel size during auto resize. If a number is provided it is used as a static pixel ratio */\n useDevicePixels?: boolean | number;\n /** Whether to track window resizes. */\n autoResize?: boolean;\n /** @see https://developer.mozilla.org/en-US/docs/Web/API/GPUCanvasContext/configure#alphamode */\n alphaMode?: 'opaque' | 'premultiplied';\n /** @see https://developer.mozilla.org/en-US/docs/Web/API/GPUCanvasContext/configure#colorspace */\n colorSpace?: 'srgb'; // GPUPredefinedColorSpace\n /** Whether to track position changes. Calls this.device.onPositionChange */\n trackPosition?: boolean;\n};\n\nexport type MutableCanvasContextProps = {\n /** Whether to size the drawing buffer to the pixel size during auto resize. If a number is provided it is used as a static pixel ratio */\n useDevicePixels?: boolean | number;\n};\n\n/**\n * Shared tracked-canvas lifecycle used by both renderable and presentation contexts.\n * - Creates a new canvas or looks up a canvas from the DOM\n * - Provides check for DOM loaded\n * @todo commit() @see https://github.com/w3ctag/design-reviews/issues/288\n * @todo transferControlToOffscreen: @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/transferControlToOffscreen\n */\nexport abstract class CanvasSurface {\n static isHTMLCanvas(canvas: unknown): canvas is HTMLCanvasElement {\n return typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement;\n }\n\n static isOffscreenCanvas(canvas: unknown): canvas is OffscreenCanvas {\n return typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas;\n }\n\n static defaultProps: Required<CanvasContextProps> = {\n id: undefined!,\n canvas: null,\n width: 800,\n height: 600,\n useDevicePixels: true,\n autoResize: true,\n container: null,\n visible: true,\n alphaMode: 'opaque',\n colorSpace: 'srgb',\n trackPosition: false\n };\n\n abstract readonly device: Device;\n abstract readonly handle: unknown;\n readonly id: string;\n\n readonly props: Required<CanvasContextProps>;\n readonly canvas: HTMLCanvasElement | OffscreenCanvas;\n /** Handle to HTML canvas */\n readonly htmlCanvas?: HTMLCanvasElement;\n /** Handle to wrapped OffScreenCanvas */\n readonly offscreenCanvas?: OffscreenCanvas;\n readonly type: 'html-canvas' | 'offscreen-canvas' | 'node';\n\n /** Promise that resolved once the resize observer has updated the pixel size */\n initialized: Promise<void>;\n isInitialized: boolean = false;\n\n /** Visibility is automatically updated (via an IntersectionObserver) */\n isVisible: boolean = true;\n\n /** Width of canvas in CSS units (tracked by a ResizeObserver) */\n cssWidth: number;\n /** Height of canvas in CSS units (tracked by a ResizeObserver) */\n cssHeight: number;\n\n /** Device pixel ratio. Automatically updated via media queries */\n devicePixelRatio: number;\n /** Exact width of canvas in physical pixels (tracked by a ResizeObserver) */\n devicePixelWidth: number;\n /** Exact height of canvas in physical pixels (tracked by a ResizeObserver) */\n devicePixelHeight: number;\n\n /** Width of drawing buffer: automatically tracks this.pixelWidth if props.autoResize is true */\n drawingBufferWidth: number;\n /** Height of drawing buffer: automatically tracks this.pixelHeight if props.autoResize is true */\n drawingBufferHeight: number;\n\n /** Resolves when the canvas is initialized, i.e. when the ResizeObserver has updated the pixel size */\n protected _initializedResolvers = withResolvers<void>();\n protected _canvasObserver: CanvasObserver;\n /** Position of the canvas in the document, updated by a timer */\n protected _position: [number, number] = [0, 0];\n /** Whether this canvas context has been destroyed */\n protected destroyed = false;\n /** Whether the drawing buffer size needs to be resized (deferred resizing to avoid flicker) */\n protected _needsDrawingBufferResize: boolean = true;\n\n abstract get [Symbol.toStringTag](): string;\n\n toString(): string {\n return `${this[Symbol.toStringTag]}(${this.id})`;\n }\n\n constructor(props?: CanvasContextProps) {\n this.props = {...CanvasSurface.defaultProps, ...props};\n props = this.props;\n\n this.initialized = this._initializedResolvers.promise;\n\n if (!isBrowser()) {\n this.canvas = {width: props.width || 1, height: props.height || 1} as OffscreenCanvas;\n } else if (!props.canvas) {\n this.canvas = createCanvasElement(props);\n } else if (typeof props.canvas === 'string') {\n this.canvas = getCanvasFromDOM(props.canvas);\n } else {\n this.canvas = props.canvas;\n }\n\n if (CanvasSurface.isHTMLCanvas(this.canvas)) {\n this.id = props.id || this.canvas.id;\n this.type = 'html-canvas';\n this.htmlCanvas = this.canvas;\n } else if (CanvasSurface.isOffscreenCanvas(this.canvas)) {\n this.id = props.id || 'offscreen-canvas';\n this.type = 'offscreen-canvas';\n this.offscreenCanvas = this.canvas;\n } else {\n this.id = props.id || 'node-canvas-context';\n this.type = 'node';\n }\n\n this.cssWidth = this.htmlCanvas?.clientWidth || this.canvas.width;\n this.cssHeight = this.htmlCanvas?.clientHeight || this.canvas.height;\n this.devicePixelWidth = this.canvas.width;\n this.devicePixelHeight = this.canvas.height;\n this.drawingBufferWidth = this.canvas.width;\n this.drawingBufferHeight = this.canvas.height;\n this.devicePixelRatio = globalThis.devicePixelRatio || 1;\n this._position = [0, 0];\n this._canvasObserver = new CanvasObserver({\n canvas: this.htmlCanvas,\n trackPosition: this.props.trackPosition,\n onResize: entries => this._handleResize(entries),\n onIntersection: entries => this._handleIntersection(entries),\n onDevicePixelRatioChange: () => this._observeDevicePixelRatio(),\n onPositionChange: () => this.updatePosition()\n });\n }\n\n destroy() {\n if (!this.destroyed) {\n this.destroyed = true;\n this._stopObservers();\n // @ts-expect-error Clear the device to make sure we don't access it after destruction.\n this.device = null;\n }\n }\n\n setProps(props: MutableCanvasContextProps): this {\n if ('useDevicePixels' in props) {\n this.props.useDevicePixels = props.useDevicePixels || false;\n this._updateDrawingBufferSize();\n }\n return this;\n }\n\n /** Returns a framebuffer with properly resized current 'swap chain' textures */\n getCurrentFramebuffer(options?: {\n depthStencilFormat?: TextureFormatDepthStencil | false;\n }): Framebuffer {\n this._resizeDrawingBufferIfNeeded();\n return this._getCurrentFramebuffer(options);\n }\n\n getCSSSize(): [number, number] {\n return [this.cssWidth, this.cssHeight];\n }\n\n getPosition() {\n return this._position;\n }\n\n getDevicePixelSize(): [number, number] {\n return [this.devicePixelWidth, this.devicePixelHeight];\n }\n\n getDrawingBufferSize(): [number, number] {\n return [this.drawingBufferWidth, this.drawingBufferHeight];\n }\n\n getMaxDrawingBufferSize(): [number, number] {\n const maxTextureDimension = this.device.limits.maxTextureDimension2D;\n return [maxTextureDimension, maxTextureDimension];\n }\n\n setDrawingBufferSize(width: number, height: number) {\n width = Math.floor(width);\n height = Math.floor(height);\n if (this.drawingBufferWidth === width && this.drawingBufferHeight === height) {\n return;\n }\n this.drawingBufferWidth = width;\n this.drawingBufferHeight = height;\n this._needsDrawingBufferResize = true;\n }\n\n getDevicePixelRatio(): number {\n const devicePixelRatio = typeof window !== 'undefined' && window.devicePixelRatio;\n return devicePixelRatio || 1;\n }\n\n cssToDevicePixels(\n cssPixel: [number, number],\n yInvert: boolean = true\n ): {\n x: number;\n y: number;\n width: number;\n height: number;\n } {\n const ratio = this.cssToDeviceRatio();\n const [width, height] = this.getDrawingBufferSize();\n return scalePixels(cssPixel, ratio, width, height, yInvert);\n }\n\n /** @deprecated - use .getDevicePixelSize() */\n getPixelSize() {\n return this.getDevicePixelSize();\n }\n\n /** @deprecated Use the current drawing buffer size for projection setup. */\n getAspect(): number {\n const [width, height] = this.getDrawingBufferSize();\n return width > 0 && height > 0 ? width / height : 1;\n }\n\n /** @deprecated Returns multiplier need to convert CSS size to Device size */\n cssToDeviceRatio(): number {\n try {\n const [drawingBufferWidth] = this.getDrawingBufferSize();\n const [cssWidth] = this.getCSSSize();\n return cssWidth ? drawingBufferWidth / cssWidth : 1;\n } catch {\n return 1;\n }\n }\n\n /** @deprecated Use canvasContext.setDrawingBufferSize() */\n resize(size: {width: number; height: number}): void {\n this.setDrawingBufferSize(size.width, size.height);\n }\n\n protected abstract _configureDevice(): void;\n\n protected abstract _getCurrentFramebuffer(options?: {\n depthStencilFormat?: TextureFormatDepthStencil | false;\n }): Framebuffer;\n\n protected _setAutoCreatedCanvasId(id: string) {\n if (this.htmlCanvas?.id === 'lumagl-auto-created-canvas') {\n this.htmlCanvas.id = id;\n }\n }\n\n /**\n * Starts DOM observation after the derived context and its device are fully initialized.\n *\n * `CanvasSurface` construction runs before subclasses can assign `this.device`, and the\n * default WebGL canvas context is created before `WebGLDevice` has initialized `limits`,\n * `features`, and the rest of its runtime state. Deferring observer startup avoids early\n * `ResizeObserver` and DPR callbacks running against a partially initialized device.\n */\n _startObservers(): void {\n if (this.destroyed) {\n return;\n }\n this._canvasObserver.start();\n }\n\n /**\n * Stops all DOM observation and timers associated with a canvas surface.\n *\n * This pairs with `_startObservers()` so teardown uses the same lifecycle whether a context is\n * explicitly destroyed, abandoned during device reuse, or temporarily has not started observing\n * yet. Centralizing shutdown here keeps resize/DPR/position watchers from surviving past the\n * lifetime of the owning device.\n */\n _stopObservers(): void {\n this._canvasObserver.stop();\n }\n\n protected _handleIntersection(entries: IntersectionObserverEntry[]) {\n if (this.destroyed) {\n return;\n }\n\n const entry = entries.find(entry_ => entry_.target === this.canvas);\n if (!entry) {\n return;\n }\n const isVisible = entry.isIntersecting;\n if (this.isVisible !== isVisible) {\n this.isVisible = isVisible;\n this.device.props.onVisibilityChange(this as CanvasContext | PresentationContext);\n }\n }\n\n protected _handleResize(entries: ResizeObserverEntry[]) {\n if (this.destroyed) {\n return;\n }\n\n const entry = entries.find(entry_ => entry_.target === this.canvas);\n if (!entry) {\n return;\n }\n\n const contentBoxSize = assertDefined(entry.contentBoxSize?.[0]);\n this.cssWidth = contentBoxSize.inlineSize;\n this.cssHeight = contentBoxSize.blockSize;\n\n const oldPixelSize = this.getDevicePixelSize();\n\n const devicePixelWidth =\n entry.devicePixelContentBoxSize?.[0]?.inlineSize ||\n contentBoxSize.inlineSize * devicePixelRatio;\n\n const devicePixelHeight =\n entry.devicePixelContentBoxSize?.[0]?.blockSize ||\n contentBoxSize.blockSize * devicePixelRatio;\n\n const [maxDevicePixelWidth, maxDevicePixelHeight] = this.getMaxDrawingBufferSize();\n this.devicePixelWidth = Math.max(1, Math.min(devicePixelWidth, maxDevicePixelWidth));\n this.devicePixelHeight = Math.max(1, Math.min(devicePixelHeight, maxDevicePixelHeight));\n\n this._updateDrawingBufferSize();\n\n this.device.props.onResize(this as CanvasContext | PresentationContext, {oldPixelSize});\n }\n\n protected _updateDrawingBufferSize() {\n if (this.props.autoResize) {\n if (typeof this.props.useDevicePixels === 'number') {\n const devicePixelRatio = this.props.useDevicePixels;\n this.setDrawingBufferSize(\n this.cssWidth * devicePixelRatio,\n this.cssHeight * devicePixelRatio\n );\n } else if (this.props.useDevicePixels) {\n this.setDrawingBufferSize(this.devicePixelWidth, this.devicePixelHeight);\n } else {\n this.setDrawingBufferSize(this.cssWidth, this.cssHeight);\n }\n }\n\n this._initializedResolvers.resolve();\n this.isInitialized = true;\n\n this.updatePosition();\n }\n\n _resizeDrawingBufferIfNeeded() {\n if (this._needsDrawingBufferResize) {\n this._needsDrawingBufferResize = false;\n const sizeChanged =\n this.drawingBufferWidth !== this.canvas.width ||\n this.drawingBufferHeight !== this.canvas.height;\n if (sizeChanged) {\n this.canvas.width = this.drawingBufferWidth;\n this.canvas.height = this.drawingBufferHeight;\n this._configureDevice();\n }\n }\n }\n\n _observeDevicePixelRatio() {\n if (this.destroyed || !this._canvasObserver.started) {\n return;\n }\n const oldRatio = this.devicePixelRatio;\n this.devicePixelRatio = window.devicePixelRatio;\n\n this.updatePosition();\n\n this.device.props.onDevicePixelRatioChange?.(this as CanvasContext | PresentationContext, {\n oldRatio\n });\n }\n\n updatePosition() {\n if (this.destroyed) {\n return;\n }\n const newRect = this.htmlCanvas?.getBoundingClientRect();\n if (newRect) {\n const position: [number, number] = [newRect.left, newRect.top];\n this._position ??= position;\n const positionChanged =\n position[0] !== this._position[0] || position[1] !== this._position[1];\n if (positionChanged) {\n const oldPosition = this._position;\n this._position = position;\n this.device.props.onPositionChange?.(this as CanvasContext | PresentationContext, {\n oldPosition\n });\n }\n }\n }\n}\n\nfunction getContainer(container: HTMLElement | string | null): HTMLElement {\n if (typeof container === 'string') {\n const element = document.getElementById(container);\n if (!element) {\n throw new Error(`${container} is not an HTML element`);\n }\n return element;\n }\n if (container) {\n return container;\n }\n return document.body;\n}\n\nfunction getCanvasFromDOM(canvasId: string): HTMLCanvasElement {\n const canvas = document.getElementById(canvasId);\n if (!CanvasSurface.isHTMLCanvas(canvas)) {\n throw new Error('Object is not a canvas element');\n }\n return canvas;\n}\n\nfunction createCanvasElement(props: CanvasContextProps) {\n const {width, height} = props;\n const newCanvas = document.createElement('canvas');\n newCanvas.id = uid('lumagl-auto-created-canvas');\n newCanvas.width = width || 1;\n newCanvas.height = height || 1;\n newCanvas.style.width = Number.isFinite(width) ? `${width}px` : '100%';\n newCanvas.style.height = Number.isFinite(height) ? `${height}px` : '100%';\n if (!props?.visible) {\n newCanvas.style.visibility = 'hidden';\n }\n const container = getContainer(props?.container || null);\n container.insertBefore(newCanvas, container.firstChild);\n\n return newCanvas;\n}\n\nfunction scalePixels(\n pixel: [number, number],\n ratio: number,\n width: number,\n height: number,\n yInvert: boolean\n): {\n x: number;\n y: number;\n width: number;\n height: number;\n} {\n const point = pixel;\n\n const x = scaleX(point[0], ratio, width);\n let y = scaleY(point[1], ratio, height, yInvert);\n\n let temporary = scaleX(point[0] + 1, ratio, width);\n const xHigh = temporary === width - 1 ? temporary : temporary - 1;\n\n temporary = scaleY(point[1] + 1, ratio, height, yInvert);\n let yHigh;\n if (yInvert) {\n temporary = temporary === 0 ? temporary : temporary + 1;\n yHigh = y;\n y = temporary;\n } else {\n yHigh = temporary === height - 1 ? temporary : temporary - 1;\n }\n return {\n x,\n y,\n width: Math.max(xHigh - x + 1, 1),\n height: Math.max(yHigh - y + 1, 1)\n };\n}\n\nfunction scaleX(x: number, ratio: number, width: number): number {\n return Math.min(Math.round(x * ratio), width - 1);\n}\n\nfunction scaleY(y: number, ratio: number, height: number, yInvert: boolean): number {\n return yInvert\n ? Math.max(0, height - 1 - Math.round(y * ratio))\n : Math.min(Math.round(y * ratio), height - 1);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\ntype CanvasObserverProps = {\n canvas?: HTMLCanvasElement;\n trackPosition: boolean;\n onResize: (entries: ResizeObserverEntry[]) => void;\n onIntersection: (entries: IntersectionObserverEntry[]) => void;\n onDevicePixelRatioChange: () => void;\n onPositionChange: () => void;\n};\n\n/**\n * Internal DOM observer orchestration for HTML canvas surfaces.\n *\n * CanvasSurface owns the tracked state and device callback dispatch. This helper only manages\n * browser observers, timers, and polling loops, then reports events through callbacks.\n */\nexport class CanvasObserver {\n readonly props: CanvasObserverProps;\n\n private _resizeObserver: ResizeObserver | undefined;\n private _intersectionObserver: IntersectionObserver | undefined;\n private _observeDevicePixelRatioTimeout: ReturnType<typeof setTimeout> | null = null;\n private _observeDevicePixelRatioMediaQuery: MediaQueryList | null = null;\n private readonly _handleDevicePixelRatioChange = () => this._refreshDevicePixelRatio();\n private _trackPositionInterval: ReturnType<typeof setInterval> | null = null;\n private _started = false;\n\n get started(): boolean {\n return this._started;\n }\n\n constructor(props: CanvasObserverProps) {\n this.props = props;\n }\n\n start(): void {\n if (this._started || !this.props.canvas) {\n return;\n }\n\n this._started = true;\n this._intersectionObserver ||= new IntersectionObserver(entries =>\n this.props.onIntersection(entries)\n );\n this._resizeObserver ||= new ResizeObserver(entries => this.props.onResize(entries));\n\n this._intersectionObserver.observe(this.props.canvas);\n try {\n this._resizeObserver.observe(this.props.canvas, {box: 'device-pixel-content-box'});\n } catch {\n this._resizeObserver.observe(this.props.canvas, {box: 'content-box'});\n }\n\n this._observeDevicePixelRatioTimeout = setTimeout(() => this._refreshDevicePixelRatio(), 0);\n\n if (this.props.trackPosition) {\n this._trackPosition();\n }\n }\n\n stop(): void {\n if (!this._started) {\n return;\n }\n\n this._started = false;\n\n if (this._observeDevicePixelRatioTimeout) {\n clearTimeout(this._observeDevicePixelRatioTimeout);\n this._observeDevicePixelRatioTimeout = null;\n }\n\n if (this._observeDevicePixelRatioMediaQuery) {\n this._observeDevicePixelRatioMediaQuery.removeEventListener(\n 'change',\n this._handleDevicePixelRatioChange\n );\n this._observeDevicePixelRatioMediaQuery = null;\n }\n\n if (this._trackPositionInterval) {\n clearInterval(this._trackPositionInterval);\n this._trackPositionInterval = null;\n }\n\n this._resizeObserver?.disconnect();\n this._intersectionObserver?.disconnect();\n }\n\n private _refreshDevicePixelRatio(): void {\n if (!this._started) {\n return;\n }\n\n this.props.onDevicePixelRatioChange();\n\n this._observeDevicePixelRatioMediaQuery?.removeEventListener(\n 'change',\n this._handleDevicePixelRatioChange\n );\n this._observeDevicePixelRatioMediaQuery = matchMedia(\n `(resolution: ${window.devicePixelRatio}dppx)`\n );\n this._observeDevicePixelRatioMediaQuery.addEventListener(\n 'change',\n this._handleDevicePixelRatioChange,\n {once: true}\n );\n }\n\n private _trackPosition(intervalMs: number = 100): void {\n if (this._trackPositionInterval) {\n return;\n }\n\n this._trackPositionInterval = setInterval(() => {\n if (!this._started) {\n if (this._trackPositionInterval) {\n clearInterval(this._trackPositionInterval);\n this._trackPositionInterval = null;\n }\n } else {\n this.props.onPositionChange();\n }\n }, intervalMs);\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// TODO - replace with Promise.withResolvers once we upgrade TS baseline\nexport function withResolvers<T>(): {\n promise: Promise<T>;\n resolve: (t: T) => void;\n reject: (error: Error) => void;\n} {\n let resolve: (t: T) => void;\n let reject: (error: Error) => void;\n const promise = new Promise<T>((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n // @ts-expect-error - in fact these are no used before initialized\n return {promise, resolve, reject};\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n/** Throws if condition is true and narrows type */\nexport function assert(condition: unknown, message?: string): asserts condition {\n if (!condition) {\n const error = new Error(message ?? 'luma.gl assertion failed.');\n Error.captureStackTrace?.(error, assert);\n throw error;\n }\n}\n\n/** Throws if value is not defined, narrows type */\nexport function assertDefined<T>(value: T | undefined, message?: string): T {\n assert(value, message);\n return value;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type {CanvasContextProps, MutableCanvasContextProps} from './canvas-surface';\nimport {CanvasSurface} from './canvas-surface';\n\n/**\n * Manages a renderable backend canvas. Supports both HTML or offscreen canvas\n * and returns backend framebuffers sourced from the canvas itself.\n */\nexport abstract class CanvasContext extends CanvasSurface {\n static override defaultProps = CanvasSurface.defaultProps;\n\n abstract override readonly handle: unknown;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {CanvasSurface} from './canvas-surface';\n\nexport type {CanvasContextProps as PresentationContextProps} from './canvas-surface';\n\n/**\n * Tracks a destination canvas for presentation.\n * Backend implementations either borrow the default GPU-backed canvas (WebGL)\n * or render directly into the destination canvas (WebGPU).\n */\nexport abstract class PresentationContext extends CanvasSurface {\n abstract present(): void;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {CompareFunction} from '../types/parameters';\nimport {Resource, ResourceProps} from './resource';\n\n/** Edge values sampling mode */\nexport type SamplerAddressMode = 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n\n/** Sampler filtering mode */\nexport type SamplerFilterMode = 'nearest' | 'linear';\n\n/**\n * Properties for initializing a sampler\n */\nexport type SamplerProps = ResourceProps & {\n /** Comparison / shadow samplers are used with depth textures. See the `Sampler.compare` field */\n type?: 'color-sampler' | 'comparison-sampler';\n /** Edge value sampling in X direction */\n addressModeU?: 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n /** Edge value sampling in Y direction */\n addressModeV?: 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n /** Edge value sampling in Z direction */\n addressModeW?: 'clamp-to-edge' | 'repeat' | 'mirror-repeat';\n\n /** Magnification: the area of the fragment in texture space is smaller than a texel */\n magFilter?: 'nearest' | 'linear';\n /** Minification: the area of the fragment in texture space is larger than a texel */\n minFilter?: 'nearest' | 'linear';\n /** mipmapping: select between multiple mipmaps based on angle and size of the texture relative to the screen. */\n mipmapFilter?: 'none' | 'nearest' | 'linear';\n /** Affects the mipmap image selection */\n lodMinClamp?: number;\n /** Affects the mipmap image selection */\n lodMaxClamp?: number;\n /** Maximum number of samples that can be taken of the texture during any one texture fetch */\n maxAnisotropy?: number;\n /** How to compare reference values provided in shader shadow sampler calls with those pulled from the texture */\n compare?: CompareFunction;\n};\n\nexport type SamplerParameters = Omit<SamplerProps, keyof ResourceProps>;\n\n/** Immutable Sampler object */\nexport abstract class Sampler extends Resource<SamplerProps> {\n static override defaultProps: Required<SamplerProps> = {\n ...Resource.defaultProps,\n type: 'color-sampler',\n addressModeU: 'clamp-to-edge',\n addressModeV: 'clamp-to-edge',\n addressModeW: 'clamp-to-edge',\n magFilter: 'nearest',\n minFilter: 'nearest',\n mipmapFilter: 'none',\n lodMinClamp: 0,\n lodMaxClamp: 32, // Per WebGPU spec\n compare: 'less-equal',\n maxAnisotropy: 1\n };\n\n override get [Symbol.toStringTag](): string {\n return 'Sampler';\n }\n\n constructor(device: Device, props: SamplerProps) {\n props = Sampler.normalizeProps(device, props);\n super(device, props, Sampler.defaultProps);\n }\n\n protected static normalizeProps(device: Device, props: SamplerProps): SamplerProps {\n return props;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {type TypedArray} from '@math.gl/types';\nimport {type Device} from '../device';\nimport {\n type TextureFormat,\n type TextureMemoryLayout,\n type TextureFormatInfo\n} from '../../shadertypes/texture-types/texture-formats';\nimport {type ExternalImage} from '../../shadertypes/image-types/image-types';\nimport {type TextureView, type TextureViewProps} from './texture-view';\nimport {Resource, type ResourceProps} from './resource';\nimport {Sampler, type SamplerProps} from './sampler';\nimport {Buffer} from './buffer';\nimport {log} from '../../utils/log';\nimport {textureFormatDecoder} from '../../shadertypes/texture-types/texture-format-decoder';\n\n/** Options for Texture.copyExternalImage */\nexport type CopyExternalImageOptions = {\n /** Image */\n image: ExternalImage;\n /** Copy from image x offset (default 0) */\n sourceX?: number;\n /** Copy from image y offset (default 0) */\n sourceY?: number;\n /** Copy area width (default 1) */\n width?: number;\n /** Copy area height (default 1) */\n height?: number;\n /** Copy depth, number of layers/depth slices(default 1) */\n depth?: number;\n /** Start copying into offset x (default 0) */\n x?: number;\n /** Start copying into offset y (default 0) */\n y?: number;\n /** Start copying into layer / depth slice z (default 0) */\n z?: number;\n /** Which mip-level to copy into (default 0) */\n mipLevel?: number;\n /** When copying into depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n /** Specific color space of image data */\n colorSpace?: 'srgb';\n /** load as premultiplied alpha */\n premultipliedAlpha?: boolean;\n /** Whether to flip the image vertically */\n flipY?: boolean;\n};\n\n/** Options for copyImageData */\nexport type CopyImageDataOptions = {\n /** Data to copy (array of bytes) */\n data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView;\n /** Offset into the data (in addition to any offset built-in to the ArrayBufferView) */\n byteOffset?: number;\n /** The stride, in bytes, between successive texel rows in the CPU source data. Tightly packed uploads can omit this. */\n bytesPerRow?: number;\n /** Number of rows that make up one image when uploading multiple layers or depth slices from CPU memory. */\n rowsPerImage?: number;\n /** Width to copy */\n width?: number;\n /** Height to copy */\n height?: number;\n /** Copy depth or number of layers */\n depthOrArrayLayers?: number;\n /** @deprecated Use `depthOrArrayLayers` */\n depth?: number;\n /** Start copying into offset x (default 0) */\n x?: number;\n /** Start copying into offset y (default 0) */\n y?: number;\n /** Start copying from depth layer z (default 0) */\n z?: number;\n /** Which mip-level to copy into (default 0) */\n mipLevel?: number;\n /** When copying into depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\nexport type TextureReadOptions = {\n /** Start reading from offset x (default 0) */\n x?: number;\n /** Start reading from offset y (default 0) */\n y?: number;\n /** Start reading from layer / depth slice z (default 0) */\n z?: number;\n /** Width of the region to read. Defaults to the mip width. */\n width?: number;\n /** Height of the region to read. Defaults to the mip height. */\n height?: number;\n /** Number of array layers or depth slices to read. Defaults to 1. */\n depthOrArrayLayers?: number;\n /** Which mip-level to read from (default 0) */\n mipLevel?: number;\n /** When reading from depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\nexport type TextureWriteOptions = {\n /** Offset into the source data or buffer, in bytes. */\n byteOffset?: number;\n /** The stride, in bytes, between successive texel rows in the source data or buffer. */\n bytesPerRow?: number;\n /** The number of rows that make up one image when writing multiple layers or slices. */\n rowsPerImage?: number;\n /** Start writing into offset x (default 0) */\n x?: number;\n /** Start writing into offset y (default 0) */\n y?: number;\n /** Start writing into layer / depth slice z (default 0) */\n z?: number;\n /** Width of the region to write. Defaults to the mip width. */\n width?: number;\n /** Height of the region to write. Defaults to the mip height. */\n height?: number;\n /** Number of array layers or depth slices to write. Defaults to 1, or the full mip depth for 3D textures. */\n depthOrArrayLayers?: number;\n /** Which mip-level to write into (default 0) */\n mipLevel?: number;\n /** When writing into depth stencil textures (default 'all') */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\nconst BASE_DIMENSIONS = {\n '1d': '1d',\n '2d': '2d',\n '2d-array': '2d',\n cube: '2d',\n 'cube-array': '2d',\n '3d': '3d'\n} as const satisfies Record<string, '1d' | '2d' | '3d'>;\n\n/** Texture properties */\nexport type TextureProps = ResourceProps & {\n /** @deprecated Use DynamicTexture to create textures with data. */\n data?: ExternalImage | TypedArray | null;\n /** Dimension of this texture. Defaults to '2d' */\n dimension?: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** The format (bit layout) of the textures pixel data */\n format?: TextureFormat;\n /** Width in texels */\n width: number;\n /** Width in texels */\n height: number;\n /** Number of depth layers */\n depth?: number;\n /** How this texture will be used. Defaults to TEXTURE | COPY_DST | RENDER_ATTACHMENT */\n usage?: number;\n /** How many mip levels */\n mipLevels?: number;\n /** Multi sampling */\n samples?: number;\n\n /** Sampler (or SamplerProps) for the default sampler for this texture. Used if no sampler provided. Note that other samplers can still be used. */\n sampler?: Sampler | SamplerProps;\n /** Props for the default TextureView for this texture. Note that other views can still be created and used. */\n view?: TextureViewProps;\n};\n\n/**\n * Abstract Texture interface\n * Texture Object\n * https://gpuweb.github.io/gpuweb/#gputexture\n */\nexport abstract class Texture extends Resource<TextureProps> {\n /** The texture can be bound for use as a sampled texture in a shader */\n static SAMPLE = 0x04;\n /** The texture can be bound for use as a storage texture in a shader */\n static STORAGE = 0x08;\n /** The texture can be used as a color or depth/stencil attachment in a render pass */\n static RENDER = 0x10;\n /** The texture can be used as the source of a copy operation */\n static COPY_SRC = 0x01;\n /** he texture can be used as the destination of a copy or write operation */\n static COPY_DST = 0x02;\n\n /** @deprecated Use Texture.SAMPLE */\n static TEXTURE = 0x04;\n /** @deprecated Use Texture.RENDER */\n static RENDER_ATTACHMENT = 0x10;\n\n /** dimension of this texture */\n readonly dimension: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** base dimension of this texture */\n readonly baseDimension: '1d' | '2d' | '3d';\n /** format of this texture */\n readonly format: TextureFormat;\n /** width in pixels of this texture */\n readonly width: number;\n /** height in pixels of this texture */\n readonly height: number;\n /** depth of this texture */\n readonly depth: number;\n /** mip levels in this texture */\n readonly mipLevels: number;\n /** sample count */\n readonly samples: number;\n /** Rows are multiples of this length, padded with extra bytes if needed */\n readonly byteAlignment: number;\n /** Default sampler for this texture */\n abstract sampler: Sampler;\n /** Default view for this texture */\n abstract view: TextureView;\n\n /** The ready promise is always resolved. It is provided for type compatibility with DynamicTexture. */\n readonly ready: Promise<Texture> = Promise.resolve(this);\n /** isReady is always true. It is provided for type compatibility with DynamicTexture. */\n readonly isReady: boolean = true;\n\n /** \"Time\" of last update. Monotonically increasing timestamp. TODO move to DynamicTexture? */\n updateTimestamp: number;\n\n override get [Symbol.toStringTag](): string {\n return 'Texture';\n }\n\n override toString(): string {\n return `Texture(${this.id},${this.format},${this.width}x${this.height})`;\n }\n\n /** Do not use directly. Create with device.createTexture() */\n constructor(device: Device, props: TextureProps, backendProps?: {byteAlignment?: number}) {\n props = Texture.normalizeProps(device, props);\n super(device, props, Texture.defaultProps);\n this.dimension = this.props.dimension;\n this.baseDimension = BASE_DIMENSIONS[this.dimension];\n this.format = this.props.format;\n\n // Size\n this.width = this.props.width;\n this.height = this.props.height;\n this.depth = this.props.depth;\n this.mipLevels = this.props.mipLevels;\n this.samples = this.props.samples || 1;\n\n if (this.dimension === 'cube') {\n this.depth = 6;\n }\n\n // Calculate size, if not provided\n if (this.props.width === undefined || this.props.height === undefined) {\n if (device.isExternalImage(props.data)) {\n const size = device.getExternalImageSize(props.data);\n this.width = size?.width || 1;\n this.height = size?.height || 1;\n } else {\n this.width = 1;\n this.height = 1;\n if (this.props.width === undefined || this.props.height === undefined) {\n log.warn(\n `${this} created with undefined width or height. This is deprecated. Use DynamicTexture instead.`\n )();\n }\n }\n }\n\n this.byteAlignment = backendProps?.byteAlignment || 1;\n\n // TODO - perhaps this should be set on async write completion?\n this.updateTimestamp = device.incrementTimestamp();\n }\n\n /**\n * Create a new texture with the same parameters and optionally a different size\n * @note Textures are immutable and cannot be resized after creation, but we can create a similar texture with the same parameters but a new size.\n * @note Does not copy contents of the texture\n */\n clone(size?: {width: number; height: number}): Texture {\n return this.device.createTexture({...this.props, ...size});\n }\n\n /** Set sampler props associated with this texture */\n setSampler(sampler: Sampler | SamplerProps): void {\n this.sampler = sampler instanceof Sampler ? sampler : this.device.createSampler(sampler);\n }\n\n /** Create a texture view for this texture */\n abstract createView(props: TextureViewProps): TextureView;\n\n /** Copy an image (e.g an ImageBitmap) into the texture */\n abstract copyExternalImage(options: CopyExternalImageOptions): {width: number; height: number};\n\n /**\n * Copy raw image data (bytes) into the texture.\n *\n * @note Deprecated compatibility wrapper over {@link writeData}.\n * @note Uses the same layout defaults and alignment rules as {@link writeData}.\n * @note Tightly packed CPU uploads can omit `bytesPerRow` and `rowsPerImage`.\n * @note If the CPU source rows are padded, pass explicit `bytesPerRow` and `rowsPerImage`.\n * @deprecated Use writeData()\n */\n copyImageData(options: CopyImageDataOptions): void {\n const {data, depth, ...writeOptions} = options;\n this.writeData(data, {\n ...writeOptions,\n depthOrArrayLayers: writeOptions.depthOrArrayLayers ?? depth\n });\n }\n\n /**\n * Calculates the memory layout of the texture, required when reading and writing data.\n * @return the backend-aligned linear layout, in particular bytesPerRow which includes any required padding for buffer copy/read paths\n */\n computeMemoryLayout(options_: TextureReadOptions = {}): TextureMemoryLayout {\n const options = this._normalizeTextureReadOptions(options_);\n const {width = this.width, height = this.height, depthOrArrayLayers = this.depth} = options;\n const {format, byteAlignment} = this;\n\n // TODO - does the overriding above make sense?\n // return textureFormatDecoder.computeMemoryLayout(this);\n return textureFormatDecoder.computeMemoryLayout({\n format,\n width,\n height,\n depth: depthOrArrayLayers,\n byteAlignment\n });\n }\n\n /**\n * Read the contents of a texture into a GPU Buffer.\n * @returns A Buffer containing the texture data.\n *\n * @note The memory layout of the texture data is determined by the texture format and dimensions.\n * @note The application can call Texture.computeMemoryLayout() to compute the backend-aligned layout.\n * @note The application can call Buffer.readAsync() to read the returned buffer on the CPU.\n * @note The destination buffer must be supplied by the caller and must be large enough for the requested region.\n * @note On WebGPU this corresponds to a texture-to-buffer copy and uses buffer-copy alignment rules.\n * @note On WebGL, luma.gl emulates the same logical readback behavior.\n */\n readBuffer(options?: TextureReadOptions, buffer?: Buffer): Buffer {\n throw new Error('readBuffer not implemented');\n }\n\n /**\n * Reads data from a texture into an ArrayBuffer.\n * @returns An ArrayBuffer containing the texture data.\n *\n * @note The memory layout of the texture data is determined by the texture format and dimensions.\n * @note The application can call Texture.computeMemoryLayout() to compute the layout.\n * @deprecated Use Texture.readBuffer() with an explicit destination buffer, or DynamicTexture.readAsync() for convenience readback.\n */\n readDataAsync(options?: TextureReadOptions): Promise<ArrayBuffer> {\n throw new Error('readBuffer not implemented');\n }\n\n /**\n * Writes a GPU Buffer into a texture.\n *\n * @param buffer - Source GPU buffer.\n * @param options - Destination subresource, extent, and source layout options.\n * @note The memory layout of the texture data is determined by the texture format and dimensions.\n * @note The application can call Texture.computeMemoryLayout() to compute the backend-aligned layout.\n * @note On WebGPU this corresponds to a buffer-to-texture copy and uses buffer-copy alignment rules.\n * @note On WebGL, luma.gl emulates the same destination and layout semantics.\n */\n writeBuffer(buffer: Buffer, options?: TextureWriteOptions): void {\n throw new Error('readBuffer not implemented');\n }\n\n /**\n * Writes an array buffer into a texture.\n *\n * @param data - Source texel data.\n * @param options - Destination subresource, extent, and source layout options.\n * @note If `bytesPerRow` and `rowsPerImage` are omitted, luma.gl computes a tightly packed CPU-memory layout for the requested region.\n * @note On WebGPU this corresponds to `GPUQueue.writeTexture()` and does not implicitly pad rows to 256 bytes.\n * @note On WebGL, padded CPU data is supported via the same `bytesPerRow` and `rowsPerImage` options.\n */\n writeData(\n data: ArrayBuffer | SharedArrayBuffer | ArrayBufferView,\n options?: TextureWriteOptions\n ): void {\n throw new Error('readBuffer not implemented');\n }\n\n // IMPLEMENTATION SPECIFIC\n\n /**\n * WebGL can read data synchronously.\n * @note While it is convenient, the performance penalty is very significant\n */\n readDataSyncWebGL(options?: TextureReadOptions): ArrayBuffer | ArrayBufferView {\n throw new Error('readDataSyncWebGL not available');\n }\n\n /** Generate mipmaps (WebGL only) */\n generateMipmapsWebGL(): void {\n throw new Error('generateMipmapsWebGL not available');\n }\n\n // HELPERS\n\n /** Ensure we have integer coordinates */\n protected static normalizeProps(device: Device, props: TextureProps): TextureProps {\n const newProps = {...props};\n\n // Ensure we have integer coordinates\n const {width, height} = newProps;\n if (typeof width === 'number') {\n newProps.width = Math.max(1, Math.ceil(width));\n }\n if (typeof height === 'number') {\n newProps.height = Math.max(1, Math.ceil(height));\n }\n return newProps;\n }\n\n /** Initialize texture with supplied props */\n // eslint-disable-next-line max-statements\n _initializeData(data: TextureProps['data']): void {\n // Store opts for accessors\n\n if (this.device.isExternalImage(data)) {\n this.copyExternalImage({\n image: data,\n width: this.width,\n height: this.height,\n depth: this.depth,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all',\n colorSpace: 'srgb',\n premultipliedAlpha: false,\n flipY: false\n });\n } else if (data) {\n this.copyImageData({\n data,\n // width: this.width,\n // height: this.height,\n // depth: this.depth,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all'\n });\n }\n }\n\n _normalizeCopyImageDataOptions(options_: CopyImageDataOptions): Required<CopyImageDataOptions> {\n const {data, depth, ...writeOptions} = options_;\n const options = this._normalizeTextureWriteOptions({\n ...writeOptions,\n depthOrArrayLayers: writeOptions.depthOrArrayLayers ?? depth\n });\n return {data, depth: options.depthOrArrayLayers, ...options};\n }\n\n _normalizeCopyExternalImageOptions(\n options_: CopyExternalImageOptions\n ): Required<CopyExternalImageOptions> {\n const optionsWithoutUndefined = Texture._omitUndefined(options_);\n const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const size = this.device.getExternalImageSize(options_.image);\n const options = {\n ...Texture.defaultCopyExternalImageOptions,\n ...mipLevelSize,\n ...size,\n ...optionsWithoutUndefined\n };\n // WebGL will error if we try to copy outside the bounds of the texture\n options.width = Math.min(options.width, mipLevelSize.width - options.x);\n options.height = Math.min(options.height, mipLevelSize.height - options.y);\n options.depth = Math.min(options.depth, mipLevelSize.depthOrArrayLayers - options.z);\n return options;\n }\n\n _normalizeTextureReadOptions(options_: TextureReadOptions): Required<TextureReadOptions> {\n const optionsWithoutUndefined = Texture._omitUndefined(options_);\n const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const options = {\n ...Texture.defaultTextureReadOptions,\n ...mipLevelSize,\n ...optionsWithoutUndefined\n };\n // WebGL will error if we try to copy outside the bounds of the texture\n options.width = Math.min(options.width, mipLevelSize.width - options.x);\n options.height = Math.min(options.height, mipLevelSize.height - options.y);\n options.depthOrArrayLayers = Math.min(\n options.depthOrArrayLayers,\n mipLevelSize.depthOrArrayLayers - options.z\n );\n return options;\n }\n\n /**\n * Normalizes a texture read request and validates the color-only readback contract used by the\n * current texture read APIs. Supported dimensions are `2d`, `cube`, `cube-array`,\n * `2d-array`, and `3d`.\n *\n * @throws if the texture format, aspect, or dimension is not supported by the first-pass\n * color-read implementation.\n */\n protected _getSupportedColorReadOptions(\n options_: TextureReadOptions\n ): Required<TextureReadOptions> {\n const options = this._normalizeTextureReadOptions(options_);\n const formatInfo = textureFormatDecoder.getInfo(this.format);\n\n this._validateColorReadAspect(options);\n this._validateColorReadFormat(formatInfo);\n\n switch (this.dimension) {\n case '2d':\n case 'cube':\n case 'cube-array':\n case '2d-array':\n case '3d':\n return options;\n\n default:\n throw new Error(`${this} color readback does not support ${this.dimension} textures`);\n }\n }\n\n /** Validates that a read request targets the full color aspect of the texture. */\n protected _validateColorReadAspect(options: Required<TextureReadOptions>): void {\n if (options.aspect !== 'all') {\n throw new Error(`${this} color readback only supports aspect 'all'`);\n }\n }\n\n /** Validates that a read request targets an uncompressed color-renderable texture format. */\n protected _validateColorReadFormat(formatInfo: TextureFormatInfo): void {\n if (formatInfo.compressed) {\n throw new Error(\n `${this} color readback does not support compressed formats (${this.format})`\n );\n }\n\n switch (formatInfo.attachment) {\n case 'color':\n return;\n\n case 'depth':\n throw new Error(`${this} color readback does not support depth formats (${this.format})`);\n\n case 'stencil':\n throw new Error(`${this} color readback does not support stencil formats (${this.format})`);\n\n case 'depth-stencil':\n throw new Error(\n `${this} color readback does not support depth-stencil formats (${this.format})`\n );\n\n default:\n throw new Error(`${this} color readback does not support format ${this.format}`);\n }\n }\n\n _normalizeTextureWriteOptions(options_: TextureWriteOptions): Required<TextureWriteOptions> {\n const optionsWithoutUndefined = Texture._omitUndefined(options_);\n const mipLevel = optionsWithoutUndefined.mipLevel ?? 0;\n const mipLevelSize = this._getMipLevelSize(mipLevel);\n const options = {\n ...Texture.defaultTextureWriteOptions,\n ...mipLevelSize,\n ...optionsWithoutUndefined\n };\n\n options.width = Math.min(options.width, mipLevelSize.width - options.x);\n options.height = Math.min(options.height, mipLevelSize.height - options.y);\n options.depthOrArrayLayers = Math.min(\n options.depthOrArrayLayers,\n mipLevelSize.depthOrArrayLayers - options.z\n );\n\n const layout = textureFormatDecoder.computeMemoryLayout({\n format: this.format,\n width: options.width,\n height: options.height,\n depth: options.depthOrArrayLayers,\n byteAlignment: this.byteAlignment\n });\n\n const minimumBytesPerRow = layout.bytesPerPixel * options.width;\n options.bytesPerRow = optionsWithoutUndefined.bytesPerRow ?? layout.bytesPerRow;\n options.rowsPerImage = optionsWithoutUndefined.rowsPerImage ?? options.height;\n\n if (options.bytesPerRow < minimumBytesPerRow) {\n throw new Error(\n `bytesPerRow (${options.bytesPerRow}) must be at least ${minimumBytesPerRow} for ${this.format}`\n );\n }\n if (options.rowsPerImage < options.height) {\n throw new Error(\n `rowsPerImage (${options.rowsPerImage}) must be at least ${options.height} for ${this.format}`\n );\n }\n\n const bytesPerPixel = this.device.getTextureFormatInfo(this.format).bytesPerPixel;\n if (bytesPerPixel && options.bytesPerRow % bytesPerPixel !== 0) {\n throw new Error(\n `bytesPerRow (${options.bytesPerRow}) must be a multiple of bytesPerPixel (${bytesPerPixel}) for ${this.format}`\n );\n }\n\n return options;\n }\n\n protected _getMipLevelSize(\n mipLevel: number\n ): Required<Pick<TextureReadOptions, 'width' | 'height' | 'depthOrArrayLayers'>> {\n const width = Math.max(1, this.width >> mipLevel);\n const height = this.baseDimension === '1d' ? 1 : Math.max(1, this.height >> mipLevel);\n const depthOrArrayLayers =\n this.dimension === '3d' ? Math.max(1, this.depth >> mipLevel) : this.depth;\n\n return {width, height, depthOrArrayLayers};\n }\n\n protected getAllocatedByteLength(): number {\n let allocatedByteLength = 0;\n\n for (let mipLevel = 0; mipLevel < this.mipLevels; mipLevel++) {\n const {width, height, depthOrArrayLayers} = this._getMipLevelSize(mipLevel);\n allocatedByteLength += textureFormatDecoder.computeMemoryLayout({\n format: this.format,\n width,\n height,\n depth: depthOrArrayLayers,\n byteAlignment: 1\n }).byteLength;\n }\n\n return allocatedByteLength * this.samples;\n }\n\n protected static _omitUndefined<T extends object>(options: T): Partial<T> {\n return Object.fromEntries(\n Object.entries(options).filter(([, value]) => value !== undefined)\n ) as Partial<T>;\n }\n\n static override defaultProps: Required<TextureProps> = {\n ...Resource.defaultProps,\n data: null,\n dimension: '2d',\n format: 'rgba8unorm',\n usage: Texture.SAMPLE | Texture.RENDER | Texture.COPY_DST,\n width: undefined!,\n height: undefined!,\n depth: 1,\n mipLevels: 1,\n samples: undefined!,\n sampler: {},\n view: undefined!\n };\n\n protected static defaultCopyDataOptions: Required<CopyImageDataOptions> = {\n data: undefined!,\n byteOffset: 0,\n bytesPerRow: undefined!,\n rowsPerImage: undefined!,\n width: undefined!,\n height: undefined!,\n depthOrArrayLayers: undefined!,\n depth: 1,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all'\n };\n\n /** Default options */\n protected static defaultCopyExternalImageOptions: Required<CopyExternalImageOptions> = {\n image: undefined!,\n sourceX: 0,\n sourceY: 0,\n width: undefined!,\n height: undefined!,\n depth: 1,\n mipLevel: 0,\n x: 0,\n y: 0,\n z: 0,\n aspect: 'all',\n colorSpace: 'srgb',\n premultipliedAlpha: false,\n flipY: false\n };\n\n protected static defaultTextureReadOptions: Required<TextureReadOptions> = {\n x: 0,\n y: 0,\n z: 0,\n width: undefined!,\n height: undefined!,\n depthOrArrayLayers: 1,\n mipLevel: 0,\n aspect: 'all'\n };\n\n protected static defaultTextureWriteOptions: Required<TextureWriteOptions> = {\n byteOffset: 0,\n bytesPerRow: undefined!,\n rowsPerImage: undefined!,\n x: 0,\n y: 0,\n z: 0,\n width: undefined!,\n height: undefined!,\n depthOrArrayLayers: 1,\n mipLevel: 0,\n aspect: 'all'\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {Texture} from './texture';\nimport type {TextureFormat} from '../../shadertypes/texture-types/texture-formats';\nimport {Resource, ResourceProps} from './resource';\n\n/** Properties for initializing a texture view */\nexport type TextureViewProps = ResourceProps & {\n /** The format of the texture view. Must be either the format of the texture or one of the viewFormats specified during its creation. */\n format?: TextureFormat;\n /** The dimension to view the texture as. */\n dimension?: '1d' | '2d' | '2d-array' | 'cube' | 'cube-array' | '3d';\n /** Which aspect(s) of the texture are accessible to the texture view. default \"all\"*/\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n /** The first (most detailed) mipmap level accessible to the texture view. default 0*/\n baseMipLevel?: number;\n /** How many mipmap levels, starting with baseMipLevel, are accessible to the texture view. */\n mipLevelCount: number;\n /** The index of the first array layer accessible to the texture view. default 0 */\n baseArrayLayer?: number;\n /** How many array layers, starting with baseArrayLayer, are accessible to the texture view. */\n arrayLayerCount: number;\n};\n\n/** Immutable TextureView object */\nexport abstract class TextureView extends Resource<TextureViewProps> {\n abstract texture: Texture;\n\n override get [Symbol.toStringTag](): string {\n return 'TextureView';\n }\n\n /** Should not be constructed directly. Use `texture.createView(props)` */\n constructor(device: Device, props: TextureViewProps & {texture: Texture}) {\n super(device, props, TextureView.defaultProps);\n }\n\n static override defaultProps: Required<TextureViewProps> = {\n ...Resource.defaultProps,\n format: undefined!,\n dimension: undefined!,\n aspect: 'all',\n baseMipLevel: 0,\n mipLevelCount: undefined!,\n baseArrayLayer: 0,\n arrayLayerCount: undefined!\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\nexport type ExternalTextureProps = ResourceProps & {\n source: HTMLVideoElement; // | null;\n colorSpace?: 'srgb';\n};\nexport abstract class ExternalTexture extends Resource<ExternalTextureProps> {\n override get [Symbol.toStringTag](): string {\n return 'ExternalTexture';\n }\n\n constructor(device: Device, props: ExternalTextureProps) {\n super(device, props, ExternalTexture.defaultProps);\n }\n\n static override defaultProps: Required<ExternalTextureProps> = {\n ...Resource.defaultProps,\n source: undefined!,\n colorSpace: 'srgb'\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CompilerMessage} from '../adapter/types/compiler-message';\n\n/** @returns annotated errors or warnings */\nexport function formatCompilerLog(\n shaderLog: readonly CompilerMessage[],\n source: string,\n options?: {\n /** Include source code in the log. Either just the lines before issues or all source code */\n showSourceCode?: 'no' | 'issues' | 'all';\n html?: boolean;\n }\n): string {\n let formattedLog = '';\n const lines = source.split(/\\r?\\n/);\n const log = shaderLog.slice().sort((a, b) => a.lineNum - b.lineNum);\n\n switch (options?.showSourceCode || 'no') {\n case 'all':\n // Parse the error - note: browser and driver dependent\n let currentMessageIndex = 0;\n for (let lineNum = 1; lineNum <= lines.length; lineNum++) {\n const line = lines[lineNum - 1];\n const currentMessage = log[currentMessageIndex];\n if (line && currentMessage) {\n formattedLog += getNumberedLine(line, lineNum, options);\n }\n while (log.length > currentMessageIndex && currentMessage.lineNum === lineNum) {\n const message = log[currentMessageIndex++];\n if (message) {\n formattedLog += formatCompilerMessage(message, lines, message.lineNum, {\n ...options,\n inlineSource: false\n });\n }\n }\n }\n // Print any remaining messages\n while (log.length > currentMessageIndex) {\n const message = log[currentMessageIndex++];\n if (message) {\n formattedLog += formatCompilerMessage(message, [], 0, {\n ...options,\n inlineSource: false\n });\n }\n }\n return formattedLog;\n\n case 'issues':\n case 'no':\n // Parse the error - note: browser and driver dependent\n for (const message of shaderLog) {\n formattedLog += formatCompilerMessage(message, lines, message.lineNum, {\n inlineSource: options?.showSourceCode !== 'no'\n });\n }\n return formattedLog;\n }\n}\n\n// Helpers\n\n/** Format one message */\nfunction formatCompilerMessage(\n message: CompilerMessage,\n lines: readonly string[],\n lineNum: number,\n options: {\n inlineSource?: boolean;\n html?: boolean;\n }\n): string {\n if (options?.inlineSource) {\n const numberedLines = getNumberedLines(lines, lineNum);\n // If we got error position on line add a `^^^` indicator on next line\n const positionIndicator = message.linePos > 0 ? `${' '.repeat(message.linePos + 5)}^^^\\n` : '';\n return `\n${numberedLines}${positionIndicator}${message.type.toUpperCase()}: ${message.message}\n\n`;\n }\n const color = message.type === 'error' ? 'red' : 'orange';\n return options?.html\n ? `<div class='luma-compiler-log-${message.type}' style=\"color:${color};\"><b> ${message.type.toUpperCase()}: ${\n message.message\n }</b></div>`\n : `${message.type.toUpperCase()}: ${message.message}`;\n}\n\nfunction getNumberedLines(\n lines: readonly string[],\n lineNum: number,\n options?: {html?: boolean}\n): string {\n let numberedLines = '';\n for (let lineIndex = lineNum - 2; lineIndex <= lineNum; lineIndex++) {\n const sourceLine = lines[lineIndex - 1];\n if (sourceLine !== undefined) {\n numberedLines += getNumberedLine(sourceLine, lineNum, options);\n }\n }\n return numberedLines;\n}\n\nfunction getNumberedLine(line: string, lineNum: number, options?: {html?: boolean}): string {\n const escapedLine = options?.html ? escapeHTML(line) : line;\n return `${padLeft(String(lineNum), 4)}: ${escapedLine}${options?.html ? '<br/>' : '\\n'}`;\n}\n\n/**\n * Pads a string with a number of spaces (space characters) to the left\n * @param {String} string - string to pad\n * @param {Number} digits - number of spaces to add\n * @return {String} string - The padded string\n */\nfunction padLeft(string: string, paddedLength: number): string {\n let result = '';\n for (let i = string.length; i < paddedLength; ++i) {\n result += ' ';\n }\n return result + string;\n}\n\nfunction escapeHTML(unsafe: string): string {\n return unsafe\n .replaceAll('&', '&amp;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;')\n .replaceAll('\"', '&quot;')\n .replaceAll(\"'\", '&#039;');\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n// import { log } from '../../utils/log';\nimport {uid} from '../../utils/uid';\nimport {CompilerMessage} from '../types/compiler-message';\nimport {formatCompilerLog} from '../../adapter-utils/format-compiler-log';\n\n/**\n * Properties for a Shader\n */\nexport type ShaderProps = ResourceProps & {\n /** Shader language (defaults to auto) */\n language?: 'glsl' | 'wgsl' | 'auto';\n /** Which stage are we compiling? Required for GLSL. Ignored for WGSL. */\n stage?: 'vertex' | 'fragment' | 'compute';\n /** Shader source code */\n source: string;\n /** Optional shader source map (WebGPU only) */\n sourceMap?: string | null;\n /** Optional shader entry point (WebGPU only) */\n entryPoint?: string;\n /** Show shader source in browser? Overrides the device.props.debugShaders setting */\n debugShaders?: 'never' | 'errors' | 'warnings' | 'always';\n};\n\n/**\n * Immutable Shader object\n * In WebGPU the handle can be copied between threads\n */\nexport abstract class Shader extends Resource<ShaderProps> {\n override get [Symbol.toStringTag](): string {\n return 'Shader';\n }\n\n /** The stage of this shader */\n readonly stage: 'vertex' | 'fragment' | 'compute';\n /** The source code of this shader */\n readonly source: string;\n /** The compilation status of the shader. 'pending' if compilation is asynchronous, and on production */\n compilationStatus: 'pending' | 'success' | 'error' = 'pending';\n\n /** Create a new Shader instance */\n constructor(device: Device, props: ShaderProps) {\n props = {...props, debugShaders: props.debugShaders || device.props.debugShaders || 'errors'};\n super(device, {id: getShaderIdFromProps(props), ...props}, Shader.defaultProps);\n this.stage = this.props.stage;\n this.source = this.props.source;\n }\n\n abstract get asyncCompilationStatus(): Promise<'pending' | 'success' | 'error'>;\n\n /** Get compiler log asynchronously */\n abstract getCompilationInfo(): Promise<readonly CompilerMessage[]>;\n\n /** Get compiler log synchronously (WebGL only) */\n getCompilationInfoSync(): readonly CompilerMessage[] | null {\n return null;\n }\n\n /** Get translated shader source in host platform's native language (HLSL, GLSL, and even GLSL ES), if available */\n getTranslatedSource(): string | null {\n return null;\n }\n\n // PORTABLE HELPERS\n\n /** In browser logging of errors */\n async debugShader(): Promise<void> {\n const trigger = this.props.debugShaders;\n switch (trigger) {\n case 'never':\n return;\n case 'errors':\n // On WebGL - Don't extract the log unless errors\n if (this.compilationStatus === 'success') {\n return;\n }\n break;\n case 'warnings':\n case 'always':\n break;\n }\n\n const messages = await this.getCompilationInfo();\n if (trigger === 'warnings' && messages?.length === 0) {\n return;\n }\n this._displayShaderLog(messages, this.id);\n }\n\n // PRIVATE\n\n /**\n * In-browser UI logging of errors\n * TODO - this HTML formatting code should not be in Device, should be pluggable\n */\n protected _displayShaderLog(messages: readonly CompilerMessage[], shaderId: string): void {\n // Return if under Node.js / incomplete `document` polyfills\n if (typeof document === 'undefined' || !document?.createElement) {\n return;\n }\n\n const shaderName: string = shaderId; // getShaderName(this.source) || ;\n const shaderTitle: string = `${this.stage} shader \"${shaderName}\"`;\n const htmlLog = formatCompilerLog(messages, this.source, {showSourceCode: 'all', html: true});\n // Show translated source if available\n const translatedSource = this.getTranslatedSource();\n\n const container = document.createElement('div');\n container.innerHTML = `\\\n<h1>Compilation error in ${shaderTitle}</h1>\n<div style=\"display:flex;position:fixed;top:10px;right:20px;gap:2px;\">\n<button id=\"copy\">Copy source</button><br/>\n<button id=\"close\">Close</button>\n</div>\n<code><pre>${htmlLog}</pre></code>`;\n if (translatedSource) {\n container.innerHTML += `<br /><h1>Translated Source</h1><br /><br /><code><pre>${translatedSource}</pre></code>`;\n }\n container.style.top = '0';\n container.style.left = '0';\n container.style.background = 'white';\n container.style.position = 'fixed';\n container.style.zIndex = '9999';\n container.style.maxWidth = '100vw';\n container.style.maxHeight = '100vh';\n container.style.overflowY = 'auto';\n document.body.appendChild(container);\n const error = container.querySelector('.luma-compiler-log-error');\n error?.scrollIntoView();\n (container.querySelector('button#close') as HTMLButtonElement).onclick = () => {\n container.remove();\n };\n (container.querySelector('button#copy') as HTMLButtonElement).onclick = () => {\n navigator.clipboard.writeText(this.source);\n };\n }\n\n static override defaultProps: Required<ShaderProps> = {\n ...Resource.defaultProps,\n language: 'auto',\n stage: undefined!,\n source: '',\n sourceMap: null,\n entryPoint: 'main',\n debugShaders: undefined!\n };\n}\n\n// HELPERS\n\n/** Deduce an id, from shader source, or supplied id, or shader type */\nfunction getShaderIdFromProps(props: ShaderProps): string {\n return getShaderName(props.source) || props.id || uid(`unnamed ${props.stage}-shader`);\n}\n\n/** Extracts GLSLIFY style naming of shaders: `#define SHADER_NAME ...` */\nfunction getShaderName(shader: string, defaultName: string = 'unnamed'): string {\n const SHADER_NAME_REGEXP = /#define[\\s*]SHADER_NAME[\\s*]([A-Za-z0-9_-]+)[\\s*]/;\n const match = SHADER_NAME_REGEXP.exec(shader);\n return match?.[1] ?? defaultName;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n TextureFormatColor,\n TextureFormatDepthStencil,\n TextureFormat\n} from '../../shadertypes/texture-types/texture-formats';\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\nimport {Texture} from './texture';\nimport {TextureView} from './texture-view';\nimport {log} from '../../utils/log';\n\nexport type FramebufferProps = ResourceProps & {\n width?: number;\n height?: number;\n colorAttachments?: (TextureView | Texture | TextureFormatColor)[];\n depthStencilAttachment?: (TextureView | Texture | TextureFormatDepthStencil) | null;\n};\n\n/**\n * Create new textures with correct size for all attachments.\n * @note resize() destroys existing textures (if size has changed).\n */\nexport abstract class Framebuffer extends Resource<FramebufferProps> {\n override get [Symbol.toStringTag](): string {\n return 'Framebuffer';\n }\n\n /** Width of all attachments in this framebuffer */\n width: number;\n /** Height of all attachments in this framebuffer */\n height: number;\n /** Color attachments */\n abstract colorAttachments: TextureView[];\n /** Depth-stencil attachment, if provided */\n abstract depthStencilAttachment: TextureView | null;\n\n constructor(device: Device, props: FramebufferProps = {}) {\n super(device, props, Framebuffer.defaultProps);\n this.width = this.props.width;\n this.height = this.props.height;\n }\n\n /**\n * Create a copy of this framebuffer with new attached textures, with same props but of the specified size.\n * @note Does not copy contents of the attached textures.\n */\n clone(size?: {width: number; height: number}): Framebuffer {\n const colorAttachments = this.colorAttachments.map(colorAttachment =>\n colorAttachment.texture.clone(size)\n );\n\n const depthStencilAttachment =\n this.depthStencilAttachment && this.depthStencilAttachment.texture.clone(size);\n\n return this.device.createFramebuffer({\n ...this.props,\n ...size,\n colorAttachments,\n depthStencilAttachment\n });\n }\n\n /**\n * Resizes all attachments\n * @note resize() destroys existing textures (if size has changed).\n * @deprecated Use framebuffer.clone()\n */\n resize(size: {width: number; height: number}): void;\n resize(size: [width: number, height: number]): void;\n resize(): void;\n resize(size?: {width: number; height: number} | [width: number, height: number]): void {\n let updateSize: boolean = !size;\n if (size) {\n const [width, height] = Array.isArray(size) ? size : [size.width, size.height];\n updateSize = updateSize || height !== this.height || width !== this.width;\n this.width = width;\n this.height = height;\n }\n if (updateSize) {\n log.log(2, `Resizing framebuffer ${this.id} to ${this.width}x${this.height}`)();\n this.resizeAttachments(this.width, this.height);\n }\n }\n\n /** Auto creates any textures */\n protected autoCreateAttachmentTextures(): void {\n if (this.props.colorAttachments.length === 0 && !this.props.depthStencilAttachment) {\n throw new Error('Framebuffer has noattachments');\n }\n\n this.colorAttachments = this.props.colorAttachments.map((attachment, index) => {\n if (typeof attachment === 'string') {\n const texture = this.createColorTexture(attachment, index);\n this.attachResource(texture);\n return texture.view;\n }\n if (attachment instanceof Texture) {\n return attachment.view;\n }\n return attachment;\n });\n\n const attachment = this.props.depthStencilAttachment;\n if (attachment) {\n if (typeof attachment === 'string') {\n const texture = this.createDepthStencilTexture(attachment);\n this.attachResource(texture);\n this.depthStencilAttachment = texture.view;\n } else if (attachment instanceof Texture) {\n this.depthStencilAttachment = attachment.view;\n } else {\n this.depthStencilAttachment = attachment;\n }\n }\n }\n\n /** Create a color texture */\n protected createColorTexture(format: TextureFormat, index: number): Texture {\n return this.device.createTexture({\n id: `${this.id}-color-attachment-${index}`,\n usage: Texture.RENDER_ATTACHMENT,\n format,\n width: this.width,\n height: this.height,\n // TODO deprecated? - luma.gl v8 compatibility\n sampler: {\n magFilter: 'linear',\n minFilter: 'linear'\n }\n });\n }\n\n /** Create depth stencil texture */\n protected createDepthStencilTexture(format: TextureFormat): Texture {\n return this.device.createTexture({\n id: `${this.id}-depth-stencil-attachment`,\n usage: Texture.RENDER_ATTACHMENT,\n format,\n width: this.width,\n height: this.height\n });\n }\n\n /**\n * Default implementation of resize\n * Creates new textures with correct size for all attachments.\n * and destroys existing textures if owned\n */\n protected resizeAttachments(width: number, height: number): void {\n this.colorAttachments.forEach((colorAttachment, i) => {\n const resizedTexture = colorAttachment.texture.clone({\n width,\n height\n });\n this.destroyAttachedResource(colorAttachment);\n this.colorAttachments[i] = resizedTexture.view;\n this.attachResource(resizedTexture.view);\n });\n\n if (this.depthStencilAttachment) {\n const resizedTexture = this.depthStencilAttachment.texture.clone({\n width,\n height\n });\n this.destroyAttachedResource(this.depthStencilAttachment);\n this.depthStencilAttachment = resizedTexture.view;\n this.attachResource(resizedTexture);\n }\n\n this.updateAttachments();\n }\n\n /** Implementation is expected to update any underlying binding (WebGL framebuffer attachment) */\n protected abstract updateAttachments(): void;\n\n static override defaultProps: Required<FramebufferProps> = {\n ...Resource.defaultProps,\n width: 1,\n height: 1,\n colorAttachments: [], // ['rgba8unorm'],\n depthStencilAttachment: null // 'depth24plus-stencil8'\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {PrimitiveTopology, RenderPipelineParameters} from '../types/parameters';\nimport type {ShaderLayout, Bindings, BindingsByGroup} from '../types/shader-layout';\nimport type {BufferLayout} from '../types/buffer-layout';\nimport type {\n TextureFormatColor,\n TextureFormatDepthStencil\n} from '@luma.gl/core/shadertypes/texture-types/texture-formats';\nimport type {Shader} from './shader';\nimport type {SharedRenderPipeline} from './shared-render-pipeline';\nimport type {RenderPass} from './render-pass';\nimport {Resource, ResourceProps} from './resource';\nimport {VertexArray} from './vertex-array';\nimport {TransformFeedback} from './transform-feedback';\n\nexport type RenderPipelineProps = ResourceProps & {\n // Shaders and shader layout\n\n /** Compiled vertex shader */\n vs?: Shader | null;\n /** Name of vertex shader stage main function (defaults to 'main'). WGSL only */\n vertexEntryPoint?: string; //\n /** Constant values to apply to compiled vertex shader. Do not require re-compilation. (WGSL only) */\n vsConstants?: Record<string, number>; // WGSL only\n /** Compiled fragment shader */\n fs?: Shader | null;\n /** Name of fragment shader stage main function (defaults to 'main'). WGSL only */\n fragmentEntryPoint?: string; // WGSL only\n /** Constant values to apply to compiled fragment shader. Do not require re-compilation. (WGSL only) */\n fsConstants?: Record<string, number>;\n\n /** Describes the attributes and bindings exposed by the pipeline shader(s). */\n shaderLayout?: ShaderLayout | null;\n /** Describes the buffers accepted by this pipeline and how they are mapped to shader attributes. */\n bufferLayout?: BufferLayout[]; // Record<string, Omit<BufferLayout, 'name'>\n\n /** Determines how vertices are read from the 'vertex' attributes */\n topology?: PrimitiveTopology;\n\n // color attachment information (needed on WebGPU)\n\n /** Color attachments expected by this pipeline. Defaults to [device.preferredColorFormat]. Array needs not be contiguous. */\n colorAttachmentFormats?: (TextureFormatColor | null)[];\n /** Depth attachment expected by this pipeline. Defaults to device.preferredDepthFormat, if depthWriteEnables parameter is set */\n depthStencilAttachmentFormat?: TextureFormatDepthStencil;\n\n /** Parameters that are controlled by pipeline */\n parameters?: RenderPipelineParameters;\n\n /** Transform feedback varyings captured when linking a WebGL render pipeline. WebGL only. */\n varyings?: string[];\n /** Transform feedback buffer mode used when linking a WebGL render pipeline. WebGL only. */\n bufferMode?: number;\n\n /** Some applications intentionally supply unused attributes and bindings, and want to disable warnings */\n disableWarnings?: boolean;\n\n /** Internal hook for backend-specific shared pipeline implementations. */\n _sharedRenderPipeline?: SharedRenderPipeline;\n\n // Dynamic bindings (TODO - pipelines should be immutable, move to RenderPass)\n /** Buffers, Textures, Samplers for the shader bindings */\n bindings?: Bindings;\n /** Bindings grouped by bind-group index */\n bindGroups?: BindingsByGroup;\n};\n\n/**\n * A compiled and linked shader program\n */\nexport abstract class RenderPipeline extends Resource<RenderPipelineProps> {\n override get [Symbol.toStringTag](): string {\n return 'RenderPipeline';\n }\n\n abstract readonly vs: Shader;\n abstract readonly fs: Shader | null;\n\n /** The merged layout */\n shaderLayout: ShaderLayout;\n /** Buffer map describing buffer interleaving etc */\n readonly bufferLayout: BufferLayout[];\n /** The linking status of the pipeline. 'pending' if linking is asynchronous, and on production */\n linkStatus: 'pending' | 'success' | 'error' = 'pending';\n /** The hash of the pipeline */\n hash: string = '';\n /** Optional shared backend implementation */\n sharedRenderPipeline: SharedRenderPipeline | null = null;\n\n /** Whether shader or pipeline compilation/linking is still in progress */\n get isPending(): boolean {\n return (\n this.linkStatus === 'pending' ||\n this.vs.compilationStatus === 'pending' ||\n this.fs?.compilationStatus === 'pending'\n );\n }\n\n /** Whether shader or pipeline compilation/linking has failed */\n get isErrored(): boolean {\n return (\n this.linkStatus === 'error' ||\n this.vs.compilationStatus === 'error' ||\n this.fs?.compilationStatus === 'error'\n );\n }\n\n constructor(device: Device, props: RenderPipelineProps) {\n super(device, props, RenderPipeline.defaultProps);\n this.shaderLayout = this.props.shaderLayout!;\n this.bufferLayout = this.props.bufferLayout || [];\n this.sharedRenderPipeline = this.props._sharedRenderPipeline || null;\n }\n\n /** Draw call. Returns false if the draw call was aborted (due to resources still initializing) */\n abstract draw(options: {\n /** Render pass to draw into (targeting screen or framebuffer) */\n renderPass?: RenderPass;\n /** Parameters to be set during draw call. Note that most parameters can only be overridden in WebGL. */\n parameters?: RenderPipelineParameters;\n /** Topology. Note can only be overridden in WebGL. */\n topology?: PrimitiveTopology;\n /** vertex attributes */\n vertexArray: VertexArray;\n /** Use instanced rendering? */\n isInstanced?: boolean;\n /** Number of \"rows\" in 'instance' buffers */\n instanceCount?: number;\n /** Number of \"rows\" in 'vertex' buffers */\n vertexCount?: number;\n /** Number of \"rows\" in index buffer */\n indexCount?: number;\n /** First vertex to draw from */\n firstVertex?: number;\n /** First index to draw from */\n firstIndex?: number;\n /** First instance to draw from */\n firstInstance?: number;\n baseVertex?: number;\n /** Transform feedback. WebGL only. */\n transformFeedback?: TransformFeedback;\n /** Bindings applied for this draw (textures, samplers, uniform buffers) */\n bindings?: Bindings;\n /** Bindings grouped by bind-group index */\n bindGroups?: BindingsByGroup;\n /** Optional stable cache keys for backend bind-group reuse */\n _bindGroupCacheKeys?: Partial<Record<number, object>>;\n /** WebGL-only uniforms */\n uniforms?: Record<string, unknown>;\n }): boolean;\n\n static override defaultProps: Required<RenderPipelineProps> = {\n ...Resource.defaultProps,\n\n vs: null,\n vertexEntryPoint: 'vertexMain',\n vsConstants: {},\n\n fs: null,\n fragmentEntryPoint: 'fragmentMain',\n fsConstants: {},\n\n shaderLayout: null,\n bufferLayout: [],\n topology: 'triangle-list',\n\n colorAttachmentFormats: undefined!,\n depthStencilAttachmentFormat: undefined!,\n\n parameters: {},\n varyings: undefined!,\n bufferMode: undefined!,\n disableWarnings: false,\n _sharedRenderPipeline: undefined!,\n bindings: undefined!,\n bindGroups: undefined!\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport type {Shader} from './shader';\nimport {Resource, type ResourceProps} from './resource';\n\nexport type SharedRenderPipelineProps = ResourceProps & {\n handle?: unknown;\n vs: Shader;\n fs: Shader;\n varyings?: string[];\n bufferMode?: number;\n};\n\n/**\n * Internal base class for backend-specific shared render-pipeline implementations.\n * Backends may use this to share expensive linked/program state across multiple\n * `RenderPipeline` wrappers.\n */\nexport abstract class SharedRenderPipeline extends Resource<SharedRenderPipelineProps> {\n override get [Symbol.toStringTag](): string {\n return 'SharedRenderPipeline';\n }\n\n abstract override readonly device: Device;\n abstract override readonly handle: unknown;\n\n constructor(device: Device, props: SharedRenderPipelineProps) {\n super(device, props, {\n ...Resource.defaultProps,\n handle: undefined!,\n vs: undefined!,\n fs: undefined!,\n varyings: undefined!,\n bufferMode: undefined!\n });\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Resource, ResourceProps} from './resource';\nimport type {ComputeShaderLayout, Bindings, BindingsByGroup} from '../types/shader-layout';\nimport type {Device} from '../device';\nimport type {Shader} from './shader';\n\n/**\n * Properties for a compute pipeline\n */\nexport type ComputePipelineProps = ResourceProps & {\n handle?: unknown;\n /** Compiled shader object */\n shader: Shader;\n /** The entry point, defaults to main */\n entryPoint?: string;\n /** These are WGSL constant values - different from GLSL defines in that shader does not need to be recompiled */\n constants?: Record<string, number>;\n /** Describes the attributes and bindings exposed by the pipeline shader(s). */\n shaderLayout?: ComputeShaderLayout | null;\n};\n\n/**\n * A compiled and linked shader program for compute\n */\nexport abstract class ComputePipeline extends Resource<ComputePipelineProps> {\n override get [Symbol.toStringTag](): string {\n return 'ComputePipeline';\n }\n\n hash: string = '';\n /** The merged shader layout */\n shaderLayout: ComputeShaderLayout;\n\n constructor(device: Device, props: ComputePipelineProps) {\n super(device, props, ComputePipeline.defaultProps);\n this.shaderLayout = props.shaderLayout!;\n }\n\n /**\n * @todo Use renderpass.setBindings() ?\n * @todo Do we want to expose BindGroups in the API and remove this?\n */\n abstract setBindings(bindings: Bindings | BindingsByGroup): void;\n\n static override defaultProps: Required<ComputePipelineProps> = {\n ...Resource.defaultProps,\n shader: undefined!,\n entryPoint: undefined!,\n constants: {},\n shaderLayout: undefined!\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../adapter/device';\nimport {ComputePipeline, type ComputePipelineProps} from '../adapter/resources/compute-pipeline';\nimport {RenderPipeline, type RenderPipelineProps} from '../adapter/resources/render-pipeline';\nimport {Resource} from '../adapter/resources/resource';\nimport type {SharedRenderPipeline} from '../adapter/resources/shared-render-pipeline';\nimport {log} from '../utils/log';\nimport {uid} from '../utils/uid';\nimport type {CoreModuleState} from './core-module-state';\n\nexport type PipelineFactoryProps = RenderPipelineProps;\n\ntype CacheItem<ResourceT extends Resource<any>> = {resource: ResourceT; useCount: number};\n\n/**\n * Efficiently creates / caches pipelines\n */\nexport class PipelineFactory {\n static defaultProps: Required<PipelineFactoryProps> = {...RenderPipeline.defaultProps};\n\n /** Get the singleton default pipeline factory for the specified device */\n static getDefaultPipelineFactory(device: Device): PipelineFactory {\n const moduleData = device.getModuleData<CoreModuleState>('@luma.gl/core');\n moduleData.defaultPipelineFactory ||= new PipelineFactory(device);\n return moduleData.defaultPipelineFactory;\n }\n\n readonly device: Device;\n\n private _hashCounter: number = 0;\n private readonly _hashes: Record<string, number> = {};\n private readonly _renderPipelineCache: Record<string, CacheItem<RenderPipeline>> = {};\n private readonly _computePipelineCache: Record<string, CacheItem<ComputePipeline>> = {};\n private readonly _sharedRenderPipelineCache: Record<string, CacheItem<SharedRenderPipeline>> = {};\n\n get [Symbol.toStringTag](): string {\n return 'PipelineFactory';\n }\n\n toString(): string {\n return `PipelineFactory(${this.device.id})`;\n }\n\n constructor(device: Device) {\n this.device = device;\n }\n\n /**\n * WebGL has two cache layers with different priorities:\n * - `_sharedRenderPipelineCache` owns `WEBGLSharedRenderPipeline` / `WebGLProgram` reuse.\n * - `_renderPipelineCache` owns `RenderPipeline` wrapper reuse.\n *\n * Shared WebGL program reuse is the hard requirement. Wrapper reuse is beneficial,\n * but wrapper cache misses are acceptable if that keeps the cache logic simple and\n * prevents incorrect cache hits.\n *\n * In particular, wrapper hash logic must never force program creation or linked-program\n * introspection just to decide whether a shared WebGL program can be reused.\n */\n /** Return a RenderPipeline matching supplied props. Reuses an equivalent pipeline if already created. */\n createRenderPipeline(props: RenderPipelineProps): RenderPipeline {\n if (!this.device.props._cachePipelines) {\n return this.device.createRenderPipeline(props);\n }\n\n const allProps: Required<RenderPipelineProps> = {...RenderPipeline.defaultProps, ...props};\n\n const cache = this._renderPipelineCache;\n const hash = this._hashRenderPipeline(allProps);\n\n let pipeline: RenderPipeline = cache[hash]?.resource;\n if (!pipeline) {\n const sharedRenderPipeline =\n this.device.type === 'webgl' && this.device.props._sharePipelines\n ? this.createSharedRenderPipeline(allProps)\n : undefined;\n pipeline = this.device.createRenderPipeline({\n ...allProps,\n id: allProps.id ? `${allProps.id}-cached` : uid('unnamed-cached'),\n _sharedRenderPipeline: sharedRenderPipeline\n });\n pipeline.hash = hash;\n cache[hash] = {resource: pipeline, useCount: 1};\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} created, count=${cache[hash].useCount}`)();\n }\n } else {\n cache[hash].useCount++;\n if (this.device.props.debugFactories) {\n log.log(\n 3,\n `${this}: ${cache[hash].resource} reused, count=${cache[hash].useCount}, (id=${props.id})`\n )();\n }\n }\n\n return pipeline;\n }\n\n /** Return a ComputePipeline matching supplied props. Reuses an equivalent pipeline if already created. */\n createComputePipeline(props: ComputePipelineProps): ComputePipeline {\n if (!this.device.props._cachePipelines) {\n return this.device.createComputePipeline(props);\n }\n\n const allProps: Required<ComputePipelineProps> = {...ComputePipeline.defaultProps, ...props};\n\n const cache = this._computePipelineCache;\n const hash = this._hashComputePipeline(allProps);\n\n let pipeline: ComputePipeline = cache[hash]?.resource;\n if (!pipeline) {\n pipeline = this.device.createComputePipeline({\n ...allProps,\n id: allProps.id ? `${allProps.id}-cached` : undefined\n });\n pipeline.hash = hash;\n cache[hash] = {resource: pipeline, useCount: 1};\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} created, count=${cache[hash].useCount}`)();\n }\n } else {\n cache[hash].useCount++;\n if (this.device.props.debugFactories) {\n log.log(\n 3,\n `${this}: ${cache[hash].resource} reused, count=${cache[hash].useCount}, (id=${props.id})`\n )();\n }\n }\n\n return pipeline;\n }\n\n release(pipeline: RenderPipeline | ComputePipeline): void {\n if (!this.device.props._cachePipelines) {\n pipeline.destroy();\n return;\n }\n\n const cache = this._getCache(pipeline);\n const hash = pipeline.hash;\n\n cache[hash].useCount--;\n if (cache[hash].useCount === 0) {\n this._destroyPipeline(pipeline);\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} released and destroyed`)();\n }\n } else if (cache[hash].useCount < 0) {\n log.error(`${this}: ${pipeline} released, useCount < 0, resetting`)();\n cache[hash].useCount = 0;\n } else if (this.device.props.debugFactories) {\n log.log(3, `${this}: ${pipeline} released, count=${cache[hash].useCount}`)();\n }\n }\n\n createSharedRenderPipeline(props: RenderPipelineProps): SharedRenderPipeline {\n const sharedPipelineHash = this._hashSharedRenderPipeline(props);\n let sharedCacheItem = this._sharedRenderPipelineCache[sharedPipelineHash];\n if (!sharedCacheItem) {\n const sharedRenderPipeline = this.device._createSharedRenderPipelineWebGL(props);\n sharedCacheItem = {resource: sharedRenderPipeline, useCount: 0};\n this._sharedRenderPipelineCache[sharedPipelineHash] = sharedCacheItem;\n }\n sharedCacheItem.useCount++;\n return sharedCacheItem.resource;\n }\n\n releaseSharedRenderPipeline(pipeline: RenderPipeline): void {\n if (!pipeline.sharedRenderPipeline) {\n return;\n }\n\n const sharedPipelineHash = this._hashSharedRenderPipeline(pipeline.sharedRenderPipeline.props);\n const sharedCacheItem = this._sharedRenderPipelineCache[sharedPipelineHash];\n if (!sharedCacheItem) {\n return;\n }\n\n sharedCacheItem.useCount--;\n if (sharedCacheItem.useCount === 0) {\n sharedCacheItem.resource.destroy();\n delete this._sharedRenderPipelineCache[sharedPipelineHash];\n }\n }\n\n // PRIVATE\n\n /** Destroy a cached pipeline, removing it from the cache if configured to do so. */\n private _destroyPipeline(pipeline: RenderPipeline | ComputePipeline): boolean {\n const cache = this._getCache(pipeline);\n\n if (!this.device.props._destroyPipelines) {\n return false;\n }\n\n delete cache[pipeline.hash];\n pipeline.destroy();\n if (pipeline instanceof RenderPipeline) {\n this.releaseSharedRenderPipeline(pipeline);\n }\n return true;\n }\n\n /** Get the appropriate cache for the type of pipeline */\n private _getCache(\n pipeline: RenderPipeline | ComputePipeline\n ): Record<string, CacheItem<RenderPipeline>> | Record<string, CacheItem<ComputePipeline>> {\n let cache:\n | Record<string, CacheItem<RenderPipeline>>\n | Record<string, CacheItem<ComputePipeline>>\n | undefined;\n if (pipeline instanceof ComputePipeline) {\n cache = this._computePipelineCache;\n }\n if (pipeline instanceof RenderPipeline) {\n cache = this._renderPipelineCache;\n }\n if (!cache) {\n throw new Error(`${this}`);\n }\n if (!cache[pipeline.hash]) {\n throw new Error(`${this}: ${pipeline} matched incorrect entry`);\n }\n return cache;\n }\n\n /** Calculate a hash based on all the inputs for a compute pipeline */\n private _hashComputePipeline(props: ComputePipelineProps): string {\n const {type} = this.device;\n const shaderHash = this._getHash(props.shader.source);\n const shaderLayoutHash = this._getHash(JSON.stringify(props.shaderLayout));\n return `${type}/C/${shaderHash}SL${shaderLayoutHash}`;\n }\n\n /** Calculate a hash based on all the inputs for a render pipeline */\n private _hashRenderPipeline(props: RenderPipelineProps): string {\n // Backend-specific hashing requirements:\n // - WebGPU hash keys must include every immutable descriptor-shaping input that can\n // change the created `GPURenderPipeline`, including attachment formats.\n // - WebGL hash keys only govern wrapper reuse. They must remain compatible with\n // shared-program reuse and must not depend on linked-program introspection just\n // to decide whether a shared `WebGLProgram` can be reused.\n //\n // General exclusions:\n // - `id`, `handle`: resource identity / caller-supplied handles, not cache shape\n // - `bindings`: mutable per-pipeline compatibility state\n // - `disableWarnings`: logging only, no rendering impact\n // - `vsConstants`, `fsConstants`: currently unused by pipeline creation\n const vsHash = props.vs ? this._getHash(props.vs.source) : 0;\n const fsHash = props.fs ? this._getHash(props.fs.source) : 0;\n const varyingHash = this._getWebGLVaryingHash(props);\n const shaderLayoutHash = this._getHash(JSON.stringify(props.shaderLayout));\n const bufferLayoutHash = this._getHash(JSON.stringify(props.bufferLayout));\n\n const {type} = this.device;\n switch (type) {\n case 'webgl':\n // WebGL wrappers preserve default topology and parameter semantics for direct\n // callers, even though the underlying linked program may be shared separately.\n // Future WebGL-only additions here must not turn wrapper reuse into a prerequisite\n // for shared `WebGLProgram` reuse.\n const webglParameterHash = this._getHash(JSON.stringify(props.parameters));\n return `${type}/R/${vsHash}/${fsHash}V${varyingHash}T${props.topology}P${webglParameterHash}SL${shaderLayoutHash}BL${bufferLayoutHash}`;\n\n case 'webgpu':\n default:\n // On WebGPU we need to rebuild the pipeline if topology, entry points,\n // shader/layout data, parameters, bufferLayout or attachment formats change.\n // Attachment formats must stay in the key so screen and offscreen passes do not\n // accidentally alias the same cached `GPURenderPipeline`.\n const entryPointHash = this._getHash(\n JSON.stringify({\n vertexEntryPoint: props.vertexEntryPoint,\n fragmentEntryPoint: props.fragmentEntryPoint\n })\n );\n const parameterHash = this._getHash(JSON.stringify(props.parameters));\n const attachmentHash = this._getWebGPUAttachmentHash(props);\n // TODO - Can json.stringify() generate different strings for equivalent objects if order of params is different?\n // create a deepHash() to deduplicate?\n return `${type}/R/${vsHash}/${fsHash}V${varyingHash}T${props.topology}EP${entryPointHash}P${parameterHash}SL${shaderLayoutHash}BL${bufferLayoutHash}A${attachmentHash}`;\n }\n }\n\n // This is the only gate for shared `WebGLProgram` reuse.\n // Only include inputs that affect program linking or transform-feedback linkage.\n // Wrapper-only concerns such as topology, parameters, attachment formats and layout\n // overrides must not be added here.\n private _hashSharedRenderPipeline(props: RenderPipelineProps): string {\n const vsHash = props.vs ? this._getHash(props.vs.source) : 0;\n const fsHash = props.fs ? this._getHash(props.fs.source) : 0;\n const varyingHash = this._getWebGLVaryingHash(props);\n return `webgl/S/${vsHash}/${fsHash}V${varyingHash}`;\n }\n\n private _getHash(key: string): number {\n if (this._hashes[key] === undefined) {\n this._hashes[key] = this._hashCounter++;\n }\n return this._hashes[key];\n }\n\n private _getWebGLVaryingHash(props: RenderPipelineProps): number {\n const {varyings = [], bufferMode = null} = props;\n return this._getHash(JSON.stringify({varyings, bufferMode}));\n }\n\n private _getWebGPUAttachmentHash(props: RenderPipelineProps): number {\n const colorAttachmentFormats = props.colorAttachmentFormats ?? [\n this.device.preferredColorFormat\n ];\n const depthStencilAttachmentFormat = props.parameters?.depthWriteEnabled\n ? props.depthStencilAttachmentFormat || this.device.preferredDepthFormat\n : null;\n\n return this._getHash(\n JSON.stringify({\n colorAttachmentFormats,\n depthStencilAttachmentFormat\n })\n );\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../adapter/device';\nimport {Shader, type ShaderProps} from '../adapter/resources/shader';\nimport {log} from '../utils/log';\nimport type {CoreModuleState} from './core-module-state';\n\ntype CacheItem = {resource: Shader; useCount: number};\n\n/** Manages a cached pool of Shaders for reuse. */\nexport class ShaderFactory {\n static readonly defaultProps: Required<ShaderProps> = {...Shader.defaultProps};\n\n /** Returns the default ShaderFactory for the given {@link Device}, creating one if necessary. */\n static getDefaultShaderFactory(device: Device): ShaderFactory {\n const moduleData = device.getModuleData<CoreModuleState>('@luma.gl/core');\n moduleData.defaultShaderFactory ||= new ShaderFactory(device);\n return moduleData.defaultShaderFactory;\n }\n\n public readonly device: Device;\n\n private readonly _cache: Record<string, CacheItem> = {};\n\n get [Symbol.toStringTag](): string {\n return 'ShaderFactory';\n }\n\n toString(): string {\n return `${this[Symbol.toStringTag]}(${this.device.id})`;\n }\n\n /** @internal */\n constructor(device: Device) {\n this.device = device;\n }\n\n /** Requests a {@link Shader} from the cache, creating a new Shader only if necessary. */\n createShader(props: ShaderProps): Shader {\n if (!this.device.props._cacheShaders) {\n return this.device.createShader(props);\n }\n\n const key = this._hashShader(props);\n\n let cacheEntry = this._cache[key];\n if (!cacheEntry) {\n const resource = this.device.createShader({\n ...props,\n id: props.id ? `${props.id}-cached` : undefined\n });\n this._cache[key] = cacheEntry = {resource, useCount: 1};\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: Created new shader ${resource.id}`)();\n }\n } else {\n cacheEntry.useCount++;\n if (this.device.props.debugFactories) {\n log.log(\n 3,\n `${this}: Reusing shader ${cacheEntry.resource.id} count=${cacheEntry.useCount}`\n )();\n }\n }\n\n return cacheEntry.resource;\n }\n\n /** Releases a previously-requested {@link Shader}, destroying it if no users remain. */\n release(shader: Shader): void {\n if (!this.device.props._cacheShaders) {\n shader.destroy();\n return;\n }\n\n const key = this._hashShader(shader);\n const cacheEntry = this._cache[key];\n if (cacheEntry) {\n cacheEntry.useCount--;\n if (cacheEntry.useCount === 0) {\n if (this.device.props._destroyShaders) {\n delete this._cache[key];\n cacheEntry.resource.destroy();\n if (this.device.props.debugFactories) {\n log.log(3, `${this}: Releasing shader ${shader.id}, destroyed`)();\n }\n }\n } else if (cacheEntry.useCount < 0) {\n throw new Error(`ShaderFactory: Shader ${shader.id} released too many times`);\n } else if (this.device.props.debugFactories) {\n log.log(3, `${this}: Releasing shader ${shader.id} count=${cacheEntry.useCount}`)();\n }\n }\n }\n\n // PRIVATE\n\n protected _hashShader(value: Shader | ShaderProps): string {\n return `${value.stage}:${value.source}`;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n BindingDeclaration,\n Bindings,\n BindingsByGroup,\n ComputeShaderLayout,\n ShaderLayout\n} from '../adapter/types/shader-layout';\nimport {log} from '../utils/log';\n\ntype AnyShaderLayout = Pick<ShaderLayout | ComputeShaderLayout, 'bindings'>;\n\nexport function getShaderLayoutBinding(\n shaderLayout: AnyShaderLayout,\n bindingName: string,\n options?: {ignoreWarnings?: boolean}\n): BindingDeclaration | null {\n const bindingLayout = shaderLayout.bindings.find(\n binding =>\n binding.name === bindingName ||\n `${binding.name.toLocaleLowerCase()}uniforms` === bindingName.toLocaleLowerCase()\n );\n\n if (!bindingLayout && !options?.ignoreWarnings) {\n log.warn(`Binding ${bindingName} not set: Not found in shader layout.`)();\n }\n\n return bindingLayout || null;\n}\n\nexport function normalizeBindingsByGroup(\n shaderLayout: AnyShaderLayout,\n bindingsOrBindGroups?: Bindings | BindingsByGroup\n): BindingsByGroup {\n if (!bindingsOrBindGroups) {\n return {};\n }\n\n if (areBindingsGrouped(bindingsOrBindGroups)) {\n const bindGroups = bindingsOrBindGroups as BindingsByGroup;\n return Object.fromEntries(\n Object.entries(bindGroups).map(([group, bindings]) => [Number(group), {...bindings}])\n ) as BindingsByGroup;\n }\n\n const bindGroups: BindingsByGroup = {};\n for (const [bindingName, binding] of Object.entries(bindingsOrBindGroups as Bindings)) {\n const bindingLayout = getShaderLayoutBinding(shaderLayout, bindingName);\n const group = bindingLayout?.group ?? 0;\n bindGroups[group] ||= {};\n bindGroups[group][bindingName] = binding;\n }\n\n return bindGroups;\n}\n\nexport function flattenBindingsByGroup(bindGroups: BindingsByGroup): Bindings {\n const bindings: Bindings = {};\n for (const groupBindings of Object.values(bindGroups)) {\n Object.assign(bindings, groupBindings);\n }\n return bindings;\n}\n\nfunction areBindingsGrouped(bindingsOrBindGroups: Bindings | BindingsByGroup): boolean {\n const keys = Object.keys(bindingsOrBindGroups);\n return keys.length > 0 && keys.every(key => /^\\d+$/.test(key));\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {\n Bindings,\n BindingsByGroup,\n ComputeShaderLayout,\n ShaderLayout\n} from '../adapter/types/shader-layout';\nimport type {Device} from '../adapter/device';\nimport type {ComputePipeline} from '../adapter/resources/compute-pipeline';\nimport type {RenderPipeline} from '../adapter/resources/render-pipeline';\nimport {normalizeBindingsByGroup} from '../adapter-utils/bind-groups';\n\ntype AnyPipeline = RenderPipeline | ComputePipeline;\ntype AnyShaderLayout = ShaderLayout | ComputeShaderLayout;\ntype BindGroupCacheKeys = Partial<Record<number, object>>;\ntype BindGroupMap = Partial<Record<number, unknown>>;\ntype LayoutCache = Partial<Record<number, object>>;\ntype LayoutBindGroupCache = {\n bindGroupsBySource: WeakMap<object, unknown | null>;\n emptyBindGroup?: unknown;\n};\n\nexport class BindGroupFactory {\n readonly device: Device;\n\n private readonly _layoutCacheByPipeline: WeakMap<AnyPipeline, LayoutCache> = new WeakMap();\n private readonly _bindGroupCacheByLayout: WeakMap<object, LayoutBindGroupCache> = new WeakMap();\n\n constructor(device: Device) {\n this.device = device;\n }\n\n getBindGroups(\n pipeline: AnyPipeline,\n bindings?: Bindings | BindingsByGroup,\n bindGroupCacheKeys?: BindGroupCacheKeys\n ): BindGroupMap {\n if (this.device.type !== 'webgpu' || pipeline.shaderLayout.bindings.length === 0) {\n return {};\n }\n\n const bindingsByGroup = normalizeBindingsByGroup(pipeline.shaderLayout, bindings);\n const resolvedBindGroups: BindGroupMap = {};\n\n for (const group of getBindGroupIndicesUpToMax(pipeline.shaderLayout.bindings)) {\n const groupBindings = bindingsByGroup[group];\n const bindGroupLayout = this._getBindGroupLayout(pipeline, group);\n const bindGroupLabel = getBindGroupLabel(pipeline, pipeline.shaderLayout, group);\n\n if (!groupBindings || Object.keys(groupBindings).length === 0) {\n if (!hasBindingsInGroup(pipeline.shaderLayout.bindings, group)) {\n resolvedBindGroups[group] = this._getEmptyBindGroup(\n bindGroupLayout,\n pipeline.shaderLayout,\n group,\n bindGroupLabel\n );\n }\n continue;\n }\n\n const bindGroupCacheKey = bindGroupCacheKeys?.[group];\n if (bindGroupCacheKey) {\n const layoutCache = this._getLayoutBindGroupCache(bindGroupLayout);\n if (layoutCache.bindGroupsBySource.has(bindGroupCacheKey)) {\n resolvedBindGroups[group] = layoutCache.bindGroupsBySource.get(bindGroupCacheKey) || null;\n continue;\n }\n\n const bindGroup = this.device._createBindGroupWebGPU(\n bindGroupLayout,\n pipeline.shaderLayout,\n groupBindings,\n group,\n bindGroupLabel\n );\n layoutCache.bindGroupsBySource.set(bindGroupCacheKey, bindGroup);\n resolvedBindGroups[group] = bindGroup;\n } else {\n resolvedBindGroups[group] = this.device._createBindGroupWebGPU(\n bindGroupLayout,\n pipeline.shaderLayout,\n groupBindings,\n group,\n bindGroupLabel\n );\n }\n }\n\n return resolvedBindGroups;\n }\n\n private _getBindGroupLayout(pipeline: AnyPipeline, group: number): object {\n let layoutCache = this._layoutCacheByPipeline.get(pipeline);\n if (!layoutCache) {\n layoutCache = {};\n this._layoutCacheByPipeline.set(pipeline, layoutCache);\n }\n\n layoutCache[group] ||= this.device._createBindGroupLayoutWebGPU(pipeline, group) as object;\n return layoutCache[group];\n }\n\n private _getEmptyBindGroup(\n bindGroupLayout: object,\n shaderLayout: AnyShaderLayout,\n group: number,\n label: string\n ): unknown {\n const layoutCache = this._getLayoutBindGroupCache(bindGroupLayout);\n layoutCache.emptyBindGroup ||=\n this.device._createBindGroupWebGPU(bindGroupLayout, shaderLayout, {}, group, label) || null;\n return layoutCache.emptyBindGroup;\n }\n\n private _getLayoutBindGroupCache(bindGroupLayout: object): LayoutBindGroupCache {\n let layoutCache = this._bindGroupCacheByLayout.get(bindGroupLayout);\n if (!layoutCache) {\n layoutCache = {bindGroupsBySource: new WeakMap()};\n this._bindGroupCacheByLayout.set(bindGroupLayout, layoutCache);\n }\n return layoutCache;\n }\n}\n\nexport function _getDefaultBindGroupFactory(device: Device): BindGroupFactory {\n device._factories.bindGroupFactory ||= new BindGroupFactory(device);\n return device._factories.bindGroupFactory as BindGroupFactory;\n}\n\nfunction getBindGroupIndicesUpToMax(bindings: AnyShaderLayout['bindings']): number[] {\n const maxGroup = bindings.reduce(\n (highestGroup, binding) => Math.max(highestGroup, binding.group),\n -1\n );\n return Array.from({length: maxGroup + 1}, (_, group) => group);\n}\n\nfunction hasBindingsInGroup(bindings: AnyShaderLayout['bindings'], group: number): boolean {\n return bindings.some(binding => binding.group === group);\n}\n\nfunction getBindGroupLabel(\n pipeline: AnyPipeline,\n shaderLayout: AnyShaderLayout,\n group: number\n): string {\n const bindingNames = shaderLayout.bindings\n .filter(binding => binding.group === group)\n .sort((left, right) => left.location - right.location)\n .map(binding => binding.name);\n const bindingSuffix = bindingNames.length > 0 ? bindingNames.join(',') : 'empty';\n return `${pipeline.id}/group${group}[${bindingSuffix}]`;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {NumberArray4, TypedArray} from '@math.gl/types';\nimport type {Device} from '../device';\nimport type {RenderPassParameters} from '../types/parameters';\n// import {Binding} from '../types/shader-layout';\nimport {Resource, ResourceProps} from './resource';\nimport {Framebuffer} from './framebuffer';\nimport {QuerySet} from './query-set';\n\n/**\n * Properties for a RenderPass instance is a required parameter to all draw calls.\n */\nexport type RenderPassProps = ResourceProps & {\n /** Framebuffer specifies which textures to render into. Default gets framebuffer from canvas context. */\n framebuffer?: Framebuffer | null;\n /** Control viewport, scissor rect, blend constant and stencil ref */\n parameters?: RenderPassParameters;\n\n // TODO - API needs to be able to control multiple render targets\n\n /** Clear value for color attachment, or false to preserve the previous value */\n clearColor?: NumberArray4 | TypedArray | false;\n /** Experimental: Clear color values for multiple color attachments. Must specify typed arrays. props.clearColor will be ignored. */\n clearColors?: (TypedArray | false)[];\n /** Clear value for depth attachment (true === `1`), or false to preserve the previous value. Must be between 0.0 (near) and 1.0 (far), inclusive. */\n clearDepth?: number | false;\n /** Clear value for stencil attachment (true === `0`), or false to preserve the previous value. Converted to the type and number of LSBs as the number of bits in the stencil aspect */\n clearStencil?: number | false;\n\n /** Indicates that the depth component is read only. */\n depthReadOnly?: boolean;\n /** Indicates that the stencil component is read only. */\n stencilReadOnly?: boolean;\n\n /** Whether to disable / discard the output of the rasterizer */\n discard?: boolean;\n\n /** QuerySet to write begin/end timestamps to */\n occlusionQuerySet?: QuerySet;\n /** QuerySet to write begin/end timestamps to */\n timestampQuerySet?: QuerySet;\n /** QuerySet index to write begin timestamp to. No timestamp is written if not provided. */\n beginTimestampIndex?: number;\n /** QuerySet index to write end timestamp to. No timestamp is written if not provided. */\n endTimestampIndex?: number;\n};\n\n/**\n * A RenderPass instance is a required parameter to all draw calls.\n *\n * It holds a combination of\n * - render targets (specified via a framebuffer)\n * - clear colors, read/write, discard information for the framebuffer attachments\n * - a couple of mutable parameters ()\n */\nexport abstract class RenderPass extends Resource<RenderPassProps> {\n /** TODO - should be [0, 0, 0, 0], update once deck.gl tests run clean */\n static defaultClearColor: [number, number, number, number] = [0, 0, 0, 1];\n /** Depth 1.0 represents the far plance */\n static defaultClearDepth = 1;\n /** Clears all stencil bits */\n static defaultClearStencil = 0;\n\n override get [Symbol.toStringTag](): string {\n return 'RenderPass';\n }\n\n constructor(device: Device, props: RenderPassProps) {\n props = RenderPass.normalizeProps(device, props);\n super(device, props, RenderPass.defaultProps);\n }\n\n /** Call when rendering is done in this pass. */\n abstract end(): void;\n\n /** A few parameters can be changed at any time (viewport, scissorRect, blendColor, stencilReference) */\n abstract setParameters(parameters: RenderPassParameters): void;\n\n // executeBundles(bundles: Iterable<GPURenderBundle>): void;\n\n /** Being an occlusion query. Value will be stored in the occlusionQuerySet at the index. Occlusion queries cannot be nested. */\n abstract beginOcclusionQuery(queryIndex: number): void;\n /** End an occlusion query. Stores result in the index specified in beginOcclusionQuery. */\n abstract endOcclusionQuery(): void;\n\n /** Begins a labeled debug group containing subsequent commands */\n abstract pushDebugGroup(groupLabel: string): void;\n /** Ends the labeled debug group most recently started by pushDebugGroup() */\n abstract popDebugGroup(): void;\n /** Marks a point in a stream of commands with a label */\n abstract insertDebugMarker(markerLabel: string): void;\n\n protected static normalizeProps(device: Device, props: RenderPassProps): RenderPassProps {\n return props;\n }\n\n /** Default properties for RenderPass */\n static override defaultProps: Required<RenderPassProps> = {\n ...Resource.defaultProps,\n framebuffer: null,\n parameters: undefined!,\n clearColor: RenderPass.defaultClearColor,\n clearColors: undefined!,\n clearDepth: RenderPass.defaultClearDepth,\n clearStencil: RenderPass.defaultClearStencil,\n depthReadOnly: false,\n stencilReadOnly: false,\n discard: false,\n\n occlusionQuerySet: undefined!,\n timestampQuerySet: undefined!,\n beginTimestampIndex: undefined!,\n endTimestampIndex: undefined!\n };\n}\n\n// TODO - Can we align WebGL implementation with WebGPU API?\n// In WebGPU the following methods are on the renderpass instead of the renderpipeline\n// luma.gl keeps them on the pipeline for now, but that has some issues.\n\n// abstract setPipeline(pipeline: RenderPipeline): void {}\n// abstract setIndexBuffer()\n// abstract setVertexBuffer(slot: number, buffer: Buffer, offset: number): void;\n// abstract setBindings(bindings: Record<string, Binding>): void;\n// abstract setParameters(parameters: RenderPassParameters);\n// abstract draw(options: {\n// abstract drawIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): void;\n// abstract drawIndexedIndirect(indirectBuffer: GPUBuffer, indirectOffset: number): void;\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Resource, ResourceProps} from './resource';\nimport {ComputePipeline} from './compute-pipeline';\nimport type {Device} from '../device';\nimport {Buffer} from './buffer';\nimport {QuerySet} from './query-set';\n\nexport type ComputePassProps = ResourceProps & {\n /** QuerySet to write beging/end timestamps to */\n timestampQuerySet?: QuerySet;\n /** QuerySet index to write begin timestamp to. No timestamp is written if not provided. */\n beginTimestampIndex?: number;\n /** QuerySet index to write end timestamp to. No timestamp is written if not provided. */\n endTimestampIndex?: number;\n};\n\nexport abstract class ComputePass extends Resource<ComputePassProps> {\n constructor(device: Device, props: ComputePassProps) {\n super(device, props, ComputePass.defaultProps);\n }\n\n abstract override destroy(): void;\n\n abstract end(): void;\n\n abstract setPipeline(pipeline: ComputePipeline): void;\n\n /** Sets an array of bindings (uniform buffers, samplers, textures, ...) */\n // abstract setBindings(bindings: Binding[]): void;\n\n /**\n * Dispatch work to be performed with the current ComputePipeline.\n * @param x X dimension of the grid of workgroups to dispatch.\n * @param y Y dimension of the grid of workgroups to dispatch.\n * @param z Z dimension of the grid of workgroups to dispatch.\n */\n abstract dispatch(x: number, y?: number, z?: number): void;\n\n /**\n * Dispatch work to be performed with the current ComputePipeline.\n * @param indirectBuffer buffer must be a tightly packed block of three 32-bit unsigned integer values (12 bytes total), given in the same order as the arguments for dispatch()\n * @param indirectOffset\n */\n abstract dispatchIndirect(indirectBuffer: Buffer, indirectOffset?: number): void;\n\n /** Begins a labeled debug group containing subsequent commands */\n abstract pushDebugGroup(groupLabel: string): void;\n /** Ends the labeled debug group most recently started by pushDebugGroup() */\n abstract popDebugGroup(): void;\n /** Marks a point in a stream of commands with a label */\n abstract insertDebugMarker(markerLabel: string): void;\n\n static override defaultProps: Required<ComputePassProps> = {\n ...Resource.defaultProps,\n timestampQuerySet: undefined!,\n beginTimestampIndex: undefined!,\n endTimestampIndex: undefined!\n };\n\n override get [Symbol.toStringTag](): string {\n return 'ComputePass';\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\n// import type {TypedArray} from '@math.gl/types';\nimport {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\nimport {QuerySet} from './query-set';\nimport {Buffer} from './buffer';\nimport {Texture} from './texture';\nimport type {RenderPass, RenderPassProps} from './render-pass';\nimport type {ComputePass, ComputePassProps} from './compute-pass';\nimport type {CommandBuffer, CommandBufferProps} from './command-buffer';\n\n// WEBGPU COMMAND ENCODER OPERATIONS\n\nexport type CopyBufferToBufferOptions = {\n sourceBuffer: Buffer;\n sourceOffset?: number;\n destinationBuffer: Buffer;\n destinationOffset?: number;\n size: number;\n};\n\nexport type CopyBufferToTextureOptions = {\n sourceBuffer: Buffer;\n byteOffset?: number;\n destinationTexture: Texture;\n mipLevel?: number; // = 0;\n origin?: [number, number, number];\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n bytesPerRow: number;\n rowsPerImage: number;\n size: [number, number, number];\n};\n\nexport type CopyTextureToBufferOptions = {\n /** Texture to copy to/from. */\n sourceTexture: Texture;\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n mipLevel?: number;\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to/from.\n * Together with `copySize`, defines the full copy sub-region.\n */\n /** Defines which aspects of the texture to copy to/from. */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n\n /** Width to copy */\n width?: number;\n height?: number;\n depthOrArrayLayers?: number;\n origin?: [number, number, number];\n\n /** Destination buffer */\n destinationBuffer: Buffer;\n /** Offset, in bytes, from the beginning of the buffer to the start of the image data (default 0) */\n byteOffset?: number;\n /**\n * The stride, in bytes, between the beginning of each block row and the subsequent block row.\n * Required if there are multiple block rows (i.e. the copy height or depth is more than one block).\n */\n bytesPerRow?: number;\n /**\n * Number of block rows per single image of the texture.\n * rowsPerImage &times; bytesPerRow is the stride, in bytes, between the beginning of each image of data and the subsequent image.\n * Required if there are multiple images (i.e. the copy depth is more than one).\n */\n rowsPerImage?: number;\n};\n\nexport type CopyTextureToTextureOptions = {\n /** Texture to copy to/from. */\n sourceTexture: Texture;\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n mipLevel?: number;\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy from. */\n origin?: [number, number, number];\n /** Defines which aspects of the {@link GPUImageCopyTexture#texture} to copy to/from. */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n\n /** Texture to copy to/from. */\n destinationTexture: Texture;\n /** Mip-map level of the texture to copy to/from. (Default 0) */\n destinationMipLevel?: number;\n /** Defines the origin of the copy - the minimum corner of the texture sub-region to copy to. */\n destinationOrigin?: [number, number, number];\n /** Defines which aspects of the {@link GPUImageCopyTexture#texture} to copy to/from. */\n destinationAspect?: 'all' | 'stencil-only' | 'depth-only';\n\n /** Width to copy */\n width?: number;\n height?: number;\n depthOrArrayLayers?: number;\n};\n\n// ADDITIONAL COMMAND ENCODER OPERATIONS DEFINED BY LUMA.GL\n\n/** Options for clearing a texture mip level */\nexport type ClearTextureOptions = {\n /** Texture to Clear. */\n texture: Texture;\n /** Mip-map level of the texture clear. (Default 0) */\n mipLevel?: number;\n /** Defines which aspects of the Texture to clear. */\n aspect?: 'all' | 'stencil-only' | 'depth-only';\n};\n\n// export type WriteBufferOptions = {\n// buffer: Buffer;\n// bufferOffset?: number;\n// data: BufferSource;\n// dataOffset?: number;\n// size?: number;\n// };\n\n// export type TextureWriteOptions = {\n// destination: Texture;\n// mipLevel?: number; // = 0;\n// origin?: [number, number, number] | number[];\n// aspect?: 'all' | 'stencil-only' | 'depth-only';\n// data: BufferSource;\n// // dataLayout;\n// offset: number;\n// bytesPerRow: number;\n// rowsPerImage: number;\n// size: [number, number, number] | number[];\n// };\n\nexport type CommandEncoderProps = ResourceProps & {\n measureExecutionTime?: boolean;\n timeProfilingQuerySet?: QuerySet | null;\n};\n\ntype PassWithTimestamps = {\n timestampQuerySet?: QuerySet;\n beginTimestampIndex?: number;\n endTimestampIndex?: number;\n};\n\n/**\n * Records commands onto a single backend command encoder and can finish them into one command\n * buffer. Resource helpers invoked through a CommandEncoder must record onto that encoder rather\n * than allocating hidden encoders or submitting work eagerly.\n */\nexport abstract class CommandEncoder extends Resource<CommandEncoderProps> {\n override get [Symbol.toStringTag](): string {\n return 'CommandEncoder';\n }\n\n protected _timeProfilingQuerySet: QuerySet | null = null;\n protected _timeProfilingSlotCount: number = 0;\n _gpuTimeMs?: number;\n\n constructor(device: Device, props: CommandEncoderProps) {\n super(device, props, CommandEncoder.defaultProps);\n this._timeProfilingQuerySet = props.timeProfilingQuerySet ?? null;\n this._timeProfilingSlotCount = 0;\n this._gpuTimeMs = undefined;\n }\n\n /** Completes recording of the commands sequence */\n abstract finish(props?: CommandBufferProps): CommandBuffer;\n\n /** Create a RenderPass using the default CommandEncoder */\n abstract beginRenderPass(props?: RenderPassProps): RenderPass;\n\n /** Create a ComputePass using the default CommandEncoder*/\n abstract beginComputePass(props?: ComputePassProps): ComputePass;\n\n /** Add a command that that copies data from a sub-region of a Buffer to a sub-region of another Buffer. */\n abstract copyBufferToBuffer(options: CopyBufferToBufferOptions): void;\n\n /** Add a command that copies data from a sub-region of a GPUBuffer to a sub-region of one or multiple continuous texture subresources. */\n abstract copyBufferToTexture(options: CopyBufferToTextureOptions): void;\n\n /** Add a command that copies data from a sub-region of one or multiple continuous texture subresources to a sub-region of a Buffer. */\n abstract copyTextureToBuffer(options: CopyTextureToBufferOptions): void;\n\n /** Add a command that copies data from a sub-region of one or multiple contiguous texture subresources to another sub-region of one or multiple continuous texture subresources. */\n abstract copyTextureToTexture(options: CopyTextureToTextureOptions): void;\n\n /** Add a command that clears a texture mip level. */\n // abstract clearTexture(options: ClearTextureOptions): void;\n\n // abstract readTexture(options: TextureReadOptions): Promise<TypedArray>;\n\n /** Reads results from a query set into a GPU buffer. Values are 64 bits so byteLength must be querySet.props.count * 8 */\n abstract resolveQuerySet(\n querySet: QuerySet,\n destination: Buffer,\n options?: {\n firstQuery?: number;\n queryCount?: number;\n destinationOffset?: number;\n }\n ): void;\n\n /**\n * Reads all resolved timestamp pairs on the current profiler query set and caches the sum\n * as milliseconds on this encoder.\n */\n async resolveTimeProfilingQuerySet(): Promise<void> {\n this._gpuTimeMs = undefined;\n\n if (!this._timeProfilingQuerySet) {\n return;\n }\n\n const pairCount = Math.floor(this._timeProfilingSlotCount / 2);\n if (pairCount <= 0) {\n return;\n }\n\n const queryCount = pairCount * 2;\n const results = await this._timeProfilingQuerySet.readResults({\n firstQuery: 0,\n queryCount\n });\n\n let totalDurationNanoseconds = 0n;\n for (let queryIndex = 0; queryIndex < queryCount; queryIndex += 2) {\n totalDurationNanoseconds += results[queryIndex + 1] - results[queryIndex];\n }\n\n this._gpuTimeMs = Number(totalDurationNanoseconds) / 1e6;\n }\n\n /** Returns the number of query slots consumed by automatic pass profiling on this encoder. */\n getTimeProfilingSlotCount(): number {\n return this._timeProfilingSlotCount;\n }\n\n getTimeProfilingQuerySet(): QuerySet | null {\n return this._timeProfilingQuerySet;\n }\n\n /** Internal helper for auto-assigning timestamp slots to render/compute passes on this encoder. */\n protected _applyTimeProfilingToPassProps<P extends PassWithTimestamps>(props?: P): P {\n const passProps = (props || {}) as P;\n\n if (!this._supportsTimestampQueries() || !this._timeProfilingQuerySet) {\n return passProps;\n }\n\n if (\n passProps.timestampQuerySet !== undefined ||\n passProps.beginTimestampIndex !== undefined ||\n passProps.endTimestampIndex !== undefined\n ) {\n return passProps;\n }\n\n const beginTimestampIndex = this._timeProfilingSlotCount;\n if (beginTimestampIndex + 1 >= this._timeProfilingQuerySet.props.count) {\n return passProps;\n }\n\n this._timeProfilingSlotCount += 2;\n\n return {\n ...passProps,\n timestampQuerySet: this._timeProfilingQuerySet,\n beginTimestampIndex,\n endTimestampIndex: beginTimestampIndex + 1\n };\n }\n\n protected _supportsTimestampQueries(): boolean {\n return this.device.features.has('timestamp-query');\n }\n\n /** Begins a labeled debug group containing subsequent commands */\n abstract pushDebugGroup(groupLabel: string): void;\n /** Ends the labeled debug group most recently started by pushDebugGroup() */\n abstract popDebugGroup(): void;\n /** Marks a point in a stream of commands with a label */\n abstract insertDebugMarker(markerLabel: string): void;\n\n // TODO - luma.gl has these on the device, should we align with WebGPU API?\n // beginRenderPass(GPURenderPassDescriptor descriptor): GPURenderPassEncoder;\n // beginComputePass(optional GPUComputePassDescriptor descriptor = {}): GPUComputePassEncoder;\n\n static override defaultProps: Required<CommandEncoderProps> = {\n ...Resource.defaultProps,\n measureExecutionTime: undefined!,\n timeProfilingQuerySet: undefined!\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\n// interface Queue {\n// submit(commandBuffers);\n\n// // onSubmittedWorkDone(): Promise<undefined>;\n\n// writeBuffer(options: WriteBufferOptions): void;\n// writeTexture(options: TextureWriteOptions): void;\n\n// // copyExternalImageToTexture(\n// // GPUImageCopyExternalImage source,\n// // GPUImageCopyTextureTagged destination,\n// // GPUExtent3D copySize\n// // ): void;\n// }\n\nexport type CommandBufferProps = ResourceProps & {};\n\n/**\n * Represents the finished contents of exactly one CommandEncoder. Backends may store native\n * command buffers or replayable command lists internally, but submission must preserve the same\n * recorded command ordering.\n */\nexport abstract class CommandBuffer extends Resource<CommandBufferProps> {\n override get [Symbol.toStringTag](): string {\n return 'CommandBuffer';\n }\n\n constructor(device: Device, props: CommandBufferProps) {\n super(device, props, CommandBuffer.defaultProps);\n }\n\n static override defaultProps: Required<CommandBufferProps> = {\n ...Resource.defaultProps\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {type PrimitiveDataType} from '../data-types/data-types';\nimport {\n type VariableShaderType,\n type AttributeShaderType,\n type VariableShaderTypeAlias,\n type AttributeShaderTypeAlias\n} from './shader-types';\n\n/** Information extracted from a VariableShaderType constant */\nexport type VariableShaderTypeInfo = {\n type: PrimitiveDataType;\n components: number;\n};\n\n/** Information extracted from a AttributeShaderType constant */\nexport type AttributeShaderTypeInfo = {\n /** WGSL-style primitive data type, f32, i32, u32 */\n primitiveType: PrimitiveDataType;\n /** Whether this is a normalized integer (that must be used as float) */\n components: 1 | 2 | 3 | 4;\n /** Length in bytes of the data for one vertex */\n byteLength?: number;\n /** Whether this is for integer or float vert */\n integer: boolean;\n /** Whether this data type is signed */\n signed: boolean;\n};\n\n/** Split a uniform type string into type and components */\nexport function getVariableShaderTypeInfo(\n format: VariableShaderType | VariableShaderTypeAlias\n): VariableShaderTypeInfo {\n const resolvedFormat = resolveVariableShaderTypeAlias(format);\n const decoded = UNIFORM_FORMATS[resolvedFormat];\n if (!decoded) {\n throw new Error(`Unsupported variable shader type: ${format}`);\n }\n return decoded;\n}\n\n/** Decodes a vertex type, returning byte length and flags (integer, signed, normalized) */\nexport function getAttributeShaderTypeInfo(\n attributeType: AttributeShaderType | AttributeShaderTypeAlias\n): AttributeShaderTypeInfo {\n const resolvedAttributeType = resolveAttributeShaderTypeAlias(attributeType);\n const decoded = TYPE_INFO[resolvedAttributeType];\n if (!decoded) {\n throw new Error(`Unsupported attribute shader type: ${attributeType}`);\n }\n const [primitiveType, components] = decoded;\n const integer: boolean = primitiveType === 'i32' || primitiveType === 'u32';\n const signed: boolean = primitiveType !== 'u32';\n\n const byteLength = PRIMITIVE_TYPE_SIZES[primitiveType] * components;\n return {\n primitiveType,\n components,\n byteLength,\n integer,\n signed\n };\n}\n\nexport class ShaderTypeDecoder {\n getVariableShaderTypeInfo(\n format: VariableShaderType | VariableShaderTypeAlias\n ): VariableShaderTypeInfo {\n return getVariableShaderTypeInfo(format);\n }\n\n getAttributeShaderTypeInfo(\n attributeType: AttributeShaderType | AttributeShaderTypeAlias\n ): AttributeShaderTypeInfo {\n return getAttributeShaderTypeInfo(attributeType);\n }\n\n makeShaderAttributeType(\n primitiveType: PrimitiveDataType,\n components: 1 | 2 | 3 | 4\n ): AttributeShaderType {\n return makeShaderAttributeType(primitiveType, components);\n }\n\n resolveAttributeShaderTypeAlias(\n alias: AttributeShaderTypeAlias | AttributeShaderType\n ): AttributeShaderType {\n return resolveAttributeShaderTypeAlias(alias);\n }\n\n resolveVariableShaderTypeAlias(\n alias: VariableShaderTypeAlias | VariableShaderType\n ): VariableShaderType {\n return resolveVariableShaderTypeAlias(alias);\n }\n}\n\nexport function makeShaderAttributeType(\n primitiveType: PrimitiveDataType,\n components: 1 | 2 | 3 | 4\n): AttributeShaderType {\n return components === 1 ? primitiveType : `vec${components}<${primitiveType}>`;\n}\n\nexport function resolveAttributeShaderTypeAlias(\n alias: AttributeShaderTypeAlias | AttributeShaderType\n): AttributeShaderType {\n return WGSL_ATTRIBUTE_TYPE_ALIAS_MAP[alias as AttributeShaderTypeAlias] || alias;\n}\n\nexport function resolveVariableShaderTypeAlias(\n alias: VariableShaderTypeAlias | VariableShaderType\n): VariableShaderType {\n return WGSL_VARIABLE_TYPE_ALIAS_MAP[alias as VariableShaderTypeAlias] || alias;\n}\n\n/** Decoder for luma.gl shader types */\nexport const shaderTypeDecoder = new ShaderTypeDecoder();\n\n// TABLES\n\nconst PRIMITIVE_TYPE_SIZES: Record<PrimitiveDataType, 2 | 4> = {\n f32: 4,\n f16: 2,\n i32: 4,\n u32: 4\n // 'bool-webgl': 4,\n};\n\n/** All valid shader attribute types. A table guarantees exhaustive list and fast execution */\nconst TYPE_INFO: Record<AttributeShaderType, [PrimitiveDataType, components: 1 | 2 | 3 | 4]> = {\n f32: ['f32', 1],\n 'vec2<f32>': ['f32', 2],\n 'vec3<f32>': ['f32', 3],\n 'vec4<f32>': ['f32', 4],\n f16: ['f16', 1],\n 'vec2<f16>': ['f16', 2],\n 'vec3<f16>': ['f16', 3],\n 'vec4<f16>': ['f16', 4],\n i32: ['i32', 1],\n 'vec2<i32>': ['i32', 2],\n 'vec3<i32>': ['i32', 3],\n 'vec4<i32>': ['i32', 4],\n u32: ['u32', 1],\n 'vec2<u32>': ['u32', 2],\n 'vec3<u32>': ['u32', 3],\n 'vec4<u32>': ['u32', 4]\n};\n\n/** @todo These tables are quite big, consider parsing type strings instead */\nconst UNIFORM_FORMATS: Record<VariableShaderType, {type: PrimitiveDataType; components: number}> = {\n f32: {type: 'f32', components: 1},\n f16: {type: 'f16', components: 1},\n i32: {type: 'i32', components: 1},\n u32: {type: 'u32', components: 1},\n // 'bool-webgl': {type: 'bool-webgl', components: 1},\n 'vec2<f32>': {type: 'f32', components: 2},\n 'vec3<f32>': {type: 'f32', components: 3},\n 'vec4<f32>': {type: 'f32', components: 4},\n 'vec2<f16>': {type: 'f16', components: 2},\n 'vec3<f16>': {type: 'f16', components: 3},\n 'vec4<f16>': {type: 'f16', components: 4},\n 'vec2<i32>': {type: 'i32', components: 2},\n 'vec3<i32>': {type: 'i32', components: 3},\n 'vec4<i32>': {type: 'i32', components: 4},\n 'vec2<u32>': {type: 'u32', components: 2},\n 'vec3<u32>': {type: 'u32', components: 3},\n 'vec4<u32>': {type: 'u32', components: 4},\n\n 'mat2x2<f32>': {type: 'f32', components: 4},\n 'mat2x3<f32>': {type: 'f32', components: 6},\n 'mat2x4<f32>': {type: 'f32', components: 8},\n 'mat3x2<f32>': {type: 'f32', components: 6},\n 'mat3x3<f32>': {type: 'f32', components: 9},\n 'mat3x4<f32>': {type: 'f32', components: 12},\n 'mat4x2<f32>': {type: 'f32', components: 8},\n 'mat4x3<f32>': {type: 'f32', components: 12},\n 'mat4x4<f32>': {type: 'f32', components: 16},\n\n 'mat2x2<f16>': {type: 'f16', components: 4},\n 'mat2x3<f16>': {type: 'f16', components: 6},\n 'mat2x4<f16>': {type: 'f16', components: 8},\n 'mat3x2<f16>': {type: 'f16', components: 6},\n 'mat3x3<f16>': {type: 'f16', components: 9},\n 'mat3x4<f16>': {type: 'f16', components: 12},\n 'mat4x2<f16>': {type: 'f16', components: 8},\n 'mat4x3<f16>': {type: 'f16', components: 12},\n 'mat4x4<f16>': {type: 'f16', components: 16},\n\n 'mat2x2<i32>': {type: 'i32', components: 4},\n 'mat2x3<i32>': {type: 'i32', components: 6},\n 'mat2x4<i32>': {type: 'i32', components: 8},\n 'mat3x2<i32>': {type: 'i32', components: 6},\n 'mat3x3<i32>': {type: 'i32', components: 9},\n 'mat3x4<i32>': {type: 'i32', components: 12},\n 'mat4x2<i32>': {type: 'i32', components: 8},\n 'mat4x3<i32>': {type: 'i32', components: 12},\n 'mat4x4<i32>': {type: 'i32', components: 16},\n\n 'mat2x2<u32>': {type: 'u32', components: 4},\n 'mat2x3<u32>': {type: 'u32', components: 6},\n 'mat2x4<u32>': {type: 'u32', components: 8},\n 'mat3x2<u32>': {type: 'u32', components: 6},\n 'mat3x3<u32>': {type: 'u32', components: 9},\n 'mat3x4<u32>': {type: 'u32', components: 12},\n 'mat4x2<u32>': {type: 'u32', components: 8},\n 'mat4x3<u32>': {type: 'u32', components: 12},\n 'mat4x4<u32>': {type: 'u32', components: 16}\n};\n\n/** Predeclared aliases @see https://www.w3.org/TR/WGSL/#vector-types */\nexport const WGSL_ATTRIBUTE_TYPE_ALIAS_MAP: Record<AttributeShaderTypeAlias, AttributeShaderType> =\n {\n vec2i: 'vec2<i32>',\n vec3i: 'vec3<i32>',\n vec4i: 'vec4<i32>',\n vec2u: 'vec2<u32>',\n vec3u: 'vec3<u32>',\n vec4u: 'vec4<u32>',\n vec2f: 'vec2<f32>',\n vec3f: 'vec3<f32>',\n vec4f: 'vec4<f32>',\n // Requires the f16 extension.\n vec2h: 'vec2<f16>',\n vec3h: 'vec3<f16>',\n vec4h: 'vec4<f16>'\n };\n\n/** @todo These tables are quite big, consider parsing alias strings instead */\nexport const WGSL_VARIABLE_TYPE_ALIAS_MAP: Record<VariableShaderTypeAlias, VariableShaderType> = {\n vec2i: 'vec2<i32>',\n vec3i: 'vec3<i32>',\n vec4i: 'vec4<i32>',\n vec2u: 'vec2<u32>',\n vec3u: 'vec3<u32>',\n vec4u: 'vec4<u32>',\n vec2f: 'vec2<f32>',\n vec3f: 'vec3<f32>',\n vec4f: 'vec4<f32>',\n vec2h: 'vec2<f16>',\n vec3h: 'vec3<f16>',\n vec4h: 'vec4<f16>',\n mat2x2f: 'mat2x2<f32>',\n mat2x3f: 'mat2x3<f32>',\n mat2x4f: 'mat2x4<f32>',\n mat3x2f: 'mat3x2<f32>',\n mat3x3f: 'mat3x3<f32>',\n mat3x4f: 'mat3x4<f32>',\n mat4x2f: 'mat4x2<f32>',\n mat4x3f: 'mat4x3<f32>',\n mat4x4f: 'mat4x4<f32>',\n\n mat2x2i: 'mat2x2<i32>',\n mat2x3i: 'mat2x3<i32>',\n mat2x4i: 'mat2x4<i32>',\n mat3x2i: 'mat3x2<i32>',\n mat3x3i: 'mat3x3<i32>',\n mat3x4i: 'mat3x4<i32>',\n mat4x2i: 'mat4x2<i32>',\n mat4x3i: 'mat4x3<i32>',\n mat4x4i: 'mat4x4<i32>',\n\n mat2x2u: 'mat2x2<u32>',\n mat2x3u: 'mat2x3<u32>',\n mat2x4u: 'mat2x4<u32>',\n mat3x2u: 'mat3x2<u32>',\n mat3x3u: 'mat3x3<u32>',\n mat3x4u: 'mat3x4<u32>',\n mat4x2u: 'mat4x2<u32>',\n mat4x3u: 'mat4x3<u32>',\n mat4x4u: 'mat4x4<u32>',\n\n mat2x2h: 'mat2x2<f16>',\n mat2x3h: 'mat2x3<f16>',\n mat2x4h: 'mat2x4<f16>',\n mat3x2h: 'mat3x2<f16>',\n mat3x3h: 'mat3x3<f16>',\n mat3x4h: 'mat3x4<f16>',\n mat4x2h: 'mat4x2<f16>',\n mat4x3h: 'mat4x3<f16>',\n mat4x4h: 'mat4x4<f16>'\n};\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {log} from '../utils/log';\nimport type {PrimitiveDataType, NormalizedDataType} from '../shadertypes/data-types/data-types';\nimport type {AttributeShaderType} from '../shadertypes/shader-types/shader-types';\nimport type {VertexFormat} from '../shadertypes/vertex-types/vertex-formats';\nimport {shaderTypeDecoder} from '../shadertypes/shader-types/shader-type-decoder';\nimport {vertexFormatDecoder} from '../shadertypes/vertex-types/vertex-format-decoder';\nimport type {ShaderLayout, AttributeDeclaration} from '../adapter/types/shader-layout';\nimport type {BufferLayout} from '../adapter/types/buffer-layout';\n\n/** Resolved info for a buffer / attribute combination to help backend configure it correctly */\nexport type AttributeInfo = {\n /** Attribute name */\n attributeName: string;\n /** Location in shader */\n location: number;\n /** Type / precision used in shader (buffer values may be converted) */\n shaderType: AttributeShaderType;\n /** Calculations are done in this type in the shader's attribute declaration */\n primitiveType: PrimitiveDataType;\n /** Components refer to the number of components in the shader's attribute declaration */\n shaderComponents: 1 | 2 | 3 | 4;\n /** It is the shader attribute declaration that determines whether GPU will process as integer or float */\n integer: boolean;\n\n /** BufferName */\n bufferName: string;\n /** Format of buffer data */\n vertexFormat: VertexFormat;\n /** Memory data type refers to the data type in the buffer */\n bufferDataType: NormalizedDataType;\n /** Components refer to the number of components in the buffer's vertex format */\n bufferComponents: 1 | 2 | 3 | 4;\n /** Normalization is encoded in the buffer layout's vertex format... */\n normalized: boolean;\n\n /** If not specified, the step mode is inferred from the attribute name in the shader (contains string instance) */\n stepMode: 'vertex' | 'instance';\n\n /** The byteOffset is encoded in or calculated from the buffer layout */\n byteOffset: number;\n /** The byteStride is encoded in or calculated from the buffer layout */\n byteStride: number;\n};\n\ntype BufferAttributeInfo = {\n attributeName: string;\n bufferName: string;\n stepMode?: 'vertex' | 'instance';\n vertexFormat: VertexFormat;\n byteOffset: number;\n byteStride: number;\n};\n\n/**\n * Map from \"attribute names\" to \"resolved attribute infos\"\n * containing information about both buffer layouts and shader attribute declarations\n */\nexport function getAttributeInfosFromLayouts(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[]\n): Record<string, AttributeInfo> {\n const attributeInfos: Record<string, AttributeInfo> = {};\n for (const attribute of shaderLayout.attributes) {\n const attributeInfo = getAttributeInfoFromLayouts(shaderLayout, bufferLayout, attribute.name);\n if (attributeInfo) {\n attributeInfos[attribute.name] = attributeInfo;\n }\n }\n return attributeInfos;\n}\n\n/**\n * Array indexed by \"location\" holding \"resolved attribute infos\"\n */\nexport function getAttributeInfosByLocation(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[],\n maxVertexAttributes: number = 16\n): AttributeInfo[] {\n const attributeInfos = getAttributeInfosFromLayouts(shaderLayout, bufferLayout);\n const locationInfos: AttributeInfo[] = new Array(maxVertexAttributes).fill(null);\n for (const attributeInfo of Object.values(attributeInfos)) {\n locationInfos[attributeInfo.location] = attributeInfo;\n }\n return locationInfos;\n}\n\n/**\n * Get the combined information from a shader layout and a buffer layout for a specific attribute\n */\nfunction getAttributeInfoFromLayouts(\n shaderLayout: ShaderLayout,\n bufferLayout: BufferLayout[],\n name: string\n): AttributeInfo | null {\n const shaderDeclaration = getAttributeFromShaderLayout(shaderLayout, name);\n const bufferMapping: BufferAttributeInfo | null = getAttributeFromBufferLayout(\n bufferLayout,\n name\n );\n\n // TODO should no longer happen\n if (!shaderDeclaration) {\n // || !bufferMapping\n return null;\n }\n\n const attributeTypeInfo = shaderTypeDecoder.getAttributeShaderTypeInfo(shaderDeclaration.type);\n const defaultVertexFormat = vertexFormatDecoder.getCompatibleVertexFormat(attributeTypeInfo);\n const vertexFormat = bufferMapping?.vertexFormat || defaultVertexFormat;\n const vertexFormatInfo = vertexFormatDecoder.getVertexFormatInfo(vertexFormat);\n\n return {\n attributeName: bufferMapping?.attributeName || shaderDeclaration.name,\n bufferName: bufferMapping?.bufferName || shaderDeclaration.name,\n location: shaderDeclaration.location,\n shaderType: shaderDeclaration.type,\n primitiveType: attributeTypeInfo.primitiveType,\n shaderComponents: attributeTypeInfo.components,\n vertexFormat,\n bufferDataType: vertexFormatInfo.type,\n bufferComponents: vertexFormatInfo.components,\n // normalized is a property of the buffer's vertex format\n normalized: vertexFormatInfo.normalized,\n // integer is a property of the shader declaration\n integer: attributeTypeInfo.integer,\n stepMode: bufferMapping?.stepMode || shaderDeclaration.stepMode || 'vertex',\n byteOffset: bufferMapping?.byteOffset || 0,\n byteStride: bufferMapping?.byteStride || 0\n };\n}\n\nfunction getAttributeFromShaderLayout(\n shaderLayout: ShaderLayout,\n name: string\n): AttributeDeclaration | null {\n const attribute = shaderLayout.attributes.find(attr => attr.name === name);\n if (!attribute) {\n log.warn(`shader layout attribute \"${name}\" not present in shader`);\n }\n return attribute || null;\n}\n\nfunction getAttributeFromBufferLayout(\n bufferLayouts: BufferLayout[],\n name: string\n): BufferAttributeInfo | null {\n // Check that bufferLayouts are valid (each either has format or attribute)\n checkBufferLayouts(bufferLayouts);\n\n let bufferLayoutInfo = getAttributeFromShortHand(bufferLayouts, name);\n if (bufferLayoutInfo) {\n return bufferLayoutInfo;\n }\n\n bufferLayoutInfo = getAttributeFromAttributesList(bufferLayouts, name);\n if (bufferLayoutInfo) {\n return bufferLayoutInfo;\n }\n\n // Didn't find...\n log.warn(`layout for attribute \"${name}\" not present in buffer layout`);\n return null;\n}\n\n/** Check that bufferLayouts are valid (each either has format or attribute) */\nfunction checkBufferLayouts(bufferLayouts: BufferLayout[]) {\n for (const bufferLayout of bufferLayouts) {\n if (\n (bufferLayout.attributes && bufferLayout.format) ||\n (!bufferLayout.attributes && !bufferLayout.format)\n ) {\n log.warn(`BufferLayout ${name} must have either 'attributes' or 'format' field`);\n }\n }\n}\n\n/** Get attribute from format shorthand if specified */\nfunction getAttributeFromShortHand(\n bufferLayouts: BufferLayout[],\n name: string\n): BufferAttributeInfo | null {\n for (const bufferLayout of bufferLayouts) {\n if (bufferLayout.format && bufferLayout.name === name) {\n return {\n attributeName: bufferLayout.name,\n bufferName: name,\n stepMode: bufferLayout.stepMode,\n vertexFormat: bufferLayout.format,\n // If offset is needed, use `attributes` field.\n byteOffset: 0,\n byteStride: bufferLayout.byteStride || 0\n };\n }\n }\n return null;\n}\n\n/**\n * Search attribute mappings (e.g. interleaved attributes) for buffer mapping.\n * Not the name of the buffer might be the same as one of the interleaved attributes.\n */\nfunction getAttributeFromAttributesList(\n bufferLayouts: BufferLayout[],\n name: string\n): BufferAttributeInfo | null {\n for (const bufferLayout of bufferLayouts) {\n let byteStride: number | undefined = bufferLayout.byteStride;\n\n // Calculate a default byte stride if not provided\n if (typeof bufferLayout.byteStride !== 'number') {\n for (const attributeMapping of bufferLayout.attributes || []) {\n const info = vertexFormatDecoder.getVertexFormatInfo(attributeMapping.format);\n // @ts-ignore\n byteStride += info.byteLength;\n }\n }\n\n const attributeMapping = bufferLayout.attributes?.find(mapping => mapping.attribute === name);\n if (attributeMapping) {\n return {\n attributeName: attributeMapping.attribute,\n bufferName: bufferLayout.name,\n stepMode: bufferLayout.stepMode,\n vertexFormat: attributeMapping.format,\n byteOffset: attributeMapping.byteOffset,\n // @ts-ignore\n byteStride\n };\n }\n }\n\n return null;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '../../types';\nimport {\n AttributeInfo,\n getAttributeInfosByLocation\n} from '../../adapter-utils/get-attribute-from-layouts';\nimport type {Device} from '../device';\nimport type {Buffer} from './buffer';\nimport type {RenderPass} from './render-pass';\nimport {Resource, ResourceProps} from './resource';\nimport {ShaderLayout} from '../types/shader-layout';\nimport {BufferLayout} from '../types/buffer-layout';\n\n/** Properties for initializing a VertexArray */\nexport type VertexArrayProps = ResourceProps & {\n shaderLayout: ShaderLayout;\n bufferLayout: BufferLayout[];\n};\n\n/**\n * Stores attribute bindings.\n * Makes it easy to share a render pipeline and use separate vertex arrays.\n * @note On WebGL, VertexArray allows non-constant bindings to be performed in advance\n * reducing the number of WebGL calls per draw call.\n * @note On WebGPU this is just a convenience class that collects the bindings.\n */\nexport abstract class VertexArray extends Resource<VertexArrayProps> {\n static override defaultProps: Required<VertexArrayProps> = {\n ...Resource.defaultProps,\n shaderLayout: undefined!,\n bufferLayout: []\n };\n\n override get [Symbol.toStringTag](): string {\n return 'VertexArray';\n }\n\n /** Max number of vertex attributes */\n readonly maxVertexAttributes: number;\n /** Attribute infos indexed by location - TODO only needed by webgl module? */\n protected readonly attributeInfos: AttributeInfo[];\n\n /** Index buffer */\n indexBuffer: Buffer | null = null;\n /** Attributes indexed by buffer slot */\n attributes: (Buffer | TypedArray | null)[];\n\n constructor(device: Device, props: VertexArrayProps) {\n super(device, props, VertexArray.defaultProps);\n this.maxVertexAttributes = device.limits.maxVertexAttributes;\n this.attributes = new Array(this.maxVertexAttributes).fill(null);\n this.attributeInfos = getAttributeInfosByLocation(\n props.shaderLayout,\n props.bufferLayout,\n this.maxVertexAttributes\n );\n }\n\n /** Set attributes (stored on pipeline and set before each call) */\n abstract setIndexBuffer(indices: Buffer | null): void;\n /** Set attributes (stored on pipeline and set before each call) */\n abstract setBuffer(bufferSlot: number, buffer: Buffer | null): void;\n\n abstract bindBeforeRender(renderPass: RenderPass): void;\n abstract unbindAfterRender(renderPass: RenderPass): void;\n\n // DEPRECATED METHODS\n\n /** @deprecated Set constant attributes (WebGL only) */\n setConstantWebGL(location: number, value: TypedArray | null): void {\n this.device.reportError(new Error('constant attributes not supported'), this)();\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {PrimitiveTopology} from '../types/parameters';\nimport {ShaderLayout} from '../types/shader-layout';\nimport type {Buffer} from './buffer';\nimport {Resource, ResourceProps} from './resource';\n\n/** For bindRange */\nexport type BufferRange = {\n buffer: Buffer;\n byteOffset?: number;\n byteLength?: number;\n};\n\n/** Configures a set of output buffers for pipeline (WebGL only) */\nexport type TransformFeedbackProps = ResourceProps & {\n /** Layout of shader (for varyings) */\n layout: ShaderLayout;\n /** Buffer bindings (for varyings) */\n buffers: Record<string, Buffer | BufferRange>;\n};\n\n/** Holds a set of output buffers for pipeline (WebGL only) */\nexport abstract class TransformFeedback extends Resource<TransformFeedbackProps> {\n static override defaultProps: Required<TransformFeedbackProps> = {\n ...Resource.defaultProps,\n layout: undefined!,\n buffers: {}\n };\n\n get [Symbol.toStringTag](): string {\n return 'TransformFeedback';\n }\n\n constructor(device: Device, props: TransformFeedbackProps) {\n super(device, props, TransformFeedback.defaultProps);\n }\n\n abstract begin(topology?: PrimitiveTopology): void;\n abstract end(): void;\n\n abstract setBuffers(buffers: Record<string, Buffer | BufferRange>): void;\n abstract setBuffer(locationOrName: string | number, bufferOrRange: Buffer | BufferRange): void;\n abstract getBuffer(locationOrName: string | number): Buffer | BufferRange | null;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, ResourceProps} from './resource';\n\n/**\n * Properties for creating a QuerySet\n * - 'timestamp' - query the GPU timestamp counter at the start and end of render passes\n * timestamp queries are available if the 'timestamp-query' feature is present.\n * - 'occlusion' - query the number of fragment samples that pass all per-fragment tests for a set of drawing commands\n * including scissor, sample mask, alpha to coverage, stencil, and depth tests\n */\nexport type QuerySetProps = ResourceProps & {\n /**\n * The type of query set\n * occlusion - query the number of fragment samples that pass all the per-fragment tests for a set of drawing commands, including scissor, sample mask, alpha to coverage, stencil, and depth tests\n * timestamp - query the GPU timestamp counter. Timestamp queries are available if the\n * `timestamp-query` feature is present.\n */\n type: 'occlusion' | 'timestamp';\n /** The number of queries managed by the query set */\n count: number;\n};\n\n/** Immutable QuerySet object */\nexport abstract class QuerySet extends Resource<QuerySetProps> {\n get [Symbol.toStringTag](): string {\n return 'QuerySet';\n }\n\n constructor(device: Device, props: QuerySetProps) {\n super(device, props, QuerySet.defaultProps);\n }\n\n static override defaultProps: Required<QuerySetProps> = {\n ...Resource.defaultProps,\n type: undefined!,\n count: undefined!\n };\n\n /**\n * Returns true if the requested result has been captured and can be read without blocking.\n * Backends may implement this conservatively.\n */\n abstract isResultAvailable(queryIndex?: number): boolean;\n\n /** Reads query results as 64-bit values. */\n abstract readResults(options?: {firstQuery?: number; queryCount?: number}): Promise<bigint[]>;\n\n /**\n * Reads a timestamp duration in milliseconds between a begin and end query index.\n * Portable duration profiling requires adjacent indices that identify one logical pair.\n */\n abstract readTimestampDuration(beginIndex: number, endIndex: number): Promise<number>;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {Device} from '../device';\nimport {Resource, type ResourceProps} from './resource';\n\nexport type FenceProps = ResourceProps;\n\n/** Synchronization primitive that resolves when GPU work is completed */\nexport abstract class Fence extends Resource<FenceProps> {\n static override defaultProps: Required<FenceProps> = {\n ...Resource.defaultProps\n };\n\n override get [Symbol.toStringTag](): string {\n return 'Fence';\n }\n\n /** Promise that resolves when the fence is signaled */\n abstract readonly signaled: Promise<void>;\n\n constructor(device: Device, props: FenceProps = {}) {\n super(device, props, Fence.defaultProps);\n }\n\n /** Destroy the fence and release any resources */\n abstract override destroy(): void;\n\n /** Check if the fence has been signaled */\n abstract isSignaled(): boolean;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {Device} from '../device';\nimport {ShaderLayout} from '../types/shader-layout';\nimport {Resource, ResourceProps} from './resource';\n\nexport type PipelineLayoutProps = ResourceProps & {\n shaderLayout: ShaderLayout;\n};\n\n/** Immutable PipelineLayout object */\nexport abstract class PipelineLayout extends Resource<PipelineLayoutProps> {\n get [Symbol.toStringTag](): string {\n return 'PipelineLayout';\n }\n\n constructor(device: Device, props: PipelineLayoutProps) {\n super(device, props, PipelineLayout.defaultProps);\n }\n\n static override defaultProps: Required<PipelineLayoutProps> = {\n ...Resource.defaultProps,\n shaderLayout: {\n attributes: [],\n bindings: []\n }\n };\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray, TypedArrayConstructor} from '../../types';\nimport {PrimitiveDataType, SignedDataType, NormalizedDataType, DataTypeInfo} from './data-types';\n\n/**\n * Gets info about a data type constant (signed or normalized)\n * @returns underlying primitive / signed types, byte length, normalization, integer, signed flags\n */\nexport function getDataTypeInfo(type: NormalizedDataType): DataTypeInfo {\n const normalized: boolean = type.includes('norm');\n const integer: boolean = !normalized && !type.startsWith('float');\n const signed: boolean = type.startsWith('s');\n const typeInfo = NORMALIZED_TYPE_MAP[type];\n const [signedType, primitiveType, byteLength] = typeInfo || ['uint8 ', 'i32', 1];\n return {\n signedType,\n primitiveType,\n byteLength,\n normalized,\n integer,\n signed\n };\n}\n\n/** Build a vertex format from a signed data type and a component */\nexport function getNormalizedDataType(signedDataType: SignedDataType): NormalizedDataType {\n const dataType: NormalizedDataType = signedDataType;\n // biome-ignore format: preserve layout\n switch (dataType) {\n case 'uint8': return 'unorm8';\n case 'sint8': return 'snorm8';\n case 'uint16': return 'unorm16';\n case 'sint16': return 'snorm16';\n default: return dataType;\n }\n}\n\n/** Align offset to 1, 2 or 4 elements (4, 8 or 16 bytes) */\nexport function alignTo(size: number, count: number): number {\n // biome-ignore format: preserve layout\n switch (count) {\n case 1: return size; // Pad upwards to even multiple of 2\n case 2: return size + (size % 2); // Pad upwards to even multiple of 2\n default: return size + ((4 - (size % 4)) % 4); // Pad upwards to even multiple of 4\n }\n}\n\n/** Returns the VariableShaderType that corresponds to a typed array */\nexport function getDataType(arrayOrType: TypedArray | TypedArrayConstructor): SignedDataType {\n const Constructor = ArrayBuffer.isView(arrayOrType) ? arrayOrType.constructor : arrayOrType;\n if (Constructor === Uint8ClampedArray) {\n return 'uint8';\n }\n const info = Object.values(NORMALIZED_TYPE_MAP).find(entry => Constructor === entry[4]);\n if (!info) {\n throw new Error(Constructor.name);\n }\n return info[0];\n}\n\n/** Returns the TypedArray that corresponds to a shader data type */\nexport function getTypedArrayConstructor(type: NormalizedDataType): TypedArrayConstructor {\n const [, , , , Constructor] = NORMALIZED_TYPE_MAP[type];\n return Constructor;\n}\n\nconst NORMALIZED_TYPE_MAP: Record<\n NormalizedDataType,\n [\n SignedDataType,\n PrimitiveDataType,\n bytes: 1 | 2 | 4,\n normalized: boolean,\n arrayConstructor: TypedArrayConstructor\n ]\n> = {\n uint8: ['uint8', 'u32', 1, false, Uint8Array],\n sint8: ['sint8', 'i32', 1, false, Int8Array],\n unorm8: ['uint8', 'f32', 1, true, Uint8Array],\n snorm8: ['sint8', 'f32', 1, true, Int8Array],\n uint16: ['uint16', 'u32', 2, false, Uint16Array],\n sint16: ['sint16', 'i32', 2, false, Int16Array],\n unorm16: ['uint16', 'u32', 2, true, Uint16Array],\n snorm16: ['sint16', 'i32', 2, true, Int16Array],\n float16: ['float16', 'f16', 2, false, Uint16Array],\n float32: ['float32', 'f32', 4, false, Float32Array],\n uint32: ['uint32', 'u32', 4, false, Uint32Array],\n sint32: ['sint32', 'i32', 4, false, Int32Array]\n};\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {PrimitiveDataType} from '../data-types/data-types';\nimport type {CompositeShaderType, VariableShaderType} from './shader-types';\nimport {alignTo} from '../data-types/decode-data-types';\nimport {getVariableShaderTypeInfo, resolveVariableShaderTypeAlias} from './shader-type-decoder';\n\n/**\n * Describes the packing for one flattened field in a shader block.\n *\n * Offsets, sizes, and strides are expressed in 32-bit words so the result can\n * be consumed directly by typed-array writers.\n */\nexport type ShaderBlockLayoutEntry = {\n /** Offset in 32-bit words from the start of the block. */\n offset: number;\n /** Occupied size in 32-bit words, excluding external array stride. */\n size: number;\n /** Number of logical scalar components in the declared value. */\n components: number;\n /** Number of matrix columns, or `1` for scalars and vectors. */\n columns: number;\n /** Number of rows in each column, or vector length for vectors. */\n rows: number;\n /** Distance between matrix columns in 32-bit words. */\n columnStride: number;\n /** Canonical shader type after alias resolution. */\n shaderType: VariableShaderType;\n /** Scalar data type used to write the value. */\n type: PrimitiveDataType;\n};\n\n/**\n * Options for {@link makeShaderBlockLayout}.\n */\nexport type ShaderBlockLayoutOptions = {\n /**\n * Packing rules to apply when building the layout.\n *\n * Defaults to `'std140'`.\n */\n layout?: 'std140' | 'wgsl-uniform' | 'wgsl-storage';\n};\n\n/**\n * Immutable layout metadata for a uniform or storage-style shader block.\n */\nexport type ShaderBlockLayout = {\n /** Packing rules used when this layout was created. */\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage';\n /** Exact number of packed bytes required by the block. */\n byteLength: number;\n /** Original composite shader type declarations keyed by top-level field. */\n uniformTypes: Record<string, CompositeShaderType>;\n /** Flattened leaf field layouts keyed by field path. */\n fields: Record<string, ShaderBlockLayoutEntry>;\n};\n\n/**\n * Builds a deterministic shader-block layout from composite shader type declarations.\n *\n * The returned value is pure layout metadata. It records the packed field\n * offsets and exact packed byte length, but it does not allocate buffers or\n * serialize values.\n */\nexport function makeShaderBlockLayout(\n uniformTypes: Readonly<Record<string, CompositeShaderType>>,\n options: ShaderBlockLayoutOptions = {}\n): ShaderBlockLayout {\n const copiedUniformTypes = {...uniformTypes};\n const layout = options.layout ?? 'std140';\n const fields: Record<string, ShaderBlockLayoutEntry> = {};\n\n let size = 0;\n for (const [key, uniformType] of Object.entries(copiedUniformTypes)) {\n size = addToLayout(fields, key, uniformType, size, layout);\n }\n\n size = alignTo(size, getTypeAlignment(copiedUniformTypes, layout));\n\n return {\n layout,\n byteLength: size * 4,\n uniformTypes: copiedUniformTypes,\n fields\n };\n}\n\n/**\n * Returns the layout metadata for a scalar, vector, or matrix leaf type.\n *\n * The result includes both the occupied size in 32-bit words and the alignment\n * requirement that must be applied before placing the value in a shader block.\n */\nexport function getLeafLayoutInfo(\n type: VariableShaderType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): Omit<ShaderBlockLayoutEntry, 'offset'> & {alignment: 1 | 2 | 4} {\n const resolvedType = resolveVariableShaderTypeAlias(type);\n const decodedType = getVariableShaderTypeInfo(resolvedType);\n const matrixMatch = /^mat(\\d)x(\\d)<.+>$/.exec(resolvedType);\n\n if (matrixMatch) {\n const columns = Number(matrixMatch[1]);\n const rows = Number(matrixMatch[2]);\n const columnInfo = getVectorLayoutInfo(\n rows as 2 | 3 | 4,\n resolvedType,\n decodedType.type,\n layout\n );\n const columnStride = getMatrixColumnStride(columnInfo.size, columnInfo.alignment, layout);\n\n return {\n alignment: columnInfo.alignment,\n size: columns * columnStride,\n components: columns * rows,\n columns,\n rows,\n columnStride,\n shaderType: resolvedType,\n type: decodedType.type\n };\n }\n\n const vectorMatch = /^vec(\\d)<.+>$/.exec(resolvedType);\n if (vectorMatch) {\n return getVectorLayoutInfo(\n Number(vectorMatch[1]) as 2 | 3 | 4,\n resolvedType,\n decodedType.type,\n layout\n );\n }\n\n return {\n alignment: 1,\n size: 1,\n components: 1,\n columns: 1,\n rows: 1,\n columnStride: 1,\n shaderType: resolvedType,\n type: decodedType.type\n };\n}\n\n/**\n * Type guard for composite struct declarations.\n */\nexport function isCompositeShaderTypeStruct(\n value: CompositeShaderType\n): value is Record<string, CompositeShaderType> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Recursively adds a composite type to the flattened field map.\n *\n * @returns The next free 32-bit-word offset after the inserted type.\n */\nfunction addToLayout(\n fields: Record<string, ShaderBlockLayoutEntry>,\n name: string,\n type: CompositeShaderType,\n offset: number,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n if (typeof type === 'string') {\n const info = getLeafLayoutInfo(type, layout);\n const alignedOffset = alignTo(offset, info.alignment);\n fields[name] = {\n offset: alignedOffset,\n ...info\n };\n return alignedOffset + info.size;\n }\n\n if (Array.isArray(type)) {\n if (Array.isArray(type[0])) {\n throw new Error(`Nested arrays are not supported for ${name}`);\n }\n\n const elementType = type[0] as CompositeShaderType;\n const length = type[1] as number;\n const stride = getArrayStride(elementType, layout);\n const arrayOffset = alignTo(offset, getTypeAlignment(type, layout));\n\n for (let i = 0; i < length; i++) {\n addToLayout(fields, `${name}[${i}]`, elementType, arrayOffset + i * stride, layout);\n }\n return arrayOffset + stride * length;\n }\n\n if (isCompositeShaderTypeStruct(type)) {\n const structAlignment = getTypeAlignment(type, layout);\n let structOffset = alignTo(offset, structAlignment);\n for (const [memberName, memberType] of Object.entries(type)) {\n structOffset = addToLayout(fields, `${name}.${memberName}`, memberType, structOffset, layout);\n }\n return alignTo(structOffset, structAlignment);\n }\n\n throw new Error(`Unsupported CompositeShaderType for ${name}`);\n}\n\n/**\n * Returns the occupied size of a composite type in 32-bit words.\n */\nfunction getTypeSize(\n type: CompositeShaderType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n if (typeof type === 'string') {\n return getLeafLayoutInfo(type, layout).size;\n }\n\n if (Array.isArray(type)) {\n const elementType = type[0] as CompositeShaderType;\n const length = type[1] as number;\n\n if (Array.isArray(elementType)) {\n throw new Error('Nested arrays are not supported');\n }\n\n return getArrayStride(elementType, layout) * length;\n }\n\n let size = 0;\n for (const memberType of Object.values(type)) {\n const compositeMemberType = memberType as CompositeShaderType;\n size = alignTo(size, getTypeAlignment(compositeMemberType, layout));\n size += getTypeSize(compositeMemberType, layout);\n }\n\n return alignTo(size, getTypeAlignment(type, layout));\n}\n\n/**\n * Returns the required alignment of a composite type in 32-bit words.\n */\nfunction getTypeAlignment(\n type: CompositeShaderType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): 1 | 2 | 4 {\n if (typeof type === 'string') {\n return getLeafLayoutInfo(type, layout).alignment;\n }\n\n if (Array.isArray(type)) {\n const elementType = type[0] as CompositeShaderType;\n const elementAlignment = getTypeAlignment(elementType, layout);\n return uses16ByteArrayAlignment(layout)\n ? (Math.max(elementAlignment, 4) as 1 | 2 | 4)\n : elementAlignment;\n }\n\n let maxAlignment: 1 | 2 | 4 = 1;\n for (const memberType of Object.values(type)) {\n const memberAlignment = getTypeAlignment(memberType as CompositeShaderType, layout);\n maxAlignment = Math.max(maxAlignment, memberAlignment) as 1 | 2 | 4;\n }\n\n return uses16ByteStructAlignment(layout)\n ? (Math.max(maxAlignment, 4) as 1 | 2 | 4)\n : maxAlignment;\n}\n\n/**\n * Returns the layout metadata for a vector leaf type.\n */\nfunction getVectorLayoutInfo(\n components: 2 | 3 | 4,\n shaderType: VariableShaderType,\n type: PrimitiveDataType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): Omit<ShaderBlockLayoutEntry, 'offset'> & {alignment: 1 | 2 | 4} {\n return {\n alignment: components === 2 ? 2 : 4,\n size: components === 3 ? 3 : components,\n components,\n columns: 1,\n rows: components,\n columnStride: components === 3 ? 3 : components,\n shaderType,\n type\n };\n}\n\n/**\n * Returns the stride of an array element in 32-bit words.\n *\n * This includes any layout-specific padding between adjacent array elements.\n */\nfunction getArrayStride(\n elementType: CompositeShaderType,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n const elementSize = getTypeSize(elementType, layout);\n const elementAlignment = getTypeAlignment(elementType, layout);\n return getArrayLikeStride(elementSize, elementAlignment, layout);\n}\n\n/**\n * Returns the common stride rule shared by array-like elements in the target layout.\n */\nfunction getArrayLikeStride(\n size: number,\n alignment: 1 | 2 | 4,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n return alignTo(size, uses16ByteArrayAlignment(layout) ? 4 : alignment);\n}\n\n/**\n * Returns the stride of a matrix column in 32-bit words.\n */\nfunction getMatrixColumnStride(\n size: number,\n alignment: 1 | 2 | 4,\n layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'\n): number {\n return layout === 'std140' ? 4 : alignTo(size, alignment);\n}\n\n/**\n * Returns `true` when arrays must be rounded up to 16-byte boundaries.\n */\nfunction uses16ByteArrayAlignment(layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'): boolean {\n return layout === 'std140' || layout === 'wgsl-uniform';\n}\n\n/**\n * Returns `true` when structs must be rounded up to 16-byte boundaries.\n */\nfunction uses16ByteStructAlignment(layout: 'std140' | 'wgsl-uniform' | 'wgsl-storage'): boolean {\n return layout === 'std140' || layout === 'wgsl-uniform';\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray} from '../types';\n\nlet arrayBuffer: ArrayBuffer;\n\nexport function getScratchArrayBuffer(byteLength: number): ArrayBuffer {\n if (!arrayBuffer || arrayBuffer.byteLength < byteLength) {\n arrayBuffer = new ArrayBuffer(byteLength);\n }\n return arrayBuffer;\n}\n\nexport function getScratchArray(Type: any, length: number): TypedArray {\n const scratchArrayBuffer = getScratchArrayBuffer(Type.BYTES_PER_ELEMENT * length);\n return new Type(scratchArrayBuffer, 0, length); // arrayBuffer, byteOffset, length (in elements)\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {TypedArray, NumberArray} from '../types';\n\n/**\n * Check is an array is a typed array\n * @param value value to be tested\n * @returns input as TypedArray, or null\n * @todo this should be provided by @math.gl/types\n */\nexport function isTypedArray(value: unknown): value is TypedArray {\n return ArrayBuffer.isView(value) && !(value instanceof DataView);\n}\n\n/**\n * Check is an array is a numeric array (typed array or array of numbers)\n * @param value value to be tested\n * @returns input as NumberArray, or null\n * @todo this should be provided by @math.gl/types\n */\nexport function isNumberArray(value: unknown): value is NumberArray {\n if (Array.isArray(value)) {\n return value.length === 0 || typeof value[0] === 'number';\n }\n return isTypedArray(value);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CompositeUniformValue, UniformValue} from '../adapter/types/uniforms';\nimport {getScratchArrayBuffer} from '../utils/array-utils-flat';\nimport {isNumberArray} from '../utils/is-array';\nimport {log} from '../utils/log';\nimport type {\n CompositeShaderType,\n VariableShaderType\n} from '../shadertypes/shader-types/shader-types';\nimport {\n getLeafLayoutInfo,\n isCompositeShaderTypeStruct,\n type ShaderBlockLayout\n} from '../shadertypes/shader-types/shader-block-layout';\n\n/**\n * Serializes nested JavaScript uniform values according to a {@link ShaderBlockLayout}.\n */\nexport class ShaderBlockWriter {\n /** Layout metadata used to flatten and serialize values. */\n readonly layout: ShaderBlockLayout;\n\n /**\n * Creates a writer for a precomputed shader-block layout.\n */\n constructor(layout: ShaderBlockLayout) {\n this.layout = layout;\n }\n\n /**\n * Returns `true` if the flattened layout contains the given field.\n */\n has(name: string): boolean {\n return Boolean(this.layout.fields[name]);\n }\n\n /**\n * Returns offset and size metadata for a flattened field.\n */\n get(name: string): {offset: number; size: number} | undefined {\n const entry = this.layout.fields[name];\n return entry ? {offset: entry.offset, size: entry.size} : undefined;\n }\n\n /**\n * Flattens nested composite values into leaf-path values understood by {@link UniformBlock}.\n *\n * Top-level values may be supplied either in nested object form matching the\n * declared composite shader types or as already-flattened leaf-path values.\n */\n getFlatUniformValues(\n uniformValues: Readonly<Record<string, CompositeUniformValue>>\n ): Record<string, UniformValue> {\n const flattenedUniformValues: Record<string, UniformValue> = {};\n\n for (const [name, value] of Object.entries(uniformValues)) {\n const uniformType = this.layout.uniformTypes[name];\n if (uniformType) {\n this._flattenCompositeValue(flattenedUniformValues, name, uniformType, value);\n } else if (this.layout.fields[name]) {\n flattenedUniformValues[name] = value as UniformValue;\n }\n }\n\n return flattenedUniformValues;\n }\n\n /**\n * Serializes the supplied values into buffer-backed binary data.\n *\n * The returned view length matches {@link ShaderBlockLayout.byteLength}, which\n * is the exact packed size of the block.\n */\n getData(uniformValues: Readonly<Record<string, CompositeUniformValue>>): Uint8Array {\n const buffer = getScratchArrayBuffer(this.layout.byteLength);\n new Uint8Array(buffer, 0, this.layout.byteLength).fill(0);\n const typedArrays = {\n i32: new Int32Array(buffer),\n u32: new Uint32Array(buffer),\n f32: new Float32Array(buffer),\n f16: new Uint16Array(buffer)\n };\n\n const flattenedUniformValues = this.getFlatUniformValues(uniformValues);\n for (const [name, value] of Object.entries(flattenedUniformValues)) {\n this._writeLeafValue(typedArrays, name, value);\n }\n\n return new Uint8Array(buffer, 0, this.layout.byteLength);\n }\n\n /**\n * Recursively flattens nested values using the declared composite shader type.\n */\n private _flattenCompositeValue(\n flattenedUniformValues: Record<string, UniformValue>,\n baseName: string,\n uniformType: CompositeShaderType,\n value: CompositeUniformValue | undefined\n ): void {\n if (value === undefined) {\n return;\n }\n\n if (typeof uniformType === 'string' || this.layout.fields[baseName]) {\n flattenedUniformValues[baseName] = value as UniformValue;\n return;\n }\n\n if (Array.isArray(uniformType)) {\n const elementType = uniformType[0] as CompositeShaderType;\n const length = uniformType[1] as number;\n\n if (Array.isArray(elementType)) {\n throw new Error(`Nested arrays are not supported for ${baseName}`);\n }\n\n if (typeof elementType === 'string' && isNumberArray(value)) {\n this._flattenPackedArray(flattenedUniformValues, baseName, elementType, length, value);\n return;\n }\n\n if (!Array.isArray(value)) {\n log.warn(`Unsupported uniform array value for ${baseName}:`, value)();\n return;\n }\n\n for (let index = 0; index < Math.min(value.length, length); index++) {\n const elementValue = value[index];\n if (elementValue === undefined) {\n continue;\n }\n\n this._flattenCompositeValue(\n flattenedUniformValues,\n `${baseName}[${index}]`,\n elementType,\n elementValue\n );\n }\n return;\n }\n\n if (isCompositeShaderTypeStruct(uniformType) && isCompositeUniformObject(value)) {\n for (const [key, subValue] of Object.entries(value)) {\n if (subValue === undefined) {\n continue;\n }\n\n const nestedName = `${baseName}.${key}`;\n this._flattenCompositeValue(flattenedUniformValues, nestedName, uniformType[key], subValue);\n }\n return;\n }\n\n log.warn(`Unsupported uniform value for ${baseName}:`, value)();\n }\n\n /**\n * Expands tightly packed numeric arrays into per-element leaf fields.\n */\n private _flattenPackedArray(\n flattenedUniformValues: Record<string, UniformValue>,\n baseName: string,\n elementType: VariableShaderType,\n length: number,\n value: UniformValue\n ): void {\n const numericValue = value as Readonly<ArrayLike<number>>;\n const elementLayout = getLeafLayoutInfo(elementType, this.layout.layout);\n const packedElementLength = elementLayout.components;\n\n for (let index = 0; index < length; index++) {\n const start = index * packedElementLength;\n if (start >= numericValue.length) {\n break;\n }\n\n if (packedElementLength === 1) {\n flattenedUniformValues[`${baseName}[${index}]`] = Number(numericValue[start]);\n } else {\n flattenedUniformValues[`${baseName}[${index}]`] = sliceNumericArray(\n value,\n start,\n start + packedElementLength\n ) as UniformValue;\n }\n }\n }\n\n /**\n * Writes one flattened leaf value into its typed-array view.\n */\n private _writeLeafValue(\n typedArrays: Record<string, any>,\n name: string,\n value: UniformValue\n ): void {\n const entry = this.layout.fields[name];\n if (!entry) {\n log.warn(`Uniform ${name} not found in layout`)();\n return;\n }\n\n const {type, components, columns, rows, offset, columnStride} = entry;\n const array = typedArrays[type];\n\n if (components === 1) {\n array[offset] = Number(value);\n return;\n }\n\n const sourceValue = value as Readonly<ArrayLike<number>>;\n\n if (columns === 1) {\n for (let componentIndex = 0; componentIndex < components; componentIndex++) {\n array[offset + componentIndex] = Number(sourceValue[componentIndex] ?? 0);\n }\n return;\n }\n\n let sourceIndex = 0;\n for (let columnIndex = 0; columnIndex < columns; columnIndex++) {\n const columnOffset = offset + columnIndex * columnStride;\n for (let rowIndex = 0; rowIndex < rows; rowIndex++) {\n array[columnOffset + rowIndex] = Number(sourceValue[sourceIndex++] ?? 0);\n }\n }\n }\n}\n\n/**\n * Type guard for nested uniform objects.\n */\nfunction isCompositeUniformObject(\n value: CompositeUniformValue\n): value is Record<string, CompositeUniformValue | undefined> {\n return (\n Boolean(value) &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !ArrayBuffer.isView(value)\n );\n}\n\n/**\n * Slices a numeric array-like value without changing its numeric representation.\n */\nfunction sliceNumericArray(value: UniformValue, start: number, end: number): number[] {\n return Array.prototype.slice.call(value, start, end) as number[];\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {isNumberArray} from './is-array';\n\nconst MAX_ELEMENTWISE_ARRAY_COMPARE_LENGTH = 128;\n\n/** Test if two arrays are deep equal, with a small-array length limit that defaults to 16 */\nexport function arrayEqual(a: unknown, b: unknown, limit: number = 16) {\n if (a === b) {\n return true;\n }\n\n const arrayA = a;\n const arrayB = b;\n if (!isNumberArray(arrayA) || !isNumberArray(arrayB)) {\n return false;\n }\n\n if (arrayA.length !== arrayB.length) {\n return false;\n }\n\n const maxCompareLength = Math.min(limit, MAX_ELEMENTWISE_ARRAY_COMPARE_LENGTH);\n if (arrayA.length > maxCompareLength) {\n return false;\n }\n\n for (let i = 0; i < arrayA.length; ++i) {\n if (arrayB[i] !== arrayA[i]) {\n return false;\n }\n }\n\n return true;\n}\n\n/** Copy a value */\nexport function arrayCopy<T>(a: T): T {\n if (isNumberArray(a)) {\n return a.slice() as T;\n }\n return a;\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {VariableShaderType} from '../shadertypes/shader-types/shader-types';\nimport type {UniformValue} from '../adapter/types/uniforms';\nimport {\n ShaderLayout,\n UniformInfo,\n UniformBufferBindingLayout\n} from '../adapter/types/shader-layout';\nimport {arrayEqual, arrayCopy} from '../utils/array-equal';\n\n/**\n * A uniform block holds values of the of uniform values for one uniform block / buffer.\n * It also does some book keeping on what has changed, to minimize unnecessary writes to uniform buffers.\n */\nexport class UniformBlock<\n TUniforms extends Record<string, UniformValue> = Record<string, UniformValue>\n> {\n name: string;\n\n uniforms: Record<keyof TUniforms, UniformValue> = {} as Record<keyof TUniforms, UniformValue>;\n modifiedUniforms: Record<keyof TUniforms, boolean> = {} as Record<keyof TUniforms, boolean>;\n modified: boolean = true;\n\n readonly bindingLayout: Record<string, UniformInfo> = {};\n needsRedraw: string | false = 'initialized';\n\n constructor(props?: {\n name?: string;\n shaderLayout?: ShaderLayout;\n uniformTypes?: Record<keyof TUniforms, Record<string, VariableShaderType>>;\n }) {\n this.name = props?.name || 'unnamed';\n\n // TODO - Extract uniform layout from the shaderLayout object\n if (props?.name && props?.shaderLayout) {\n const binding = props?.shaderLayout.bindings?.find(\n binding_ => binding_.type === 'uniform' && binding_.name === props?.name\n );\n if (!binding) {\n throw new Error(props?.name);\n }\n\n const uniformBlock = binding as UniformBufferBindingLayout;\n for (const uniform of uniformBlock.uniforms || []) {\n this.bindingLayout[uniform.name] = uniform;\n }\n }\n }\n\n /** Set a map of uniforms */\n setUniforms(uniforms: Partial<TUniforms>): void {\n for (const [key, value] of Object.entries(uniforms)) {\n this._setUniform(key, value);\n if (!this.needsRedraw) {\n this.setNeedsRedraw(`${this.name}.${key}=${value}`);\n }\n }\n }\n\n setNeedsRedraw(reason: string): void {\n this.needsRedraw = this.needsRedraw || reason;\n }\n\n /** Returns all uniforms */\n getAllUniforms(): Record<string, UniformValue> {\n // @ts-expect-error\n this.modifiedUniforms = {};\n this.needsRedraw = false;\n return (this.uniforms || {}) as Record<string, UniformValue>;\n }\n\n /** Set a single uniform */\n private _setUniform(key: keyof TUniforms, value: UniformValue) {\n if (arrayEqual(this.uniforms[key], value)) {\n return;\n }\n this.uniforms[key] = arrayCopy(value);\n this.modifiedUniforms[key] = true;\n this.modified = true;\n }\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport type {CompositeShaderType} from '../shadertypes/shader-types/shader-types';\nimport type {CompositeUniformValue} from '../adapter/types/uniforms';\nimport type {Device} from '../adapter/device';\nimport {Buffer} from '../adapter/resources/buffer';\nimport {log} from '../utils/log';\nimport {\n makeShaderBlockLayout,\n type ShaderBlockLayout\n} from '../shadertypes/shader-types/shader-block-layout';\nimport {UniformBlock} from './uniform-block';\nimport {ShaderBlockWriter} from './shader-block-writer';\n\n/** Definition of a single managed uniform block. */\nexport type UniformStoreBlockDefinition = {\n /** Declared shader types for the block's uniforms. */\n uniformTypes?: Record<string, CompositeShaderType>;\n /** Reserved for future prop-level defaults. */\n defaultProps?: Record<string, unknown>;\n /** Initial uniform values written into the backing block. */\n defaultUniforms?: Record<string, CompositeUniformValue>;\n /** Explicit shader-block layout override. */\n layout?: 'std140' | 'wgsl-uniform' | 'wgsl-storage';\n};\n\n/** Uniform block definitions keyed by block name. */\nexport type UniformStoreBlocks<TPropGroups extends Record<string, Record<string, unknown>>> =\n Record<keyof TPropGroups, UniformStoreBlockDefinition>;\n\n/**\n * Smallest buffer size that can be used for uniform buffers.\n *\n * This is an allocation policy rather than part of {@link ShaderBlockLayout}.\n * Layouts report the exact packed size, while the store applies any minimum\n * buffer-size rule when allocating GPU buffers.\n *\n * TODO - does this depend on device?\n */\nconst minUniformBufferSize = 1024;\n\n/**\n * A uniform store holds a uniform values for one or more uniform blocks,\n * - It can generate binary data for any uniform buffer\n * - It can manage a uniform buffer for each block\n * - It can update managed uniform buffers with a single call\n * - It performs some book keeping on what has changed to minimize unnecessary writes to uniform buffers.\n */\nexport class UniformStore<\n TPropGroups extends Record<string, Record<string, unknown>> = Record<\n string,\n Record<string, unknown>\n >\n> {\n /** Device used to infer layout and allocate buffers. */\n readonly device: Device;\n /** Stores the uniform values for each uniform block */\n uniformBlocks = new Map<keyof TPropGroups, UniformBlock>();\n /** Flattened layout metadata for each block. */\n shaderBlockLayouts = new Map<keyof TPropGroups, ShaderBlockLayout>();\n /** Serializers for block-backed uniform data. */\n shaderBlockWriters = new Map<keyof TPropGroups, ShaderBlockWriter>();\n /** Actual buffer for the blocks */\n uniformBuffers = new Map<keyof TPropGroups, Buffer>();\n\n /**\n * Creates a new {@link UniformStore} for the supplied device and block definitions.\n */\n constructor(device: Device, blocks: UniformStoreBlocks<TPropGroups>) {\n this.device = device;\n\n for (const [bufferName, block] of Object.entries(blocks)) {\n const uniformBufferName = bufferName as keyof TPropGroups;\n\n // Create a layout object to help us generate correctly formatted binary uniform buffers\n const shaderBlockLayout = makeShaderBlockLayout(block.uniformTypes ?? {}, {\n layout: block.layout ?? getDefaultUniformBufferLayout(device)\n });\n const shaderBlockWriter = new ShaderBlockWriter(shaderBlockLayout);\n this.shaderBlockLayouts.set(uniformBufferName, shaderBlockLayout);\n this.shaderBlockWriters.set(uniformBufferName, shaderBlockWriter);\n\n // Create a Uniform block to store the uniforms for each buffer.\n const uniformBlock = new UniformBlock({name: bufferName});\n uniformBlock.setUniforms(shaderBlockWriter.getFlatUniformValues(block.defaultUniforms || {}));\n this.uniformBlocks.set(uniformBufferName, uniformBlock);\n }\n }\n\n /** Destroy any managed uniform buffers */\n destroy(): void {\n for (const uniformBuffer of this.uniformBuffers.values()) {\n uniformBuffer.destroy();\n }\n }\n\n /**\n * Set uniforms\n *\n * Makes all group properties partial and eagerly propagates changes to any\n * managed GPU buffers.\n */\n setUniforms(\n uniforms: Partial<{[group in keyof TPropGroups]: Partial<TPropGroups[group]>}>\n ): void {\n for (const [blockName, uniformValues] of Object.entries(uniforms)) {\n const uniformBufferName = blockName as keyof TPropGroups;\n const shaderBlockWriter = this.shaderBlockWriters.get(uniformBufferName);\n const flattenedUniforms = shaderBlockWriter?.getFlatUniformValues(\n (uniformValues || {}) as Record<string, CompositeUniformValue>\n );\n this.uniformBlocks.get(uniformBufferName)?.setUniforms(flattenedUniforms || {});\n // We leverage logging in updateUniformBuffers(), even though slightly less efficient\n // this.updateUniformBuffer(blockName);\n }\n\n this.updateUniformBuffers();\n }\n\n /**\n * Returns the allocation size for the named uniform buffer.\n *\n * This may exceed the packed layout size because minimum buffer-size policy is\n * applied at the store layer.\n */\n getUniformBufferByteLength(uniformBufferName: keyof TPropGroups): number {\n const packedByteLength = this.shaderBlockLayouts.get(uniformBufferName)?.byteLength || 0;\n return Math.max(packedByteLength, minUniformBufferSize);\n }\n\n /**\n * Returns packed binary data that can be uploaded to the named uniform buffer.\n *\n * The returned view length matches the packed block size and is not padded to\n * the store's minimum allocation size.\n */\n getUniformBufferData(uniformBufferName: keyof TPropGroups): Uint8Array {\n const uniformValues = this.uniformBlocks.get(uniformBufferName)?.getAllUniforms() || {};\n const shaderBlockWriter = this.shaderBlockWriters.get(uniformBufferName);\n return shaderBlockWriter?.getData(uniformValues) || new Uint8Array(0);\n }\n\n /**\n * Creates an unmanaged uniform buffer initialized with the current or supplied values.\n */\n createUniformBuffer(\n uniformBufferName: keyof TPropGroups,\n uniforms?: Partial<{[group in keyof TPropGroups]: Partial<TPropGroups[group]>}>\n ): Buffer {\n if (uniforms) {\n this.setUniforms(uniforms);\n }\n const byteLength = this.getUniformBufferByteLength(uniformBufferName);\n const uniformBuffer = this.device.createBuffer({\n usage: Buffer.UNIFORM | Buffer.COPY_DST,\n byteLength\n });\n // Note that this clears the needs redraw flag\n const uniformBufferData = this.getUniformBufferData(uniformBufferName);\n uniformBuffer.write(uniformBufferData);\n return uniformBuffer;\n }\n\n /** Returns the managed uniform buffer for the named block. */\n getManagedUniformBuffer(uniformBufferName: keyof TPropGroups): Buffer {\n if (!this.uniformBuffers.get(uniformBufferName)) {\n const byteLength = this.getUniformBufferByteLength(uniformBufferName);\n const uniformBuffer = this.device.createBuffer({\n usage: Buffer.UNIFORM | Buffer.COPY_DST,\n byteLength\n });\n this.uniformBuffers.set(uniformBufferName, uniformBuffer);\n }\n // this.updateUniformBuffers();\n // @ts-ignore\n return this.uniformBuffers.get(uniformBufferName);\n }\n\n /**\n * Updates every managed uniform buffer whose source uniforms have changed.\n *\n * @returns The first redraw reason encountered, or `false` if nothing changed.\n */\n updateUniformBuffers(): false | string {\n let reason: false | string = false;\n for (const uniformBufferName of this.uniformBlocks.keys()) {\n const bufferReason = this.updateUniformBuffer(uniformBufferName);\n reason ||= bufferReason;\n }\n if (reason) {\n log.log(3, `UniformStore.updateUniformBuffers(): ${reason}`)();\n }\n return reason;\n }\n\n /**\n * Updates one managed uniform buffer if its corresponding block is dirty.\n *\n * @returns The redraw reason for the update, or `false` if no write occurred.\n */\n updateUniformBuffer(uniformBufferName: keyof TPropGroups): false | string {\n const uniformBlock = this.uniformBlocks.get(uniformBufferName);\n let uniformBuffer = this.uniformBuffers.get(uniformBufferName);\n\n let reason: false | string = false;\n if (uniformBuffer && uniformBlock?.needsRedraw) {\n reason ||= uniformBlock.needsRedraw;\n // This clears the needs redraw flag\n const uniformBufferData = this.getUniformBufferData(uniformBufferName);\n\n uniformBuffer = this.uniformBuffers.get(uniformBufferName);\n uniformBuffer?.write(uniformBufferData);\n\n // logging - TODO - don't query the values unnecessarily\n const uniformValues = this.uniformBlocks.get(uniformBufferName)?.getAllUniforms();\n log.log(\n 4,\n `Writing to uniform buffer ${String(uniformBufferName)}`,\n uniformBufferData,\n uniformValues\n )();\n }\n return reason;\n }\n}\n\n/**\n * Returns the default uniform-buffer layout for the supplied device.\n */\nfunction getDefaultUniformBufferLayout(device: Device): 'std140' | 'wgsl-uniform' | 'wgsl-storage' {\n return device.type === 'webgpu' ? 'wgsl-uniform' : 'std140';\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nimport {TypedArray} from '@math.gl/types';\nimport {type TextureFormat, type TextureMemoryLayout} from './texture-formats';\nimport {textureFormatDecoder} from './texture-format-decoder';\n\nexport function getTextureImageView<T extends TextureFormat>(\n arrayBuffer: ArrayBuffer,\n memoryLayout: TextureMemoryLayout,\n format: T,\n image = 0\n) {\n const formatInfo = textureFormatDecoder.getInfo(format);\n const bytesPerComponent = formatInfo.bytesPerPixel / formatInfo.components;\n const {bytesPerImage} = memoryLayout;\n const offset = bytesPerImage * image;\n const totalPixels = memoryLayout.bytesPerImage / bytesPerComponent;\n\n switch (format) {\n case 'rgba8unorm':\n case 'bgra8unorm':\n case 'rgba8uint':\n return new Uint8Array(arrayBuffer, offset, totalPixels);\n case 'r8unorm':\n return new Uint8Array(arrayBuffer, offset, totalPixels);\n case 'r16uint':\n case 'rgba16uint':\n return new Uint16Array(arrayBuffer, offset, totalPixels);\n case 'r32uint':\n case 'rgba32uint':\n return new Uint32Array(arrayBuffer, offset, totalPixels);\n case 'r32float':\n return new Float32Array(arrayBuffer, offset, totalPixels);\n case 'rgba16float':\n return new Uint16Array(arrayBuffer, offset, totalPixels); // 4 channels\n case 'rgba32float':\n return new Float32Array(arrayBuffer, offset, totalPixels);\n default:\n throw new Error(`Unsupported format: ${format}`);\n }\n}\n\nexport function setTextureImageData<T extends TextureFormat>(\n arrayBuffer: ArrayBuffer,\n memoryLayout: TextureMemoryLayout,\n format: T,\n data: TypedArray,\n image = 0\n): void {\n const offset = 0; // memoryLayout.bytesPerImage * image;\n\n const totalPixels = memoryLayout.bytesPerImage / memoryLayout.bytesPerPixel;\n const subArray = data.subarray(0, totalPixels);\n\n const typedArray = getTextureImageView(arrayBuffer, memoryLayout, format, image);\n\n typedArray.set(subArray, offset);\n}\n", "// luma.gl\n// SPDX-License-Identifier: MIT\n// Copyright (c) vis.gl contributors\n\nexport type ImageData = {\n /** Offset into the data (in addition to any offset built-in to the ArrayBufferView) */\n byteOffset?: number;\n /** The stride, in bytes, between the beginning of each texel block row and the subsequent texel block row. Required if there are multiple texel block rows (i.e. the copy height or depth is more than one block). */\n bytesPerRow?: number;\n /** Number or rows per image (needed if multiple images are being set) */\n rowsPerImage?: number;\n /** Bits per channel */\n bitsPerChannel: [number, number, number, number];\n};\n\nexport type PixelData = {\n arrayBuffer: ArrayBuffer;\n width: number;\n height: number;\n /** Bytes per pixel */\n bytesPerPixel: number;\n bytesPerRow: number;\n bitsPerChannel: [number, number, number, number];\n};\n\n/**\n * Extracts a single RGBA pixel value from PixelData at the given (x, y) coordinate.\n *\n * The pixel's data is assumed to be packed according to pixelData.bitsPerChannel.\n * The pixel data for a given row is padded to pixelData.bytesPerRow.\n *\n * @param pixelData - The metadata and data for the pixel buffer.\n * @param x - The x coordinate (0-based).\n * @param y - The y coordinate (0-based).\n * @returns A tuple [r, g, b, a] where each channel is the extracted numeric value.\n *\n* @example\n\nAssume you obtained an ArrayBuffer from copyTextureToBuffer and have the following metadata:\n\n const pixelData: PixelData = {\n bitsPerChannel: [5, 6, 5, 0], // For example, a 16-bit RGB565 format (no alpha)\n width: 800,\n height: 600,\n bytesPerPixel: 2, // 16 bits per pixel\n bytesPerRow: 1600, // Assuming no extra padding\n arrayBuffer: myTextureBuffer, // Obtained from copyTextureToBuffer\n };\n\nYou can then extract the pixel at (x, y) like so:\n\n const rgba = extractPixel(pixelData, x, y);\n console.log(\"Extracted RGBA:\", rgba);\n\nFor RGBA formats where all channels are present (e.g. [8, 8, 8, 8]), the function will extract a 4-channel pixel value.\n*/\n\nexport function readPixel(\n pixelData: PixelData,\n x: number,\n y: number,\n bitsPerChannel: [number, number, number, number]\n): [number, number, number, number] {\n if (x < 0 || x >= pixelData.width || y < 0 || y >= pixelData.height) {\n throw new Error('Coordinates out of bounds.');\n }\n\n // Compute the byte offset of the pixel in the buffer.\n const byteOffset = y * pixelData.bytesPerRow + x * pixelData.bytesPerPixel;\n\n // Create a Uint8Array view for this pixel's bytes.\n // We only need to view pixelData.bytesPerPixel bytes.\n const pixelDataView = new DataView(pixelData.arrayBuffer, byteOffset, pixelData.bytesPerPixel);\n\n let bitOffsetWithinPixel = 0;\n const channels: number[] = [];\n\n // Extract each of the four channels.\n for (let i = 0; i < 4; i++) {\n const bits = bitsPerChannel[i] ?? 0;\n // If a channel's bit width is zero or negative, consider it not present.\n if (bits <= 0) {\n channels.push(0);\n } else {\n const channelValue = readBitsFromDataView(pixelDataView, bitOffsetWithinPixel, bits);\n channels.push(channelValue);\n bitOffsetWithinPixel += bits;\n }\n }\n\n return [channels[0] ?? 0, channels[1] ?? 0, channels[2] ?? 0, channels[3] ?? 0];\n}\n\n/**\n * Encodes an RGBA pixel into a DataView at a given bit offset according to a specified bit layout.\n *\n * The channels are written sequentially in the order R, G, B, A. For each channel, the number\n * of bits is taken from the bitsPerChannel array. Channel values are masked to fit within the specified width.\n *\n * @param dataView - The DataView into which the pixel will be encoded.\n * @param bitOffset - The bit offset in the DataView where the pixel should be written.\n * @param bitsPerChannel - A tuple specifying the number of bits for each channel: [R, G, B, A].\n * @param pixel - A tuple [r, g, b, a] containing the channel values (as numbers).\n *\n * @example\n\nAssume you want to encode a pixel into a packed format where:\n - Red uses 5 bits\n - Green uses 6 bits\n - Blue uses 5 bits\n - Alpha is not used (0 bits)\nAnd the pixel format is packed into 16 bits total.\n\nYou might have:\n const bitsPerChannel: [number, number, number, number] = [5, 6, 5, 0];\n const pixel: [number, number, number, number] = [15, 31, 15, 0]; // Example values\n const buffer = new ArrayBuffer(2); // 16 bits = 2 bytes\n const dataView = new DataView(buffer);\n\nNow encode the pixel at bit offset 0:\n encodePixel(dataView, 0, bitsPerChannel, pixel);\n\nThe dataView now contains the 16-bit packed pixel value in big-endian order.\n*/\nexport function writePixel(\n dataView: DataView,\n bitOffset: number,\n bitsPerChannel: [number, number, number, number],\n pixel: [number, number, number, number]\n): void {\n let currentBitOffset = bitOffset;\n for (let channel = 0; channel < 4; channel++) {\n const bits = bitsPerChannel[channel] ?? 0;\n // Clamp the channel value to the maximum allowed by the bit width.\n const maxValue = (1 << bits) - 1;\n const channelValue = (pixel[channel] ?? 0) & maxValue;\n writeBitsToDataView(dataView, currentBitOffset, bits, channelValue);\n currentBitOffset += bits;\n }\n}\n\n/**\n * Reads a specified number of bits from a DataView starting at a given bit offset.\n *\n * For channels with a bit width of 8, 16, or 32 bits and when the bitOffset is byte-aligned,\n * this function uses DataView methods for fast extraction.\n *\n * Bits are assumed to be stored in big-endian order (i.e. the most-significant bit is at position 7 in each byte).\n *\n * @param dataView - The DataView containing the data.\n * @param bitOffset - The offset (in bits) within the data from which to start reading.\n * @param bitCount - The number of bits to read (supported range: 1 to 32).\n * @returns The extracted value as a number.\n */\nexport function readBitsFromDataView(\n dataView: DataView,\n bitOffset: number,\n bitCount: number\n): number {\n // Check if we can optimize when bitOffset is byte-aligned.\n if (bitOffset % 8 === 0) {\n const byteOffset = bitOffset / 8;\n if (bitCount === 8 && byteOffset + 1 <= dataView.byteLength) {\n return dataView.getUint8(byteOffset);\n } else if (bitCount === 16 && byteOffset + 2 <= dataView.byteLength) {\n // false for big-endian reading.\n return dataView.getUint16(byteOffset, false);\n } else if (bitCount === 32 && byteOffset + 4 <= dataView.byteLength) {\n return dataView.getUint32(byteOffset, false);\n }\n }\n\n // Fallback: bit-level extraction for non-aligned or non-standard bit widths.\n let value = 0;\n for (let i = 0; i < bitCount; i++) {\n const overallBitIndex = bitOffset + i;\n const byteIndex = Math.floor(overallBitIndex / 8);\n const bitIndex = overallBitIndex % 8;\n // Read the byte and extract the bit at position (7 - bitIndex).\n const byteValue = dataView.getUint8(byteIndex);\n const bit = (byteValue >> (7 - bitIndex)) & 1;\n value = (value << 1) | bit;\n }\n return value;\n}\n\n/**\n * Writes a specified number of bits from a value into a DataView at a given bit offset.\n *\n * For channels with a bit width of 8, 16, or 32 bits and when the bit offset is byte-aligned,\n * this function uses DataView methods for fast writing.\n *\n * Bits are assumed to be stored in big-endian order (i.e. the most-significant bit is at position 7 in each byte).\n *\n * @param dataView - The DataView to write into.\n * @param bitOffset - The bit offset at which to begin writing.\n * @param bitCount - The number of bits to write (supported range: 1 to 32).\n * @param value - The numeric value whose lower bitCount bits will be written.\n */\nexport function writeBitsToDataView(\n dataView: DataView,\n bitOffset: number,\n bitCount: number,\n value: number\n): void {\n // If the bitOffset is byte-aligned, we may optimize for common bit widths.\n if (bitOffset % 8 === 0) {\n const byteOffset = bitOffset / 8;\n if (bitCount === 8 && byteOffset + 1 <= dataView.byteLength) {\n dataView.setUint8(byteOffset, value & 0xff);\n return;\n } else if (bitCount === 16 && byteOffset + 2 <= dataView.byteLength) {\n dataView.setUint16(byteOffset, value & 0xffff, false); // big-endian\n return;\n } else if (bitCount === 32 && byteOffset + 4 <= dataView.byteLength) {\n dataView.setUint32(byteOffset, value, false); // big-endian\n return;\n }\n }\n\n // Fallback: write bit-by-bit.\n for (let i = 0; i < bitCount; i++) {\n const overallBitIndex = bitOffset + i;\n const byteIndex = Math.floor(overallBitIndex / 8);\n const bitIndex = overallBitIndex % 8;\n const mask = 1 << (7 - bitIndex);\n // Extract the i-th bit from value (starting from the most-significant bit)\n const bitValue = (value >> (bitCount - 1 - i)) & 1;\n // Read the current byte.\n let currentByte = dataView.getUint8(byteIndex);\n // Clear the target bit.\n currentByte &= ~mask;\n // Set the target bit if bitValue is 1.\n if (bitValue) {\n currentByte |= mask;\n }\n dataView.setUint8(byteIndex, currentByte);\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;gBAAAA;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACIA,mBAA0B;AAE1B,IAAM,4BAA4B;AAClC,IAAM,iCAAiC;EACrC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAEF,IAAM,sBAAsB,oBAAI,QAAO;AAIvC,IAAM,8BAA8B,oBAAI,QAAO;AAKzC,IAAO,eAAP,MAAmB;EACvB,QAAQ,oBAAI,IAAG;EAEf,SAASC,OAAY;AACnB,WAAO,KAAK,IAAIA,KAAI;EACtB;EAEA,IAAIA,OAAY;AACd,QAAI,CAAC,KAAK,MAAM,IAAIA,KAAI,GAAG;AACzB,WAAK,MAAM,IAAIA,OAAM,IAAI,mBAAM,EAAC,IAAIA,MAAI,CAAC,CAAC;IAC5C;AAEA,UAAM,QAAQ,KAAK,MAAM,IAAIA,KAAI;AACjC,QAAIA,UAAS,2BAA2B;AACtC,sBAAgB,OAAO,8BAA8B;IACvD;AAEA,WAAO;EACT;;AAIK,IAAM,YAA0B,IAAI,aAAY;AAEvD,SAAS,gBAAgB,OAAc,kBAAmC;AACxE,QAAM,WAAW,MAAM;AACvB,MAAI,mBAAmB;AACvB,aAAW,YAAY,kBAAkB;AACvC,QAAI,CAAC,SAAS,QAAQ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AI,IAAM;AAEjD,QAAI,cAAc,SAAS,SAAS,SAAS;AAE7C,mBAAe,CAAC;AAEhB,QAAI,UAAU;AACZ,qBAAe;IACjB;AACA,aAAS,SAAS,WAAW,WAAW;EAC1C;AACF;",
6
+ "names": ["Buffer", "name", "GPU_TIME_AND_MEMORY_STATS", "ORDERED_STATS_CACHE", "ORDERED_STAT_NAME_SET_CACHE", "initializeStats", "name", "arrayBuffer", "Buffer", "Buffer", "import_env", "devicePixelRatio", "log", "attachment", "bindGroups", "name", "attributeMapping", "NORMALIZED_TYPE_MAP", "name", "name", "Buffer", "arrayBuffer"]
7
7
  }