@lightningjs/renderer 0.7.2 → 0.7.3

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 (188) hide show
  1. package/COPYING +1 -0
  2. package/LICENSE +202 -202
  3. package/NOTICE +3 -3
  4. package/README.md +221 -221
  5. package/dist/src/common/CommonTypes.d.ts +7 -0
  6. package/dist/src/core/Stage.d.ts +2 -1
  7. package/dist/src/core/Stage.js +4 -0
  8. package/dist/src/core/Stage.js.map +1 -1
  9. package/dist/src/core/animations/CoreAnimation.js +3 -0
  10. package/dist/src/core/animations/CoreAnimation.js.map +1 -1
  11. package/dist/src/core/animations/CoreAnimationController.d.ts +8 -0
  12. package/dist/src/core/animations/CoreAnimationController.js +26 -0
  13. package/dist/src/core/animations/CoreAnimationController.js.map +1 -1
  14. package/dist/src/core/lib/ImageWorker.js +21 -21
  15. package/dist/src/core/renderers/webgl/shaders/DefaultShader.js +47 -47
  16. package/dist/src/core/renderers/webgl/shaders/DefaultShaderBatched.js +61 -61
  17. package/dist/src/core/renderers/webgl/shaders/DynamicShader.js +93 -93
  18. package/dist/src/core/renderers/webgl/shaders/RoundedRectangle.js +63 -63
  19. package/dist/src/core/renderers/webgl/shaders/SdfShader.js +49 -49
  20. package/dist/src/core/renderers/webgl/shaders/effects/BorderBottomEffect.js +15 -15
  21. package/dist/src/core/renderers/webgl/shaders/effects/BorderEffect.js +5 -5
  22. package/dist/src/core/renderers/webgl/shaders/effects/BorderLeftEffect.js +15 -15
  23. package/dist/src/core/renderers/webgl/shaders/effects/BorderRightEffect.js +15 -15
  24. package/dist/src/core/renderers/webgl/shaders/effects/BorderTopEffect.js +15 -15
  25. package/dist/src/core/renderers/webgl/shaders/effects/FadeOutEffect.js +42 -42
  26. package/dist/src/core/renderers/webgl/shaders/effects/GlitchEffect.js +44 -44
  27. package/dist/src/core/renderers/webgl/shaders/effects/GrayscaleEffect.js +3 -3
  28. package/dist/src/core/renderers/webgl/shaders/effects/LinearGradientEffect.js +31 -31
  29. package/dist/src/core/renderers/webgl/shaders/effects/RadialGradientEffect.js +13 -13
  30. package/dist/src/core/renderers/webgl/shaders/effects/RadialProgressEffect.js +37 -37
  31. package/dist/src/core/renderers/webgl/shaders/effects/RadiusEffect.js +19 -19
  32. package/dist/src/main-api/ICoreDriver.d.ts +2 -1
  33. package/dist/src/main-api/Inspector.d.ts +6 -0
  34. package/dist/src/main-api/Inspector.js +105 -19
  35. package/dist/src/main-api/Inspector.js.map +1 -1
  36. package/dist/src/main-api/RendererMain.d.ts +12 -0
  37. package/dist/src/main-api/RendererMain.js +19 -1
  38. package/dist/src/main-api/RendererMain.js.map +1 -1
  39. package/dist/src/render-drivers/main/MainCoreDriver.d.ts +2 -1
  40. package/dist/src/render-drivers/main/MainCoreDriver.js +7 -1
  41. package/dist/src/render-drivers/main/MainCoreDriver.js.map +1 -1
  42. package/dist/src/render-drivers/threadx/ThreadXCoreDriver.d.ts +2 -1
  43. package/dist/src/render-drivers/threadx/ThreadXCoreDriver.js +7 -0
  44. package/dist/src/render-drivers/threadx/ThreadXCoreDriver.js.map +1 -1
  45. package/dist/src/render-drivers/threadx/ThreadXRendererMessage.d.ts +9 -1
  46. package/dist/src/render-drivers/threadx/ThreadXRendererMessage.js.map +1 -1
  47. package/dist/tsconfig.dist.tsbuildinfo +1 -1
  48. package/exports/core-api.ts +102 -102
  49. package/exports/main-api.ts +60 -60
  50. package/exports/utils.ts +41 -41
  51. package/package.json +5 -3
  52. package/scripts/please-use-pnpm.js +13 -0
  53. package/src/common/CommonTypes.ts +113 -105
  54. package/src/common/EventEmitter.ts +77 -77
  55. package/src/common/IAnimationController.ts +29 -29
  56. package/src/core/CoreExtension.ts +32 -32
  57. package/src/core/CoreNode.ts +926 -926
  58. package/src/core/CoreShaderManager.ts +243 -243
  59. package/src/core/CoreTextNode.ts +391 -391
  60. package/src/core/CoreTextureManager.ts +326 -326
  61. package/src/core/Stage.ts +354 -342
  62. package/src/core/animations/AnimationManager.ts +38 -38
  63. package/src/core/animations/CoreAnimation.ts +181 -177
  64. package/src/core/animations/CoreAnimationController.ts +148 -117
  65. package/src/core/lib/ContextSpy.ts +41 -41
  66. package/src/core/lib/ImageWorker.ts +124 -124
  67. package/src/core/lib/Matrix3d.ts +290 -290
  68. package/src/core/lib/WebGlContextWrapper.ts +992 -992
  69. package/src/core/lib/textureCompression.ts +152 -152
  70. package/src/core/lib/utils.ts +241 -241
  71. package/src/core/platform.ts +46 -46
  72. package/src/core/renderers/CoreContextTexture.ts +30 -30
  73. package/src/core/renderers/CoreRenderOp.ts +22 -22
  74. package/src/core/renderers/CoreRenderer.ts +63 -63
  75. package/src/core/renderers/CoreShader.ts +41 -41
  76. package/src/core/renderers/webgl/WebGlCoreCtxSubTexture.ts +37 -37
  77. package/src/core/renderers/webgl/WebGlCoreCtxTexture.ts +231 -231
  78. package/src/core/renderers/webgl/WebGlCoreRenderOp.ts +107 -107
  79. package/src/core/renderers/webgl/WebGlCoreRenderer.ts +520 -520
  80. package/src/core/renderers/webgl/WebGlCoreShader.ts +337 -337
  81. package/src/core/renderers/webgl/internal/BufferCollection.ts +54 -54
  82. package/src/core/renderers/webgl/internal/RendererUtils.ts +131 -131
  83. package/src/core/renderers/webgl/internal/ShaderUtils.ts +136 -136
  84. package/src/core/renderers/webgl/internal/WebGlUtils.ts +35 -35
  85. package/src/core/renderers/webgl/shaders/DefaultShader.ts +95 -95
  86. package/src/core/renderers/webgl/shaders/DefaultShaderBatched.ts +132 -132
  87. package/src/core/renderers/webgl/shaders/DynamicShader.ts +474 -474
  88. package/src/core/renderers/webgl/shaders/RoundedRectangle.ts +161 -161
  89. package/src/core/renderers/webgl/shaders/SdfShader.ts +174 -174
  90. package/src/core/renderers/webgl/shaders/effects/BorderBottomEffect.ts +101 -101
  91. package/src/core/renderers/webgl/shaders/effects/BorderEffect.ts +86 -86
  92. package/src/core/renderers/webgl/shaders/effects/BorderLeftEffect.ts +101 -101
  93. package/src/core/renderers/webgl/shaders/effects/BorderRightEffect.ts +101 -101
  94. package/src/core/renderers/webgl/shaders/effects/BorderTopEffect.ts +101 -101
  95. package/src/core/renderers/webgl/shaders/effects/EffectUtils.ts +33 -33
  96. package/src/core/renderers/webgl/shaders/effects/FadeOutEffect.ts +135 -135
  97. package/src/core/renderers/webgl/shaders/effects/GlitchEffect.ts +145 -145
  98. package/src/core/renderers/webgl/shaders/effects/GrayscaleEffect.ts +67 -67
  99. package/src/core/renderers/webgl/shaders/effects/LinearGradientEffect.ts +176 -176
  100. package/src/core/renderers/webgl/shaders/effects/RadialGradientEffect.ts +159 -159
  101. package/src/core/renderers/webgl/shaders/effects/RadialProgressEffect.ts +186 -186
  102. package/src/core/renderers/webgl/shaders/effects/RadiusEffect.ts +121 -121
  103. package/src/core/renderers/webgl/shaders/effects/ShaderEffect.ts +114 -114
  104. package/src/core/text-rendering/TextTextureRendererUtils.ts +189 -189
  105. package/src/core/text-rendering/TrFontManager.ts +96 -96
  106. package/src/core/text-rendering/font-face-types/SdfTrFontFace/SdfTrFontFace.ts +141 -141
  107. package/src/core/text-rendering/font-face-types/SdfTrFontFace/internal/FontShaper.ts +139 -139
  108. package/src/core/text-rendering/font-face-types/SdfTrFontFace/internal/SdfFontShaper.test.ts +173 -173
  109. package/src/core/text-rendering/font-face-types/SdfTrFontFace/internal/SdfFontShaper.ts +169 -169
  110. package/src/core/text-rendering/font-face-types/TrFontFace.ts +105 -105
  111. package/src/core/text-rendering/font-face-types/WebTrFontFace.ts +77 -77
  112. package/src/core/text-rendering/renderers/CanvasTextRenderer.ts +751 -751
  113. package/src/core/text-rendering/renderers/LightningTextTextureRenderer.ts +741 -741
  114. package/src/core/text-rendering/renderers/SdfTextRenderer/SdfTextRenderer.ts +775 -775
  115. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/PeekableGenerator.test.ts +48 -48
  116. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/PeekableGenerator.ts +66 -66
  117. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/SpecialCodepoints.ts +52 -52
  118. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/constants.ts +32 -32
  119. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/getStartConditions.ts +84 -84
  120. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/getUnicodeCodepoints.test.ts +133 -133
  121. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/getUnicodeCodepoints.ts +38 -38
  122. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText.ts +393 -393
  123. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/measureText.test.ts +49 -49
  124. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/measureText.ts +51 -51
  125. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/setRenderWindow.test.ts +205 -205
  126. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/setRenderWindow.ts +93 -93
  127. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/util.ts +40 -40
  128. package/src/core/text-rendering/renderers/TextRenderer.ts +504 -504
  129. package/src/core/textures/ColorTexture.ts +86 -86
  130. package/src/core/textures/ImageTexture.ts +133 -133
  131. package/src/core/textures/NoiseTexture.ts +96 -96
  132. package/src/core/textures/SubTexture.ts +143 -143
  133. package/src/core/textures/Texture.ts +218 -218
  134. package/src/core/utils.ts +224 -224
  135. package/src/env.d.ts +7 -7
  136. package/src/main-api/ICoreDriver.ts +66 -61
  137. package/src/main-api/INode.ts +470 -470
  138. package/src/main-api/Inspector.ts +432 -0
  139. package/src/main-api/RendererMain.ts +649 -610
  140. package/src/main-api/texture-usage-trackers/FinalizationRegistryTextureUsageTracker.ts +45 -45
  141. package/src/main-api/texture-usage-trackers/ManualCountTextureUsageTracker.ts +154 -154
  142. package/src/main-api/texture-usage-trackers/TextureUsageTracker.ts +54 -54
  143. package/src/render-drivers/main/MainCoreDriver.ts +148 -133
  144. package/src/render-drivers/main/MainOnlyNode.ts +453 -453
  145. package/src/render-drivers/main/MainOnlyTextNode.ts +261 -261
  146. package/src/render-drivers/threadx/NodeStruct.ts +300 -300
  147. package/src/render-drivers/threadx/SharedNode.ts +97 -97
  148. package/src/render-drivers/threadx/TextNodeStruct.ts +211 -211
  149. package/src/render-drivers/threadx/ThreadXCoreDriver.ts +285 -273
  150. package/src/render-drivers/threadx/ThreadXMainAnimationController.ts +99 -99
  151. package/src/render-drivers/threadx/ThreadXMainNode.ts +178 -178
  152. package/src/render-drivers/threadx/ThreadXMainTextNode.ts +85 -85
  153. package/src/render-drivers/threadx/ThreadXRendererMessage.ts +110 -97
  154. package/src/render-drivers/threadx/worker/ThreadXRendererNode.ts +238 -238
  155. package/src/render-drivers/threadx/worker/ThreadXRendererTextNode.ts +149 -149
  156. package/src/render-drivers/threadx/worker/renderer.ts +151 -151
  157. package/src/render-drivers/utils.ts +57 -57
  158. package/src/utils.ts +207 -207
  159. package/dist/src/core/lib/WebGlContext.d.ts +0 -414
  160. package/dist/src/core/lib/WebGlContext.js +0 -640
  161. package/dist/src/core/lib/WebGlContext.js.map +0 -1
  162. package/dist/src/core/scene/Scene.d.ts +0 -59
  163. package/dist/src/core/scene/Scene.js +0 -106
  164. package/dist/src/core/scene/Scene.js.map +0 -1
  165. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/findNearestMultiple.d.ts +0 -8
  166. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/findNearestMultiple.js +0 -29
  167. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/findNearestMultiple.js.map +0 -1
  168. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2/SdfBufferHelper.d.ts +0 -19
  169. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2/SdfBufferHelper.js +0 -84
  170. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2/SdfBufferHelper.js.map +0 -1
  171. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2/layoutLine.d.ts +0 -8
  172. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2/layoutLine.js +0 -40
  173. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2/layoutLine.js.map +0 -1
  174. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2/layoutText2.d.ts +0 -2
  175. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2/layoutText2.js +0 -41
  176. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2/layoutText2.js.map +0 -1
  177. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2/utils.d.ts +0 -1
  178. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2/utils.js +0 -4
  179. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2/utils.js.map +0 -1
  180. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2.d.ts +0 -1
  181. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2.js +0 -2
  182. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText2.js.map +0 -1
  183. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/makeRenderWindow.d.ts +0 -20
  184. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/makeRenderWindow.js +0 -55
  185. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/makeRenderWindow.js.map +0 -1
  186. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/roundUpToMultiple.d.ts +0 -9
  187. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/roundUpToMultiple.js +0 -32
  188. package/dist/src/core/text-rendering/renderers/SdfTextRenderer/internal/roundUpToMultiple.js.map +0 -1
@@ -1,775 +1,775 @@
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 {
21
- type Bound,
22
- type Rect,
23
- createBound,
24
- type BoundWithValid,
25
- intersectRect,
26
- type RectWithValid,
27
- copyRect,
28
- boundsOverlap,
29
- convertBoundToRect,
30
- } from '../../../lib/utils.js';
31
- import {
32
- TextRenderer,
33
- type TrProps,
34
- type TextRendererState,
35
- type TrFontProps,
36
- type TrPropSetters,
37
- } from '../TextRenderer.js';
38
- import { SdfTrFontFace } from '../../font-face-types/SdfTrFontFace/SdfTrFontFace.js';
39
- import { FLOATS_PER_GLYPH } from './internal/constants.js';
40
- import { getStartConditions } from './internal/getStartConditions.js';
41
- import { layoutText } from './internal/layoutText.js';
42
- import {
43
- setRenderWindow,
44
- type SdfRenderWindow,
45
- } from './internal/setRenderWindow.js';
46
- import type { TrFontFace } from '../../font-face-types/TrFontFace.js';
47
- import { TrFontManager, type FontFamilyMap } from '../../TrFontManager.js';
48
- import { assertTruthy, mergeColorAlpha } from '../../../../utils.js';
49
- import type { Stage } from '../../../Stage.js';
50
- import { WebGlCoreRenderOp } from '../../../renderers/webgl/WebGlCoreRenderOp.js';
51
- import { BufferCollection } from '../../../renderers/webgl/internal/BufferCollection.js';
52
- import type {
53
- SdfShader,
54
- SdfShaderProps,
55
- } from '../../../renderers/webgl/shaders/SdfShader.js';
56
- import type { WebGlCoreCtxTexture } from '../../../renderers/webgl/WebGlCoreCtxTexture.js';
57
- import { EventEmitter } from '../../../../common/EventEmitter.js';
58
- import type { Matrix3d } from '../../../lib/Matrix3d.js';
59
-
60
- declare module '../TextRenderer.js' {
61
- interface TextRendererMap {
62
- sdf: SdfTextRenderer;
63
- }
64
-
65
- // Add prefixed SDF-specific props to TextRendererDebugProps
66
- interface TextRendererDebugProps {
67
- sdfShaderDebug: boolean;
68
- }
69
- }
70
-
71
- export interface LineCacheItem {
72
- codepointIndex: number;
73
- maxY: number;
74
- maxX: number;
75
- }
76
-
77
- export interface SdfTextRendererState extends TextRendererState {
78
- /**
79
- * Cache for layout resume points indexed by the `curY` for each line
80
- * in the render sequence.
81
- *
82
- * Allows faster rendering by skipping parts of the layout loop that are
83
- * outside of the renderWindow.
84
- */
85
- lineCache: LineCacheItem[];
86
-
87
- renderWindow: SdfRenderWindow;
88
-
89
- elementBounds: BoundWithValid;
90
-
91
- clippingRect: RectWithValid;
92
-
93
- bufferNumFloats: number;
94
-
95
- bufferNumQuads: number;
96
-
97
- vertexBuffer: Float32Array | undefined;
98
-
99
- webGlBuffers: BufferCollection | null;
100
-
101
- bufferUploaded: boolean;
102
-
103
- distanceRange: number;
104
-
105
- trFontFace: SdfTrFontFace | undefined;
106
- }
107
-
108
- /**
109
- * Ephemeral rect object used for calculations
110
- */
111
- const tmpRect: Rect = {
112
- x: 0,
113
- y: 0,
114
- width: 0,
115
- height: 0,
116
- };
117
-
118
- /**
119
- * Singleton class for rendering text using signed distance fields.
120
- *
121
- * @remarks
122
- * SdfTextRenderer supports both single-channel and multi-channel signed distance fields.
123
- */
124
- export class SdfTextRenderer extends TextRenderer<SdfTextRendererState> {
125
- /**
126
- * Map of font family names to a set of font faces.
127
- */
128
- private ssdfFontFamilies: FontFamilyMap = {};
129
- private msdfFontFamilies: FontFamilyMap = {};
130
- private sdfShader: SdfShader;
131
- private rendererBounds: Bound;
132
-
133
- constructor(stage: Stage) {
134
- super(stage);
135
- this.sdfShader = this.stage.shManager.loadShader('SdfShader').shader;
136
- this.rendererBounds = {
137
- x1: 0,
138
- y1: 0,
139
- x2: this.stage.options.appWidth,
140
- y2: this.stage.options.appHeight,
141
- };
142
- }
143
-
144
- //#region Overrides
145
- getPropertySetters(): Partial<TrPropSetters<SdfTextRendererState>> {
146
- return {
147
- fontFamily: (state, value) => {
148
- state.props.fontFamily = value;
149
- state.trFontFace = undefined;
150
- this.invalidateLayoutCache(state);
151
- },
152
- fontWeight: (state, value) => {
153
- state.props.fontWeight = value;
154
- state.trFontFace = undefined;
155
- this.invalidateLayoutCache(state);
156
- },
157
- fontStyle: (state, value) => {
158
- state.props.fontStyle = value;
159
- state.trFontFace = undefined;
160
- this.invalidateLayoutCache(state);
161
- },
162
- fontStretch: (state, value) => {
163
- state.props.fontStretch = value;
164
- state.trFontFace = undefined;
165
- this.invalidateLayoutCache(state);
166
- },
167
- fontSize: (state, value) => {
168
- state.props.fontSize = value;
169
- this.invalidateLayoutCache(state);
170
- },
171
- text: (state, value) => {
172
- state.props.text = value;
173
- this.invalidateLayoutCache(state);
174
- },
175
- textAlign: (state, value) => {
176
- state.props.textAlign = value;
177
- this.invalidateLayoutCache(state);
178
- },
179
- color: (state, value) => {
180
- state.props.color = value;
181
- },
182
- x: (state, value) => {
183
- state.props.x = value;
184
- if (state.elementBounds.valid) {
185
- this.setElementBoundsX(state);
186
- // Only schedule an update if the text is not already rendered
187
- // (renderWindow is invalid) and the element possibly overlaps the screen
188
- // This is to avoid unnecessary updates when we know text is off-screen
189
- if (
190
- !state.renderWindow.valid &&
191
- boundsOverlap(state.elementBounds, this.rendererBounds)
192
- ) {
193
- this.scheduleUpdateState(state);
194
- }
195
- }
196
- },
197
- y: (state, value) => {
198
- state.props.y = value;
199
- if (state.elementBounds.valid) {
200
- this.setElementBoundsY(state);
201
- // See x() for explanation
202
- if (
203
- !state.renderWindow.valid &&
204
- boundsOverlap(state.elementBounds, this.rendererBounds)
205
- ) {
206
- this.scheduleUpdateState(state);
207
- }
208
- }
209
- },
210
- contain: (state, value) => {
211
- state.props.contain = value;
212
- this.invalidateLayoutCache(state);
213
- },
214
- width: (state, value) => {
215
- state.props.width = value;
216
- this.invalidateLayoutCache(state);
217
- },
218
- height: (state, value) => {
219
- state.props.height = value;
220
- this.invalidateLayoutCache(state);
221
- },
222
- offsetY: (state, value) => {
223
- state.props.offsetY = value;
224
- this.invalidateLayoutCache(state);
225
- },
226
- scrollable: (state, value) => {
227
- state.props.scrollable = value;
228
- this.invalidateLayoutCache(state);
229
- },
230
- scrollY: (state, value) => {
231
- state.props.scrollY = value;
232
- // Scrolling doesn't need to invalidate any caches, but it does need to
233
- // schedule an update
234
- this.scheduleUpdateState(state);
235
- },
236
- letterSpacing: (state, value) => {
237
- state.props.letterSpacing = value;
238
- this.invalidateLayoutCache(state);
239
- },
240
- lineHeight: (state, value) => {
241
- state.props.lineHeight = value;
242
- this.invalidateLayoutCache(state);
243
- },
244
- maxLines: (state, value) => {
245
- state.props.maxLines = value;
246
- this.invalidateLayoutCache(state);
247
- },
248
- textBaseline: (state, value) => {
249
- state.props.textBaseline = value;
250
- this.invalidateLayoutCache(state);
251
- },
252
- verticalAlign: (state, value) => {
253
- state.props.verticalAlign = value;
254
- this.invalidateLayoutCache(state);
255
- },
256
- overflowSuffix: (state, value) => {
257
- state.props.overflowSuffix = value;
258
- this.invalidateLayoutCache(state);
259
- },
260
- debug: (state, value) => {
261
- state.props.debug = value;
262
- },
263
- };
264
- }
265
-
266
- override canRenderFont(props: TrFontProps): boolean {
267
- // TODO: Support matching on font stretch, weight and style (if/when needed)
268
- // For now we just match on the font family name
269
- // '$$SDF_FAILURE_TEST$$' is used to test the 'failure' event coming from text
270
- const { fontFamily } = props;
271
- return (
272
- fontFamily in this.ssdfFontFamilies ||
273
- fontFamily in this.msdfFontFamilies ||
274
- fontFamily === '$$SDF_FAILURE_TEST$$'
275
- );
276
- }
277
-
278
- override isFontFaceSupported(fontFace: TrFontFace): boolean {
279
- return fontFace instanceof SdfTrFontFace;
280
- }
281
-
282
- override addFontFace(fontFace: TrFontFace): void {
283
- // Make sure the font face is an SDF font face (it should have already passed
284
- // the `isFontFaceSupported` check)
285
- assertTruthy(fontFace instanceof SdfTrFontFace);
286
- const familyName = fontFace.fontFamily;
287
- const fontFamiles =
288
- fontFace.type === 'ssdf'
289
- ? this.ssdfFontFamilies
290
- : fontFace.type === 'msdf'
291
- ? this.msdfFontFamilies
292
- : undefined;
293
- if (!fontFamiles) {
294
- console.warn(`Invalid font face type: ${fontFace.type as string}`);
295
- return;
296
- }
297
- let faceSet = fontFamiles[familyName];
298
- if (!faceSet) {
299
- faceSet = new Set();
300
- fontFamiles[familyName] = faceSet;
301
- }
302
- faceSet.add(fontFace);
303
- }
304
-
305
- override createState(props: TrProps): SdfTextRendererState {
306
- return {
307
- props,
308
- status: 'initialState',
309
- updateScheduled: false,
310
- emitter: new EventEmitter(),
311
- lineCache: [],
312
- forceFullLayoutCalc: false,
313
- renderWindow: {
314
- screen: {
315
- x1: 0,
316
- y1: 0,
317
- x2: 0,
318
- y2: 0,
319
- },
320
- sdf: {
321
- x1: 0,
322
- y1: 0,
323
- x2: 0,
324
- y2: 0,
325
- },
326
- firstLineIdx: 0,
327
- numLines: 0,
328
- valid: false,
329
- },
330
- elementBounds: {
331
- x1: 0,
332
- y1: 0,
333
- x2: 0,
334
- y2: 0,
335
- valid: false,
336
- },
337
- clippingRect: {
338
- x: 0,
339
- y: 0,
340
- width: 0,
341
- height: 0,
342
- valid: false,
343
- },
344
- bufferNumFloats: 0,
345
- bufferNumQuads: 0,
346
- vertexBuffer: undefined,
347
- webGlBuffers: null,
348
- bufferUploaded: false,
349
- textH: undefined,
350
- textW: undefined,
351
- distanceRange: 0,
352
- trFontFace: undefined,
353
- debugData: {
354
- updateCount: 0,
355
- layoutCount: 0,
356
- lastLayoutNumCharacters: 0,
357
- layoutSum: 0,
358
- drawSum: 0,
359
- drawCount: 0,
360
- bufferSize: 0,
361
- },
362
- };
363
- }
364
-
365
- override updateState(state: SdfTextRendererState): void {
366
- let { trFontFace } = state;
367
- const { textH, lineCache, debugData, forceFullLayoutCalc } = state;
368
- debugData.updateCount++;
369
-
370
- // On the first update call we need to set the status to loading
371
- if (state.status === 'initialState') {
372
- this.setStatus(state, 'loading');
373
- }
374
-
375
- // Resolve font face if we haven't yet
376
- if (!trFontFace) {
377
- trFontFace = this.resolveFontFace(state.props);
378
- state.trFontFace = trFontFace;
379
- if (!trFontFace) {
380
- const msg = `SdfTextRenderer: Could not resolve font face for family: '${state.props.fontFamily}'`;
381
- console.error(msg);
382
- this.setStatus(state, 'failed', new Error(msg));
383
- return;
384
- }
385
- }
386
-
387
- // If the font hasn't been loaded yet, stop here.
388
- // Listen for the 'loaded' event and forward fontLoaded event
389
- if (!trFontFace.loaded) {
390
- trFontFace.once('loaded', () => {
391
- this.scheduleUpdateState(state);
392
- });
393
- return;
394
- }
395
-
396
- // If the font is loaded then so should the data
397
- assertTruthy(trFontFace.data, 'Font face data should be loaded');
398
-
399
- const {
400
- text,
401
- fontSize,
402
- x,
403
- y,
404
- contain,
405
- width,
406
- height,
407
- lineHeight,
408
- verticalAlign,
409
- scrollable,
410
- overflowSuffix,
411
- maxLines,
412
- } = state.props;
413
-
414
- // scrollY only has an effect when contain === 'both' and scrollable === true
415
- const scrollY = contain === 'both' && scrollable ? state.props.scrollY : 0;
416
-
417
- const { renderWindow } = state;
418
-
419
- /**
420
- * The font size of the SDF font face (the basis for SDF space units)
421
- */
422
- const sdfFontSize = trFontFace.data.info.size;
423
-
424
- /**
425
- * Divide screen space units by this to get the SDF space units
426
- * Mulitple SDF space units by this to get screen space units
427
- */
428
- const fontSizeRatio = fontSize / sdfFontSize;
429
-
430
- // Needed in renderWindow calculation
431
- const sdfLineHeight = lineHeight / fontSizeRatio;
432
-
433
- state.distanceRange =
434
- fontSizeRatio * trFontFace.data.distanceField.distanceRange;
435
-
436
- // Allocate buffers if needed
437
- const neededLength = text.length * FLOATS_PER_GLYPH;
438
- let vertexBuffer = state.vertexBuffer;
439
- if (!vertexBuffer || vertexBuffer.length < neededLength) {
440
- vertexBuffer = new Float32Array(neededLength * 2);
441
- }
442
-
443
- const elementBounds = state.elementBounds;
444
- if (!elementBounds.valid) {
445
- this.setElementBoundsX(state);
446
- this.setElementBoundsY(state);
447
- elementBounds.valid = true;
448
- }
449
-
450
- // Return early if we're still viewing inside the established render window
451
- // No need to re-render what we've already rendered
452
- // (Only if there's an established renderWindow and we're not suppressing early exit)
453
- if (!forceFullLayoutCalc && renderWindow.valid) {
454
- const rwScreen = renderWindow.screen;
455
- if (
456
- x + rwScreen.x1 <= elementBounds.x1 &&
457
- x + rwScreen.x2 >= elementBounds.x2 &&
458
- y - scrollY + rwScreen.y1 <= elementBounds.y1 &&
459
- y - scrollY + rwScreen.y2 >= elementBounds.y2
460
- ) {
461
- this.setStatus(state, 'loaded');
462
- return;
463
- }
464
- // Otherwise invalidate the renderWindow so it can be redone
465
- renderWindow.valid = false;
466
- this.setStatus(state, 'loading');
467
- }
468
-
469
- const { offsetY, textAlign } = state.props;
470
-
471
- // Create a new renderWindow if needed
472
- if (!renderWindow.valid) {
473
- const isPossiblyOnScreen = boundsOverlap(
474
- elementBounds,
475
- this.rendererBounds,
476
- );
477
-
478
- if (!isPossiblyOnScreen) {
479
- // If the element is not possibly on screen, we can skip the layout and rendering completely
480
- return;
481
- }
482
-
483
- setRenderWindow(
484
- renderWindow,
485
- x,
486
- y,
487
- scrollY,
488
- lineHeight,
489
- contain === 'both' ? elementBounds.y2 - elementBounds.y1 : 0,
490
- elementBounds,
491
- fontSizeRatio,
492
- );
493
- // console.log('newRenderWindow', renderWindow);
494
- }
495
-
496
- const start = getStartConditions(
497
- sdfFontSize,
498
- sdfLineHeight,
499
- lineHeight,
500
- verticalAlign,
501
- offsetY,
502
- fontSizeRatio,
503
- renderWindow,
504
- lineCache,
505
- textH,
506
- );
507
-
508
- if (!start) {
509
- // Nothing to render, return early, but still mark as loaded (since the text is just scrolled
510
- // out of view)
511
- this.setStatus(state, 'loaded');
512
- return;
513
- }
514
-
515
- const { letterSpacing } = state.props;
516
-
517
- const out2 = layoutText(
518
- start.lineIndex,
519
- start.sdfX,
520
- start.sdfY,
521
- text,
522
- textAlign,
523
- width,
524
- height,
525
- fontSize,
526
- lineHeight,
527
- letterSpacing,
528
- vertexBuffer,
529
- contain,
530
- lineCache,
531
- renderWindow.sdf,
532
- trFontFace,
533
- forceFullLayoutCalc,
534
- scrollable,
535
- overflowSuffix,
536
- maxLines,
537
- );
538
-
539
- state.bufferUploaded = false;
540
- state.bufferNumFloats = out2.bufferNumFloats;
541
- state.bufferNumQuads = out2.bufferNumQuads;
542
- state.vertexBuffer = vertexBuffer;
543
- state.renderWindow = renderWindow;
544
- debugData.lastLayoutNumCharacters = out2.layoutNumCharacters;
545
- debugData.bufferSize = vertexBuffer.byteLength;
546
-
547
- // If we didn't exit early, we know we have completely computed w/h
548
- if (out2.fullyProcessed) {
549
- state.textW = out2.maxX * fontSizeRatio;
550
- state.textH = out2.maxY * fontSizeRatio;
551
- }
552
-
553
- // if (state.props.debug.printLayoutTime) {
554
- // debugData.layoutSum += performance.now() - updateStartTime;
555
- // debugData.layoutCount++;
556
- // }
557
- this.setStatus(state, 'loaded');
558
- }
559
-
560
- override renderQuads(
561
- state: SdfTextRendererState,
562
- transform: Matrix3d,
563
- clippingRect: Readonly<RectWithValid>,
564
- alpha: number,
565
- ): void {
566
- if (!state.vertexBuffer) {
567
- // Nothing to draw
568
- return;
569
- }
570
-
571
- const { renderer } = this.stage;
572
-
573
- const { fontSize, color, contain, scrollable, zIndex, debug } = state.props;
574
-
575
- // scrollY only has an effect when contain === 'both' and scrollable === true
576
- const scrollY = contain === 'both' && scrollable ? state.props.scrollY : 0;
577
-
578
- const {
579
- textW = 0,
580
- textH = 0,
581
- distanceRange,
582
- vertexBuffer,
583
- bufferUploaded,
584
- trFontFace,
585
- elementBounds,
586
- } = state;
587
-
588
- let { webGlBuffers } = state;
589
-
590
- if (!webGlBuffers) {
591
- const glw = renderer.glw;
592
- const stride = 4 * Float32Array.BYTES_PER_ELEMENT;
593
- const webGlBuffer = glw.createBuffer();
594
- assertTruthy(webGlBuffer);
595
- state.webGlBuffers = new BufferCollection([
596
- {
597
- buffer: webGlBuffer,
598
- attributes: {
599
- a_position: {
600
- name: 'a_position',
601
- size: 2, // 2 components per iteration
602
- type: glw.FLOAT, // the data is 32bit floats
603
- normalized: false, // don't normalize the data
604
- stride, // 0 = move forward size * sizeof(type) each iteration to get the next position
605
- offset: 0, // start at the beginning of the buffer
606
- },
607
- a_textureCoordinate: {
608
- name: 'a_textureCoordinate',
609
- size: 2,
610
- type: glw.FLOAT,
611
- normalized: false,
612
- stride,
613
- offset: 2 * Float32Array.BYTES_PER_ELEMENT,
614
- },
615
- },
616
- },
617
- ]);
618
- state.bufferUploaded = false;
619
- assertTruthy(state.webGlBuffers);
620
- webGlBuffers = state.webGlBuffers;
621
- }
622
-
623
- if (!bufferUploaded) {
624
- const glw = renderer.glw;
625
-
626
- const buffer = webGlBuffers?.getBuffer('a_textureCoordinate') ?? null;
627
- glw.arrayBufferData(buffer, vertexBuffer, glw.STATIC_DRAW);
628
- state.bufferUploaded = true;
629
- }
630
-
631
- assertTruthy(trFontFace);
632
- if (scrollable && contain === 'both') {
633
- assertTruthy(elementBounds.valid);
634
- const elementRect = convertBoundToRect(elementBounds, tmpRect);
635
-
636
- if (clippingRect.valid) {
637
- state.clippingRect.valid = true;
638
- clippingRect = intersectRect(
639
- clippingRect,
640
- elementRect,
641
- state.clippingRect,
642
- );
643
- } else {
644
- state.clippingRect.valid = true;
645
- clippingRect = copyRect(elementRect, state.clippingRect);
646
- }
647
- }
648
-
649
- const renderOp = new WebGlCoreRenderOp(
650
- renderer.glw,
651
- renderer.options,
652
- webGlBuffers,
653
- this.sdfShader,
654
- {
655
- transform: transform.data,
656
- // IMPORTANT: The SDF Shader expects the color NOT to be premultiplied
657
- // for the best blending results. Which is why we use `mergeColorAlpha`
658
- // instead of `mergeColorAlphaPremultiplied` here.
659
- color: mergeColorAlpha(color, alpha),
660
- size: fontSize / (trFontFace.data?.info.size || 0),
661
- scrollY,
662
- distanceRange,
663
- debug: debug.sdfShaderDebug,
664
- } satisfies SdfShaderProps,
665
- alpha,
666
- clippingRect,
667
- { height: textH, width: textW },
668
- 0,
669
- zIndex,
670
- );
671
-
672
- const texture = state.trFontFace?.texture;
673
- assertTruthy(texture);
674
- const ctxTexture = this.stage.txManager.getCtxTexture(texture);
675
-
676
- renderOp.addTexture(ctxTexture as WebGlCoreCtxTexture);
677
- renderOp.length = state.bufferNumFloats;
678
- renderOp.numQuads = state.bufferNumQuads;
679
-
680
- renderer.addRenderOp(renderOp);
681
-
682
- // if (!debug.disableScissor) {
683
- // renderer.enableScissor(
684
- // visibleRect.x,
685
- // visibleRect.y,
686
- // visibleRect.w,
687
- // visibleRect.h,
688
- // );
689
- // }
690
-
691
- // Draw the arrays
692
- // gl.drawArrays(
693
- // gl.TRIANGLES, // Primitive type
694
- // 0,
695
- // bufferNumVertices, // Number of verticies
696
- // );
697
-
698
- // renderer.disableScissor();
699
-
700
- // if (debug.showElementRect) {
701
- // this.renderer.drawBorder(
702
- // Colors.Blue,
703
- // elementRect.x,
704
- // elementRect.y,
705
- // elementRect.w,
706
- // elementRect.h,
707
- // );
708
- // }
709
-
710
- // if (debug.showVisibleRect) {
711
- // this.renderer.drawBorder(
712
- // Colors.Green,
713
- // visibleRect.x,
714
- // visibleRect.y,
715
- // visibleRect.w,
716
- // visibleRect.h,
717
- // );
718
- // }
719
-
720
- // if (debug.showRenderWindow && renderWindow) {
721
- // this.renderer.drawBorder(
722
- // Colors.Red,
723
- // x + renderWindow.x1,
724
- // y + renderWindow.y1 - scrollY,
725
- // x + renderWindow.x2 - (x + renderWindow.x1),
726
- // y + renderWindow.y2 - scrollY - (y + renderWindow.y1 - scrollY),
727
- // );
728
- // }
729
- // if (debug.printLayoutTime) {
730
- // debugData.drawSum += performance.now() - drawStartTime;
731
- // debugData.drawCount++;
732
- // }
733
- }
734
- //#endregion Overrides
735
-
736
- public resolveFontFace(props: TrFontProps): SdfTrFontFace | undefined {
737
- return TrFontManager.resolveFontFace(
738
- [this.msdfFontFamilies, this.ssdfFontFamilies],
739
- props,
740
- ) as SdfTrFontFace | undefined;
741
- }
742
-
743
- /**
744
- * Invalidate the layout cache stored in the state. This will cause the text
745
- * to be re-layed out on the next update.
746
- *
747
- * @remarks
748
- * This also invalidates the visible window cache.
749
- *
750
- * @param state
751
- */
752
- protected invalidateLayoutCache(state: SdfTextRendererState): void {
753
- state.renderWindow.valid = false;
754
- state.elementBounds.valid = false;
755
- state.textH = undefined;
756
- state.textW = undefined;
757
- state.lineCache = [];
758
- this.setStatus(state, 'loading');
759
- this.scheduleUpdateState(state);
760
- }
761
-
762
- protected setElementBoundsX(state: SdfTextRendererState): void {
763
- const { x, contain, width } = state.props;
764
- const { elementBounds } = state;
765
- elementBounds.x1 = x;
766
- elementBounds.x2 = contain !== 'none' ? x + width : Infinity;
767
- }
768
-
769
- protected setElementBoundsY(state: SdfTextRendererState): void {
770
- const { y, contain, height } = state.props;
771
- const { elementBounds } = state;
772
- elementBounds.y1 = y;
773
- elementBounds.y2 = contain === 'both' ? y + height : Infinity;
774
- }
775
- }
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 {
21
+ type Bound,
22
+ type Rect,
23
+ createBound,
24
+ type BoundWithValid,
25
+ intersectRect,
26
+ type RectWithValid,
27
+ copyRect,
28
+ boundsOverlap,
29
+ convertBoundToRect,
30
+ } from '../../../lib/utils.js';
31
+ import {
32
+ TextRenderer,
33
+ type TrProps,
34
+ type TextRendererState,
35
+ type TrFontProps,
36
+ type TrPropSetters,
37
+ } from '../TextRenderer.js';
38
+ import { SdfTrFontFace } from '../../font-face-types/SdfTrFontFace/SdfTrFontFace.js';
39
+ import { FLOATS_PER_GLYPH } from './internal/constants.js';
40
+ import { getStartConditions } from './internal/getStartConditions.js';
41
+ import { layoutText } from './internal/layoutText.js';
42
+ import {
43
+ setRenderWindow,
44
+ type SdfRenderWindow,
45
+ } from './internal/setRenderWindow.js';
46
+ import type { TrFontFace } from '../../font-face-types/TrFontFace.js';
47
+ import { TrFontManager, type FontFamilyMap } from '../../TrFontManager.js';
48
+ import { assertTruthy, mergeColorAlpha } from '../../../../utils.js';
49
+ import type { Stage } from '../../../Stage.js';
50
+ import { WebGlCoreRenderOp } from '../../../renderers/webgl/WebGlCoreRenderOp.js';
51
+ import { BufferCollection } from '../../../renderers/webgl/internal/BufferCollection.js';
52
+ import type {
53
+ SdfShader,
54
+ SdfShaderProps,
55
+ } from '../../../renderers/webgl/shaders/SdfShader.js';
56
+ import type { WebGlCoreCtxTexture } from '../../../renderers/webgl/WebGlCoreCtxTexture.js';
57
+ import { EventEmitter } from '../../../../common/EventEmitter.js';
58
+ import type { Matrix3d } from '../../../lib/Matrix3d.js';
59
+
60
+ declare module '../TextRenderer.js' {
61
+ interface TextRendererMap {
62
+ sdf: SdfTextRenderer;
63
+ }
64
+
65
+ // Add prefixed SDF-specific props to TextRendererDebugProps
66
+ interface TextRendererDebugProps {
67
+ sdfShaderDebug: boolean;
68
+ }
69
+ }
70
+
71
+ export interface LineCacheItem {
72
+ codepointIndex: number;
73
+ maxY: number;
74
+ maxX: number;
75
+ }
76
+
77
+ export interface SdfTextRendererState extends TextRendererState {
78
+ /**
79
+ * Cache for layout resume points indexed by the `curY` for each line
80
+ * in the render sequence.
81
+ *
82
+ * Allows faster rendering by skipping parts of the layout loop that are
83
+ * outside of the renderWindow.
84
+ */
85
+ lineCache: LineCacheItem[];
86
+
87
+ renderWindow: SdfRenderWindow;
88
+
89
+ elementBounds: BoundWithValid;
90
+
91
+ clippingRect: RectWithValid;
92
+
93
+ bufferNumFloats: number;
94
+
95
+ bufferNumQuads: number;
96
+
97
+ vertexBuffer: Float32Array | undefined;
98
+
99
+ webGlBuffers: BufferCollection | null;
100
+
101
+ bufferUploaded: boolean;
102
+
103
+ distanceRange: number;
104
+
105
+ trFontFace: SdfTrFontFace | undefined;
106
+ }
107
+
108
+ /**
109
+ * Ephemeral rect object used for calculations
110
+ */
111
+ const tmpRect: Rect = {
112
+ x: 0,
113
+ y: 0,
114
+ width: 0,
115
+ height: 0,
116
+ };
117
+
118
+ /**
119
+ * Singleton class for rendering text using signed distance fields.
120
+ *
121
+ * @remarks
122
+ * SdfTextRenderer supports both single-channel and multi-channel signed distance fields.
123
+ */
124
+ export class SdfTextRenderer extends TextRenderer<SdfTextRendererState> {
125
+ /**
126
+ * Map of font family names to a set of font faces.
127
+ */
128
+ private ssdfFontFamilies: FontFamilyMap = {};
129
+ private msdfFontFamilies: FontFamilyMap = {};
130
+ private sdfShader: SdfShader;
131
+ private rendererBounds: Bound;
132
+
133
+ constructor(stage: Stage) {
134
+ super(stage);
135
+ this.sdfShader = this.stage.shManager.loadShader('SdfShader').shader;
136
+ this.rendererBounds = {
137
+ x1: 0,
138
+ y1: 0,
139
+ x2: this.stage.options.appWidth,
140
+ y2: this.stage.options.appHeight,
141
+ };
142
+ }
143
+
144
+ //#region Overrides
145
+ getPropertySetters(): Partial<TrPropSetters<SdfTextRendererState>> {
146
+ return {
147
+ fontFamily: (state, value) => {
148
+ state.props.fontFamily = value;
149
+ state.trFontFace = undefined;
150
+ this.invalidateLayoutCache(state);
151
+ },
152
+ fontWeight: (state, value) => {
153
+ state.props.fontWeight = value;
154
+ state.trFontFace = undefined;
155
+ this.invalidateLayoutCache(state);
156
+ },
157
+ fontStyle: (state, value) => {
158
+ state.props.fontStyle = value;
159
+ state.trFontFace = undefined;
160
+ this.invalidateLayoutCache(state);
161
+ },
162
+ fontStretch: (state, value) => {
163
+ state.props.fontStretch = value;
164
+ state.trFontFace = undefined;
165
+ this.invalidateLayoutCache(state);
166
+ },
167
+ fontSize: (state, value) => {
168
+ state.props.fontSize = value;
169
+ this.invalidateLayoutCache(state);
170
+ },
171
+ text: (state, value) => {
172
+ state.props.text = value;
173
+ this.invalidateLayoutCache(state);
174
+ },
175
+ textAlign: (state, value) => {
176
+ state.props.textAlign = value;
177
+ this.invalidateLayoutCache(state);
178
+ },
179
+ color: (state, value) => {
180
+ state.props.color = value;
181
+ },
182
+ x: (state, value) => {
183
+ state.props.x = value;
184
+ if (state.elementBounds.valid) {
185
+ this.setElementBoundsX(state);
186
+ // Only schedule an update if the text is not already rendered
187
+ // (renderWindow is invalid) and the element possibly overlaps the screen
188
+ // This is to avoid unnecessary updates when we know text is off-screen
189
+ if (
190
+ !state.renderWindow.valid &&
191
+ boundsOverlap(state.elementBounds, this.rendererBounds)
192
+ ) {
193
+ this.scheduleUpdateState(state);
194
+ }
195
+ }
196
+ },
197
+ y: (state, value) => {
198
+ state.props.y = value;
199
+ if (state.elementBounds.valid) {
200
+ this.setElementBoundsY(state);
201
+ // See x() for explanation
202
+ if (
203
+ !state.renderWindow.valid &&
204
+ boundsOverlap(state.elementBounds, this.rendererBounds)
205
+ ) {
206
+ this.scheduleUpdateState(state);
207
+ }
208
+ }
209
+ },
210
+ contain: (state, value) => {
211
+ state.props.contain = value;
212
+ this.invalidateLayoutCache(state);
213
+ },
214
+ width: (state, value) => {
215
+ state.props.width = value;
216
+ this.invalidateLayoutCache(state);
217
+ },
218
+ height: (state, value) => {
219
+ state.props.height = value;
220
+ this.invalidateLayoutCache(state);
221
+ },
222
+ offsetY: (state, value) => {
223
+ state.props.offsetY = value;
224
+ this.invalidateLayoutCache(state);
225
+ },
226
+ scrollable: (state, value) => {
227
+ state.props.scrollable = value;
228
+ this.invalidateLayoutCache(state);
229
+ },
230
+ scrollY: (state, value) => {
231
+ state.props.scrollY = value;
232
+ // Scrolling doesn't need to invalidate any caches, but it does need to
233
+ // schedule an update
234
+ this.scheduleUpdateState(state);
235
+ },
236
+ letterSpacing: (state, value) => {
237
+ state.props.letterSpacing = value;
238
+ this.invalidateLayoutCache(state);
239
+ },
240
+ lineHeight: (state, value) => {
241
+ state.props.lineHeight = value;
242
+ this.invalidateLayoutCache(state);
243
+ },
244
+ maxLines: (state, value) => {
245
+ state.props.maxLines = value;
246
+ this.invalidateLayoutCache(state);
247
+ },
248
+ textBaseline: (state, value) => {
249
+ state.props.textBaseline = value;
250
+ this.invalidateLayoutCache(state);
251
+ },
252
+ verticalAlign: (state, value) => {
253
+ state.props.verticalAlign = value;
254
+ this.invalidateLayoutCache(state);
255
+ },
256
+ overflowSuffix: (state, value) => {
257
+ state.props.overflowSuffix = value;
258
+ this.invalidateLayoutCache(state);
259
+ },
260
+ debug: (state, value) => {
261
+ state.props.debug = value;
262
+ },
263
+ };
264
+ }
265
+
266
+ override canRenderFont(props: TrFontProps): boolean {
267
+ // TODO: Support matching on font stretch, weight and style (if/when needed)
268
+ // For now we just match on the font family name
269
+ // '$$SDF_FAILURE_TEST$$' is used to test the 'failure' event coming from text
270
+ const { fontFamily } = props;
271
+ return (
272
+ fontFamily in this.ssdfFontFamilies ||
273
+ fontFamily in this.msdfFontFamilies ||
274
+ fontFamily === '$$SDF_FAILURE_TEST$$'
275
+ );
276
+ }
277
+
278
+ override isFontFaceSupported(fontFace: TrFontFace): boolean {
279
+ return fontFace instanceof SdfTrFontFace;
280
+ }
281
+
282
+ override addFontFace(fontFace: TrFontFace): void {
283
+ // Make sure the font face is an SDF font face (it should have already passed
284
+ // the `isFontFaceSupported` check)
285
+ assertTruthy(fontFace instanceof SdfTrFontFace);
286
+ const familyName = fontFace.fontFamily;
287
+ const fontFamiles =
288
+ fontFace.type === 'ssdf'
289
+ ? this.ssdfFontFamilies
290
+ : fontFace.type === 'msdf'
291
+ ? this.msdfFontFamilies
292
+ : undefined;
293
+ if (!fontFamiles) {
294
+ console.warn(`Invalid font face type: ${fontFace.type as string}`);
295
+ return;
296
+ }
297
+ let faceSet = fontFamiles[familyName];
298
+ if (!faceSet) {
299
+ faceSet = new Set();
300
+ fontFamiles[familyName] = faceSet;
301
+ }
302
+ faceSet.add(fontFace);
303
+ }
304
+
305
+ override createState(props: TrProps): SdfTextRendererState {
306
+ return {
307
+ props,
308
+ status: 'initialState',
309
+ updateScheduled: false,
310
+ emitter: new EventEmitter(),
311
+ lineCache: [],
312
+ forceFullLayoutCalc: false,
313
+ renderWindow: {
314
+ screen: {
315
+ x1: 0,
316
+ y1: 0,
317
+ x2: 0,
318
+ y2: 0,
319
+ },
320
+ sdf: {
321
+ x1: 0,
322
+ y1: 0,
323
+ x2: 0,
324
+ y2: 0,
325
+ },
326
+ firstLineIdx: 0,
327
+ numLines: 0,
328
+ valid: false,
329
+ },
330
+ elementBounds: {
331
+ x1: 0,
332
+ y1: 0,
333
+ x2: 0,
334
+ y2: 0,
335
+ valid: false,
336
+ },
337
+ clippingRect: {
338
+ x: 0,
339
+ y: 0,
340
+ width: 0,
341
+ height: 0,
342
+ valid: false,
343
+ },
344
+ bufferNumFloats: 0,
345
+ bufferNumQuads: 0,
346
+ vertexBuffer: undefined,
347
+ webGlBuffers: null,
348
+ bufferUploaded: false,
349
+ textH: undefined,
350
+ textW: undefined,
351
+ distanceRange: 0,
352
+ trFontFace: undefined,
353
+ debugData: {
354
+ updateCount: 0,
355
+ layoutCount: 0,
356
+ lastLayoutNumCharacters: 0,
357
+ layoutSum: 0,
358
+ drawSum: 0,
359
+ drawCount: 0,
360
+ bufferSize: 0,
361
+ },
362
+ };
363
+ }
364
+
365
+ override updateState(state: SdfTextRendererState): void {
366
+ let { trFontFace } = state;
367
+ const { textH, lineCache, debugData, forceFullLayoutCalc } = state;
368
+ debugData.updateCount++;
369
+
370
+ // On the first update call we need to set the status to loading
371
+ if (state.status === 'initialState') {
372
+ this.setStatus(state, 'loading');
373
+ }
374
+
375
+ // Resolve font face if we haven't yet
376
+ if (!trFontFace) {
377
+ trFontFace = this.resolveFontFace(state.props);
378
+ state.trFontFace = trFontFace;
379
+ if (!trFontFace) {
380
+ const msg = `SdfTextRenderer: Could not resolve font face for family: '${state.props.fontFamily}'`;
381
+ console.error(msg);
382
+ this.setStatus(state, 'failed', new Error(msg));
383
+ return;
384
+ }
385
+ }
386
+
387
+ // If the font hasn't been loaded yet, stop here.
388
+ // Listen for the 'loaded' event and forward fontLoaded event
389
+ if (!trFontFace.loaded) {
390
+ trFontFace.once('loaded', () => {
391
+ this.scheduleUpdateState(state);
392
+ });
393
+ return;
394
+ }
395
+
396
+ // If the font is loaded then so should the data
397
+ assertTruthy(trFontFace.data, 'Font face data should be loaded');
398
+
399
+ const {
400
+ text,
401
+ fontSize,
402
+ x,
403
+ y,
404
+ contain,
405
+ width,
406
+ height,
407
+ lineHeight,
408
+ verticalAlign,
409
+ scrollable,
410
+ overflowSuffix,
411
+ maxLines,
412
+ } = state.props;
413
+
414
+ // scrollY only has an effect when contain === 'both' and scrollable === true
415
+ const scrollY = contain === 'both' && scrollable ? state.props.scrollY : 0;
416
+
417
+ const { renderWindow } = state;
418
+
419
+ /**
420
+ * The font size of the SDF font face (the basis for SDF space units)
421
+ */
422
+ const sdfFontSize = trFontFace.data.info.size;
423
+
424
+ /**
425
+ * Divide screen space units by this to get the SDF space units
426
+ * Mulitple SDF space units by this to get screen space units
427
+ */
428
+ const fontSizeRatio = fontSize / sdfFontSize;
429
+
430
+ // Needed in renderWindow calculation
431
+ const sdfLineHeight = lineHeight / fontSizeRatio;
432
+
433
+ state.distanceRange =
434
+ fontSizeRatio * trFontFace.data.distanceField.distanceRange;
435
+
436
+ // Allocate buffers if needed
437
+ const neededLength = text.length * FLOATS_PER_GLYPH;
438
+ let vertexBuffer = state.vertexBuffer;
439
+ if (!vertexBuffer || vertexBuffer.length < neededLength) {
440
+ vertexBuffer = new Float32Array(neededLength * 2);
441
+ }
442
+
443
+ const elementBounds = state.elementBounds;
444
+ if (!elementBounds.valid) {
445
+ this.setElementBoundsX(state);
446
+ this.setElementBoundsY(state);
447
+ elementBounds.valid = true;
448
+ }
449
+
450
+ // Return early if we're still viewing inside the established render window
451
+ // No need to re-render what we've already rendered
452
+ // (Only if there's an established renderWindow and we're not suppressing early exit)
453
+ if (!forceFullLayoutCalc && renderWindow.valid) {
454
+ const rwScreen = renderWindow.screen;
455
+ if (
456
+ x + rwScreen.x1 <= elementBounds.x1 &&
457
+ x + rwScreen.x2 >= elementBounds.x2 &&
458
+ y - scrollY + rwScreen.y1 <= elementBounds.y1 &&
459
+ y - scrollY + rwScreen.y2 >= elementBounds.y2
460
+ ) {
461
+ this.setStatus(state, 'loaded');
462
+ return;
463
+ }
464
+ // Otherwise invalidate the renderWindow so it can be redone
465
+ renderWindow.valid = false;
466
+ this.setStatus(state, 'loading');
467
+ }
468
+
469
+ const { offsetY, textAlign } = state.props;
470
+
471
+ // Create a new renderWindow if needed
472
+ if (!renderWindow.valid) {
473
+ const isPossiblyOnScreen = boundsOverlap(
474
+ elementBounds,
475
+ this.rendererBounds,
476
+ );
477
+
478
+ if (!isPossiblyOnScreen) {
479
+ // If the element is not possibly on screen, we can skip the layout and rendering completely
480
+ return;
481
+ }
482
+
483
+ setRenderWindow(
484
+ renderWindow,
485
+ x,
486
+ y,
487
+ scrollY,
488
+ lineHeight,
489
+ contain === 'both' ? elementBounds.y2 - elementBounds.y1 : 0,
490
+ elementBounds,
491
+ fontSizeRatio,
492
+ );
493
+ // console.log('newRenderWindow', renderWindow);
494
+ }
495
+
496
+ const start = getStartConditions(
497
+ sdfFontSize,
498
+ sdfLineHeight,
499
+ lineHeight,
500
+ verticalAlign,
501
+ offsetY,
502
+ fontSizeRatio,
503
+ renderWindow,
504
+ lineCache,
505
+ textH,
506
+ );
507
+
508
+ if (!start) {
509
+ // Nothing to render, return early, but still mark as loaded (since the text is just scrolled
510
+ // out of view)
511
+ this.setStatus(state, 'loaded');
512
+ return;
513
+ }
514
+
515
+ const { letterSpacing } = state.props;
516
+
517
+ const out2 = layoutText(
518
+ start.lineIndex,
519
+ start.sdfX,
520
+ start.sdfY,
521
+ text,
522
+ textAlign,
523
+ width,
524
+ height,
525
+ fontSize,
526
+ lineHeight,
527
+ letterSpacing,
528
+ vertexBuffer,
529
+ contain,
530
+ lineCache,
531
+ renderWindow.sdf,
532
+ trFontFace,
533
+ forceFullLayoutCalc,
534
+ scrollable,
535
+ overflowSuffix,
536
+ maxLines,
537
+ );
538
+
539
+ state.bufferUploaded = false;
540
+ state.bufferNumFloats = out2.bufferNumFloats;
541
+ state.bufferNumQuads = out2.bufferNumQuads;
542
+ state.vertexBuffer = vertexBuffer;
543
+ state.renderWindow = renderWindow;
544
+ debugData.lastLayoutNumCharacters = out2.layoutNumCharacters;
545
+ debugData.bufferSize = vertexBuffer.byteLength;
546
+
547
+ // If we didn't exit early, we know we have completely computed w/h
548
+ if (out2.fullyProcessed) {
549
+ state.textW = out2.maxX * fontSizeRatio;
550
+ state.textH = out2.maxY * fontSizeRatio;
551
+ }
552
+
553
+ // if (state.props.debug.printLayoutTime) {
554
+ // debugData.layoutSum += performance.now() - updateStartTime;
555
+ // debugData.layoutCount++;
556
+ // }
557
+ this.setStatus(state, 'loaded');
558
+ }
559
+
560
+ override renderQuads(
561
+ state: SdfTextRendererState,
562
+ transform: Matrix3d,
563
+ clippingRect: Readonly<RectWithValid>,
564
+ alpha: number,
565
+ ): void {
566
+ if (!state.vertexBuffer) {
567
+ // Nothing to draw
568
+ return;
569
+ }
570
+
571
+ const { renderer } = this.stage;
572
+
573
+ const { fontSize, color, contain, scrollable, zIndex, debug } = state.props;
574
+
575
+ // scrollY only has an effect when contain === 'both' and scrollable === true
576
+ const scrollY = contain === 'both' && scrollable ? state.props.scrollY : 0;
577
+
578
+ const {
579
+ textW = 0,
580
+ textH = 0,
581
+ distanceRange,
582
+ vertexBuffer,
583
+ bufferUploaded,
584
+ trFontFace,
585
+ elementBounds,
586
+ } = state;
587
+
588
+ let { webGlBuffers } = state;
589
+
590
+ if (!webGlBuffers) {
591
+ const glw = renderer.glw;
592
+ const stride = 4 * Float32Array.BYTES_PER_ELEMENT;
593
+ const webGlBuffer = glw.createBuffer();
594
+ assertTruthy(webGlBuffer);
595
+ state.webGlBuffers = new BufferCollection([
596
+ {
597
+ buffer: webGlBuffer,
598
+ attributes: {
599
+ a_position: {
600
+ name: 'a_position',
601
+ size: 2, // 2 components per iteration
602
+ type: glw.FLOAT, // the data is 32bit floats
603
+ normalized: false, // don't normalize the data
604
+ stride, // 0 = move forward size * sizeof(type) each iteration to get the next position
605
+ offset: 0, // start at the beginning of the buffer
606
+ },
607
+ a_textureCoordinate: {
608
+ name: 'a_textureCoordinate',
609
+ size: 2,
610
+ type: glw.FLOAT,
611
+ normalized: false,
612
+ stride,
613
+ offset: 2 * Float32Array.BYTES_PER_ELEMENT,
614
+ },
615
+ },
616
+ },
617
+ ]);
618
+ state.bufferUploaded = false;
619
+ assertTruthy(state.webGlBuffers);
620
+ webGlBuffers = state.webGlBuffers;
621
+ }
622
+
623
+ if (!bufferUploaded) {
624
+ const glw = renderer.glw;
625
+
626
+ const buffer = webGlBuffers?.getBuffer('a_textureCoordinate') ?? null;
627
+ glw.arrayBufferData(buffer, vertexBuffer, glw.STATIC_DRAW);
628
+ state.bufferUploaded = true;
629
+ }
630
+
631
+ assertTruthy(trFontFace);
632
+ if (scrollable && contain === 'both') {
633
+ assertTruthy(elementBounds.valid);
634
+ const elementRect = convertBoundToRect(elementBounds, tmpRect);
635
+
636
+ if (clippingRect.valid) {
637
+ state.clippingRect.valid = true;
638
+ clippingRect = intersectRect(
639
+ clippingRect,
640
+ elementRect,
641
+ state.clippingRect,
642
+ );
643
+ } else {
644
+ state.clippingRect.valid = true;
645
+ clippingRect = copyRect(elementRect, state.clippingRect);
646
+ }
647
+ }
648
+
649
+ const renderOp = new WebGlCoreRenderOp(
650
+ renderer.glw,
651
+ renderer.options,
652
+ webGlBuffers,
653
+ this.sdfShader,
654
+ {
655
+ transform: transform.data,
656
+ // IMPORTANT: The SDF Shader expects the color NOT to be premultiplied
657
+ // for the best blending results. Which is why we use `mergeColorAlpha`
658
+ // instead of `mergeColorAlphaPremultiplied` here.
659
+ color: mergeColorAlpha(color, alpha),
660
+ size: fontSize / (trFontFace.data?.info.size || 0),
661
+ scrollY,
662
+ distanceRange,
663
+ debug: debug.sdfShaderDebug,
664
+ } satisfies SdfShaderProps,
665
+ alpha,
666
+ clippingRect,
667
+ { height: textH, width: textW },
668
+ 0,
669
+ zIndex,
670
+ );
671
+
672
+ const texture = state.trFontFace?.texture;
673
+ assertTruthy(texture);
674
+ const ctxTexture = this.stage.txManager.getCtxTexture(texture);
675
+
676
+ renderOp.addTexture(ctxTexture as WebGlCoreCtxTexture);
677
+ renderOp.length = state.bufferNumFloats;
678
+ renderOp.numQuads = state.bufferNumQuads;
679
+
680
+ renderer.addRenderOp(renderOp);
681
+
682
+ // if (!debug.disableScissor) {
683
+ // renderer.enableScissor(
684
+ // visibleRect.x,
685
+ // visibleRect.y,
686
+ // visibleRect.w,
687
+ // visibleRect.h,
688
+ // );
689
+ // }
690
+
691
+ // Draw the arrays
692
+ // gl.drawArrays(
693
+ // gl.TRIANGLES, // Primitive type
694
+ // 0,
695
+ // bufferNumVertices, // Number of verticies
696
+ // );
697
+
698
+ // renderer.disableScissor();
699
+
700
+ // if (debug.showElementRect) {
701
+ // this.renderer.drawBorder(
702
+ // Colors.Blue,
703
+ // elementRect.x,
704
+ // elementRect.y,
705
+ // elementRect.w,
706
+ // elementRect.h,
707
+ // );
708
+ // }
709
+
710
+ // if (debug.showVisibleRect) {
711
+ // this.renderer.drawBorder(
712
+ // Colors.Green,
713
+ // visibleRect.x,
714
+ // visibleRect.y,
715
+ // visibleRect.w,
716
+ // visibleRect.h,
717
+ // );
718
+ // }
719
+
720
+ // if (debug.showRenderWindow && renderWindow) {
721
+ // this.renderer.drawBorder(
722
+ // Colors.Red,
723
+ // x + renderWindow.x1,
724
+ // y + renderWindow.y1 - scrollY,
725
+ // x + renderWindow.x2 - (x + renderWindow.x1),
726
+ // y + renderWindow.y2 - scrollY - (y + renderWindow.y1 - scrollY),
727
+ // );
728
+ // }
729
+ // if (debug.printLayoutTime) {
730
+ // debugData.drawSum += performance.now() - drawStartTime;
731
+ // debugData.drawCount++;
732
+ // }
733
+ }
734
+ //#endregion Overrides
735
+
736
+ public resolveFontFace(props: TrFontProps): SdfTrFontFace | undefined {
737
+ return TrFontManager.resolveFontFace(
738
+ [this.msdfFontFamilies, this.ssdfFontFamilies],
739
+ props,
740
+ ) as SdfTrFontFace | undefined;
741
+ }
742
+
743
+ /**
744
+ * Invalidate the layout cache stored in the state. This will cause the text
745
+ * to be re-layed out on the next update.
746
+ *
747
+ * @remarks
748
+ * This also invalidates the visible window cache.
749
+ *
750
+ * @param state
751
+ */
752
+ protected invalidateLayoutCache(state: SdfTextRendererState): void {
753
+ state.renderWindow.valid = false;
754
+ state.elementBounds.valid = false;
755
+ state.textH = undefined;
756
+ state.textW = undefined;
757
+ state.lineCache = [];
758
+ this.setStatus(state, 'loading');
759
+ this.scheduleUpdateState(state);
760
+ }
761
+
762
+ protected setElementBoundsX(state: SdfTextRendererState): void {
763
+ const { x, contain, width } = state.props;
764
+ const { elementBounds } = state;
765
+ elementBounds.x1 = x;
766
+ elementBounds.x2 = contain !== 'none' ? x + width : Infinity;
767
+ }
768
+
769
+ protected setElementBoundsY(state: SdfTextRendererState): void {
770
+ const { y, contain, height } = state.props;
771
+ const { elementBounds } = state;
772
+ elementBounds.y1 = y;
773
+ elementBounds.y2 = contain === 'both' ? y + height : Infinity;
774
+ }
775
+ }