@lightningjs/renderer 2.9.0 → 2.9.2

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 (224) hide show
  1. package/COPYING +1 -0
  2. package/LICENSE +202 -202
  3. package/NOTICE +3 -3
  4. package/README.md +147 -147
  5. package/dist/src/core/CoreNode.js +1 -1
  6. package/dist/src/core/CoreNode.js.map +1 -1
  7. package/dist/src/core/lib/utils.d.ts +1 -0
  8. package/dist/src/core/lib/utils.js +3 -0
  9. package/dist/src/core/lib/utils.js.map +1 -1
  10. package/dist/src/core/renderers/canvas/CanvasCoreRenderer.js +6 -3
  11. package/dist/src/core/renderers/canvas/CanvasCoreRenderer.js.map +1 -1
  12. package/dist/src/core/renderers/webgl/shaders/DefaultShader.js +45 -45
  13. package/dist/src/core/renderers/webgl/shaders/DefaultShaderBatched.js +61 -61
  14. package/dist/src/core/renderers/webgl/shaders/DynamicShader.js +93 -93
  15. package/dist/src/core/renderers/webgl/shaders/RoundedRectangle.js +63 -63
  16. package/dist/src/core/renderers/webgl/shaders/SdfShader.js +62 -62
  17. package/dist/src/core/renderers/webgl/shaders/effects/BorderBottomEffect.js +15 -15
  18. package/dist/src/core/renderers/webgl/shaders/effects/BorderEffect.js +6 -6
  19. package/dist/src/core/renderers/webgl/shaders/effects/BorderLeftEffect.js +15 -15
  20. package/dist/src/core/renderers/webgl/shaders/effects/BorderRightEffect.js +15 -15
  21. package/dist/src/core/renderers/webgl/shaders/effects/BorderTopEffect.js +15 -15
  22. package/dist/src/core/renderers/webgl/shaders/effects/FadeOutEffect.js +42 -42
  23. package/dist/src/core/renderers/webgl/shaders/effects/GlitchEffect.js +44 -44
  24. package/dist/src/core/renderers/webgl/shaders/effects/GrayscaleEffect.js +3 -3
  25. package/dist/src/core/renderers/webgl/shaders/effects/HolePunchEffect.js +22 -22
  26. package/dist/src/core/renderers/webgl/shaders/effects/LinearGradientEffect.js +28 -28
  27. package/dist/src/core/renderers/webgl/shaders/effects/RadialGradientEffect.js +10 -10
  28. package/dist/src/core/renderers/webgl/shaders/effects/RadialProgressEffect.js +37 -37
  29. package/dist/src/core/renderers/webgl/shaders/effects/RadiusEffect.js +19 -19
  30. package/dist/src/core/text-rendering/font-face-types/WebTrFontFace.js +7 -3
  31. package/dist/src/core/text-rendering/font-face-types/WebTrFontFace.js.map +1 -1
  32. package/dist/src/core/text-rendering/renderers/LightningTextTextureRenderer.js +7 -0
  33. package/dist/src/core/text-rendering/renderers/LightningTextTextureRenderer.js.map +1 -1
  34. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText.js +5 -1
  35. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText.js.map +1 -1
  36. package/dist/src/core/textures/ImageTexture.js +5 -4
  37. package/dist/src/core/textures/ImageTexture.js.map +1 -1
  38. package/dist/src/core/textures/SubTexture.d.ts +1 -0
  39. package/dist/src/core/textures/SubTexture.js +7 -0
  40. package/dist/src/core/textures/SubTexture.js.map +1 -1
  41. package/dist/src/core/textures/Texture.d.ts +9 -0
  42. package/dist/src/core/textures/Texture.js +23 -13
  43. package/dist/src/core/textures/Texture.js.map +1 -1
  44. package/dist/tsconfig.dist.tsbuildinfo +1 -1
  45. package/exports/canvas.ts +39 -39
  46. package/exports/index.ts +89 -89
  47. package/exports/inspector.ts +24 -24
  48. package/exports/utils.ts +44 -44
  49. package/exports/webgl.ts +38 -38
  50. package/package.json +1 -1
  51. package/scripts/please-use-pnpm.js +13 -13
  52. package/src/common/CommonTypes.ts +139 -139
  53. package/src/common/EventEmitter.ts +77 -77
  54. package/src/common/IAnimationController.ts +92 -92
  55. package/src/common/IEventEmitter.ts +28 -28
  56. package/src/core/CoreNode.test.ts +199 -199
  57. package/src/core/CoreNode.ts +2335 -2335
  58. package/src/core/CoreShaderManager.ts +292 -292
  59. package/src/core/CoreTextNode.ts +455 -455
  60. package/src/core/CoreTextureManager.ts +548 -548
  61. package/src/core/Stage.ts +700 -700
  62. package/src/core/TextureMemoryManager.ts +277 -277
  63. package/src/core/animations/AnimationManager.ts +38 -38
  64. package/src/core/animations/CoreAnimation.ts +340 -340
  65. package/src/core/animations/CoreAnimationController.ts +157 -157
  66. package/src/core/lib/ContextSpy.ts +41 -41
  67. package/src/core/lib/ImageWorker.ts +270 -270
  68. package/src/core/lib/Matrix3d.ts +244 -244
  69. package/src/core/lib/RenderCoords.ts +86 -86
  70. package/src/core/lib/WebGlContextWrapper.ts +1322 -1322
  71. package/src/core/lib/textureCompression.ts +152 -152
  72. package/src/core/lib/textureSvg.ts +78 -78
  73. package/src/core/lib/utils.ts +310 -306
  74. package/src/core/platform.ts +61 -61
  75. package/src/core/renderers/CoreContextTexture.ts +43 -43
  76. package/src/core/renderers/CoreRenderOp.ts +22 -22
  77. package/src/core/renderers/CoreRenderer.ts +114 -114
  78. package/src/core/renderers/CoreShader.ts +41 -41
  79. package/src/core/renderers/canvas/CanvasCoreRenderer.ts +369 -364
  80. package/src/core/renderers/canvas/CanvasCoreTexture.ts +150 -150
  81. package/src/core/renderers/canvas/internal/C2DShaderUtils.ts +231 -231
  82. package/src/core/renderers/canvas/internal/ColorUtils.ts +69 -69
  83. package/src/core/renderers/canvas/shaders/UnsupportedShader.ts +48 -48
  84. package/src/core/renderers/webgl/WebGlCoreCtxRenderTexture.ts +79 -79
  85. package/src/core/renderers/webgl/WebGlCoreCtxSubTexture.ts +50 -50
  86. package/src/core/renderers/webgl/WebGlCoreCtxTexture.ts +298 -298
  87. package/src/core/renderers/webgl/WebGlCoreRenderOp.ts +125 -125
  88. package/src/core/renderers/webgl/WebGlCoreRenderer.ts +805 -805
  89. package/src/core/renderers/webgl/WebGlCoreShader.ts +362 -362
  90. package/src/core/renderers/webgl/internal/BufferCollection.ts +54 -54
  91. package/src/core/renderers/webgl/internal/RendererUtils.ts +155 -155
  92. package/src/core/renderers/webgl/internal/ShaderUtils.ts +143 -143
  93. package/src/core/renderers/webgl/internal/WebGlUtils.ts +35 -35
  94. package/src/core/renderers/webgl/shaders/DefaultShader.ts +93 -93
  95. package/src/core/renderers/webgl/shaders/DefaultShaderBatched.ts +132 -132
  96. package/src/core/renderers/webgl/shaders/DynamicShader.ts +580 -580
  97. package/src/core/renderers/webgl/shaders/RoundedRectangle.ts +167 -167
  98. package/src/core/renderers/webgl/shaders/SdfShader.ts +204 -204
  99. package/src/core/renderers/webgl/shaders/effects/BorderBottomEffect.ts +101 -101
  100. package/src/core/renderers/webgl/shaders/effects/BorderEffect.ts +87 -87
  101. package/src/core/renderers/webgl/shaders/effects/BorderLeftEffect.ts +101 -101
  102. package/src/core/renderers/webgl/shaders/effects/BorderRightEffect.ts +101 -101
  103. package/src/core/renderers/webgl/shaders/effects/BorderTopEffect.ts +101 -101
  104. package/src/core/renderers/webgl/shaders/effects/EffectUtils.ts +159 -159
  105. package/src/core/renderers/webgl/shaders/effects/FadeOutEffect.ts +127 -127
  106. package/src/core/renderers/webgl/shaders/effects/GlitchEffect.ts +148 -148
  107. package/src/core/renderers/webgl/shaders/effects/GrayscaleEffect.ts +67 -67
  108. package/src/core/renderers/webgl/shaders/effects/HolePunchEffect.ts +157 -157
  109. package/src/core/renderers/webgl/shaders/effects/LinearGradientEffect.ts +171 -171
  110. package/src/core/renderers/webgl/shaders/effects/RadialGradientEffect.ts +168 -168
  111. package/src/core/renderers/webgl/shaders/effects/RadialProgressEffect.ts +187 -187
  112. package/src/core/renderers/webgl/shaders/effects/RadiusEffect.ts +110 -110
  113. package/src/core/renderers/webgl/shaders/effects/ShaderEffect.ts +196 -196
  114. package/src/core/text-rendering/TextRenderingUtils.ts +36 -36
  115. package/src/core/text-rendering/TextTextureRendererUtils.ts +263 -263
  116. package/src/core/text-rendering/TrFontManager.ts +183 -183
  117. package/src/core/text-rendering/font-face-types/SdfTrFontFace/SdfTrFontFace.ts +176 -176
  118. package/src/core/text-rendering/font-face-types/SdfTrFontFace/internal/FontShaper.ts +139 -139
  119. package/src/core/text-rendering/font-face-types/SdfTrFontFace/internal/SdfFontShaper.test.ts +173 -173
  120. package/src/core/text-rendering/font-face-types/SdfTrFontFace/internal/SdfFontShaper.ts +171 -171
  121. package/src/core/text-rendering/font-face-types/TrFontFace.ts +187 -187
  122. package/src/core/text-rendering/font-face-types/WebTrFontFace.ts +94 -89
  123. package/src/core/text-rendering/renderers/CanvasTextRenderer.ts +509 -509
  124. package/src/core/text-rendering/renderers/LightningTextTextureRenderer.ts +808 -798
  125. package/src/core/text-rendering/renderers/SdfTextRenderer/SdfTextRenderer.ts +853 -853
  126. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/PeekableGenerator.test.ts +48 -48
  127. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/PeekableGenerator.ts +66 -66
  128. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/SpecialCodepoints.ts +52 -52
  129. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/constants.ts +32 -32
  130. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/getStartConditions.ts +117 -117
  131. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/getUnicodeCodepoints.test.ts +133 -133
  132. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/getUnicodeCodepoints.ts +38 -38
  133. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText.ts +408 -403
  134. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/measureText.test.ts +49 -49
  135. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/measureText.ts +52 -52
  136. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/setRenderWindow.test.ts +205 -205
  137. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/setRenderWindow.ts +93 -93
  138. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/util.ts +40 -40
  139. package/src/core/text-rendering/renderers/TextRenderer.ts +557 -557
  140. package/src/core/textures/ColorTexture.ts +102 -102
  141. package/src/core/textures/ImageTexture.ts +379 -378
  142. package/src/core/textures/NoiseTexture.ts +104 -104
  143. package/src/core/textures/RenderTexture.ts +85 -85
  144. package/src/core/textures/SubTexture.ts +179 -171
  145. package/src/core/textures/Texture.ts +435 -423
  146. package/src/core/utils.ts +227 -227
  147. package/src/env.d.ts +7 -7
  148. package/src/main-api/DynamicShaderController.ts +104 -104
  149. package/src/main-api/INode.ts +101 -101
  150. package/src/main-api/Inspector.ts +505 -505
  151. package/src/main-api/Renderer.ts +693 -693
  152. package/src/main-api/ShaderController.ts +80 -80
  153. package/src/main-api/utils.ts +45 -45
  154. package/src/utils.ts +248 -248
  155. package/dist/exports/core-api.d.ts +0 -74
  156. package/dist/exports/core-api.js +0 -96
  157. package/dist/exports/core-api.js.map +0 -1
  158. package/dist/exports/main-api.d.ts +0 -30
  159. package/dist/exports/main-api.js +0 -45
  160. package/dist/exports/main-api.js.map +0 -1
  161. package/dist/src/core/CoreExtension.d.ts +0 -12
  162. package/dist/src/core/CoreExtension.js +0 -29
  163. package/dist/src/core/CoreExtension.js.map +0 -1
  164. package/dist/src/main-api/ICoreDriver.d.ts +0 -24
  165. package/dist/src/main-api/ICoreDriver.js +0 -20
  166. package/dist/src/main-api/ICoreDriver.js.map +0 -1
  167. package/dist/src/main-api/RendererMain.d.ts +0 -378
  168. package/dist/src/main-api/RendererMain.js +0 -367
  169. package/dist/src/main-api/RendererMain.js.map +0 -1
  170. package/dist/src/main-api/texture-usage-trackers/FinalizationRegistryTextureUsageTracker.d.ts +0 -9
  171. package/dist/src/main-api/texture-usage-trackers/FinalizationRegistryTextureUsageTracker.js +0 -38
  172. package/dist/src/main-api/texture-usage-trackers/FinalizationRegistryTextureUsageTracker.js.map +0 -1
  173. package/dist/src/main-api/texture-usage-trackers/ManualCountTextureUsageTracker.d.ts +0 -56
  174. package/dist/src/main-api/texture-usage-trackers/ManualCountTextureUsageTracker.js +0 -101
  175. package/dist/src/main-api/texture-usage-trackers/ManualCountTextureUsageTracker.js.map +0 -1
  176. package/dist/src/main-api/texture-usage-trackers/TextureUsageTracker.d.ts +0 -32
  177. package/dist/src/main-api/texture-usage-trackers/TextureUsageTracker.js +0 -28
  178. package/dist/src/main-api/texture-usage-trackers/TextureUsageTracker.js.map +0 -1
  179. package/dist/src/render-drivers/main/MainCoreDriver.d.ts +0 -21
  180. package/dist/src/render-drivers/main/MainCoreDriver.js +0 -115
  181. package/dist/src/render-drivers/main/MainCoreDriver.js.map +0 -1
  182. package/dist/src/render-drivers/main/MainOnlyNode.d.ts +0 -101
  183. package/dist/src/render-drivers/main/MainOnlyNode.js +0 -425
  184. package/dist/src/render-drivers/main/MainOnlyNode.js.map +0 -1
  185. package/dist/src/render-drivers/main/MainOnlyTextNode.d.ts +0 -47
  186. package/dist/src/render-drivers/main/MainOnlyTextNode.js +0 -204
  187. package/dist/src/render-drivers/main/MainOnlyTextNode.js.map +0 -1
  188. package/dist/src/render-drivers/threadx/NodeStruct.d.ts +0 -93
  189. package/dist/src/render-drivers/threadx/NodeStruct.js +0 -290
  190. package/dist/src/render-drivers/threadx/NodeStruct.js.map +0 -1
  191. package/dist/src/render-drivers/threadx/SharedNode.d.ts +0 -40
  192. package/dist/src/render-drivers/threadx/SharedNode.js +0 -61
  193. package/dist/src/render-drivers/threadx/SharedNode.js.map +0 -1
  194. package/dist/src/render-drivers/threadx/TextNodeStruct.d.ts +0 -44
  195. package/dist/src/render-drivers/threadx/TextNodeStruct.js +0 -203
  196. package/dist/src/render-drivers/threadx/TextNodeStruct.js.map +0 -1
  197. package/dist/src/render-drivers/threadx/ThreadXCoreDriver.d.ts +0 -25
  198. package/dist/src/render-drivers/threadx/ThreadXCoreDriver.js +0 -232
  199. package/dist/src/render-drivers/threadx/ThreadXCoreDriver.js.map +0 -1
  200. package/dist/src/render-drivers/threadx/ThreadXMainAnimationController.d.ts +0 -24
  201. package/dist/src/render-drivers/threadx/ThreadXMainAnimationController.js +0 -113
  202. package/dist/src/render-drivers/threadx/ThreadXMainAnimationController.js.map +0 -1
  203. package/dist/src/render-drivers/threadx/ThreadXMainNode.d.ts +0 -46
  204. package/dist/src/render-drivers/threadx/ThreadXMainNode.js +0 -160
  205. package/dist/src/render-drivers/threadx/ThreadXMainNode.js.map +0 -1
  206. package/dist/src/render-drivers/threadx/ThreadXMainTextNode.d.ts +0 -28
  207. package/dist/src/render-drivers/threadx/ThreadXMainTextNode.js +0 -55
  208. package/dist/src/render-drivers/threadx/ThreadXMainTextNode.js.map +0 -1
  209. package/dist/src/render-drivers/threadx/ThreadXRendererMessage.d.ts +0 -70
  210. package/dist/src/render-drivers/threadx/ThreadXRendererMessage.js +0 -32
  211. package/dist/src/render-drivers/threadx/ThreadXRendererMessage.js.map +0 -1
  212. package/dist/src/render-drivers/threadx/worker/ThreadXRendererNode.d.ts +0 -19
  213. package/dist/src/render-drivers/threadx/worker/ThreadXRendererNode.js +0 -184
  214. package/dist/src/render-drivers/threadx/worker/ThreadXRendererNode.js.map +0 -1
  215. package/dist/src/render-drivers/threadx/worker/ThreadXRendererTextNode.d.ts +0 -27
  216. package/dist/src/render-drivers/threadx/worker/ThreadXRendererTextNode.js +0 -109
  217. package/dist/src/render-drivers/threadx/worker/ThreadXRendererTextNode.js.map +0 -1
  218. package/dist/src/render-drivers/threadx/worker/renderer.d.ts +0 -1
  219. package/dist/src/render-drivers/threadx/worker/renderer.js +0 -147
  220. package/dist/src/render-drivers/threadx/worker/renderer.js.map +0 -1
  221. package/dist/src/render-drivers/utils.d.ts +0 -12
  222. package/dist/src/render-drivers/utils.js +0 -74
  223. package/dist/src/render-drivers/utils.js.map +0 -1
  224. package/dist/tsconfig.tsbuildinfo +0 -1
@@ -1,548 +1,548 @@
1
- /*
2
- * If not stated otherwise in this file or this component's LICENSE file the
3
- * following copyright and licenses apply:
4
- *
5
- * Copyright 2023 Comcast Cable Communications Management, LLC.
6
- *
7
- * Licensed under the Apache License, Version 2.0 (the License);
8
- * you may not use this file except in compliance with the License.
9
- * You may obtain a copy of the License at
10
- *
11
- * http://www.apache.org/licenses/LICENSE-2.0
12
- *
13
- * Unless required by applicable law or agreed to in writing, software
14
- * distributed under the License is distributed on an "AS IS" BASIS,
15
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
- * See the License for the specific language governing permissions and
17
- * limitations under the License.
18
- */
19
-
20
- import { ImageWorkerManager } from './lib/ImageWorker.js';
21
- import type { CoreRenderer } from './renderers/CoreRenderer.js';
22
- import { ColorTexture } from './textures/ColorTexture.js';
23
- import { ImageTexture } from './textures/ImageTexture.js';
24
- import { NoiseTexture } from './textures/NoiseTexture.js';
25
- import { SubTexture } from './textures/SubTexture.js';
26
- import { RenderTexture } from './textures/RenderTexture.js';
27
- import type { Texture } from './textures/Texture.js';
28
- import { EventEmitter } from '../common/EventEmitter.js';
29
-
30
- /**
31
- * Augmentable map of texture class types
32
- *
33
- * @remarks
34
- * This interface can be augmented by other modules/apps to add additional
35
- * texture types. The ones included directly here are the ones that are
36
- * included in the core library.
37
- */
38
- export interface TextureMap {
39
- ColorTexture: typeof ColorTexture;
40
- ImageTexture: typeof ImageTexture;
41
- NoiseTexture: typeof NoiseTexture;
42
- SubTexture: typeof SubTexture;
43
- RenderTexture: typeof RenderTexture;
44
- }
45
-
46
- export interface CreateImageBitmapSupport {
47
- basic: boolean; // Supports createImageBitmap(image)
48
- options: boolean; // Supports createImageBitmap(image, options)
49
- full: boolean; // Supports createImageBitmap(image, sx, sy, sw, sh, options)
50
- }
51
-
52
- export type ExtractProps<Type> = Type extends { z$__type__Props: infer Props }
53
- ? Props
54
- : never;
55
-
56
- /**
57
- * Contains information about the texture manager's internal state
58
- * for debugging purposes.
59
- */
60
- export interface TextureManagerDebugInfo {
61
- keyCacheSize: number;
62
- }
63
-
64
- export type ResizeModeOptions =
65
- | {
66
- /**
67
- * Specifies that the image should be resized to cover the specified dimensions.
68
- */
69
- type: 'cover';
70
- /**
71
- * The horizontal clipping position
72
- * To clip the left, set clipX to 0. To clip the right, set clipX to 1.
73
- * clipX 0.5 will clip a equal amount from left and right
74
- *
75
- * @defaultValue 0.5
76
- */
77
- clipX?: number;
78
- /**
79
- * The vertical clipping position
80
- * To clip the top, set clipY to 0. To clip the bottom, set clipY to 1.
81
- * clipY 0.5 will clip a equal amount from top and bottom
82
- *
83
- * @defaultValue 0.5
84
- */
85
- clipY?: number;
86
- }
87
- | {
88
- /**
89
- * Specifies that the image should be resized to fit within the specified dimensions.
90
- */
91
- type: 'contain';
92
- };
93
-
94
- /**
95
- * Universal options for all texture types
96
- *
97
- * @remarks
98
- * Texture Options provide a way to specify options that are relevant to the
99
- * texture loading process (including caching) and specifically for how a
100
- * texture is rendered within a specific Node (or set of Nodes).
101
- *
102
- * They are not used in determining the cache key for a texture (except if
103
- * the `cacheKey` option is provided explicitly to oveerride the default
104
- * cache key for the texture instance) nor are they stored/referenced within
105
- * the texture instance itself. Instead, the options are stored/referenced
106
- * within individual Nodes. So a single texture instance can be used in
107
- * multiple Nodes each using a different set of options.
108
- */
109
- export interface TextureOptions {
110
- /**
111
- * Preload the texture immediately even if it's not being rendered to the
112
- * screen.
113
- *
114
- * @remarks
115
- * This allows the texture to be used immediately without any delay when it
116
- * is first needed for rendering. Otherwise the loading process will start
117
- * when the texture is first rendered, which may cause a delay in that texture
118
- * being shown properly.
119
- *
120
- * @defaultValue `false`
121
- */
122
- preload?: boolean;
123
-
124
- /**
125
- * Prevent clean up of the texture when it is no longer being used.
126
- *
127
- * @remarks
128
- * This is useful when you want to keep the texture in memory for later use.
129
- * Regardless of whether the texture is being used or not, it will not be
130
- * cleaned up.
131
- *
132
- * @defaultValue `false`
133
- */
134
- preventCleanup?: boolean;
135
-
136
- /**
137
- * Flip the texture horizontally when rendering
138
- *
139
- * @defaultValue `false`
140
- */
141
- flipX?: boolean;
142
-
143
- /**
144
- * Flip the texture vertically when rendering
145
- *
146
- * @defaultValue `false`
147
- */
148
- flipY?: boolean;
149
-
150
- /**
151
- * You can use resizeMode to determine the clipping automatically from the width
152
- * and height of the source texture. This can be convenient if you are unsure about
153
- * the exact image sizes but want the image to cover a specific area.
154
- *
155
- * The resize modes cover and contain are supported
156
- */
157
- resizeMode?: ResizeModeOptions;
158
- }
159
-
160
- export class CoreTextureManager extends EventEmitter {
161
- /**
162
- * Map of textures by cache key
163
- */
164
- keyCache: Map<string, Texture> = new Map();
165
-
166
- /**
167
- * Map of cache keys by texture
168
- */
169
- inverseKeyCache: WeakMap<Texture, string> = new WeakMap();
170
-
171
- /**
172
- * Map of texture constructors by their type name
173
- */
174
- txConstructors: Partial<TextureMap> = {};
175
-
176
- private downloadTextureSourceQueue: Array<Texture> = [];
177
- private priorityQueue: Array<Texture> = [];
178
- private uploadTextureQueue: Array<Texture> = [];
179
- private initialized = false;
180
-
181
- imageWorkerManager: ImageWorkerManager | null = null;
182
- hasCreateImageBitmap = !!self.createImageBitmap;
183
- imageBitmapSupported = {
184
- basic: false,
185
- options: false,
186
- full: false,
187
- };
188
-
189
- hasWorker = !!self.Worker;
190
- /**
191
- * Renderer that this texture manager is associated with
192
- *
193
- * @remarks
194
- * This MUST be set before the texture manager is used. Otherwise errors
195
- * will occur when using the texture manager.
196
- */
197
- renderer!: CoreRenderer;
198
-
199
- /**
200
- * The current frame time in milliseconds
201
- *
202
- * @remarks
203
- * This is used to populate the `lastRenderableChangeTime` property of
204
- * {@link Texture} instances when their renderable state changes.
205
- *
206
- * Set by stage via `updateFrameTime` method.
207
- */
208
- frameTime = 0;
209
-
210
- constructor(numImageWorkers: number) {
211
- super();
212
- this.validateCreateImageBitmap()
213
- .then((result) => {
214
- this.hasCreateImageBitmap =
215
- result.basic || result.options || result.full;
216
- this.imageBitmapSupported = result;
217
-
218
- if (!this.hasCreateImageBitmap) {
219
- console.warn(
220
- '[Lightning] createImageBitmap is not supported on this browser. ImageTexture will be slower.',
221
- );
222
- }
223
-
224
- if (
225
- this.hasCreateImageBitmap &&
226
- this.hasWorker &&
227
- numImageWorkers > 0
228
- ) {
229
- this.imageWorkerManager = new ImageWorkerManager(
230
- numImageWorkers,
231
- result,
232
- );
233
- } else {
234
- console.warn(
235
- '[Lightning] Imageworker is 0 or not supported on this browser. Image loading will be slower.',
236
- );
237
- }
238
-
239
- this.initialized = true;
240
- this.emit('initialized');
241
- })
242
- .catch((e) => {
243
- console.warn(
244
- '[Lightning] createImageBitmap is not supported on this browser. ImageTexture will be slower.',
245
- );
246
-
247
- // initialized without image worker manager and createImageBitmap
248
- this.initialized = true;
249
- this.emit('initialized');
250
- });
251
-
252
- this.registerTextureType('ImageTexture', ImageTexture);
253
- this.registerTextureType('ColorTexture', ColorTexture);
254
- this.registerTextureType('NoiseTexture', NoiseTexture);
255
- this.registerTextureType('SubTexture', SubTexture);
256
- this.registerTextureType('RenderTexture', RenderTexture);
257
- }
258
-
259
- private async validateCreateImageBitmap(): Promise<CreateImageBitmapSupport> {
260
- // Test if createImageBitmap is supported using a simple 1x1 PNG image
261
- // prettier-ignore
262
- const pngBinaryData = new Uint8Array([
263
- 0x89, 0x50, 0x4e, 0x47,
264
- 0x0d, 0x0a, 0x1a, 0x0a, // PNG signature
265
- 0x00, 0x00, 0x00, 0x0d, // IHDR chunk length
266
- 0x49, 0x48, 0x44, 0x52, // "IHDR" chunk type
267
- 0x00, 0x00, 0x00, 0x01, // Width: 1
268
- 0x00, 0x00, 0x00, 0x01, // Height: 1
269
- 0x01, // Bit depth: 1
270
- 0x03, // Color type: Indexed
271
- 0x00, // Compression method: Deflate
272
- 0x00, // Filter method: None
273
- 0x00, // Interlace method: None
274
- 0x25, 0xdb, 0x56, 0xca, // CRC for IHDR
275
- 0x00, 0x00, 0x00, 0x03, // PLTE chunk length
276
- 0x50, 0x4c, 0x54, 0x45, // "PLTE" chunk type
277
- 0x00, 0x00, 0x00, // Palette entry: Black
278
- 0xa7, 0x7a, 0x3d, 0xda, // CRC for PLTE
279
- 0x00, 0x00, 0x00, 0x01, // tRNS chunk length
280
- 0x74, 0x52, 0x4e, 0x53, // "tRNS" chunk type
281
- 0x00, // Transparency for black: Fully transparent
282
- 0x40, 0xe6, 0xd8, 0x66, // CRC for tRNS
283
- 0x00, 0x00, 0x00, 0x0a, // IDAT chunk length
284
- 0x49, 0x44, 0x41, 0x54, // "IDAT" chunk type
285
- 0x08, 0xd7, // Deflate header
286
- 0x63, 0x60, 0x00, 0x00,
287
- 0x00, 0x02, 0x00, 0x01, // Zlib-compressed data
288
- 0xe2, 0x21, 0xbc, 0x33, // CRC for IDAT
289
- 0x00, 0x00, 0x00, 0x00, // IEND chunk length
290
- 0x49, 0x45, 0x4e, 0x44, // "IEND" chunk type
291
- 0xae, 0x42, 0x60, 0x82, // CRC for IEND
292
- ]);
293
-
294
- const support: CreateImageBitmapSupport = {
295
- basic: false,
296
- options: false,
297
- full: false,
298
- };
299
-
300
- // Test basic createImageBitmap support
301
- const blob = new Blob([pngBinaryData], { type: 'image/png' });
302
- const bitmap = await createImageBitmap(blob);
303
- bitmap.close?.();
304
- support.basic = true;
305
-
306
- // Test createImageBitmap with options support
307
- try {
308
- const options = { premultiplyAlpha: 'none' as const };
309
- const bitmapWithOptions = await createImageBitmap(blob, options);
310
- bitmapWithOptions.close?.();
311
- support.options = true;
312
- } catch (e) {
313
- /* ignore */
314
- }
315
-
316
- // Test createImageBitmap with full options support
317
- try {
318
- const bitmapWithFullOptions = await createImageBitmap(blob, 0, 0, 1, 1, {
319
- premultiplyAlpha: 'none',
320
- });
321
- bitmapWithFullOptions.close?.();
322
- support.full = true;
323
- } catch (e) {
324
- /* ignore */
325
- }
326
-
327
- return support;
328
- }
329
-
330
- registerTextureType<Type extends keyof TextureMap>(
331
- textureType: Type,
332
- textureClass: TextureMap[Type],
333
- ): void {
334
- this.txConstructors[textureType] = textureClass;
335
- }
336
-
337
- /**
338
- * Enqueue a texture for downloading its source image.
339
- */
340
- enqueueDownloadTextureSource(texture: Texture): void {
341
- if (!this.downloadTextureSourceQueue.includes(texture)) {
342
- this.downloadTextureSourceQueue.push(texture);
343
- }
344
- }
345
-
346
- /**
347
- * Enqueue a texture for uploading to the GPU.
348
- *
349
- * @param texture - The texture to upload
350
- */
351
- enqueueUploadTexture(texture: Texture): void {
352
- if (this.uploadTextureQueue.includes(texture) === false) {
353
- this.uploadTextureQueue.push(texture);
354
- }
355
- }
356
-
357
- /**
358
- * Create a texture
359
- *
360
- * @param textureType - The type of texture to create
361
- * @param props - The properties to use for the texture
362
- */
363
- createTexture<Type extends keyof TextureMap>(
364
- textureType: Type,
365
- props: ExtractProps<TextureMap[Type]>,
366
- ): InstanceType<TextureMap[Type]> {
367
- let texture: Texture | undefined;
368
- const TextureClass = this.txConstructors[textureType];
369
- if (!TextureClass) {
370
- throw new Error(`Texture type "${textureType}" is not registered`);
371
- }
372
-
373
- const cacheKey = TextureClass.makeCacheKey(props as any);
374
- if (cacheKey && this.keyCache.has(cacheKey)) {
375
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
376
- texture = this.keyCache.get(cacheKey)!;
377
- } else {
378
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
379
- texture = new TextureClass(this, props as any);
380
-
381
- if (cacheKey) {
382
- this.initTextureToCache(texture, cacheKey);
383
- }
384
- }
385
-
386
- return texture as InstanceType<TextureMap[Type]>;
387
- }
388
-
389
- /**
390
- * Override loadTexture to use the batched approach.
391
- *
392
- * @param texture - The texture to load
393
- * @param immediate - Whether to prioritize the texture for immediate loading
394
- */
395
- loadTexture(texture: Texture, priority?: boolean): void {
396
- if (texture.state === 'loaded' || texture.state === 'loading') {
397
- return;
398
- }
399
-
400
- texture.setSourceState('loading');
401
- texture.setCoreCtxState('loading');
402
-
403
- // if we're not initialized, just queue the texture into the priority queue
404
- if (this.initialized === false) {
405
- this.priorityQueue.push(texture);
406
- return;
407
- }
408
-
409
- // prioritize the texture for immediate loading
410
- if (priority === true) {
411
- texture
412
- .getTextureData()
413
- .then(() => {
414
- this.uploadTexture(texture);
415
- })
416
- .catch((err) => {
417
- console.error(err);
418
- });
419
- }
420
-
421
- // enqueue the texture for download and upload
422
- this.enqueueDownloadTextureSource(texture);
423
- }
424
-
425
- /**
426
- * Upload a texture to the GPU
427
- *
428
- * @param texture Texture to upload
429
- */
430
- uploadTexture(texture: Texture): void {
431
- const coreContext = texture.loadCtxTexture();
432
- coreContext.load();
433
- }
434
-
435
- /**
436
- * Process a limited number of downloads and uploads.
437
- *
438
- * @param maxItems - The maximum number of items to process
439
- */
440
- processSome(maxItems = 0): void {
441
- if (this.initialized === false) {
442
- return;
443
- }
444
-
445
- let itemsProcessed = 0;
446
-
447
- // Process priority queue
448
- while (
449
- this.priorityQueue.length > 0 &&
450
- (maxItems === 0 || itemsProcessed < maxItems)
451
- ) {
452
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
453
- const texture = this.priorityQueue.shift()!;
454
- texture.getTextureData().then(() => {
455
- this.uploadTexture(texture);
456
- });
457
- itemsProcessed++;
458
- }
459
-
460
- // Process uploads
461
- while (
462
- this.uploadTextureQueue.length > 0 &&
463
- (maxItems === 0 || itemsProcessed < maxItems)
464
- ) {
465
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
466
- this.uploadTexture(this.uploadTextureQueue.shift()!);
467
- itemsProcessed++;
468
- }
469
-
470
- // Process downloads
471
- while (
472
- this.downloadTextureSourceQueue.length > 0 &&
473
- (maxItems === 0 || itemsProcessed < maxItems)
474
- ) {
475
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
476
- const texture = this.downloadTextureSourceQueue.shift()!;
477
- queueMicrotask(() => {
478
- texture.getTextureData().then(() => {
479
- this.enqueueUploadTexture(texture);
480
- });
481
- });
482
-
483
- itemsProcessed++;
484
- }
485
- }
486
-
487
- public hasUpdates(): boolean {
488
- return (
489
- this.downloadTextureSourceQueue.length > 0 ||
490
- this.uploadTextureQueue.length > 0
491
- );
492
- }
493
-
494
- /**
495
- * Initialize a texture to the cache
496
- *
497
- * @param texture Texture to cache
498
- * @param cacheKey Cache key for the texture
499
- */
500
- initTextureToCache(texture: Texture, cacheKey: string) {
501
- const { keyCache, inverseKeyCache } = this;
502
- keyCache.set(cacheKey, texture);
503
- inverseKeyCache.set(texture, cacheKey);
504
- }
505
-
506
- /**
507
- * Get a texture from the cache
508
- *
509
- * @param cacheKey
510
- */
511
- getTextureFromCache(cacheKey: string): Texture | undefined {
512
- return this.keyCache.get(cacheKey);
513
- }
514
-
515
- /**
516
- * Remove a texture from the cache
517
- *
518
- * @remarks
519
- * Called by Texture Cleanup when a texture is freed.
520
- *
521
- * @param texture
522
- */
523
- removeTextureFromCache(texture: Texture) {
524
- const { inverseKeyCache, keyCache } = this;
525
- const cacheKey = inverseKeyCache.get(texture);
526
- if (cacheKey) {
527
- keyCache.delete(cacheKey);
528
- }
529
- }
530
-
531
- /**
532
- * Resolve a parent texture from the cache or fallback to the provided texture.
533
- *
534
- * @param texture - The provided texture to resolve.
535
- * @returns The cached or provided texture.
536
- */
537
- resolveParentTexture(texture: ImageTexture): Texture {
538
- if (!texture?.props) {
539
- return texture;
540
- }
541
-
542
- const cacheKey = ImageTexture.makeCacheKey(texture.props);
543
- const cachedTexture = cacheKey
544
- ? this.getTextureFromCache(cacheKey)
545
- : undefined;
546
- return cachedTexture ?? texture;
547
- }
548
- }
1
+ /*
2
+ * If not stated otherwise in this file or this component's LICENSE file the
3
+ * following copyright and licenses apply:
4
+ *
5
+ * Copyright 2023 Comcast Cable Communications Management, LLC.
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the License);
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+
20
+ import { ImageWorkerManager } from './lib/ImageWorker.js';
21
+ import type { CoreRenderer } from './renderers/CoreRenderer.js';
22
+ import { ColorTexture } from './textures/ColorTexture.js';
23
+ import { ImageTexture } from './textures/ImageTexture.js';
24
+ import { NoiseTexture } from './textures/NoiseTexture.js';
25
+ import { SubTexture } from './textures/SubTexture.js';
26
+ import { RenderTexture } from './textures/RenderTexture.js';
27
+ import type { Texture } from './textures/Texture.js';
28
+ import { EventEmitter } from '../common/EventEmitter.js';
29
+
30
+ /**
31
+ * Augmentable map of texture class types
32
+ *
33
+ * @remarks
34
+ * This interface can be augmented by other modules/apps to add additional
35
+ * texture types. The ones included directly here are the ones that are
36
+ * included in the core library.
37
+ */
38
+ export interface TextureMap {
39
+ ColorTexture: typeof ColorTexture;
40
+ ImageTexture: typeof ImageTexture;
41
+ NoiseTexture: typeof NoiseTexture;
42
+ SubTexture: typeof SubTexture;
43
+ RenderTexture: typeof RenderTexture;
44
+ }
45
+
46
+ export interface CreateImageBitmapSupport {
47
+ basic: boolean; // Supports createImageBitmap(image)
48
+ options: boolean; // Supports createImageBitmap(image, options)
49
+ full: boolean; // Supports createImageBitmap(image, sx, sy, sw, sh, options)
50
+ }
51
+
52
+ export type ExtractProps<Type> = Type extends { z$__type__Props: infer Props }
53
+ ? Props
54
+ : never;
55
+
56
+ /**
57
+ * Contains information about the texture manager's internal state
58
+ * for debugging purposes.
59
+ */
60
+ export interface TextureManagerDebugInfo {
61
+ keyCacheSize: number;
62
+ }
63
+
64
+ export type ResizeModeOptions =
65
+ | {
66
+ /**
67
+ * Specifies that the image should be resized to cover the specified dimensions.
68
+ */
69
+ type: 'cover';
70
+ /**
71
+ * The horizontal clipping position
72
+ * To clip the left, set clipX to 0. To clip the right, set clipX to 1.
73
+ * clipX 0.5 will clip a equal amount from left and right
74
+ *
75
+ * @defaultValue 0.5
76
+ */
77
+ clipX?: number;
78
+ /**
79
+ * The vertical clipping position
80
+ * To clip the top, set clipY to 0. To clip the bottom, set clipY to 1.
81
+ * clipY 0.5 will clip a equal amount from top and bottom
82
+ *
83
+ * @defaultValue 0.5
84
+ */
85
+ clipY?: number;
86
+ }
87
+ | {
88
+ /**
89
+ * Specifies that the image should be resized to fit within the specified dimensions.
90
+ */
91
+ type: 'contain';
92
+ };
93
+
94
+ /**
95
+ * Universal options for all texture types
96
+ *
97
+ * @remarks
98
+ * Texture Options provide a way to specify options that are relevant to the
99
+ * texture loading process (including caching) and specifically for how a
100
+ * texture is rendered within a specific Node (or set of Nodes).
101
+ *
102
+ * They are not used in determining the cache key for a texture (except if
103
+ * the `cacheKey` option is provided explicitly to oveerride the default
104
+ * cache key for the texture instance) nor are they stored/referenced within
105
+ * the texture instance itself. Instead, the options are stored/referenced
106
+ * within individual Nodes. So a single texture instance can be used in
107
+ * multiple Nodes each using a different set of options.
108
+ */
109
+ export interface TextureOptions {
110
+ /**
111
+ * Preload the texture immediately even if it's not being rendered to the
112
+ * screen.
113
+ *
114
+ * @remarks
115
+ * This allows the texture to be used immediately without any delay when it
116
+ * is first needed for rendering. Otherwise the loading process will start
117
+ * when the texture is first rendered, which may cause a delay in that texture
118
+ * being shown properly.
119
+ *
120
+ * @defaultValue `false`
121
+ */
122
+ preload?: boolean;
123
+
124
+ /**
125
+ * Prevent clean up of the texture when it is no longer being used.
126
+ *
127
+ * @remarks
128
+ * This is useful when you want to keep the texture in memory for later use.
129
+ * Regardless of whether the texture is being used or not, it will not be
130
+ * cleaned up.
131
+ *
132
+ * @defaultValue `false`
133
+ */
134
+ preventCleanup?: boolean;
135
+
136
+ /**
137
+ * Flip the texture horizontally when rendering
138
+ *
139
+ * @defaultValue `false`
140
+ */
141
+ flipX?: boolean;
142
+
143
+ /**
144
+ * Flip the texture vertically when rendering
145
+ *
146
+ * @defaultValue `false`
147
+ */
148
+ flipY?: boolean;
149
+
150
+ /**
151
+ * You can use resizeMode to determine the clipping automatically from the width
152
+ * and height of the source texture. This can be convenient if you are unsure about
153
+ * the exact image sizes but want the image to cover a specific area.
154
+ *
155
+ * The resize modes cover and contain are supported
156
+ */
157
+ resizeMode?: ResizeModeOptions;
158
+ }
159
+
160
+ export class CoreTextureManager extends EventEmitter {
161
+ /**
162
+ * Map of textures by cache key
163
+ */
164
+ keyCache: Map<string, Texture> = new Map();
165
+
166
+ /**
167
+ * Map of cache keys by texture
168
+ */
169
+ inverseKeyCache: WeakMap<Texture, string> = new WeakMap();
170
+
171
+ /**
172
+ * Map of texture constructors by their type name
173
+ */
174
+ txConstructors: Partial<TextureMap> = {};
175
+
176
+ private downloadTextureSourceQueue: Array<Texture> = [];
177
+ private priorityQueue: Array<Texture> = [];
178
+ private uploadTextureQueue: Array<Texture> = [];
179
+ private initialized = false;
180
+
181
+ imageWorkerManager: ImageWorkerManager | null = null;
182
+ hasCreateImageBitmap = !!self.createImageBitmap;
183
+ imageBitmapSupported = {
184
+ basic: false,
185
+ options: false,
186
+ full: false,
187
+ };
188
+
189
+ hasWorker = !!self.Worker;
190
+ /**
191
+ * Renderer that this texture manager is associated with
192
+ *
193
+ * @remarks
194
+ * This MUST be set before the texture manager is used. Otherwise errors
195
+ * will occur when using the texture manager.
196
+ */
197
+ renderer!: CoreRenderer;
198
+
199
+ /**
200
+ * The current frame time in milliseconds
201
+ *
202
+ * @remarks
203
+ * This is used to populate the `lastRenderableChangeTime` property of
204
+ * {@link Texture} instances when their renderable state changes.
205
+ *
206
+ * Set by stage via `updateFrameTime` method.
207
+ */
208
+ frameTime = 0;
209
+
210
+ constructor(numImageWorkers: number) {
211
+ super();
212
+ this.validateCreateImageBitmap()
213
+ .then((result) => {
214
+ this.hasCreateImageBitmap =
215
+ result.basic || result.options || result.full;
216
+ this.imageBitmapSupported = result;
217
+
218
+ if (!this.hasCreateImageBitmap) {
219
+ console.warn(
220
+ '[Lightning] createImageBitmap is not supported on this browser. ImageTexture will be slower.',
221
+ );
222
+ }
223
+
224
+ if (
225
+ this.hasCreateImageBitmap &&
226
+ this.hasWorker &&
227
+ numImageWorkers > 0
228
+ ) {
229
+ this.imageWorkerManager = new ImageWorkerManager(
230
+ numImageWorkers,
231
+ result,
232
+ );
233
+ } else {
234
+ console.warn(
235
+ '[Lightning] Imageworker is 0 or not supported on this browser. Image loading will be slower.',
236
+ );
237
+ }
238
+
239
+ this.initialized = true;
240
+ this.emit('initialized');
241
+ })
242
+ .catch((e) => {
243
+ console.warn(
244
+ '[Lightning] createImageBitmap is not supported on this browser. ImageTexture will be slower.',
245
+ );
246
+
247
+ // initialized without image worker manager and createImageBitmap
248
+ this.initialized = true;
249
+ this.emit('initialized');
250
+ });
251
+
252
+ this.registerTextureType('ImageTexture', ImageTexture);
253
+ this.registerTextureType('ColorTexture', ColorTexture);
254
+ this.registerTextureType('NoiseTexture', NoiseTexture);
255
+ this.registerTextureType('SubTexture', SubTexture);
256
+ this.registerTextureType('RenderTexture', RenderTexture);
257
+ }
258
+
259
+ private async validateCreateImageBitmap(): Promise<CreateImageBitmapSupport> {
260
+ // Test if createImageBitmap is supported using a simple 1x1 PNG image
261
+ // prettier-ignore
262
+ const pngBinaryData = new Uint8Array([
263
+ 0x89, 0x50, 0x4e, 0x47,
264
+ 0x0d, 0x0a, 0x1a, 0x0a, // PNG signature
265
+ 0x00, 0x00, 0x00, 0x0d, // IHDR chunk length
266
+ 0x49, 0x48, 0x44, 0x52, // "IHDR" chunk type
267
+ 0x00, 0x00, 0x00, 0x01, // Width: 1
268
+ 0x00, 0x00, 0x00, 0x01, // Height: 1
269
+ 0x01, // Bit depth: 1
270
+ 0x03, // Color type: Indexed
271
+ 0x00, // Compression method: Deflate
272
+ 0x00, // Filter method: None
273
+ 0x00, // Interlace method: None
274
+ 0x25, 0xdb, 0x56, 0xca, // CRC for IHDR
275
+ 0x00, 0x00, 0x00, 0x03, // PLTE chunk length
276
+ 0x50, 0x4c, 0x54, 0x45, // "PLTE" chunk type
277
+ 0x00, 0x00, 0x00, // Palette entry: Black
278
+ 0xa7, 0x7a, 0x3d, 0xda, // CRC for PLTE
279
+ 0x00, 0x00, 0x00, 0x01, // tRNS chunk length
280
+ 0x74, 0x52, 0x4e, 0x53, // "tRNS" chunk type
281
+ 0x00, // Transparency for black: Fully transparent
282
+ 0x40, 0xe6, 0xd8, 0x66, // CRC for tRNS
283
+ 0x00, 0x00, 0x00, 0x0a, // IDAT chunk length
284
+ 0x49, 0x44, 0x41, 0x54, // "IDAT" chunk type
285
+ 0x08, 0xd7, // Deflate header
286
+ 0x63, 0x60, 0x00, 0x00,
287
+ 0x00, 0x02, 0x00, 0x01, // Zlib-compressed data
288
+ 0xe2, 0x21, 0xbc, 0x33, // CRC for IDAT
289
+ 0x00, 0x00, 0x00, 0x00, // IEND chunk length
290
+ 0x49, 0x45, 0x4e, 0x44, // "IEND" chunk type
291
+ 0xae, 0x42, 0x60, 0x82, // CRC for IEND
292
+ ]);
293
+
294
+ const support: CreateImageBitmapSupport = {
295
+ basic: false,
296
+ options: false,
297
+ full: false,
298
+ };
299
+
300
+ // Test basic createImageBitmap support
301
+ const blob = new Blob([pngBinaryData], { type: 'image/png' });
302
+ const bitmap = await createImageBitmap(blob);
303
+ bitmap.close?.();
304
+ support.basic = true;
305
+
306
+ // Test createImageBitmap with options support
307
+ try {
308
+ const options = { premultiplyAlpha: 'none' as const };
309
+ const bitmapWithOptions = await createImageBitmap(blob, options);
310
+ bitmapWithOptions.close?.();
311
+ support.options = true;
312
+ } catch (e) {
313
+ /* ignore */
314
+ }
315
+
316
+ // Test createImageBitmap with full options support
317
+ try {
318
+ const bitmapWithFullOptions = await createImageBitmap(blob, 0, 0, 1, 1, {
319
+ premultiplyAlpha: 'none',
320
+ });
321
+ bitmapWithFullOptions.close?.();
322
+ support.full = true;
323
+ } catch (e) {
324
+ /* ignore */
325
+ }
326
+
327
+ return support;
328
+ }
329
+
330
+ registerTextureType<Type extends keyof TextureMap>(
331
+ textureType: Type,
332
+ textureClass: TextureMap[Type],
333
+ ): void {
334
+ this.txConstructors[textureType] = textureClass;
335
+ }
336
+
337
+ /**
338
+ * Enqueue a texture for downloading its source image.
339
+ */
340
+ enqueueDownloadTextureSource(texture: Texture): void {
341
+ if (!this.downloadTextureSourceQueue.includes(texture)) {
342
+ this.downloadTextureSourceQueue.push(texture);
343
+ }
344
+ }
345
+
346
+ /**
347
+ * Enqueue a texture for uploading to the GPU.
348
+ *
349
+ * @param texture - The texture to upload
350
+ */
351
+ enqueueUploadTexture(texture: Texture): void {
352
+ if (this.uploadTextureQueue.includes(texture) === false) {
353
+ this.uploadTextureQueue.push(texture);
354
+ }
355
+ }
356
+
357
+ /**
358
+ * Create a texture
359
+ *
360
+ * @param textureType - The type of texture to create
361
+ * @param props - The properties to use for the texture
362
+ */
363
+ createTexture<Type extends keyof TextureMap>(
364
+ textureType: Type,
365
+ props: ExtractProps<TextureMap[Type]>,
366
+ ): InstanceType<TextureMap[Type]> {
367
+ let texture: Texture | undefined;
368
+ const TextureClass = this.txConstructors[textureType];
369
+ if (!TextureClass) {
370
+ throw new Error(`Texture type "${textureType}" is not registered`);
371
+ }
372
+
373
+ const cacheKey = TextureClass.makeCacheKey(props as any);
374
+ if (cacheKey && this.keyCache.has(cacheKey)) {
375
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
376
+ texture = this.keyCache.get(cacheKey)!;
377
+ } else {
378
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
379
+ texture = new TextureClass(this, props as any);
380
+
381
+ if (cacheKey) {
382
+ this.initTextureToCache(texture, cacheKey);
383
+ }
384
+ }
385
+
386
+ return texture as InstanceType<TextureMap[Type]>;
387
+ }
388
+
389
+ /**
390
+ * Override loadTexture to use the batched approach.
391
+ *
392
+ * @param texture - The texture to load
393
+ * @param immediate - Whether to prioritize the texture for immediate loading
394
+ */
395
+ loadTexture(texture: Texture, priority?: boolean): void {
396
+ if (texture.state === 'loaded' || texture.state === 'loading') {
397
+ return;
398
+ }
399
+
400
+ texture.setSourceState('loading');
401
+ texture.setCoreCtxState('loading');
402
+
403
+ // if we're not initialized, just queue the texture into the priority queue
404
+ if (this.initialized === false) {
405
+ this.priorityQueue.push(texture);
406
+ return;
407
+ }
408
+
409
+ // prioritize the texture for immediate loading
410
+ if (priority === true) {
411
+ texture
412
+ .getTextureData()
413
+ .then(() => {
414
+ this.uploadTexture(texture);
415
+ })
416
+ .catch((err) => {
417
+ console.error(err);
418
+ });
419
+ }
420
+
421
+ // enqueue the texture for download and upload
422
+ this.enqueueDownloadTextureSource(texture);
423
+ }
424
+
425
+ /**
426
+ * Upload a texture to the GPU
427
+ *
428
+ * @param texture Texture to upload
429
+ */
430
+ uploadTexture(texture: Texture): void {
431
+ const coreContext = texture.loadCtxTexture();
432
+ coreContext.load();
433
+ }
434
+
435
+ /**
436
+ * Process a limited number of downloads and uploads.
437
+ *
438
+ * @param maxItems - The maximum number of items to process
439
+ */
440
+ processSome(maxItems = 0): void {
441
+ if (this.initialized === false) {
442
+ return;
443
+ }
444
+
445
+ let itemsProcessed = 0;
446
+
447
+ // Process priority queue
448
+ while (
449
+ this.priorityQueue.length > 0 &&
450
+ (maxItems === 0 || itemsProcessed < maxItems)
451
+ ) {
452
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
453
+ const texture = this.priorityQueue.shift()!;
454
+ texture.getTextureData().then(() => {
455
+ this.uploadTexture(texture);
456
+ });
457
+ itemsProcessed++;
458
+ }
459
+
460
+ // Process uploads
461
+ while (
462
+ this.uploadTextureQueue.length > 0 &&
463
+ (maxItems === 0 || itemsProcessed < maxItems)
464
+ ) {
465
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
466
+ this.uploadTexture(this.uploadTextureQueue.shift()!);
467
+ itemsProcessed++;
468
+ }
469
+
470
+ // Process downloads
471
+ while (
472
+ this.downloadTextureSourceQueue.length > 0 &&
473
+ (maxItems === 0 || itemsProcessed < maxItems)
474
+ ) {
475
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
476
+ const texture = this.downloadTextureSourceQueue.shift()!;
477
+ queueMicrotask(() => {
478
+ texture.getTextureData().then(() => {
479
+ this.enqueueUploadTexture(texture);
480
+ });
481
+ });
482
+
483
+ itemsProcessed++;
484
+ }
485
+ }
486
+
487
+ public hasUpdates(): boolean {
488
+ return (
489
+ this.downloadTextureSourceQueue.length > 0 ||
490
+ this.uploadTextureQueue.length > 0
491
+ );
492
+ }
493
+
494
+ /**
495
+ * Initialize a texture to the cache
496
+ *
497
+ * @param texture Texture to cache
498
+ * @param cacheKey Cache key for the texture
499
+ */
500
+ initTextureToCache(texture: Texture, cacheKey: string) {
501
+ const { keyCache, inverseKeyCache } = this;
502
+ keyCache.set(cacheKey, texture);
503
+ inverseKeyCache.set(texture, cacheKey);
504
+ }
505
+
506
+ /**
507
+ * Get a texture from the cache
508
+ *
509
+ * @param cacheKey
510
+ */
511
+ getTextureFromCache(cacheKey: string): Texture | undefined {
512
+ return this.keyCache.get(cacheKey);
513
+ }
514
+
515
+ /**
516
+ * Remove a texture from the cache
517
+ *
518
+ * @remarks
519
+ * Called by Texture Cleanup when a texture is freed.
520
+ *
521
+ * @param texture
522
+ */
523
+ removeTextureFromCache(texture: Texture) {
524
+ const { inverseKeyCache, keyCache } = this;
525
+ const cacheKey = inverseKeyCache.get(texture);
526
+ if (cacheKey) {
527
+ keyCache.delete(cacheKey);
528
+ }
529
+ }
530
+
531
+ /**
532
+ * Resolve a parent texture from the cache or fallback to the provided texture.
533
+ *
534
+ * @param texture - The provided texture to resolve.
535
+ * @returns The cached or provided texture.
536
+ */
537
+ resolveParentTexture(texture: ImageTexture): Texture {
538
+ if (!texture?.props) {
539
+ return texture;
540
+ }
541
+
542
+ const cacheKey = ImageTexture.makeCacheKey(texture.props);
543
+ const cachedTexture = cacheKey
544
+ ? this.getTextureFromCache(cacheKey)
545
+ : undefined;
546
+ return cachedTexture ?? texture;
547
+ }
548
+ }