@mlightcad/mtext-renderer 0.4.8 → 0.4.9

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.
package/README.md ADDED
@@ -0,0 +1,485 @@
1
+ # MText Renderer for Three.js
2
+
3
+ A flexible and extensible AutoCAD MText renderer implementation using Three.js. This package provides a modular architecture to render AutoCAD MText content with different rendering engines, with a primary focus on Three.js rendering.
4
+
5
+ ## Features
6
+
7
+ - Render AutoCAD MText content using Three.js
8
+ - Modular font loading system
9
+ - Font management and dynamic font loading
10
+ - Cache parsed fonts to improve rendering performance
11
+
12
+ ## Core Components
13
+
14
+ ### FontManager
15
+
16
+ The central manager for font operations. It's a singleton class that handles font loading, caching, and text rendering.
17
+
18
+ **Public Properties:**
19
+ - `unsupportedChars`: Record of characters not supported by any loaded font
20
+ - `missedFonts`: Record of fonts that were requested but not found
21
+ - `enableFontCache`: Flag to enable/disable font caching. If it is true, parsed fonts
22
+ will be stored in local IndexedDB to improve performance. Default value is true.
23
+ - `defaultFont`: Default font to use when a requested font is not found
24
+ - `events`: Event managers for font-related events
25
+ - `fontNotFound`: Triggered when a font cannot be found
26
+ - `fontLoaded`: Triggered when a font is successfully loaded
27
+
28
+ **Public Methods:**
29
+ - `getAvaiableFonts()`: Retrieve metadata of available fonts from the configured loader
30
+ - `loadFontsByNames(names)`: Loads fonts by logical names (e.g., 'simsun', 'arial')
31
+ - `getCharShape(char, fontName, size)`: Gets text shape for a character
32
+ - `getFontScaleFactor(fontName)`: Gets scale factor for a font
33
+ - `getNotFoundTextShape(size)`: Gets shape for not found indicator
34
+ - `getUnsupportedChar()`: Gets record of unsupported characters
35
+ - `release()`: Releases all loaded fonts
36
+
37
+ ### FontLoader & DefaultFontLoader
38
+
39
+ Interface for font loading operations. The default implementation [DefaultFontLoader](./src/font/defaultFontLoader.ts) uses a [CDN-based font repository](https://cdn.jsdelivr.net/gh/mlight-lee/cad-data/fonts/). It loads font metadata from a JSON file and provides access to available fonts.
40
+
41
+ You do NOT need to create `DefaultFontLoader` yourself anymore. `FontManager` manages a loader instance internally. If you want to customize font loading, implement `FontLoader` and set it via `FontManager.instance.setFontLoader(customLoader)`.
42
+
43
+ **Public Methods:**
44
+ - `load(fontNames)`: Loads specified fonts into the system
45
+ - `getAvaiableFonts()`: Retrieves information about available fonts
46
+
47
+ ### BaseFont
48
+
49
+ Abstract base class for font implementations. Provides common functionality for font handling.
50
+
51
+ **Public Properties:**
52
+ - `type`: Type of font ('shx' or 'mesh')
53
+ - `data`: Parsed font data
54
+ - `unsupportedChars`: Record of unsupported characters
55
+
56
+ **Public Methods:**
57
+ - `getCharShape(char, size)`: Gets shape for a character
58
+ - `getScaleFactor()`: Gets font scale factor
59
+ - `getNotFoundTextShape(size)`: Gets shape for not found indicator
60
+
61
+ ### BaseTextShape
62
+
63
+ Abstract base class for text shape implementations. Provides common functionality for text shape handling.
64
+
65
+ **Public Properties:**
66
+ - `char`: Character this shape represents
67
+ - `size`: Size of the text shape
68
+
69
+ **Public Methods:**
70
+ - `getWidth()`: Gets width of text shape
71
+ - `getHeight()`: Gets height of text shape
72
+ - `toGeometry()`: Converts shape to THREE.BufferGeometry
73
+
74
+ ### FontFactory
75
+
76
+ Singleton factory class for creating font instances. Handles creation of appropriate font objects based on type and data format.
77
+
78
+ **Public Methods:**
79
+ - `createFont(data)`: Creates font from font data
80
+ - `createFontFromBuffer(fileName, buffer)`: Creates font from file data
81
+
82
+ ### FontCacheManager
83
+ Manages font data caching using IndexedDB. Provides persistent storage for font data.
84
+
85
+ **Public Methods:**
86
+ - `get(fileName)`: Retrieves font data from cache
87
+ - `set(fileName, fontData)`: Stores font data in cache
88
+ - `getAll()`: Retrieves all cached font data
89
+ - `clear()`: Clears all cached font data
90
+
91
+ ## Worker-Based Rendering System
92
+
93
+ The package provides a sophisticated worker-based rendering system that allows MText rendering to be performed in Web Workers, preventing blocking of the main UI thread. This is particularly beneficial for rendering large amounts of text or complex MText content.
94
+
95
+ ### MTextBaseRenderer Interface
96
+
97
+ Defines the common rendering contract for producing Three.js objects from MText content. All renderer implementations must conform to this interface.
98
+
99
+ **Public Methods:**
100
+ - `renderMText(mtextContent, textStyle, colorSettings?)`: Render MText content into a Three.js object hierarchy
101
+ - `destroy()`: Release any resources owned by the renderer
102
+
103
+ ### MTextObject Interface
104
+
105
+ Represents a rendered MText object that extends THREE.Object3D with additional MText-specific properties.
106
+
107
+ **Public Properties:**
108
+ - `box`: The bounding box of the MText object in local coordinates
109
+
110
+ ### MainThreadRenderer
111
+
112
+ Renders MText content directly in the main thread. This is the simplest renderer implementation that provides the same interface as worker-based renderers but runs synchronously in the main thread.
113
+
114
+ **Public Methods:**
115
+ - `renderMText(mtextContent, textStyle, colorSettings?)`: Render MText directly in the main thread
116
+ - `destroy()`: Cleanup resources
117
+
118
+ ### WebWorkerRenderer (MTextWorkerManager)
119
+
120
+ Manages communication with MText Web Workers for parallel text rendering. This renderer uses a pool of Web Workers to distribute rendering tasks, improving performance for large text content.
121
+
122
+ **Public Properties:**
123
+ - `poolSize`: Number of workers in the pool (defaults to optimal size based on hardware concurrency)
124
+
125
+ **Public Methods:**
126
+ - `renderMText(mtextContent, textStyle, colorSettings?)`: Render MText using worker pool
127
+ - `terminate()`: Terminate all workers
128
+ - `destroy()`: Cleanup all resources
129
+
130
+ **Features:**
131
+ - Automatic worker pool management
132
+ - Load balancing across workers
133
+ - Efficient serialization/deserialization of Three.js objects
134
+ - Transferable object support for optimal performance
135
+ - Error handling and timeout management
136
+
137
+ ### UnifiedRenderer
138
+
139
+ A flexible renderer that can switch between main thread and Web Worker rendering modes at runtime. This allows applications to dynamically choose the best rendering strategy based on current conditions.
140
+
141
+ **Public Properties:**
142
+ - `currentMode`: Current rendering mode ('main' or 'worker')
143
+
144
+ **Public Methods:**
145
+ - `switchMode(mode)`: Switch between main thread and worker rendering modes
146
+ - `getMode()`: Get current rendering mode
147
+ - `renderMText(mtextContent, textStyle, colorSettings?)`: Render using current mode
148
+ - `destroy()`: Clean up all resources
149
+
150
+ ### MTextWorker
151
+
152
+ The actual Web Worker implementation that handles MText rendering tasks. This worker contains its own FontManager, StyleManager, and FontLoader instances, allowing it to work independently from the main thread.
153
+
154
+ **Features:**
155
+ - Independent font and style management
156
+ - Can preload fonts on demand via a `loadFonts` message to avoid redundant concurrent loads
157
+ - Efficient object serialization for transfer to main thread
158
+ - Support for transferable objects to minimize memory copying
159
+ - Error handling and response management
160
+
161
+ ### MText
162
+ Main class for rendering AutoCAD MText content. Extends THREE.Object3D to integrate with Three.js scene graph.
163
+
164
+ **Public Properties:**
165
+ - `fontManager`: Reference to FontManager instance for font operations
166
+ - `styleManager`: Reference to StyleManager instance for style operations
167
+
168
+ ## Class Diagram
169
+
170
+ ```mermaid
171
+ classDiagram
172
+ class MText {
173
+ +content: MTextContent
174
+ +style: MTextStyle
175
+ +fontManager: FontManager
176
+ +styleManager: StyleManager
177
+ +update()
178
+ +setContent(content)
179
+ +setStyle(style)
180
+ +dispose()
181
+ }
182
+
183
+ class FontManager {
184
+ -_instance: FontManager
185
+ +unsupportedChars: Record
186
+ +missedFonts: Record
187
+ +enableFontCache: boolean
188
+ +defaultFont: string
189
+ +events: EventManagers
190
+ +loadFonts(urls)
191
+ +getCharShape(char, fontName, size)
192
+ +getFontScaleFactor(fontName)
193
+ +getNotFoundTextShape(size)
194
+ +getUnsupportedChar()
195
+ +release()
196
+ }
197
+
198
+ class FontLoader {
199
+ <<interface>>
200
+ +load(fontNames)
201
+ +getAvaiableFonts()
202
+ }
203
+
204
+ class DefaultFontLoader {
205
+ -_avaiableFonts: FontInfo[]
206
+ +load(fontNames)
207
+ +getAvaiableFonts()
208
+ }
209
+
210
+ class BaseFont {
211
+ <<abstract>>
212
+ +type: FontType
213
+ +data: unknown
214
+ +unsupportedChars: Record
215
+ +getCharShape(char, size)
216
+ +getScaleFactor()
217
+ +getNotFoundTextShape(size)
218
+ }
219
+
220
+ class BaseTextShape {
221
+ <<abstract>>
222
+ +char: string
223
+ +size: number
224
+ +getWidth()
225
+ +getHeight()
226
+ +toGeometry()
227
+ }
228
+
229
+ class FontFactory {
230
+ -_instance: FontFactory
231
+ +createFont(data)
232
+ +createFontFromBuffer(fileName, buffer)
233
+ }
234
+
235
+ class FontCacheManager {
236
+ -_instance: FontCacheManager
237
+ +get(fileName)
238
+ +set(fileName, fontData)
239
+ +getAll()
240
+ +clear()
241
+ }
242
+
243
+ class MTextBaseRenderer {
244
+ <<interface>>
245
+ +renderMText(mtextContent, textStyle, colorSettings?)
246
+ +loadFonts(fonts)
247
+ +getAvailableFonts()
248
+ +destroy()
249
+ }
250
+
251
+ class MTextObject {
252
+ <<interface>>
253
+ +box: Box3
254
+ }
255
+
256
+ class MainThreadRenderer {
257
+ -fontManager: FontManager
258
+ -styleManager: StyleManager
259
+ -fontLoader: DefaultFontLoader
260
+ +renderMText(mtextContent, textStyle, colorSettings?)
261
+ +loadFonts(fonts)
262
+ +getAvailableFonts()
263
+ +destroy()
264
+ }
265
+
266
+ class WebWorkerRenderer {
267
+ -workers: Worker[]
268
+ -inFlightPerWorker: number[]
269
+ -pendingRequests: Map
270
+ -poolSize: number
271
+ +renderMText(mtextContent, textStyle, colorSettings?)
272
+ +loadFonts(fonts)
273
+ +getAvailableFonts()
274
+ +terminate()
275
+ +destroy()
276
+ }
277
+
278
+ class UnifiedRenderer {
279
+ -workerManager: WebWorkerRenderer
280
+ -mainThreadRenderer: MainThreadRenderer
281
+ -adapter: MTextBaseRenderer
282
+ -currentMode: RenderMode
283
+ +switchMode(mode)
284
+ +getMode()
285
+ +renderMText(mtextContent, textStyle, colorSettings?)
286
+ +loadFonts(fonts)
287
+ +getAvailableFonts()
288
+ +destroy()
289
+ }
290
+
291
+ class MTextWorker {
292
+ +fontManager: FontManager
293
+ +styleManager: StyleManager
294
+ +fontLoader: DefaultFontLoader
295
+ +serializeMText(mtext)
296
+ +serializeChildren(mtext)
297
+ }
298
+
299
+ MText --> FontManager
300
+ MText --> StyleManager
301
+ FontManager --> FontFactory
302
+ FontManager --> FontCacheManager
303
+ FontManager --> BaseFont
304
+ DefaultFontLoader ..|> FontLoader
305
+ BaseFont <|-- MeshFont
306
+ BaseFont <|-- ShxFont
307
+ BaseTextShape <|-- MeshTextShape
308
+ BaseTextShape <|-- ShxTextShape
309
+ MainThreadRenderer ..|> MTextBaseRenderer
310
+ WebWorkerRenderer ..|> MTextBaseRenderer
311
+ UnifiedRenderer --> WebWorkerRenderer
312
+ UnifiedRenderer --> MainThreadRenderer
313
+ UnifiedRenderer ..|> MTextBaseRenderer
314
+ MTextWorker --> FontManager
315
+ MTextWorker --> StyleManager
316
+ MTextWorker --> DefaultFontLoader
317
+ WebWorkerRenderer --> MTextWorker
318
+ MTextBaseRenderer --> MTextObject
319
+ ```
320
+
321
+ ## Usage
322
+
323
+ ```typescript
324
+ import * as THREE from 'three';
325
+ import { FontManager, MText, StyleManager } from '@mlightcad/mtext-renderer';
326
+
327
+ // Initialize core components
328
+ const fontManager = FontManager.instance;
329
+ const styleManager = new StyleManager();
330
+
331
+ // Preload a font
332
+ await fontManager.loadFontsByNames(['simsun']);
333
+
334
+ // Create MText content
335
+ const mtextContent = {
336
+ text: '{\\fArial|b0|i0|c0|p34;Hello World}',
337
+ height: 0.1,
338
+ width: 0,
339
+ position: new THREE.Vector3(0, 0, 0),
340
+ };
341
+
342
+ // Create MText instance with style
343
+ const mtext = new MText(
344
+ mtextContent,
345
+ {
346
+ name: 'Standard',
347
+ standardFlag: 0,
348
+ fixedTextHeight: 0.1,
349
+ widthFactor: 1,
350
+ obliqueAngle: 0,
351
+ textGenerationFlag: 0,
352
+ lastHeight: 0.1,
353
+ font: 'Standard',
354
+ bigFont: '',
355
+ color: 0xffffff,
356
+ },
357
+ styleManager,
358
+ fontManager
359
+ );
360
+
361
+ // Add to Three.js scene
362
+ scene.add(mtext);
363
+ ```
364
+
365
+ ## Worker-Based Rendering Usage
366
+
367
+ ### Using MainThreadRenderer
368
+
369
+ ```typescript
370
+ import { MainThreadRenderer } from '@mlightcad/mtext-renderer';
371
+
372
+ // Create main thread renderer
373
+ const renderer = new MainThreadRenderer();
374
+
375
+ // Render MText content (fonts are loaded on demand during rendering)
376
+ const mtextObject = await renderer.renderMText(
377
+ mtextContent,
378
+ textStyle,
379
+ { byLayerColor: 0xffffff, byBlockColor: 0xffffff }
380
+ );
381
+
382
+ // Add to scene
383
+ scene.add(mtextObject);
384
+ ```
385
+
386
+ ### Using WebWorkerRenderer
387
+
388
+ ```typescript
389
+ import { WebWorkerRenderer } from '@mlightcad/mtext-renderer';
390
+
391
+ // Create worker renderer with custom pool size
392
+ const workerRenderer = new WebWorkerRenderer({ poolSize: 4 }); // 4 workers
393
+
394
+ // Optionally preload fonts once via a coordinator to avoid duplicate concurrent loads
395
+ // await workerRenderer.loadFonts(['simsun', 'arial']);
396
+
397
+ // Render MText content using workers (fonts will be loaded on demand if not preloaded)
398
+ const mtextObject = await workerRenderer.renderMText(
399
+ mtextContent,
400
+ textStyle,
401
+ { byLayerColor: 0xffffff, byBlockColor: 0xffffff }
402
+ );
403
+
404
+ // Add to scene
405
+ scene.add(mtextObject);
406
+
407
+ // Clean up when done
408
+ workerRenderer.destroy();
409
+ ```
410
+
411
+ ### Using UnifiedRenderer
412
+
413
+ ```typescript
414
+ import { UnifiedRenderer } from '@mlightcad/mtext-renderer';
415
+
416
+ // Create unified renderer starting in main thread mode
417
+ const unifiedRenderer = new UnifiedRenderer('main');
418
+
419
+ // Render using main thread (fonts loaded on demand)
420
+ let mtextObject = await unifiedRenderer.renderMText(
421
+ mtextContent,
422
+ textStyle,
423
+ { byLayerColor: 0xffffff, byBlockColor: 0xffffff }
424
+ );
425
+
426
+ scene.add(mtextObject);
427
+
428
+ // Switch to worker mode for heavy rendering tasks
429
+ unifiedRenderer.switchMode('worker');
430
+
431
+ // Optionally preload fonts in workers to avoid duplicates
432
+ // await unifiedRenderer.loadFonts(['simsun', 'arial']);
433
+
434
+ // Render using workers
435
+ mtextObject = await unifiedRenderer.renderMText(
436
+ heavyMtextContent,
437
+ textStyle,
438
+ { byLayerColor: 0xffffff, byBlockColor: 0xffffff }
439
+ );
440
+
441
+ scene.add(mtextObject);
442
+
443
+ // Clean up
444
+ unifiedRenderer.destroy();
445
+ ```
446
+
447
+ ### Performance Considerations
448
+
449
+ **When to use MainThreadRenderer:**
450
+ - Simple MText content with few characters
451
+ - When you need immediate synchronous results
452
+ - When worker overhead would be greater than rendering time
453
+
454
+ **When to use WebWorkerRenderer:**
455
+ - Large amounts of MText content
456
+ - Complex text with many formatting codes
457
+ - When you want to keep the main thread responsive
458
+ - Batch processing of multiple MText objects
459
+
460
+ **When to use UnifiedRenderer:**
461
+ - Applications that need to switch rendering strategies dynamically
462
+ - When rendering requirements vary based on content complexity
463
+ - Development environments where you want to test both approaches
464
+
465
+ If all of fonts or certain fonts are not needed any more after rendering, you can call method `release` of class `FontManager` to free memory occupied by them. Based on testing, one Chinese mesh font file may take 40M memory.
466
+
467
+ ```typescript
468
+ // ---
469
+ // FontManager: Releasing Fonts
470
+ // ---
471
+ // To release all loaded fonts and free memory:
472
+ fontManager.release();
473
+
474
+ // To release a specific font by name (e.g., 'simsun'):
475
+ fontManager.release('simsun');
476
+ // Returns true if the font was found and released, false otherwise.
477
+ ```
478
+
479
+ ## License
480
+
481
+ MIT
482
+
483
+ ## Contributing
484
+
485
+ Contributions are welcome! Please read our contributing guidelines for details.