@lightningjs/renderer 2.9.0-beta2 → 2.9.0-beta3

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 (189) 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.d.ts +2 -1
  6. package/dist/src/core/CoreNode.js +54 -43
  7. package/dist/src/core/CoreNode.js.map +1 -1
  8. package/dist/src/core/CoreTextureManager.d.ts +61 -15
  9. package/dist/src/core/CoreTextureManager.js +179 -104
  10. package/dist/src/core/CoreTextureManager.js.map +1 -1
  11. package/dist/src/core/Stage.d.ts +7 -0
  12. package/dist/src/core/Stage.js +33 -1
  13. package/dist/src/core/Stage.js.map +1 -1
  14. package/dist/src/core/TextureMemoryManager.js +2 -5
  15. package/dist/src/core/TextureMemoryManager.js.map +1 -1
  16. package/dist/src/core/lib/ImageWorker.js +31 -28
  17. package/dist/src/core/lib/ImageWorker.js.map +1 -1
  18. package/dist/src/core/lib/WebGlContextWrapper.d.ts +1 -0
  19. package/dist/src/core/lib/WebGlContextWrapper.js +2 -0
  20. package/dist/src/core/lib/WebGlContextWrapper.js.map +1 -1
  21. package/dist/src/core/renderers/CoreContextTexture.d.ts +1 -0
  22. package/dist/src/core/renderers/CoreContextTexture.js +1 -0
  23. package/dist/src/core/renderers/CoreContextTexture.js.map +1 -1
  24. package/dist/src/core/renderers/canvas/CanvasCoreRenderer.d.ts +1 -1
  25. package/dist/src/core/renderers/canvas/CanvasCoreRenderer.js +13 -5
  26. package/dist/src/core/renderers/canvas/CanvasCoreRenderer.js.map +1 -1
  27. package/dist/src/core/renderers/canvas/CanvasCoreTexture.js +6 -8
  28. package/dist/src/core/renderers/canvas/CanvasCoreTexture.js.map +1 -1
  29. package/dist/src/core/renderers/webgl/WebGlCoreCtxSubTexture.js +3 -1
  30. package/dist/src/core/renderers/webgl/WebGlCoreCtxSubTexture.js.map +1 -1
  31. package/dist/src/core/renderers/webgl/WebGlCoreCtxTexture.d.ts +1 -2
  32. package/dist/src/core/renderers/webgl/WebGlCoreCtxTexture.js +26 -24
  33. package/dist/src/core/renderers/webgl/WebGlCoreCtxTexture.js.map +1 -1
  34. package/dist/src/core/renderers/webgl/WebGlCoreRenderer.d.ts +0 -1
  35. package/dist/src/core/renderers/webgl/WebGlCoreRenderer.js +7 -17
  36. package/dist/src/core/renderers/webgl/WebGlCoreRenderer.js.map +1 -1
  37. package/dist/src/core/renderers/webgl/shaders/DefaultShader.js +45 -45
  38. package/dist/src/core/renderers/webgl/shaders/DefaultShaderBatched.js +61 -61
  39. package/dist/src/core/renderers/webgl/shaders/DynamicShader.js +93 -93
  40. package/dist/src/core/renderers/webgl/shaders/RoundedRectangle.js +63 -63
  41. package/dist/src/core/renderers/webgl/shaders/SdfShader.js +62 -62
  42. package/dist/src/core/renderers/webgl/shaders/effects/BorderBottomEffect.js +15 -15
  43. package/dist/src/core/renderers/webgl/shaders/effects/BorderEffect.js +6 -6
  44. package/dist/src/core/renderers/webgl/shaders/effects/BorderLeftEffect.js +15 -15
  45. package/dist/src/core/renderers/webgl/shaders/effects/BorderRightEffect.js +15 -15
  46. package/dist/src/core/renderers/webgl/shaders/effects/BorderTopEffect.js +15 -15
  47. package/dist/src/core/renderers/webgl/shaders/effects/FadeOutEffect.js +42 -42
  48. package/dist/src/core/renderers/webgl/shaders/effects/GlitchEffect.js +44 -44
  49. package/dist/src/core/renderers/webgl/shaders/effects/GrayscaleEffect.js +3 -3
  50. package/dist/src/core/renderers/webgl/shaders/effects/HolePunchEffect.js +22 -22
  51. package/dist/src/core/renderers/webgl/shaders/effects/LinearGradientEffect.js +28 -28
  52. package/dist/src/core/renderers/webgl/shaders/effects/RadialGradientEffect.js +10 -10
  53. package/dist/src/core/renderers/webgl/shaders/effects/RadialProgressEffect.js +37 -37
  54. package/dist/src/core/renderers/webgl/shaders/effects/RadiusEffect.js +19 -19
  55. package/dist/src/core/text-rendering/font-face-types/SdfTrFontFace/SdfTrFontFace.js +3 -5
  56. package/dist/src/core/text-rendering/font-face-types/SdfTrFontFace/SdfTrFontFace.js.map +1 -1
  57. package/dist/src/core/text-rendering/renderers/CanvasTextRenderer.js +2 -1
  58. package/dist/src/core/text-rendering/renderers/CanvasTextRenderer.js.map +1 -1
  59. package/dist/src/core/textures/ColorTexture.d.ts +1 -1
  60. package/dist/src/core/textures/ColorTexture.js +2 -1
  61. package/dist/src/core/textures/ColorTexture.js.map +1 -1
  62. package/dist/src/core/textures/ImageTexture.d.ts +8 -1
  63. package/dist/src/core/textures/ImageTexture.js +39 -1
  64. package/dist/src/core/textures/ImageTexture.js.map +1 -1
  65. package/dist/src/core/textures/NoiseTexture.d.ts +1 -1
  66. package/dist/src/core/textures/NoiseTexture.js +2 -1
  67. package/dist/src/core/textures/NoiseTexture.js.map +1 -1
  68. package/dist/src/core/textures/RenderTexture.d.ts +1 -1
  69. package/dist/src/core/textures/RenderTexture.js +2 -1
  70. package/dist/src/core/textures/RenderTexture.js.map +1 -1
  71. package/dist/src/core/textures/SubTexture.d.ts +1 -1
  72. package/dist/src/core/textures/SubTexture.js +21 -4
  73. package/dist/src/core/textures/SubTexture.js.map +1 -1
  74. package/dist/src/core/textures/Texture.d.ts +43 -21
  75. package/dist/src/core/textures/Texture.js +105 -33
  76. package/dist/src/core/textures/Texture.js.map +1 -1
  77. package/dist/src/main-api/Renderer.d.ts +18 -0
  78. package/dist/src/main-api/Renderer.js +6 -4
  79. package/dist/src/main-api/Renderer.js.map +1 -1
  80. package/dist/tsconfig.dist.tsbuildinfo +1 -1
  81. package/exports/canvas.ts +39 -39
  82. package/exports/index.ts +89 -89
  83. package/exports/inspector.ts +24 -24
  84. package/exports/utils.ts +44 -44
  85. package/exports/webgl.ts +38 -38
  86. package/package.json +1 -1
  87. package/scripts/please-use-pnpm.js +13 -13
  88. package/src/common/CommonTypes.ts +139 -139
  89. package/src/common/EventEmitter.ts +77 -77
  90. package/src/common/IAnimationController.ts +92 -92
  91. package/src/common/IEventEmitter.ts +28 -28
  92. package/src/core/CoreNode.test.ts +95 -95
  93. package/src/core/CoreNode.ts +2282 -2258
  94. package/src/core/CoreShaderManager.ts +292 -292
  95. package/src/core/CoreTextNode.ts +450 -450
  96. package/src/core/CoreTextureManager.ts +522 -432
  97. package/src/core/Stage.ts +699 -652
  98. package/src/core/TextureMemoryManager.ts +277 -279
  99. package/src/core/animations/AnimationManager.ts +38 -38
  100. package/src/core/animations/CoreAnimation.ts +340 -340
  101. package/src/core/animations/CoreAnimationController.ts +157 -157
  102. package/src/core/lib/ContextSpy.ts +41 -41
  103. package/src/core/lib/ImageWorker.ts +270 -267
  104. package/src/core/lib/Matrix3d.ts +244 -244
  105. package/src/core/lib/RenderCoords.ts +86 -86
  106. package/src/core/lib/WebGlContextWrapper.ts +1322 -1320
  107. package/src/core/lib/textureCompression.ts +152 -152
  108. package/src/core/lib/textureSvg.ts +78 -78
  109. package/src/core/lib/utils.ts +306 -306
  110. package/src/core/platform.ts +61 -61
  111. package/src/core/renderers/CoreContextTexture.ts +43 -42
  112. package/src/core/renderers/CoreRenderOp.ts +22 -22
  113. package/src/core/renderers/CoreRenderer.ts +114 -114
  114. package/src/core/renderers/CoreShader.ts +41 -41
  115. package/src/core/renderers/canvas/CanvasCoreRenderer.ts +364 -353
  116. package/src/core/renderers/canvas/CanvasCoreTexture.ts +150 -149
  117. package/src/core/renderers/canvas/internal/C2DShaderUtils.ts +231 -231
  118. package/src/core/renderers/canvas/internal/ColorUtils.ts +69 -69
  119. package/src/core/renderers/canvas/shaders/UnsupportedShader.ts +48 -48
  120. package/src/core/renderers/webgl/WebGlCoreCtxRenderTexture.ts +79 -79
  121. package/src/core/renderers/webgl/WebGlCoreCtxSubTexture.ts +50 -48
  122. package/src/core/renderers/webgl/WebGlCoreCtxTexture.ts +298 -290
  123. package/src/core/renderers/webgl/WebGlCoreRenderOp.ts +125 -125
  124. package/src/core/renderers/webgl/WebGlCoreRenderer.ts +805 -817
  125. package/src/core/renderers/webgl/WebGlCoreShader.ts +362 -362
  126. package/src/core/renderers/webgl/internal/BufferCollection.ts +54 -54
  127. package/src/core/renderers/webgl/internal/ShaderUtils.ts +143 -143
  128. package/src/core/renderers/webgl/internal/WebGlUtils.ts +35 -35
  129. package/src/core/renderers/webgl/shaders/DefaultShader.ts +93 -93
  130. package/src/core/renderers/webgl/shaders/DefaultShaderBatched.ts +132 -132
  131. package/src/core/renderers/webgl/shaders/DynamicShader.ts +580 -580
  132. package/src/core/renderers/webgl/shaders/RoundedRectangle.ts +167 -167
  133. package/src/core/renderers/webgl/shaders/SdfShader.ts +204 -204
  134. package/src/core/renderers/webgl/shaders/effects/BorderBottomEffect.ts +101 -101
  135. package/src/core/renderers/webgl/shaders/effects/BorderEffect.ts +87 -87
  136. package/src/core/renderers/webgl/shaders/effects/BorderLeftEffect.ts +101 -101
  137. package/src/core/renderers/webgl/shaders/effects/BorderRightEffect.ts +101 -101
  138. package/src/core/renderers/webgl/shaders/effects/BorderTopEffect.ts +101 -101
  139. package/src/core/renderers/webgl/shaders/effects/EffectUtils.ts +159 -159
  140. package/src/core/renderers/webgl/shaders/effects/FadeOutEffect.ts +127 -127
  141. package/src/core/renderers/webgl/shaders/effects/GlitchEffect.ts +148 -148
  142. package/src/core/renderers/webgl/shaders/effects/GrayscaleEffect.ts +67 -67
  143. package/src/core/renderers/webgl/shaders/effects/HolePunchEffect.ts +157 -157
  144. package/src/core/renderers/webgl/shaders/effects/LinearGradientEffect.ts +171 -171
  145. package/src/core/renderers/webgl/shaders/effects/RadialGradientEffect.ts +168 -168
  146. package/src/core/renderers/webgl/shaders/effects/RadialProgressEffect.ts +187 -187
  147. package/src/core/renderers/webgl/shaders/effects/RadiusEffect.ts +110 -110
  148. package/src/core/renderers/webgl/shaders/effects/ShaderEffect.ts +196 -196
  149. package/src/core/text-rendering/TextRenderingUtils.ts +36 -36
  150. package/src/core/text-rendering/TextTextureRendererUtils.ts +263 -263
  151. package/src/core/text-rendering/TrFontManager.ts +183 -183
  152. package/src/core/text-rendering/font-face-types/SdfTrFontFace/SdfTrFontFace.ts +169 -171
  153. package/src/core/text-rendering/font-face-types/SdfTrFontFace/internal/FontShaper.ts +139 -139
  154. package/src/core/text-rendering/font-face-types/SdfTrFontFace/internal/SdfFontShaper.test.ts +173 -173
  155. package/src/core/text-rendering/font-face-types/SdfTrFontFace/internal/SdfFontShaper.ts +171 -171
  156. package/src/core/text-rendering/font-face-types/TrFontFace.ts +187 -187
  157. package/src/core/text-rendering/font-face-types/WebTrFontFace.ts +89 -89
  158. package/src/core/text-rendering/renderers/CanvasTextRenderer.ts +509 -507
  159. package/src/core/text-rendering/renderers/LightningTextTextureRenderer.ts +798 -798
  160. package/src/core/text-rendering/renderers/SdfTextRenderer/SdfTextRenderer.ts +853 -853
  161. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/PeekableGenerator.test.ts +48 -48
  162. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/PeekableGenerator.ts +66 -66
  163. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/SpecialCodepoints.ts +52 -52
  164. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/constants.ts +32 -32
  165. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/getStartConditions.ts +117 -117
  166. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/getUnicodeCodepoints.test.ts +133 -133
  167. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/getUnicodeCodepoints.ts +38 -38
  168. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/layoutText.ts +403 -403
  169. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/measureText.test.ts +49 -49
  170. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/measureText.ts +52 -52
  171. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/setRenderWindow.test.ts +205 -205
  172. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/setRenderWindow.ts +93 -93
  173. package/src/core/text-rendering/renderers/SdfTextRenderer/internal/util.ts +40 -40
  174. package/src/core/text-rendering/renderers/TextRenderer.ts +557 -557
  175. package/src/core/textures/ColorTexture.ts +102 -100
  176. package/src/core/textures/ImageTexture.ts +378 -337
  177. package/src/core/textures/NoiseTexture.ts +104 -101
  178. package/src/core/textures/RenderTexture.ts +85 -83
  179. package/src/core/textures/SubTexture.ts +171 -146
  180. package/src/core/textures/Texture.ts +407 -318
  181. package/src/core/utils.ts +227 -227
  182. package/src/env.d.ts +7 -7
  183. package/src/main-api/DynamicShaderController.ts +104 -104
  184. package/src/main-api/INode.ts +101 -101
  185. package/src/main-api/Inspector.ts +505 -505
  186. package/src/main-api/Renderer.ts +693 -670
  187. package/src/main-api/ShaderController.ts +80 -80
  188. package/src/main-api/utils.ts +45 -45
  189. package/src/utils.ts +248 -248
@@ -1,798 +1,798 @@
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
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
21
-
22
- import { assertTruthy } from '../../../utils.js';
23
- import { getRgbaString, type RGBA } from '../../lib/utils.js';
24
- import { calcDefaultLineHeight } from '../TextRenderingUtils.js';
25
- import {
26
- getWebFontMetrics,
27
- isZeroWidthSpace,
28
- } from '../TextTextureRendererUtils.js';
29
- import type { NormalizedFontMetrics } from '../font-face-types/TrFontFace.js';
30
- import type { WebTrFontFace } from '../font-face-types/WebTrFontFace.js';
31
-
32
- const MAX_TEXTURE_DIMENSION = 2048;
33
-
34
- /**
35
- * Text Overflow Values
36
- */
37
- export type TextOverflow =
38
- | 'ellipsis'
39
- | 'clip'
40
- | (string & Record<never, never>);
41
-
42
- /***
43
- * Text Horizontal Align Values
44
- */
45
- export type TextAlign = 'left' | 'center' | 'right';
46
-
47
- /***
48
- * Text Baseline Values
49
- */
50
- export type TextBaseline =
51
- | 'alphabetic'
52
- | 'top'
53
- | 'hanging'
54
- | 'middle'
55
- | 'ideographic'
56
- | 'bottom';
57
-
58
- /***
59
- * Text Vertical Align Values
60
- */
61
- export type TextVerticalAlign = 'top' | 'middle' | 'bottom';
62
-
63
- /**
64
- * Text Texture Settings
65
- */
66
- export interface Settings {
67
- w: number;
68
- h: number;
69
- text: string;
70
- fontStyle: string;
71
- fontSize: number;
72
- fontBaselineRatio: number;
73
- fontFamily: string | null;
74
- trFontFace: WebTrFontFace | null;
75
- wordWrap: boolean;
76
- wordWrapWidth: number;
77
- wordBreak: boolean;
78
- textOverflow: TextOverflow | null;
79
- lineHeight: number | null;
80
- textBaseline: TextBaseline;
81
- textAlign: TextAlign;
82
- verticalAlign: TextVerticalAlign;
83
- offsetY: number | null;
84
- maxLines: number;
85
- maxHeight: number | null;
86
- overflowSuffix: string;
87
- precision: number;
88
- textColor: RGBA;
89
- paddingLeft: number;
90
- paddingRight: number;
91
- shadow: boolean;
92
- shadowColor: RGBA;
93
- shadowOffsetX: number;
94
- shadowOffsetY: number;
95
- shadowBlur: number;
96
- highlight: boolean;
97
- highlightHeight: number;
98
- highlightColor: RGBA;
99
- highlightOffset: number;
100
- highlightPaddingLeft: number;
101
- highlightPaddingRight: number;
102
- letterSpacing: number;
103
- textIndent: number;
104
- cutSx: number;
105
- cutSy: number;
106
- cutEx: number;
107
- cutEy: number;
108
- advancedRenderer: boolean;
109
-
110
- // Normally stage options
111
- textRenderIssueMargin: number;
112
- }
113
-
114
- export interface RenderInfo {
115
- w: number;
116
- h: number;
117
- lines: string[];
118
- precision: number;
119
- remainingText: string;
120
- moreTextLines: boolean;
121
- width: number;
122
- innerWidth: number;
123
- height: number;
124
- fontSize: number;
125
- cutSx: number;
126
- cutSy: number;
127
- cutEx: number;
128
- cutEy: number;
129
- lineHeight: number;
130
- defLineHeight: number;
131
- lineWidths: number[];
132
- offsetY: number;
133
- paddingLeft: number;
134
- paddingRight: number;
135
- letterSpacing: number;
136
- textIndent: number;
137
- metrics: NormalizedFontMetrics;
138
- }
139
-
140
- /**
141
- * Calculate height for the canvas
142
- *
143
- * @param textBaseline
144
- * @param fontSize
145
- * @param lineHeight
146
- * @param numLines
147
- * @param offsetY
148
- * @returns
149
- */
150
- function calcHeight(
151
- textBaseline: TextBaseline,
152
- fontSize: number,
153
- lineHeight: number,
154
- numLines: number,
155
- offsetY: number | null,
156
- ) {
157
- const baselineOffset = textBaseline !== 'bottom' ? 0.5 * fontSize : 0;
158
- return (
159
- lineHeight * (numLines - 1) +
160
- baselineOffset +
161
- Math.max(lineHeight, fontSize) +
162
- (offsetY || 0)
163
- );
164
- }
165
-
166
- export class LightningTextTextureRenderer {
167
- private _canvas: OffscreenCanvas | HTMLCanvasElement;
168
- private _context:
169
- | OffscreenCanvasRenderingContext2D
170
- | CanvasRenderingContext2D;
171
- private _settings: Settings;
172
-
173
- constructor(
174
- canvas: OffscreenCanvas | HTMLCanvasElement,
175
- context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D,
176
- ) {
177
- this._canvas = canvas;
178
- this._context = context;
179
- this._settings = this.mergeDefaults({});
180
- }
181
-
182
- set settings(v: Partial<Settings>) {
183
- this._settings = this.mergeDefaults(v);
184
- }
185
-
186
- get settings(): Settings {
187
- return this._settings;
188
- }
189
-
190
- getPrecision() {
191
- return this._settings.precision;
192
- }
193
-
194
- setFontProperties() {
195
- this._context.font = this._getFontSetting();
196
- this._context.textBaseline = this._settings.textBaseline;
197
- }
198
-
199
- _getFontSetting() {
200
- const ff = [this._settings.fontFamily];
201
-
202
- const ffs = [];
203
- for (let i = 0, n = ff.length; i < n; i++) {
204
- if (ff[i] === 'serif' || ff[i] === 'sans-serif') {
205
- ffs.push(ff[i]);
206
- } else {
207
- ffs.push(`"${ff[i]!}"`);
208
- }
209
- }
210
-
211
- return `${this._settings.fontStyle} ${
212
- this._settings.fontSize * this.getPrecision()
213
- }px ${ffs.join(',')}`;
214
- }
215
-
216
- _load() {
217
- if (true && document.fonts) {
218
- const fontSetting = this._getFontSetting();
219
- try {
220
- if (!document.fonts.check(fontSetting, this._settings.text)) {
221
- // Use a promise that waits for loading.
222
- return document.fonts
223
- .load(fontSetting, this._settings.text)
224
- .catch((err) => {
225
- // Just load the fallback font.
226
- console.warn('[Lightning] Font load error', err, fontSetting);
227
- })
228
- .then(() => {
229
- if (!document.fonts.check(fontSetting, this._settings.text)) {
230
- console.warn('[Lightning] Font not found', fontSetting);
231
- }
232
- });
233
- }
234
- } catch (e) {
235
- console.warn("[Lightning] Can't check font loading for " + fontSetting);
236
- }
237
- }
238
- }
239
-
240
- calculateRenderInfo(): RenderInfo {
241
- const renderInfo: Partial<RenderInfo> = {};
242
-
243
- const precision = this.getPrecision();
244
-
245
- const paddingLeft = this._settings.paddingLeft * precision;
246
- const paddingRight = this._settings.paddingRight * precision;
247
- const fontSize = this._settings.fontSize * precision;
248
- let offsetY =
249
- this._settings.offsetY === null
250
- ? null
251
- : this._settings.offsetY * precision;
252
- const w = this._settings.w * precision;
253
- const h = this._settings.h * precision;
254
- let wordWrapWidth = this._settings.wordWrapWidth * precision;
255
- const cutSx = this._settings.cutSx * precision;
256
- const cutEx = this._settings.cutEx * precision;
257
- const cutSy = this._settings.cutSy * precision;
258
- const cutEy = this._settings.cutEy * precision;
259
- const letterSpacing = (this._settings.letterSpacing || 0) * precision;
260
- const textIndent = this._settings.textIndent * precision;
261
- const trFontFace = this._settings.trFontFace;
262
-
263
- // Set font properties.
264
- this.setFontProperties();
265
-
266
- assertTruthy(trFontFace);
267
- const metrics = getWebFontMetrics(this._context, trFontFace, fontSize);
268
- const defLineHeight = calcDefaultLineHeight(metrics, fontSize) * precision;
269
- const lineHeight =
270
- this._settings.lineHeight !== null
271
- ? this._settings.lineHeight * precision
272
- : defLineHeight;
273
-
274
- const maxHeight = this._settings.maxHeight;
275
- const containedMaxLines =
276
- maxHeight !== null && lineHeight > 0
277
- ? Math.floor(maxHeight / lineHeight)
278
- : 0;
279
-
280
- const setMaxLines = this._settings.maxLines;
281
- const calcMaxLines =
282
- containedMaxLines > 0 && setMaxLines > 0
283
- ? Math.min(containedMaxLines, setMaxLines)
284
- : Math.max(containedMaxLines, setMaxLines);
285
-
286
- // Total width.
287
- let width = w || 2048 / this.getPrecision();
288
-
289
- // Inner width.
290
- let innerWidth = width - paddingLeft;
291
- if (innerWidth < 10) {
292
- width += 10 - innerWidth;
293
- innerWidth = 10;
294
- }
295
-
296
- if (!wordWrapWidth) {
297
- wordWrapWidth = innerWidth;
298
- }
299
-
300
- // Text overflow
301
- if (this._settings.textOverflow && !this._settings.wordWrap) {
302
- let suffix;
303
- switch (this._settings.textOverflow) {
304
- case 'clip':
305
- suffix = '';
306
- break;
307
- case 'ellipsis':
308
- suffix = this._settings.overflowSuffix;
309
- break;
310
- default:
311
- suffix = this._settings.textOverflow;
312
- }
313
- this._settings.text = this.wrapWord(
314
- this._settings.text,
315
- wordWrapWidth - textIndent,
316
- suffix,
317
- );
318
- }
319
-
320
- // word wrap
321
- // preserve original text
322
- let linesInfo: { n: number[]; l: string[] };
323
- if (this._settings.wordWrap) {
324
- linesInfo = this.wrapText(
325
- this._settings.text,
326
- wordWrapWidth,
327
- letterSpacing,
328
- textIndent,
329
- );
330
- } else {
331
- linesInfo = { l: this._settings.text.split(/(?:\r\n|\r|\n)/), n: [] };
332
- const n = linesInfo.l.length;
333
- for (let i = 0; i < n - 1; i++) {
334
- linesInfo.n.push(i);
335
- }
336
- }
337
- let lines = linesInfo.l;
338
-
339
- if (calcMaxLines && lines.length > calcMaxLines) {
340
- const usedLines = lines.slice(0, calcMaxLines);
341
-
342
- let otherLines = null;
343
- if (this._settings.overflowSuffix) {
344
- // Wrap again with max lines suffix enabled.
345
- const w = this._settings.overflowSuffix
346
- ? this.measureText(this._settings.overflowSuffix)
347
- : 0;
348
- const al = this.wrapText(
349
- usedLines[usedLines.length - 1]!,
350
- wordWrapWidth - w,
351
- letterSpacing,
352
- textIndent,
353
- );
354
- usedLines[usedLines.length - 1] = `${al.l[0]!}${
355
- this._settings.overflowSuffix
356
- }`;
357
- otherLines = [al.l.length > 1 ? al.l[1] : ''];
358
- } else {
359
- otherLines = [''];
360
- }
361
-
362
- // Re-assemble the remaining text.
363
- let i;
364
- const n = lines.length;
365
- let j = 0;
366
- const m = linesInfo.n.length;
367
- for (i = calcMaxLines; i < n; i++) {
368
- otherLines[j] += `${otherLines[j] ? ' ' : ''}${lines[i]!}`;
369
- if (i + 1 < m && linesInfo.n[i + 1]) {
370
- j++;
371
- }
372
- }
373
-
374
- renderInfo.remainingText = otherLines.join('\n');
375
-
376
- renderInfo.moreTextLines = true;
377
-
378
- lines = usedLines;
379
- } else {
380
- renderInfo.moreTextLines = false;
381
- renderInfo.remainingText = '';
382
- }
383
-
384
- // calculate text width
385
- let maxLineWidth = 0;
386
- const lineWidths: number[] = [];
387
- for (let i = 0; i < lines.length; i++) {
388
- const lineWidth =
389
- this.measureText(lines[i]!, letterSpacing) + (i === 0 ? textIndent : 0);
390
- lineWidths.push(lineWidth);
391
- maxLineWidth = Math.max(maxLineWidth, lineWidth);
392
- }
393
-
394
- renderInfo.lineWidths = lineWidths;
395
-
396
- if (!w) {
397
- // Auto-set width to max text length.
398
- width = maxLineWidth + paddingLeft + paddingRight;
399
- innerWidth = maxLineWidth;
400
- }
401
-
402
- let height;
403
- if (h) {
404
- height = h;
405
- } else {
406
- height = calcHeight(
407
- this._settings.textBaseline,
408
- fontSize,
409
- lineHeight,
410
- lines.length,
411
- offsetY,
412
- );
413
- }
414
-
415
- if (offsetY === null) {
416
- offsetY = fontSize;
417
- }
418
-
419
- renderInfo.w = width;
420
- renderInfo.h = height;
421
- renderInfo.lines = lines;
422
- renderInfo.precision = precision;
423
-
424
- if (!width) {
425
- // To prevent canvas errors.
426
- width = 1;
427
- }
428
-
429
- if (!height) {
430
- // To prevent canvas errors.
431
- height = 1;
432
- }
433
-
434
- if (cutSx || cutEx) {
435
- width = Math.min(width, cutEx - cutSx);
436
- }
437
-
438
- if (cutSy || cutEy) {
439
- height = Math.min(height, cutEy - cutSy);
440
- }
441
-
442
- renderInfo.width = width;
443
- renderInfo.innerWidth = innerWidth;
444
- renderInfo.height = height;
445
- renderInfo.fontSize = fontSize;
446
- renderInfo.cutSx = cutSx;
447
- renderInfo.cutSy = cutSy;
448
- renderInfo.cutEx = cutEx;
449
- renderInfo.cutEy = cutEy;
450
- renderInfo.lineHeight = lineHeight;
451
- renderInfo.defLineHeight = defLineHeight;
452
- renderInfo.lineWidths = lineWidths;
453
- renderInfo.offsetY = offsetY;
454
- renderInfo.paddingLeft = paddingLeft;
455
- renderInfo.paddingRight = paddingRight;
456
- renderInfo.letterSpacing = letterSpacing;
457
- renderInfo.textIndent = textIndent;
458
- renderInfo.metrics = metrics;
459
-
460
- return renderInfo as RenderInfo;
461
- }
462
-
463
- draw(
464
- renderInfo: RenderInfo,
465
- linesOverride?: { lines: string[]; lineWidths: number[] },
466
- ) {
467
- const precision = this.getPrecision();
468
-
469
- // Allow lines to be overriden for partial rendering.
470
- const lines = linesOverride?.lines || renderInfo.lines;
471
- const lineWidths = linesOverride?.lineWidths || renderInfo.lineWidths;
472
- const height = linesOverride
473
- ? calcHeight(
474
- this._settings.textBaseline,
475
- renderInfo.fontSize,
476
- renderInfo.lineHeight,
477
- linesOverride.lines.length,
478
- this._settings.offsetY === null
479
- ? null
480
- : this._settings.offsetY * precision,
481
- )
482
- : renderInfo.height;
483
-
484
- // Add extra margin to prevent issue with clipped text when scaling.
485
- this._canvas.width = Math.min(
486
- Math.ceil(renderInfo.width + this._settings.textRenderIssueMargin),
487
- MAX_TEXTURE_DIMENSION,
488
- );
489
- this._canvas.height = Math.min(Math.ceil(height), MAX_TEXTURE_DIMENSION);
490
-
491
- // Canvas context has been reset.
492
- this.setFontProperties();
493
-
494
- if (renderInfo.fontSize >= 128) {
495
- // WpeWebKit bug: must force compositing because cairo-traps-compositor will not work with text first.
496
- this._context.globalAlpha = 0.01;
497
- this._context.fillRect(0, 0, 0.01, 0.01);
498
- this._context.globalAlpha = 1.0;
499
- }
500
-
501
- if (renderInfo.cutSx || renderInfo.cutSy) {
502
- this._context.translate(-renderInfo.cutSx, -renderInfo.cutSy);
503
- }
504
-
505
- let linePositionX;
506
- let linePositionY;
507
-
508
- const drawLines = [];
509
-
510
- const { metrics } = renderInfo;
511
-
512
- /**
513
- * Ascender (in pixels)
514
- */
515
- const ascenderPx = metrics
516
- ? metrics.ascender * renderInfo.fontSize
517
- : renderInfo.fontSize;
518
-
519
- /**
520
- * Bare line height is the distance between the ascender and descender of the font.
521
- * without the line gap metric.
522
- */
523
- const bareLineHeightPx =
524
- (metrics.ascender - metrics.descender) * renderInfo.fontSize;
525
-
526
- // Draw lines line by line.
527
- for (let i = 0, n = lines.length; i < n; i++) {
528
- linePositionX = i === 0 ? renderInfo.textIndent : 0;
529
-
530
- // By default, text is aligned to top
531
- linePositionY = i * renderInfo.lineHeight + ascenderPx;
532
-
533
- if (this._settings.verticalAlign == 'middle') {
534
- linePositionY += (renderInfo.lineHeight - bareLineHeightPx) / 2;
535
- } else if (this._settings.verticalAlign == 'bottom') {
536
- linePositionY += renderInfo.lineHeight - bareLineHeightPx;
537
- }
538
-
539
- if (this._settings.textAlign === 'right') {
540
- linePositionX += renderInfo.innerWidth - lineWidths[i]!;
541
- } else if (this._settings.textAlign === 'center') {
542
- linePositionX += (renderInfo.innerWidth - lineWidths[i]!) / 2;
543
- }
544
- linePositionX += renderInfo.paddingLeft;
545
-
546
- drawLines.push({
547
- text: lines[i]!,
548
- x: linePositionX,
549
- y: linePositionY,
550
- w: lineWidths[i]!,
551
- });
552
- }
553
-
554
- // Highlight.
555
- if (this._settings.highlight) {
556
- const color = this._settings.highlightColor;
557
-
558
- const hlHeight =
559
- this._settings.highlightHeight * precision || renderInfo.fontSize * 1.5;
560
- const offset = this._settings.highlightOffset * precision;
561
- const hlPaddingLeft =
562
- this._settings.highlightPaddingLeft !== null
563
- ? this._settings.highlightPaddingLeft * precision
564
- : renderInfo.paddingLeft;
565
- const hlPaddingRight =
566
- this._settings.highlightPaddingRight !== null
567
- ? this._settings.highlightPaddingRight * precision
568
- : renderInfo.paddingRight;
569
-
570
- this._context.fillStyle = getRgbaString(color);
571
- for (let i = 0; i < drawLines.length; i++) {
572
- const drawLine = drawLines[i]!;
573
- this._context.fillRect(
574
- drawLine.x - hlPaddingLeft,
575
- drawLine.y - renderInfo.offsetY + offset,
576
- drawLine.w + hlPaddingRight + hlPaddingLeft,
577
- hlHeight,
578
- );
579
- }
580
- }
581
-
582
- // Text shadow.
583
- let prevShadowSettings: null | [string, number, number, number] = null;
584
- if (this._settings.shadow) {
585
- prevShadowSettings = [
586
- this._context.shadowColor,
587
- this._context.shadowOffsetX,
588
- this._context.shadowOffsetY,
589
- this._context.shadowBlur,
590
- ];
591
-
592
- this._context.shadowColor = getRgbaString(this._settings.shadowColor);
593
- this._context.shadowOffsetX = this._settings.shadowOffsetX * precision;
594
- this._context.shadowOffsetY = this._settings.shadowOffsetY * precision;
595
- this._context.shadowBlur = this._settings.shadowBlur * precision;
596
- }
597
-
598
- this._context.fillStyle = getRgbaString(this._settings.textColor);
599
- for (let i = 0, n = drawLines.length; i < n; i++) {
600
- const drawLine = drawLines[i]!;
601
-
602
- if (renderInfo.letterSpacing === 0) {
603
- this._context.fillText(drawLine.text, drawLine.x, drawLine.y);
604
- } else {
605
- const textSplit = drawLine.text.split('');
606
- let x = drawLine.x;
607
- for (let i = 0, j = textSplit.length; i < j; i++) {
608
- this._context.fillText(textSplit[i]!, x, drawLine.y);
609
- x += this.measureText(textSplit[i]!, renderInfo.letterSpacing);
610
- }
611
- }
612
- }
613
-
614
- if (prevShadowSettings) {
615
- this._context.shadowColor = prevShadowSettings[0];
616
- this._context.shadowOffsetX = prevShadowSettings[1];
617
- this._context.shadowOffsetY = prevShadowSettings[2];
618
- this._context.shadowBlur = prevShadowSettings[3];
619
- }
620
-
621
- if (renderInfo.cutSx || renderInfo.cutSy) {
622
- this._context.translate(renderInfo.cutSx, renderInfo.cutSy);
623
- }
624
- }
625
-
626
- wrapWord(word: string, wordWrapWidth: number, suffix: string) {
627
- const suffixWidth = this._context.measureText(suffix).width;
628
- const wordLen = word.length;
629
- const wordWidth = this._context.measureText(word).width;
630
-
631
- /* If word fits wrapWidth, do nothing */
632
- if (wordWidth <= wordWrapWidth) {
633
- return word;
634
- }
635
-
636
- /* Make initial guess for text cuttoff */
637
- let cutoffIndex = Math.floor((wordWrapWidth * wordLen) / wordWidth);
638
- let truncWordWidth =
639
- this._context.measureText(word.substring(0, cutoffIndex)).width +
640
- suffixWidth;
641
-
642
- /* In case guess was overestimated, shrink it letter by letter. */
643
- if (truncWordWidth > wordWrapWidth) {
644
- while (cutoffIndex > 0) {
645
- truncWordWidth =
646
- this._context.measureText(word.substring(0, cutoffIndex)).width +
647
- suffixWidth;
648
- if (truncWordWidth > wordWrapWidth) {
649
- cutoffIndex -= 1;
650
- } else {
651
- break;
652
- }
653
- }
654
-
655
- /* In case guess was underestimated, extend it letter by letter. */
656
- } else {
657
- while (cutoffIndex < wordLen) {
658
- truncWordWidth =
659
- this._context.measureText(word.substring(0, cutoffIndex)).width +
660
- suffixWidth;
661
- if (truncWordWidth < wordWrapWidth) {
662
- cutoffIndex += 1;
663
- } else {
664
- // Finally, when bound is crossed, retract last letter.
665
- cutoffIndex -= 1;
666
- break;
667
- }
668
- }
669
- }
670
-
671
- /* If wrapWidth is too short to even contain suffix alone, return empty string */
672
- return (
673
- word.substring(0, cutoffIndex) +
674
- (wordWrapWidth >= suffixWidth ? suffix : '')
675
- );
676
- }
677
-
678
- /**
679
- * Applies newlines to a string to have it optimally fit into the horizontal
680
- * bounds set by the Text object's wordWrapWidth property.
681
- */
682
- wrapText(
683
- text: string,
684
- wordWrapWidth: number,
685
- letterSpacing: number,
686
- indent = 0,
687
- ) {
688
- const spaceRegex = / |\u200B/g; // ZWSP and spaces
689
- const lines = text.split(/\r?\n/g);
690
- let allLines: string[] = [];
691
- const realNewlines: number[] = [];
692
-
693
- for (let i = 0; i < lines.length; i++) {
694
- const resultLines: string[] = [];
695
- let result = '';
696
- let spaceLeft = wordWrapWidth - indent;
697
-
698
- // Split the line into words, considering ZWSP
699
- const words = lines[i]!.split(spaceRegex);
700
- const spaces = lines[i]!.match(spaceRegex) || [];
701
-
702
- for (let j = 0; j < words.length; j++) {
703
- const space = spaces[j - 1] || '';
704
- const word = words[j]!;
705
- const wordWidth = this.measureText(word, letterSpacing);
706
- const wordWidthWithSpace = isZeroWidthSpace(space)
707
- ? wordWidth
708
- : wordWidth + this.measureText(space, letterSpacing);
709
-
710
- if (j === 0 || wordWidthWithSpace > spaceLeft) {
711
- if (j > 0) {
712
- resultLines.push(result);
713
- result = '';
714
- }
715
- result += word;
716
- spaceLeft = wordWrapWidth - wordWidth - (j === 0 ? indent : 0);
717
- } else {
718
- spaceLeft -= wordWidthWithSpace;
719
- result += space + word;
720
- }
721
- }
722
-
723
- resultLines.push(result);
724
- result = '';
725
- allLines = allLines.concat(resultLines);
726
-
727
- if (i < lines.length - 1) {
728
- realNewlines.push(allLines.length);
729
- }
730
- }
731
-
732
- return { l: allLines, n: realNewlines };
733
- }
734
-
735
- measureText(word: string, space = 0) {
736
- if (!space) {
737
- return this._context.measureText(word).width;
738
- }
739
-
740
- // Split word into characters, but skip ZWSP in the width calculation
741
- return word.split('').reduce((acc, char) => {
742
- // Check if the character is a zero-width space and skip it
743
- if (isZeroWidthSpace(char)) {
744
- return acc;
745
- }
746
- return acc + this._context.measureText(char).width + space;
747
- }, 0);
748
- }
749
-
750
- mergeDefaults(settings: Partial<Settings>): Settings {
751
- return {
752
- text: '',
753
- w: 0,
754
- h: 0,
755
- fontStyle: 'normal',
756
- fontSize: 40,
757
- fontFamily: null,
758
- trFontFace: null,
759
- wordWrap: true,
760
- wordWrapWidth: 0,
761
- wordBreak: false,
762
- textOverflow: '',
763
- lineHeight: null,
764
- textBaseline: 'alphabetic',
765
- textAlign: 'left',
766
- verticalAlign: 'top',
767
- offsetY: null,
768
- maxLines: 0,
769
- maxHeight: null,
770
- overflowSuffix: '...',
771
- textColor: [1.0, 1.0, 1.0, 1.0],
772
- paddingLeft: 0,
773
- paddingRight: 0,
774
- shadow: false,
775
- shadowColor: [0.0, 0.0, 0.0, 1.0],
776
- shadowOffsetX: 0,
777
- shadowOffsetY: 0,
778
- shadowBlur: 5,
779
- highlight: false,
780
- highlightHeight: 0,
781
- highlightColor: [0.0, 0.0, 0.0, 1.0],
782
- highlightOffset: 0,
783
- highlightPaddingLeft: 0,
784
- highlightPaddingRight: 0,
785
- letterSpacing: 0,
786
- textIndent: 0,
787
- cutSx: 0,
788
- cutEx: 0,
789
- cutSy: 0,
790
- cutEy: 0,
791
- advancedRenderer: false,
792
- fontBaselineRatio: 0,
793
- precision: 1,
794
- textRenderIssueMargin: 0,
795
- ...settings,
796
- };
797
- }
798
- }
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
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
21
+
22
+ import { assertTruthy } from '../../../utils.js';
23
+ import { getRgbaString, type RGBA } from '../../lib/utils.js';
24
+ import { calcDefaultLineHeight } from '../TextRenderingUtils.js';
25
+ import {
26
+ getWebFontMetrics,
27
+ isZeroWidthSpace,
28
+ } from '../TextTextureRendererUtils.js';
29
+ import type { NormalizedFontMetrics } from '../font-face-types/TrFontFace.js';
30
+ import type { WebTrFontFace } from '../font-face-types/WebTrFontFace.js';
31
+
32
+ const MAX_TEXTURE_DIMENSION = 2048;
33
+
34
+ /**
35
+ * Text Overflow Values
36
+ */
37
+ export type TextOverflow =
38
+ | 'ellipsis'
39
+ | 'clip'
40
+ | (string & Record<never, never>);
41
+
42
+ /***
43
+ * Text Horizontal Align Values
44
+ */
45
+ export type TextAlign = 'left' | 'center' | 'right';
46
+
47
+ /***
48
+ * Text Baseline Values
49
+ */
50
+ export type TextBaseline =
51
+ | 'alphabetic'
52
+ | 'top'
53
+ | 'hanging'
54
+ | 'middle'
55
+ | 'ideographic'
56
+ | 'bottom';
57
+
58
+ /***
59
+ * Text Vertical Align Values
60
+ */
61
+ export type TextVerticalAlign = 'top' | 'middle' | 'bottom';
62
+
63
+ /**
64
+ * Text Texture Settings
65
+ */
66
+ export interface Settings {
67
+ w: number;
68
+ h: number;
69
+ text: string;
70
+ fontStyle: string;
71
+ fontSize: number;
72
+ fontBaselineRatio: number;
73
+ fontFamily: string | null;
74
+ trFontFace: WebTrFontFace | null;
75
+ wordWrap: boolean;
76
+ wordWrapWidth: number;
77
+ wordBreak: boolean;
78
+ textOverflow: TextOverflow | null;
79
+ lineHeight: number | null;
80
+ textBaseline: TextBaseline;
81
+ textAlign: TextAlign;
82
+ verticalAlign: TextVerticalAlign;
83
+ offsetY: number | null;
84
+ maxLines: number;
85
+ maxHeight: number | null;
86
+ overflowSuffix: string;
87
+ precision: number;
88
+ textColor: RGBA;
89
+ paddingLeft: number;
90
+ paddingRight: number;
91
+ shadow: boolean;
92
+ shadowColor: RGBA;
93
+ shadowOffsetX: number;
94
+ shadowOffsetY: number;
95
+ shadowBlur: number;
96
+ highlight: boolean;
97
+ highlightHeight: number;
98
+ highlightColor: RGBA;
99
+ highlightOffset: number;
100
+ highlightPaddingLeft: number;
101
+ highlightPaddingRight: number;
102
+ letterSpacing: number;
103
+ textIndent: number;
104
+ cutSx: number;
105
+ cutSy: number;
106
+ cutEx: number;
107
+ cutEy: number;
108
+ advancedRenderer: boolean;
109
+
110
+ // Normally stage options
111
+ textRenderIssueMargin: number;
112
+ }
113
+
114
+ export interface RenderInfo {
115
+ w: number;
116
+ h: number;
117
+ lines: string[];
118
+ precision: number;
119
+ remainingText: string;
120
+ moreTextLines: boolean;
121
+ width: number;
122
+ innerWidth: number;
123
+ height: number;
124
+ fontSize: number;
125
+ cutSx: number;
126
+ cutSy: number;
127
+ cutEx: number;
128
+ cutEy: number;
129
+ lineHeight: number;
130
+ defLineHeight: number;
131
+ lineWidths: number[];
132
+ offsetY: number;
133
+ paddingLeft: number;
134
+ paddingRight: number;
135
+ letterSpacing: number;
136
+ textIndent: number;
137
+ metrics: NormalizedFontMetrics;
138
+ }
139
+
140
+ /**
141
+ * Calculate height for the canvas
142
+ *
143
+ * @param textBaseline
144
+ * @param fontSize
145
+ * @param lineHeight
146
+ * @param numLines
147
+ * @param offsetY
148
+ * @returns
149
+ */
150
+ function calcHeight(
151
+ textBaseline: TextBaseline,
152
+ fontSize: number,
153
+ lineHeight: number,
154
+ numLines: number,
155
+ offsetY: number | null,
156
+ ) {
157
+ const baselineOffset = textBaseline !== 'bottom' ? 0.5 * fontSize : 0;
158
+ return (
159
+ lineHeight * (numLines - 1) +
160
+ baselineOffset +
161
+ Math.max(lineHeight, fontSize) +
162
+ (offsetY || 0)
163
+ );
164
+ }
165
+
166
+ export class LightningTextTextureRenderer {
167
+ private _canvas: OffscreenCanvas | HTMLCanvasElement;
168
+ private _context:
169
+ | OffscreenCanvasRenderingContext2D
170
+ | CanvasRenderingContext2D;
171
+ private _settings: Settings;
172
+
173
+ constructor(
174
+ canvas: OffscreenCanvas | HTMLCanvasElement,
175
+ context: OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D,
176
+ ) {
177
+ this._canvas = canvas;
178
+ this._context = context;
179
+ this._settings = this.mergeDefaults({});
180
+ }
181
+
182
+ set settings(v: Partial<Settings>) {
183
+ this._settings = this.mergeDefaults(v);
184
+ }
185
+
186
+ get settings(): Settings {
187
+ return this._settings;
188
+ }
189
+
190
+ getPrecision() {
191
+ return this._settings.precision;
192
+ }
193
+
194
+ setFontProperties() {
195
+ this._context.font = this._getFontSetting();
196
+ this._context.textBaseline = this._settings.textBaseline;
197
+ }
198
+
199
+ _getFontSetting() {
200
+ const ff = [this._settings.fontFamily];
201
+
202
+ const ffs = [];
203
+ for (let i = 0, n = ff.length; i < n; i++) {
204
+ if (ff[i] === 'serif' || ff[i] === 'sans-serif') {
205
+ ffs.push(ff[i]);
206
+ } else {
207
+ ffs.push(`"${ff[i]!}"`);
208
+ }
209
+ }
210
+
211
+ return `${this._settings.fontStyle} ${
212
+ this._settings.fontSize * this.getPrecision()
213
+ }px ${ffs.join(',')}`;
214
+ }
215
+
216
+ _load() {
217
+ if (true && document.fonts) {
218
+ const fontSetting = this._getFontSetting();
219
+ try {
220
+ if (!document.fonts.check(fontSetting, this._settings.text)) {
221
+ // Use a promise that waits for loading.
222
+ return document.fonts
223
+ .load(fontSetting, this._settings.text)
224
+ .catch((err) => {
225
+ // Just load the fallback font.
226
+ console.warn('[Lightning] Font load error', err, fontSetting);
227
+ })
228
+ .then(() => {
229
+ if (!document.fonts.check(fontSetting, this._settings.text)) {
230
+ console.warn('[Lightning] Font not found', fontSetting);
231
+ }
232
+ });
233
+ }
234
+ } catch (e) {
235
+ console.warn("[Lightning] Can't check font loading for " + fontSetting);
236
+ }
237
+ }
238
+ }
239
+
240
+ calculateRenderInfo(): RenderInfo {
241
+ const renderInfo: Partial<RenderInfo> = {};
242
+
243
+ const precision = this.getPrecision();
244
+
245
+ const paddingLeft = this._settings.paddingLeft * precision;
246
+ const paddingRight = this._settings.paddingRight * precision;
247
+ const fontSize = this._settings.fontSize * precision;
248
+ let offsetY =
249
+ this._settings.offsetY === null
250
+ ? null
251
+ : this._settings.offsetY * precision;
252
+ const w = this._settings.w * precision;
253
+ const h = this._settings.h * precision;
254
+ let wordWrapWidth = this._settings.wordWrapWidth * precision;
255
+ const cutSx = this._settings.cutSx * precision;
256
+ const cutEx = this._settings.cutEx * precision;
257
+ const cutSy = this._settings.cutSy * precision;
258
+ const cutEy = this._settings.cutEy * precision;
259
+ const letterSpacing = (this._settings.letterSpacing || 0) * precision;
260
+ const textIndent = this._settings.textIndent * precision;
261
+ const trFontFace = this._settings.trFontFace;
262
+
263
+ // Set font properties.
264
+ this.setFontProperties();
265
+
266
+ assertTruthy(trFontFace);
267
+ const metrics = getWebFontMetrics(this._context, trFontFace, fontSize);
268
+ const defLineHeight = calcDefaultLineHeight(metrics, fontSize) * precision;
269
+ const lineHeight =
270
+ this._settings.lineHeight !== null
271
+ ? this._settings.lineHeight * precision
272
+ : defLineHeight;
273
+
274
+ const maxHeight = this._settings.maxHeight;
275
+ const containedMaxLines =
276
+ maxHeight !== null && lineHeight > 0
277
+ ? Math.floor(maxHeight / lineHeight)
278
+ : 0;
279
+
280
+ const setMaxLines = this._settings.maxLines;
281
+ const calcMaxLines =
282
+ containedMaxLines > 0 && setMaxLines > 0
283
+ ? Math.min(containedMaxLines, setMaxLines)
284
+ : Math.max(containedMaxLines, setMaxLines);
285
+
286
+ // Total width.
287
+ let width = w || 2048 / this.getPrecision();
288
+
289
+ // Inner width.
290
+ let innerWidth = width - paddingLeft;
291
+ if (innerWidth < 10) {
292
+ width += 10 - innerWidth;
293
+ innerWidth = 10;
294
+ }
295
+
296
+ if (!wordWrapWidth) {
297
+ wordWrapWidth = innerWidth;
298
+ }
299
+
300
+ // Text overflow
301
+ if (this._settings.textOverflow && !this._settings.wordWrap) {
302
+ let suffix;
303
+ switch (this._settings.textOverflow) {
304
+ case 'clip':
305
+ suffix = '';
306
+ break;
307
+ case 'ellipsis':
308
+ suffix = this._settings.overflowSuffix;
309
+ break;
310
+ default:
311
+ suffix = this._settings.textOverflow;
312
+ }
313
+ this._settings.text = this.wrapWord(
314
+ this._settings.text,
315
+ wordWrapWidth - textIndent,
316
+ suffix,
317
+ );
318
+ }
319
+
320
+ // word wrap
321
+ // preserve original text
322
+ let linesInfo: { n: number[]; l: string[] };
323
+ if (this._settings.wordWrap) {
324
+ linesInfo = this.wrapText(
325
+ this._settings.text,
326
+ wordWrapWidth,
327
+ letterSpacing,
328
+ textIndent,
329
+ );
330
+ } else {
331
+ linesInfo = { l: this._settings.text.split(/(?:\r\n|\r|\n)/), n: [] };
332
+ const n = linesInfo.l.length;
333
+ for (let i = 0; i < n - 1; i++) {
334
+ linesInfo.n.push(i);
335
+ }
336
+ }
337
+ let lines = linesInfo.l;
338
+
339
+ if (calcMaxLines && lines.length > calcMaxLines) {
340
+ const usedLines = lines.slice(0, calcMaxLines);
341
+
342
+ let otherLines = null;
343
+ if (this._settings.overflowSuffix) {
344
+ // Wrap again with max lines suffix enabled.
345
+ const w = this._settings.overflowSuffix
346
+ ? this.measureText(this._settings.overflowSuffix)
347
+ : 0;
348
+ const al = this.wrapText(
349
+ usedLines[usedLines.length - 1]!,
350
+ wordWrapWidth - w,
351
+ letterSpacing,
352
+ textIndent,
353
+ );
354
+ usedLines[usedLines.length - 1] = `${al.l[0]!}${
355
+ this._settings.overflowSuffix
356
+ }`;
357
+ otherLines = [al.l.length > 1 ? al.l[1] : ''];
358
+ } else {
359
+ otherLines = [''];
360
+ }
361
+
362
+ // Re-assemble the remaining text.
363
+ let i;
364
+ const n = lines.length;
365
+ let j = 0;
366
+ const m = linesInfo.n.length;
367
+ for (i = calcMaxLines; i < n; i++) {
368
+ otherLines[j] += `${otherLines[j] ? ' ' : ''}${lines[i]!}`;
369
+ if (i + 1 < m && linesInfo.n[i + 1]) {
370
+ j++;
371
+ }
372
+ }
373
+
374
+ renderInfo.remainingText = otherLines.join('\n');
375
+
376
+ renderInfo.moreTextLines = true;
377
+
378
+ lines = usedLines;
379
+ } else {
380
+ renderInfo.moreTextLines = false;
381
+ renderInfo.remainingText = '';
382
+ }
383
+
384
+ // calculate text width
385
+ let maxLineWidth = 0;
386
+ const lineWidths: number[] = [];
387
+ for (let i = 0; i < lines.length; i++) {
388
+ const lineWidth =
389
+ this.measureText(lines[i]!, letterSpacing) + (i === 0 ? textIndent : 0);
390
+ lineWidths.push(lineWidth);
391
+ maxLineWidth = Math.max(maxLineWidth, lineWidth);
392
+ }
393
+
394
+ renderInfo.lineWidths = lineWidths;
395
+
396
+ if (!w) {
397
+ // Auto-set width to max text length.
398
+ width = maxLineWidth + paddingLeft + paddingRight;
399
+ innerWidth = maxLineWidth;
400
+ }
401
+
402
+ let height;
403
+ if (h) {
404
+ height = h;
405
+ } else {
406
+ height = calcHeight(
407
+ this._settings.textBaseline,
408
+ fontSize,
409
+ lineHeight,
410
+ lines.length,
411
+ offsetY,
412
+ );
413
+ }
414
+
415
+ if (offsetY === null) {
416
+ offsetY = fontSize;
417
+ }
418
+
419
+ renderInfo.w = width;
420
+ renderInfo.h = height;
421
+ renderInfo.lines = lines;
422
+ renderInfo.precision = precision;
423
+
424
+ if (!width) {
425
+ // To prevent canvas errors.
426
+ width = 1;
427
+ }
428
+
429
+ if (!height) {
430
+ // To prevent canvas errors.
431
+ height = 1;
432
+ }
433
+
434
+ if (cutSx || cutEx) {
435
+ width = Math.min(width, cutEx - cutSx);
436
+ }
437
+
438
+ if (cutSy || cutEy) {
439
+ height = Math.min(height, cutEy - cutSy);
440
+ }
441
+
442
+ renderInfo.width = width;
443
+ renderInfo.innerWidth = innerWidth;
444
+ renderInfo.height = height;
445
+ renderInfo.fontSize = fontSize;
446
+ renderInfo.cutSx = cutSx;
447
+ renderInfo.cutSy = cutSy;
448
+ renderInfo.cutEx = cutEx;
449
+ renderInfo.cutEy = cutEy;
450
+ renderInfo.lineHeight = lineHeight;
451
+ renderInfo.defLineHeight = defLineHeight;
452
+ renderInfo.lineWidths = lineWidths;
453
+ renderInfo.offsetY = offsetY;
454
+ renderInfo.paddingLeft = paddingLeft;
455
+ renderInfo.paddingRight = paddingRight;
456
+ renderInfo.letterSpacing = letterSpacing;
457
+ renderInfo.textIndent = textIndent;
458
+ renderInfo.metrics = metrics;
459
+
460
+ return renderInfo as RenderInfo;
461
+ }
462
+
463
+ draw(
464
+ renderInfo: RenderInfo,
465
+ linesOverride?: { lines: string[]; lineWidths: number[] },
466
+ ) {
467
+ const precision = this.getPrecision();
468
+
469
+ // Allow lines to be overriden for partial rendering.
470
+ const lines = linesOverride?.lines || renderInfo.lines;
471
+ const lineWidths = linesOverride?.lineWidths || renderInfo.lineWidths;
472
+ const height = linesOverride
473
+ ? calcHeight(
474
+ this._settings.textBaseline,
475
+ renderInfo.fontSize,
476
+ renderInfo.lineHeight,
477
+ linesOverride.lines.length,
478
+ this._settings.offsetY === null
479
+ ? null
480
+ : this._settings.offsetY * precision,
481
+ )
482
+ : renderInfo.height;
483
+
484
+ // Add extra margin to prevent issue with clipped text when scaling.
485
+ this._canvas.width = Math.min(
486
+ Math.ceil(renderInfo.width + this._settings.textRenderIssueMargin),
487
+ MAX_TEXTURE_DIMENSION,
488
+ );
489
+ this._canvas.height = Math.min(Math.ceil(height), MAX_TEXTURE_DIMENSION);
490
+
491
+ // Canvas context has been reset.
492
+ this.setFontProperties();
493
+
494
+ if (renderInfo.fontSize >= 128) {
495
+ // WpeWebKit bug: must force compositing because cairo-traps-compositor will not work with text first.
496
+ this._context.globalAlpha = 0.01;
497
+ this._context.fillRect(0, 0, 0.01, 0.01);
498
+ this._context.globalAlpha = 1.0;
499
+ }
500
+
501
+ if (renderInfo.cutSx || renderInfo.cutSy) {
502
+ this._context.translate(-renderInfo.cutSx, -renderInfo.cutSy);
503
+ }
504
+
505
+ let linePositionX;
506
+ let linePositionY;
507
+
508
+ const drawLines = [];
509
+
510
+ const { metrics } = renderInfo;
511
+
512
+ /**
513
+ * Ascender (in pixels)
514
+ */
515
+ const ascenderPx = metrics
516
+ ? metrics.ascender * renderInfo.fontSize
517
+ : renderInfo.fontSize;
518
+
519
+ /**
520
+ * Bare line height is the distance between the ascender and descender of the font.
521
+ * without the line gap metric.
522
+ */
523
+ const bareLineHeightPx =
524
+ (metrics.ascender - metrics.descender) * renderInfo.fontSize;
525
+
526
+ // Draw lines line by line.
527
+ for (let i = 0, n = lines.length; i < n; i++) {
528
+ linePositionX = i === 0 ? renderInfo.textIndent : 0;
529
+
530
+ // By default, text is aligned to top
531
+ linePositionY = i * renderInfo.lineHeight + ascenderPx;
532
+
533
+ if (this._settings.verticalAlign == 'middle') {
534
+ linePositionY += (renderInfo.lineHeight - bareLineHeightPx) / 2;
535
+ } else if (this._settings.verticalAlign == 'bottom') {
536
+ linePositionY += renderInfo.lineHeight - bareLineHeightPx;
537
+ }
538
+
539
+ if (this._settings.textAlign === 'right') {
540
+ linePositionX += renderInfo.innerWidth - lineWidths[i]!;
541
+ } else if (this._settings.textAlign === 'center') {
542
+ linePositionX += (renderInfo.innerWidth - lineWidths[i]!) / 2;
543
+ }
544
+ linePositionX += renderInfo.paddingLeft;
545
+
546
+ drawLines.push({
547
+ text: lines[i]!,
548
+ x: linePositionX,
549
+ y: linePositionY,
550
+ w: lineWidths[i]!,
551
+ });
552
+ }
553
+
554
+ // Highlight.
555
+ if (this._settings.highlight) {
556
+ const color = this._settings.highlightColor;
557
+
558
+ const hlHeight =
559
+ this._settings.highlightHeight * precision || renderInfo.fontSize * 1.5;
560
+ const offset = this._settings.highlightOffset * precision;
561
+ const hlPaddingLeft =
562
+ this._settings.highlightPaddingLeft !== null
563
+ ? this._settings.highlightPaddingLeft * precision
564
+ : renderInfo.paddingLeft;
565
+ const hlPaddingRight =
566
+ this._settings.highlightPaddingRight !== null
567
+ ? this._settings.highlightPaddingRight * precision
568
+ : renderInfo.paddingRight;
569
+
570
+ this._context.fillStyle = getRgbaString(color);
571
+ for (let i = 0; i < drawLines.length; i++) {
572
+ const drawLine = drawLines[i]!;
573
+ this._context.fillRect(
574
+ drawLine.x - hlPaddingLeft,
575
+ drawLine.y - renderInfo.offsetY + offset,
576
+ drawLine.w + hlPaddingRight + hlPaddingLeft,
577
+ hlHeight,
578
+ );
579
+ }
580
+ }
581
+
582
+ // Text shadow.
583
+ let prevShadowSettings: null | [string, number, number, number] = null;
584
+ if (this._settings.shadow) {
585
+ prevShadowSettings = [
586
+ this._context.shadowColor,
587
+ this._context.shadowOffsetX,
588
+ this._context.shadowOffsetY,
589
+ this._context.shadowBlur,
590
+ ];
591
+
592
+ this._context.shadowColor = getRgbaString(this._settings.shadowColor);
593
+ this._context.shadowOffsetX = this._settings.shadowOffsetX * precision;
594
+ this._context.shadowOffsetY = this._settings.shadowOffsetY * precision;
595
+ this._context.shadowBlur = this._settings.shadowBlur * precision;
596
+ }
597
+
598
+ this._context.fillStyle = getRgbaString(this._settings.textColor);
599
+ for (let i = 0, n = drawLines.length; i < n; i++) {
600
+ const drawLine = drawLines[i]!;
601
+
602
+ if (renderInfo.letterSpacing === 0) {
603
+ this._context.fillText(drawLine.text, drawLine.x, drawLine.y);
604
+ } else {
605
+ const textSplit = drawLine.text.split('');
606
+ let x = drawLine.x;
607
+ for (let i = 0, j = textSplit.length; i < j; i++) {
608
+ this._context.fillText(textSplit[i]!, x, drawLine.y);
609
+ x += this.measureText(textSplit[i]!, renderInfo.letterSpacing);
610
+ }
611
+ }
612
+ }
613
+
614
+ if (prevShadowSettings) {
615
+ this._context.shadowColor = prevShadowSettings[0];
616
+ this._context.shadowOffsetX = prevShadowSettings[1];
617
+ this._context.shadowOffsetY = prevShadowSettings[2];
618
+ this._context.shadowBlur = prevShadowSettings[3];
619
+ }
620
+
621
+ if (renderInfo.cutSx || renderInfo.cutSy) {
622
+ this._context.translate(renderInfo.cutSx, renderInfo.cutSy);
623
+ }
624
+ }
625
+
626
+ wrapWord(word: string, wordWrapWidth: number, suffix: string) {
627
+ const suffixWidth = this._context.measureText(suffix).width;
628
+ const wordLen = word.length;
629
+ const wordWidth = this._context.measureText(word).width;
630
+
631
+ /* If word fits wrapWidth, do nothing */
632
+ if (wordWidth <= wordWrapWidth) {
633
+ return word;
634
+ }
635
+
636
+ /* Make initial guess for text cuttoff */
637
+ let cutoffIndex = Math.floor((wordWrapWidth * wordLen) / wordWidth);
638
+ let truncWordWidth =
639
+ this._context.measureText(word.substring(0, cutoffIndex)).width +
640
+ suffixWidth;
641
+
642
+ /* In case guess was overestimated, shrink it letter by letter. */
643
+ if (truncWordWidth > wordWrapWidth) {
644
+ while (cutoffIndex > 0) {
645
+ truncWordWidth =
646
+ this._context.measureText(word.substring(0, cutoffIndex)).width +
647
+ suffixWidth;
648
+ if (truncWordWidth > wordWrapWidth) {
649
+ cutoffIndex -= 1;
650
+ } else {
651
+ break;
652
+ }
653
+ }
654
+
655
+ /* In case guess was underestimated, extend it letter by letter. */
656
+ } else {
657
+ while (cutoffIndex < wordLen) {
658
+ truncWordWidth =
659
+ this._context.measureText(word.substring(0, cutoffIndex)).width +
660
+ suffixWidth;
661
+ if (truncWordWidth < wordWrapWidth) {
662
+ cutoffIndex += 1;
663
+ } else {
664
+ // Finally, when bound is crossed, retract last letter.
665
+ cutoffIndex -= 1;
666
+ break;
667
+ }
668
+ }
669
+ }
670
+
671
+ /* If wrapWidth is too short to even contain suffix alone, return empty string */
672
+ return (
673
+ word.substring(0, cutoffIndex) +
674
+ (wordWrapWidth >= suffixWidth ? suffix : '')
675
+ );
676
+ }
677
+
678
+ /**
679
+ * Applies newlines to a string to have it optimally fit into the horizontal
680
+ * bounds set by the Text object's wordWrapWidth property.
681
+ */
682
+ wrapText(
683
+ text: string,
684
+ wordWrapWidth: number,
685
+ letterSpacing: number,
686
+ indent = 0,
687
+ ) {
688
+ const spaceRegex = / |\u200B/g; // ZWSP and spaces
689
+ const lines = text.split(/\r?\n/g);
690
+ let allLines: string[] = [];
691
+ const realNewlines: number[] = [];
692
+
693
+ for (let i = 0; i < lines.length; i++) {
694
+ const resultLines: string[] = [];
695
+ let result = '';
696
+ let spaceLeft = wordWrapWidth - indent;
697
+
698
+ // Split the line into words, considering ZWSP
699
+ const words = lines[i]!.split(spaceRegex);
700
+ const spaces = lines[i]!.match(spaceRegex) || [];
701
+
702
+ for (let j = 0; j < words.length; j++) {
703
+ const space = spaces[j - 1] || '';
704
+ const word = words[j]!;
705
+ const wordWidth = this.measureText(word, letterSpacing);
706
+ const wordWidthWithSpace = isZeroWidthSpace(space)
707
+ ? wordWidth
708
+ : wordWidth + this.measureText(space, letterSpacing);
709
+
710
+ if (j === 0 || wordWidthWithSpace > spaceLeft) {
711
+ if (j > 0) {
712
+ resultLines.push(result);
713
+ result = '';
714
+ }
715
+ result += word;
716
+ spaceLeft = wordWrapWidth - wordWidth - (j === 0 ? indent : 0);
717
+ } else {
718
+ spaceLeft -= wordWidthWithSpace;
719
+ result += space + word;
720
+ }
721
+ }
722
+
723
+ resultLines.push(result);
724
+ result = '';
725
+ allLines = allLines.concat(resultLines);
726
+
727
+ if (i < lines.length - 1) {
728
+ realNewlines.push(allLines.length);
729
+ }
730
+ }
731
+
732
+ return { l: allLines, n: realNewlines };
733
+ }
734
+
735
+ measureText(word: string, space = 0) {
736
+ if (!space) {
737
+ return this._context.measureText(word).width;
738
+ }
739
+
740
+ // Split word into characters, but skip ZWSP in the width calculation
741
+ return word.split('').reduce((acc, char) => {
742
+ // Check if the character is a zero-width space and skip it
743
+ if (isZeroWidthSpace(char)) {
744
+ return acc;
745
+ }
746
+ return acc + this._context.measureText(char).width + space;
747
+ }, 0);
748
+ }
749
+
750
+ mergeDefaults(settings: Partial<Settings>): Settings {
751
+ return {
752
+ text: '',
753
+ w: 0,
754
+ h: 0,
755
+ fontStyle: 'normal',
756
+ fontSize: 40,
757
+ fontFamily: null,
758
+ trFontFace: null,
759
+ wordWrap: true,
760
+ wordWrapWidth: 0,
761
+ wordBreak: false,
762
+ textOverflow: '',
763
+ lineHeight: null,
764
+ textBaseline: 'alphabetic',
765
+ textAlign: 'left',
766
+ verticalAlign: 'top',
767
+ offsetY: null,
768
+ maxLines: 0,
769
+ maxHeight: null,
770
+ overflowSuffix: '...',
771
+ textColor: [1.0, 1.0, 1.0, 1.0],
772
+ paddingLeft: 0,
773
+ paddingRight: 0,
774
+ shadow: false,
775
+ shadowColor: [0.0, 0.0, 0.0, 1.0],
776
+ shadowOffsetX: 0,
777
+ shadowOffsetY: 0,
778
+ shadowBlur: 5,
779
+ highlight: false,
780
+ highlightHeight: 0,
781
+ highlightColor: [0.0, 0.0, 0.0, 1.0],
782
+ highlightOffset: 0,
783
+ highlightPaddingLeft: 0,
784
+ highlightPaddingRight: 0,
785
+ letterSpacing: 0,
786
+ textIndent: 0,
787
+ cutSx: 0,
788
+ cutEx: 0,
789
+ cutSy: 0,
790
+ cutEy: 0,
791
+ advancedRenderer: false,
792
+ fontBaselineRatio: 0,
793
+ precision: 1,
794
+ textRenderIssueMargin: 0,
795
+ ...settings,
796
+ };
797
+ }
798
+ }