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