-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathp5.Font.js
More file actions
1629 lines (1475 loc) · 52.5 KB
/
p5.Font.js
File metadata and controls
1629 lines (1475 loc) · 52.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module Typography
*/
import { textCoreConstants } from './textCore';
import * as constants from '../core/constants';
import { UnicodeRange } from '@japont/unicode-range';
import { unicodeRanges } from './unicodeRanges';
import { Vector } from '../math/p5.Vector';
/*
API:
loadFont("https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&display=swap")
loadFont("@font-face { font-family: "Bricolage Grotesque", serif; font-optical-sizing: auto; font-weight: <weight> font-style: normal; font-variation-settings: "wdth" 100; });
loadFont({
fontFamily: '"Bricolage Grotesque", serif';
fontOpticalSizing: 'auto';
fontWeight: '<weight>';
fontStyle: 'normal';
fontVariationSettings: '"wdth" 100';
});
loadFont("https://fonts.gstatic.com/s/bricolagegrotesque/v1/pxiAZBhjZQIdd8jGnEotWQ.woff2");
loadFont("./path/to/localFont.ttf");
loadFont("system-font-name");
NEXT:
extract axes from font file
TEST:
const font = new FontFace("Inter", "url(./fonts/inter-latin-variable-full-font.woff2)", {
style: "oblique 0deg 10deg",
weight: "100 900",
display: 'fallback'
});
*/
/*
This module defines the <a href="#/p5.Font">p5.Font</a> class and p5 methods for
loading fonts from files and urls, and extracting points from their paths.
*/
import Typr from './lib/Typr.js';
import { createFromCommands } from '@davepagurek/bezier-path';
const pathArgCounts = { M: 2, L: 2, C: 6, Q: 4 };
const validFontTypes = ['ttf', 'otf', 'woff'];//, 'woff2'];
const validFontTypesRe = new RegExp(`\\.(${validFontTypes.join('|')})`, 'i');
const extractFontNameRe = new RegExp(`([^/]+)(\\.(?:${validFontTypes.join('|')}))`, 'i');
const invalidFontError = 'Sorry, only TTF, OTF and WOFF files are supported.'; // and WOFF2
const fontFaceVariations = ['weight', 'stretch', 'style'];
export class Font {
constructor(p, fontFace, name, path, data) {
if (!(fontFace instanceof FontFace)) {
throw Error('FontFace is required');
}
this._pInst = p;
this.name = name;
this.path = path;
this.data = data;
this.face = fontFace;
}
/**
* Checks whether a font has glyph point data and
* can thus be used for textToPoints(), WEBGL mode, etc.
* @private
*/
static hasGlyphData(textFont) {
let { font } = textFont;
return typeof font === 'object' && typeof font.data !== 'undefined';
}
fontBounds(str, x, y, width, height, options) {
({ width, height, options } = this._parseArgs(width, height, options));
let renderer = options?.graphics?._renderer || this._pInst._renderer;
if (!renderer) throw Error('p5 or graphics required for fontBounds()');
return renderer.fontBounds(str, x, y, width, height);
}
textBounds(str, x, y, width, height, options) {
({ width, height, options } = this._parseArgs(width, height, options));
let renderer = options?.graphics?._renderer || this._pInst._renderer;
if (!renderer) throw Error('p5 or graphics required for fontBounds()');
return renderer.textBounds(str, x, y, width, height);
}
/**
* Returns a flat array of path commands that describe the outlines of a string of text.
*
* Each command is represented as an array of the form `[type, ...coords]`, where:
* - `type` is one of `'M'`, `'L'`, `'Q'`, `'C'`, or `'Z'`,
* - `coords` are the numeric values needed for that command.
*
* `'M'` indicates a "move to" (starting a new contour),
* `'L'` a line segment,
* `'Q'` a quadratic bezier,
* `'C'` a cubic bezier, and
* `'Z'` closes the current path.
*
* The first two parameters, `x` and `y`, specify the baseline origin for the text.
* Optionally, you can provide a `width` and `height` for text wrapping; if you don't need
* wrapping, you can omit them and directly pass `options` as the fourth parameter.
*
* @param {String} str The text to convert into path commands.
* @param {Number} x x‐coordinate of the text baseline.
* @param {Number} y y‐coordinate of the text baseline.
* @param {Number} [width] Optional width for text wrapping.
* @param {Number} [height] Optional height for text wrapping.
* @return {Array<Array>} A flat array of path commands.
*
* @example
* let font;
*
* async function setup() {
* font = await loadFont('assets/inconsolata.otf');
* createCanvas(200, 200);
* background(220);
* noLoop();
* }
*
* function draw() {
* background(220);
* stroke(0);
* noFill();
* textSize(60);
*
* // Get path commands for "Hello" (drawn at baseline x=50, y=100):
* const pathCommands = font.textToPaths('Hello', 30, 110);
*
* beginShape();
* for (let i = 0; i < pathCommands.length; i++) {
* const cmd = pathCommands[i];
* const type = cmd[0];
*
* switch (type) {
* case 'M': {
* // Move to (start a new contour)
* const x = cmd[1];
* const y = cmd[2];
* endContour(); // In case we were already drawing
* beginContour();
* vertex(x, y);
* break;
* }
* case 'L': {
* // Line to
* const x = cmd[1];
* const y = cmd[2];
* vertex(x, y);
* break;
* }
* case 'Q': {
* // Quadratic bezier
* const cx = cmd[1];
* const cy = cmd[2];
* const x = cmd[3];
* const y = cmd[4];
* bezierOrder(2);
* bezierVertex(cx, cy);
* bezierVertex(x, y);
* break;
* }
* case 'C': {
* // Cubic bezier
* const cx1 = cmd[1];
* const cy1 = cmd[2];
* const cx2 = cmd[3];
* const cy2 = cmd[4];
* const x = cmd[5];
* const y = cmd[6];
* bezierOrder(3);
* bezierVertex(cx1, cy1);
* bezierVertex(cx2, cy2);
* bezierVertex(x, y);
* break;
* }
* case 'Z': {
* // Close path
* endContour(CLOSE);
* beginContour();
* break;
* }
* }
* }
* endContour();
* endShape();
* }
*/
textToPaths(str, x, y, width, height, options) {
({ width, height, options } = this._parseArgs(width, height, options));
if (!this.data) {
throw Error('No font data available for "' + this.name
+ '"\nTry downloading a local copy of the font file');
}
// lineate and get glyphs/paths for each line
let lines = this._lineateAndPathify(str, x, y, width, height, options);
// flatten into a single array containing all the glyphs
let glyphs = lines.map(o => o.glyphs).flat();
// flatten into a single array with all the path commands
return glyphs.map(g => g.path.commands).flat();
}
/**
* Returns an array of points outlining a string of text written using the
* font.
*
* Each point object in the array has three properties that describe the
* point's location and orientation, called its path angle. For example,
* `{ x: 10, y: 20, alpha: 450 }`.
*
* The first parameter, `str`, is a string of text. The second and third
* parameters, `x` and `y`, are the text's position. By default, they set the
* coordinates of the bounding box's bottom-left corner. See
* <a href="#/p5/textAlign">textAlign()</a> for more ways to align text.
*
* The fourth parameter, `options`, is also optional. `font.textToPoints()`
* expects an object with the following properties:
*
* `sampleFactor` is the ratio of the text's path length to the number of
* samples. It defaults to 0.1. Higher values produce more points along the
* path and are more precise.
*
* `simplifyThreshold` removes collinear points if it's set to a number other
* than 0. The value represents the threshold angle in radians to use when determining
* whether two edges are collinear.
*
* @param {String} str string of text.
* @param {Number} x x-coordinate of the text.
* @param {Number} y y-coordinate of the text.
* @param {Object} [options] Configuration:
* @param {Number} [options.sampleFactor=0.1] The ratio of the text's path length to the number of samples.
* @param {Number} [options.simplifyThreshold=0] A minmum angle in radian sbetween two segments. Segments with a shallower angle will be merged.
* @return {Array<Object>} array of point objects, each with `x`, `y`, and `alpha` (path angle) properties.
*
* @example
* let font;
*
* async function setup() {
* createCanvas(100, 100);
* font = await loadFont('assets/inconsolata.otf');
*
* background(200);
* textSize(35);
*
* // Get the point array.
* let points = font.textToPoints('p5*js', 6, 60, { sampleFactor: 0.5 });
*
* // Draw a dot at each point.
* for (let p of points) {
* point(p.x, p.y);
* }
*
* describe('A set of black dots outlining the text "p5*js" on a gray background.');
* }
*/
textToPoints(str, x, y, width, height, options) {
// By segmenting per contour, pointAtLength becomes much faster
const contourPoints = this.textToContours(
str,
x, y,
width, height,
options
);
return contourPoints.reduce((acc, next) => {
acc.push(...next);
return acc;
}, []);
}
/**
* Returns an array of arrays of points outlining a string of text written using the
* font. Each array represents a contour, so the letter O will have two outer arrays:
* one for the outer edge of the shape, and one for the inner edge of the hole.
*
* Each point object in a contour array has three properties that describe the
* point's location and orientation, called its path angle. For example,
* `{ x: 10, y: 20, alpha: 450 }`.
*
* The first parameter, `str`, is a string of text. The second and third
* parameters, `x` and `y`, are the text's position. By default, they set the
* coordinates of the bounding box's bottom-left corner. See
* <a href="#/p5/textAlign">textAlign()</a> for more ways to align text.
*
* The fourth parameter, `options`, is also optional. `font.textToContours()`
* expects an object with the following properties:
*
* `sampleFactor` is the ratio of the text's path length to the number of
* samples. It defaults to 0.1. Higher values produce more points along the
* path and are more precise.
*
* `simplifyThreshold` removes collinear points if it's set to a number other
* than 0. The value represents the threshold angle in radians to use when determining
* whether two edges are collinear.
*
* @param {String} str string of text.
* @param {Number} x x-coordinate of the text.
* @param {Number} y y-coordinate of the text.
* @param {Object} [options] Configuration options:
* @param {Number} [options.sampleFactor=0.1] The ratio of the text's path length to the number of samples.
* @param {Number} [options.simplifyThreshold=0] A minmum angle in radians between two segments. Segments with a shallower angle will be merged.
* @return {Array<Array<Object>>} array of point objects, each with `x`, `y`, and `alpha` (path angle) properties.
*
* @example
* let font;
*
* async function setup() {
* createCanvas(100, 100);
* font = await loadFont('/assets/inconsolata.otf');
* }
*
* function draw() {
* background(200);
* textAlign(CENTER, CENTER);
* textSize(30);
*
* // Get the point array.
* let contours = font.textToContours('p5*js', width/2, height/2, { sampleFactor: 0.5 });
*
* beginShape();
* for (const pts of contours) {
* beginContour();
* for (const pt of pts) {
* vertex(pt.x + 5*sin(pt.y*0.1 + millis()*0.01), pt.y);
* }
* endContour(CLOSE);
* }
* endShape();
*
* describe('The text p5*js wobbling over time');
* }
*/
textToContours(str, x = 0, y = 0, width, height, options) {
({ width, height, options } = this._parseArgs(width, height, options));
const cmds = this.textToPaths(str, x, y, width, height, options);
const cmdContours = [];
for (const cmd of cmds) {
if (cmd[0] === 'M') {
cmdContours.push([]);
}
cmdContours[cmdContours.length - 1].push(cmd);
}
return cmdContours.map(commands => pathToPoints(commands, options, this));
}
/**
*
* Converts text into a 3D model that can be rendered in WebGL mode.
*
* This method transforms flat text into extruded 3D geometry, allowing
* for dynamic effects like depth, warping, and custom shading.
*
* It works by taking the outlines (contours) of each character in the
* provided text string and constructing a 3D shape from them.
*
* Once your 3D text is ready, you can rotate it in 3D space using <a href="#/p5/orbitControl">orbitControl()</a>
* — just click and drag with your mouse to see it from all angles!
*
* Use the extrude slider to give your letters depth: slide it up, and your
* flat text turns into a solid, multi-dimensional object.
*
* You can also choose from various fonts such as "Anton", "Montserrat", or "Source Serif",
* much like selecting fancy fonts in a word processor,
*
* The generated model (a Geometry object) can be manipulated further—rotated, scaled,
* or styled with shaders—to create engaging, interactive visual art.
*
* The `options` parameter is also optional. `font.textToModel()` expects an object
* with the following properties:
*
* `extrude` is the depth to extrude the text. It defaults to 0. A value of 0 produces
* flat text; higher values create thicker, 3D models.
*
* `sampleFactor` is a factor controlling the level of detail for the text contours.
* It defaults to 1. Higher values result in smoother curves.
*
* @param {String} str The text string to convert into a 3D model.
* @param {Number} x The x-coordinate for the starting position of the text.
* @param {Number} y The y-coordinate for the starting position of the text.
* @param {Number} width Maximum width of the text block (wraps text if exceeded).
* @param {Number} height Maximum height of the text block.
* @param {Object} [options] Configuration options for the 3D text:
* @param {Number} [options.extrude=0] The depth to extrude the text. A value of 0 produces
* flat text; higher values create thicker, 3D models.
* @param {Number} [options.sampleFactor=1] A factor controlling the level of detail for the text contours.
* Higher values result in smoother curves.
* @return {p5.Geometry} A geometry object representing the 3D model of the text.
*
* @example
* let font;
* let geom;
*
* async function setup() {
* createCanvas(200, 200, WEBGL);
* font = await loadFont('https://fonts.gstatic.com/s/anton/v25/1Ptgg87LROyAm0K08i4gS7lu.ttf');
*
* geom = font.textToModel("Hello", 50, 0, { sampleFactor: 2 });
* geom.clearColors();
* geom.normalize();
* }
*
* function draw() {
* background(255);
* orbitControl();
* fill("red");
* strokeWeight(4);
* scale(min(width, height) / 300);
* model(geom);
* describe('A red non-extruded "Hello" in Anton on white canvas, rotatable via mouse.');
* }
*
* @example
* let font;
* let geom;
*
* async function setup() {
* createCanvas(200, 200, WEBGL);
*
* // Alternative fonts:
* // Anton: 'https://fonts.gstatic.com/s/anton/v25/1Ptgg87LROyAm0K08i4gS7lu.ttf'
* // Montserrat: 'https://fonts.gstatic.com/s/montserrat/v29/JTUHjIg1_i6t8kCHKm4532VJOt5-QNFgpCtr6Ew-Y3tcoqK5.ttf'
* // Source Serif: 'https://fonts.gstatic.com/s/sourceserif4/v8/vEFy2_tTDB4M7-auWDN0ahZJW3IX2ih5nk3AucvUHf6OAVIJmeUDygwjihdqrhxXD-wGvjU.ttf'
*
* // Using Source Serif for this example:
* font = await loadFont('https://fonts.gstatic.com/s/sourceserif4/v8/vEFy2_tTDB4M7-auWDN0ahZJW3IX2ih5nk3AucvUHf6OAVIJmeUDygwjihdqrhxXD-wGvjU.ttf');
*
* geom = font.textToModel("Hello", 50, 0, { sampleFactor: 2, extrude: 5 });
* geom.clearColors();
* geom.normalize();
* }
*
* function draw() {
* background(255);
* orbitControl();
* fill("red");
* strokeWeight(4);
* scale(min(width, height) / 300);
* model(geom);
* describe('3D red extruded "Hello" in Source Serif on white, rotatable via mouse.');
* }
*
* @example
* let geom;
* let activeFont;
* let artShader;
* let lineShader;
*
* // Define parameters as simple variables
* let words = 'HELLO';
* let warp = 1;
* let extrude = 5;
* let palette = ["#ffe03d", "#fe4830", "#d33033", "#6d358a", "#1c509e", "#00953c"];
*
* async function setup() {
* createCanvas(200, 200, WEBGL);
*
* // Using Anton as the default font for this example:
*
* // Alternative fonts:
* // Anton: 'https://fonts.gstatic.com/s/anton/v25/1Ptgg87LROyAm0K08i4gS7lu.ttf'
* // Montserrat: 'https://fonts.gstatic.com/s/montserrat/v29/JTUHjIg1_i6t8kCHKm4532VJOt5-QNFgpCtr6Ew-Y3tcoqK5.ttf'
* // Source Serif: 'https://fonts.gstatic.com/s/sourceserif4/v8/vEFy2_tTDB4M7-auWDN0ahZJW3IX2ih5nk3AucvUHf6OAVIJmeUDygwjihdqrhxXD-wGvjU.ttf'
* activeFont = await loadFont('https://fonts.gstatic.com/s/anton/v25/1Ptgg87LROyAm0K08i4gS7lu.ttf');
*
* geom = activeFont.textToModel(words, 0, 50, { sampleFactor: 2, extrude });
* geom.clearColors();
* geom.normalize();
*
* artShader = baseMaterialShader().modify({
* uniforms: {
* 'float time': () => millis(),
* 'float warp': () => warp,
* 'float numColors': () => palette.length,
* 'vec3[6] colors': () => palette.flatMap((c) => [red(c)/255, green(c)/255, blue(c)/255]),
* },
* vertexDeclarations: 'out vec3 vPos;',
* fragmentDeclarations: 'in vec3 vPos;',
* 'Vertex getObjectInputs': `(Vertex inputs) {
* vPos = inputs.position;
* inputs.position.x += 5. * warp * sin(inputs.position.y * 0.1 + time * 0.001) / (1. + warp);
* inputs.position.y += 5. * warp * sin(inputs.position.x * 0.1 + time * 0.0009) / (1. + warp);
* return inputs;
* }`,
* 'vec4 getFinalColor': `(vec4 _c) {
* float x = vPos.x * 0.005;
* float a = floor(fract(x) * numColors);
* float b = a == numColors - 1. ? 0. : a + 1.;
* float t = fract(x * numColors);
* vec3 c = mix(colors[int(a)], colors[int(b)], t);
* return vec4(c, 1.);
* }`
* });
*
* lineShader = baseStrokeShader().modify({
* uniforms: {
* 'float time': () => millis(),
* 'float warp': () => warp,
* },
* 'StrokeVertex getObjectInputs': `(StrokeVertex inputs) {
* inputs.position.x += 5. * warp * sin(inputs.position.y * 0.1 + time * 0.001) / (1. + warp);
* inputs.position.y += 5. * warp * sin(inputs.position.x * 0.1 + time * 0.0009) / (1. + warp);
* return inputs;
* }`,
* });
* }
*
* function draw() {
* background(255);
* orbitControl();
* shader(artShader);
* strokeShader(lineShader);
* strokeWeight(4);
* scale(min(width, height) / 210);
* model(geom);
* describe('3D wavy with different color sets "Hello" in Anton on white canvas, rotatable via mouse.');
* }
*/
textToModel(str, x, y, width, height, options) {
({ width, height, options } = this._parseArgs(width, height, options));
const extrude = options?.extrude || 0;
let contours = this.textToContours(str, x, y, width, height, options);
if (!contours || contours.length === 0) {
return new p5.Geometry();
}
// Step 2: build base flat geometry - single shape
const geom = this._pInst.buildGeometry(() => {
const prevValidateFaces = this._pInst._renderer._validateFaces;
this._pInst._renderer._validateFaces = true;
this._pInst.beginShape();
for (const contour of contours) {
this._pInst.beginContour();
for (const pt of contour) {
this._pInst.vertex(pt.x, pt.y, 0);
}
this._pInst.endContour(this._pInst.CLOSE);
}
this._pInst.endShape(this._pInst.CLOSE);
this._pInst._renderer._validateFaces = prevValidateFaces;
});
if (extrude === 0) {
return geom;
}
// The tessellation process creates separate vertices for each triangle,
// even when they share the same position. We need to deduplicate them
// to find which faces are actually connected, so we can identify the
// outer edges for extrusion.
const vertexIndices = {};
const vertexId = v => `${v.x.toFixed(6)}-${v.y.toFixed(6)}-${v.z.toFixed(6)}`;
const newVertices = [];
const newVertexIndex = [];
for (const v of geom.vertices) {
const id = vertexId(v);
if (!(id in vertexIndices)) {
const index = newVertices.length;
vertexIndices[id] = index;
newVertices.push(v.copy());
}
newVertexIndex.push(vertexIndices[id]);
}
// Remap faces to use deduplicated vertices
const newFaces = geom.faces.map(f => f.map(i => newVertexIndex[i]));
//Find outer edges (edges that appear in only one face)
const seen = {};
for (const face of newFaces) {
for (let off = 0; off < face.length; off++) {
const a = face[off];
const b = face[(off + 1) % face.length];
const id = `${Math.min(a, b)}-${Math.max(a, b)}`;
if (!seen[id]) seen[id] = [];
seen[id].push([a, b]);
}
}
const validEdges = [];
for (const key in seen) {
if (seen[key].length === 1) {
validEdges.push(seen[key][0]);
}
}
// Step 5: Create extruded geometry
const extruded = this._pInst.buildGeometry(() => {});
const half = extrude * 0.5;
extruded.vertices = [];
extruded.faces = [];
extruded.edges = []; // INITIALIZE EDGES ARRAY
// Add side face vertices (separate for each edge for flat shading)
for (const [a, b] of validEdges) {
const vA = newVertices[a];
const vB = newVertices[b];
// Skip if vertices are too close (degenerate edge)
// We only need to check the perimeter edge length since the other edge
// is the extrude direction, which is always > 0 for extruded geometry
const edgeVector = new Vector(vB.x - vA.x, vB.y - vA.y, vB.z - vA.z);
const extrudeVector = new Vector(0, 0, extrude);
const crossProduct = Vector.cross(edgeVector, extrudeVector);
const dist = edgeVector.mag();
if (crossProduct.mag() < 0.0001 || dist < 0.0001) continue;
// Front face vertices
const frontA = extruded.vertices.length;
extruded.vertices.push(new Vector(vA.x, vA.y, vA.z + half));
const frontB = extruded.vertices.length;
extruded.vertices.push(new Vector(vB.x, vB.y, vB.z + half));
const backA = extruded.vertices.length;
extruded.vertices.push(new Vector(vA.x, vA.y, vA.z - half));
const backB = extruded.vertices.length;
extruded.vertices.push(new Vector(vB.x, vB.y, vB.z - half));
extruded.faces.push([frontA, backA, backB]);
extruded.faces.push([frontA, backB, frontB]);
extruded.edges.push([frontA, frontB]);
extruded.edges.push([backA, backB]);
extruded.edges.push([frontA, backA]);
extruded.edges.push([frontB, backB]);
}
// Add front face (with unshared vertices for flat shading)
const frontVertexOffset = extruded.vertices.length;
for (const v of newVertices) {
extruded.vertices.push(new Vector(v.x, v.y, v.z + half));
}
for (const face of newFaces) {
if (face.length < 3) continue;
const mappedFace = face.map(i => i + frontVertexOffset);
extruded.faces.push(mappedFace);
// ADD EDGES FOR FRONT FACE
for (let i = 0; i < mappedFace.length; i++) {
const nextIndex = (i + 1) % mappedFace.length;
extruded.edges.push([mappedFace[i], mappedFace[nextIndex]]);
}
}
// Add back face (reversed winding order)
const backVertexOffset = extruded.vertices.length;
for (const v of newVertices) {
extruded.vertices.push(new Vector(v.x, v.y, v.z - half));
}
for (const face of newFaces) {
if (face.length < 3) continue;
const mappedFace = [...face].reverse().map(i => i + backVertexOffset);
extruded.faces.push(mappedFace);
// ADD EDGES FOR BACK FACE
for (let i = 0; i < mappedFace.length; i++) {
const nextIndex = (i + 1) % mappedFace.length;
extruded.edges.push([mappedFace[i], mappedFace[nextIndex]]);
}
}
extruded.computeNormals();
return extruded;
}
variations() {
let vars = {};
if (this.data) {
let axes = this.face?.axes;
if (axes) {
axes.forEach(ax => {
vars[ax.tag] = ax.value;
});
}
}
fontFaceVariations.forEach(v => {
let val = this.face[v];
if (val !== 'normal') {
vars[v] = vars[v] || val;
}
});
return vars;
}
metadata() {
let meta = this.data?.name || {};
for (let p in this.face) {
if (!/^load/.test(p)) {
meta[p] = meta[p] || this.face[p];
}
}
return meta;
}
static async list(log = false) { // tmp
if (log) {
console.log('There are', document.fonts.size, 'font-faces\n');
let loaded = 0;
for (let fontFace of document.fonts.values()) {
console.log('FontFace: {');
for (let property in fontFace) {
console.log(' ' + property + ': ' + fontFace[property]);
}
console.log('}\n');
if (fontFace.status === 'loaded') {
loaded++;
}
}
console.log(loaded + ' loaded');
}
return await Array.from(document.fonts);
}
/////////////////////////////// HELPERS ////////////////////////////////
/*
Returns an array of line objects, each containing { text, x, y, glyphs: [ {g, path} ] }
*/
_lineateAndPathify(str, x, y, width, height, options = {}) {
let renderer = options?.graphics?._renderer || this._pInst._renderer;
renderer.push();
renderer.textFont(this);
// lineate and compute bounds for the text
let { lines, bounds } = renderer._computeBounds
(textCoreConstants._FONT_BOUNDS, str, x, y, width, height,
{ ignoreRectMode: true, ...options });
// compute positions for each of the lines
lines = this._position(renderer, lines, bounds, width, height);
// convert lines to paths
let uPE = this.data?.head?.unitsPerEm || 1000;
let scale = renderer.states.textSize / uPE;
const axs = this._currentAxes(renderer);
let pathsForLine = lines.map(l => this._lineToGlyphs(l, { scale, axs }));
renderer.pop();
return pathsForLine;
}
_currentAxes(renderer) {
let axs;
if ((this.data?.fvar?.length ?? 0) > 0) {
const fontAxes = this.data.fvar[0];
axs = fontAxes.map(([tag, minVal, defaultVal, maxVal, flags, name]) => {
if (!renderer) return defaultVal;
if (tag === 'wght') {
return renderer.states.fontWeight;
} else if (tag === 'wdth') {
// TODO: map from keywords (normal, ultra-condensed, etc) to values
// return renderer.states.fontStretch
return 100;
} else if (renderer.textCanvas().style.fontVariationSettings) {
const match = new RegExp(`\\b${tag}\s+(\d+)`)
.exec(renderer.textCanvas().style.fontVariationSettings);
if (match) {
return parseInt(match[1]);
} else {
return defaultVal;
}
} else {
return defaultVal;
}
});
}
return axs;
}
_textToPathPoints(str, x, y, width, height, options) {
({ width, height, options } = this._parseArgs(width, height, options));
// lineate and get the points for each line
let cmds = this.textToPaths(str, x, y, width, height, options);
// divide line-segments with intermediate points
const subdivide = (pts, pt1, pt2, md) => {
if (fn.dist(pt1.x, pt1.y, pt2.x, pt2.y) > md) {
let middle = { x: (pt1.x + pt2.x) / 2, y: (pt1.y + pt2.y) / 2 };
pts.push(middle);
subdivide(pts, pt1, middle, md);
subdivide(pts, middle, pt2, md);
}
};
// a point for each path-command plus line subdivisions
let pts = [];
let { textSize } = this._pInst._renderer.states;
let maxDist = (textSize / this.data.head.unitsPerEm) * 500;
for (let i = 0; i < cmds.length; i++) {
let { type, data: d } = cmds[i];
if (type !== 'Z') {
let pt = { x: d[d.length - 2], y: d[d.length - 1] };
if (type === 'L' && pts.length && !options?.nodivide > 0) {
subdivide(pts, pts[pts.length - 1], pt, maxDist);
}
pts.push(pt);
}
}
return pts;
}
_parseArgs(width, height, options = {}) {
if (typeof width === 'object') {
options = width;
width = height = undefined;
}
else if (typeof height === 'object') {
options = height;
height = undefined;
}
return { width, height, options };
}
_position(renderer, lines, bounds, width, height) {
let { textAlign, textLeading, textSize } = renderer.states;
let metrics = this._measureTextDefault(renderer, 'X');
let ascent = metrics.fontBoundingBoxAscent;
let coordify = (text, i) => {
let x = bounds.x;
let y = bounds.y + (i * textLeading) + ascent;
let lineWidth = renderer._fontWidthSingle(text);
if (textAlign === constants.CENTER) {
x += (bounds.w - lineWidth) / 2;
}
else if (textAlign === constants.RIGHT) {
x += (bounds.w - lineWidth);
}
if (typeof width !== 'undefined') {
switch (renderer.states.rectMode) {
case constants.CENTER:
x -= width / 2;
y -= height / 2;
break;
case constants.RADIUS:
x -= width;
y -= height;
break;
}
}
return { text, x, y };
};
return lines.map(coordify);
}
_lineToGlyphs(line, { scale = 1, axs } = {}) {
if (!this.data) {
throw Error('No font data available for "' + this.name
+ '"\nTry downloading a local copy of the font file');
}
let glyphShapes = Typr.U.shape(this.data, line.text, { axs });
line.glyphShapes = glyphShapes;
line.glyphs = this._shapeToPaths(glyphShapes, line, { scale, axs });
return line;
}
_positionGlyphs(text, options) {
let renderer = options?.graphics?._renderer || this._pInst._renderer;
const axs = this._currentAxes(renderer);
const glyphShapes = Typr.U.shape(this.data, text, { axs });
const positionedGlyphs = [];
let x = 0;
for (const glyph of glyphShapes) {
positionedGlyphs.push({ x, index: glyph.g, shape: glyph });
x += glyph.ax;
}
return positionedGlyphs;
}
_singleShapeToPath(shape, {
scale = 1,
x = 0,
y = 0,
lineX = 0,
lineY = 0,
axs
} = {}) {
let font = this.data;
let crdIdx = 0;
let { g, ax, ay, dx, dy } = shape;
let { crds, cmds } = Typr.U.glyphToPath(font, g, true, axs);
// can get simple points for each glyph here, but we don't need them ?
let glyph = { /*g: line.text[i], points: [],*/ path: { commands: [] } };
for (let j = 0; j < cmds.length; j++) {
let type = cmds[j], command = [type];
if (type in pathArgCounts) {
let argCount = pathArgCounts[type];
for (let k = 0; k < argCount; k += 2) {
let gx = crds[k + crdIdx] + x + dx;
let gy = crds[k + crdIdx + 1] + y + dy;
let fx = lineX + gx * scale;
let fy = lineY + gy * -scale;
command.push(fx);
command.push(fy);
/*if (k === argCount - 2) {
glyph.points.push({ x: fx, y: fy });
}*/
}
crdIdx += argCount;
}
glyph.path.commands.push(command);
}
return { glyph, ax, ay };
}
_shapeToPaths(glyphs, line, { scale = 1, axs } = {}) {
let x = 0, y = 0, paths = [];
if (glyphs.length !== line.text.length) {
throw Error('Invalid shape data');
}
// iterate over the glyphs, converting each to a glyph object
// with a path property containing an array of commands
for (let i = 0; i < glyphs.length; i++) {
const { glyph, ax, ay } = this._singleShapeToPath(glyphs[i], {
scale,
x,
y,
lineX: line.x,
lineY: line.y,
axs
});
paths.push(glyph);
x += ax; y += ay;
}
return paths;
}
_measureTextDefault(renderer, str) {
let { textAlign, textBaseline } = renderer.states;
let ctx = renderer.textDrawingContext();
ctx.textAlign = 'left';
ctx.textBaseline = 'alphabetic';
let metrics = ctx.measureText(str);
ctx.textAlign = textAlign;
ctx.textBaseline = textBaseline;
return metrics;
}
drawPaths(ctx, commands, opts) { // for debugging
ctx.strokeStyle = opts?.stroke || ctx.strokeStyle;
ctx.fillStyle = opts?.fill || ctx.fillStyle;
ctx.beginPath();
commands.forEach(([type, ...data]) => {
if (type === 'M') {
ctx.moveTo(...data);
} else if (type === 'L') {
ctx.lineTo(...data);
} else if (type === 'C') {
ctx.bezierCurveTo(...data);
} else if (type === 'Q') {
ctx.quadraticCurveTo(...data);
} else if (type === 'Z') {
ctx.closePath();
}
});
if (opts?.fill) ctx.fill();
if (opts?.stroke) ctx.stroke();
}
_pathsToCommands(paths, scale) {
let commands = [];
for (let i = 0; i < paths.length; i++) {
let pathData = paths[i];
let { x, y, path } = pathData;
let { crds, cmds } = path;
// iterate over the path, storing each non-control point
for (let c = 0, j = 0; j < cmds.length; j++) {