rapier-math 2.1.0 → 2.3.0

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.
@@ -19,9 +19,6 @@ import unicodedata
19
19
  import urllib.request
20
20
  import zlib
21
21
 
22
- from fontTools.misc.bezierTools import calcCubicParameters, solveQuadratic
23
- from fontTools.pens.basePen import BasePen
24
- from fontTools.pens.boundsPen import BoundsPen
25
22
  from fontTools.pens.svgPathPen import SVGPathPen
26
23
  from fontTools.ttLib import TTFont
27
24
 
@@ -110,15 +107,10 @@ def extract(font: TTFont):
110
107
  glyph_set = font.getGlyphSet()
111
108
  glyphs = []
112
109
  for name in names:
113
- glyph = glyph_set[name]
114
- bounds = BoundsPen(glyph_set)
115
- glyph.draw(bounds)
116
- rect = bounds.bounds or (0, 0, 0, 0)
117
- bounds_values = [math.floor(rect[0]), math.floor(rect[1]), math.ceil(rect[2]), math.ceil(rect[3])]
118
110
  path = SVGPathPen(glyph_set, ntos=number)
119
- glyph.draw(path)
111
+ glyph_set[name].draw(path)
120
112
  advance = font["hmtx"].metrics[name][0]
121
- glyphs.append([advance, *bounds_values, italic.get(name, 0), accent.get(name, advance / 2), path.getCommands()])
113
+ glyphs.append([advance, italic.get(name, 0), accent.get(name, advance / 2), path.getCommands()])
122
114
  data = {
123
115
  "units": font["head"].unitsPerEm,
124
116
  "xHeight": font["OS/2"].sxHeight,
@@ -134,7 +126,6 @@ def extract(font: TTFont):
134
126
  "dotless": {ids[name]: ids[alternates[0]] for name, alternates in dotless.items() if name in ids},
135
127
  "extendedShapes": {ids[name]: 1 for name in (info.ExtendedShapeCoverage.glyphs if info.ExtendedShapeCoverage else []) if name in ids},
136
128
  "edgeStep": EDGE_STEP,
137
- "edgeProfiles": {},
138
129
  }
139
130
  for axis, key in (("Vert", "vertical"), ("Horiz", "horizontal")):
140
131
  coverage = getattr(variants, axis + "GlyphCoverage")
@@ -159,161 +150,92 @@ def extract(font: TTFont):
159
150
  corner = getattr(record, key)
160
151
  corners.append([list(map(scalar, corner.CorrectionHeight)), list(map(scalar, corner.KernValue))] if corner else None)
161
152
  data["kern"][ids[name]] = corners
153
+ # Script kerning reads a contour profile for Latin letters and digits, the italic and script alphabets
154
+ # (with U+210E, the italic h), and their optical and dotless forms. The decoder derives each profile.
162
155
  profiled = {
163
156
  name for cp, name in cmap.items()
164
- if (cp < 128 and chr(cp).isalnum())
157
+ if (cp < 128 and chr(cp).isalnum()) or cp == 0x210E
165
158
  or any(style in unicodedata.name(chr(cp), "") for style in ("ITALIC", "SCRIPT"))
166
159
  }
167
160
  for name in list(profiled):
168
161
  profiled.update(scripts.get(name, ()))
169
162
  profiled.update(dotless.get(name, ()))
170
- for name in sorted(profiled, key=font.getGlyphID):
171
- profile = edge_profile(glyph_set, name)
172
- if profile:
173
- data["edgeProfiles"][ids[name]] = profile
163
+ data["profiled"] = sorted(ids[name] for name in profiled)
174
164
  return data
175
165
 
176
166
 
177
- class OutlinePen(BasePen):
178
- def __init__(self, glyph_set):
179
- super().__init__(glyph_set)
180
- self.segments = []
181
- self.start = None
182
-
183
- def _moveTo(self, point):
184
- self.start = point
185
-
186
- def _lineTo(self, point):
187
- self.segments.append((self._getCurrentPoint(), point))
188
-
189
- def _curveToOne(self, first, second, end):
190
- self.segments.append((self._getCurrentPoint(), first, second, end))
191
-
192
- def _closePath(self):
193
- if self._getCurrentPoint() != self.start:
194
- self.segments.append((self._getCurrentPoint(), self.start))
195
-
196
- def _endPath(self):
197
- pass
198
-
199
-
200
- def edge_profile(glyph_set, name):
201
- """Bound the original outline inside each horizontal strip."""
202
- pen = OutlinePen(glyph_set)
203
- glyph_set[name].draw(pen)
204
- bounds = BoundsPen(glyph_set)
205
- glyph_set[name].draw(bounds)
206
- if not bounds.bounds:
207
- return None
208
- first = math.floor(bounds.bounds[1] / EDGE_STEP) * EDGE_STEP
209
- count = max(1, math.ceil((bounds.bounds[3] - first) / EDGE_STEP))
210
- strips = [[] for _ in range(count)]
211
- for segment in pen.segments:
212
- if len(segment) == 2:
213
- (x, y), (end_x, end_y) = segment
214
- for index, strip in enumerate(strips):
215
- lower, upper = first + index * EDGE_STEP, first + (index + 1) * EDGE_STEP
216
- values = [0, 1]
217
- if end_y != y:
218
- values.extend(((lower - y) / (end_y - y), (upper - y) / (end_y - y)))
219
- strip.extend(x + t * (end_x - x) for t in values if 0 <= t <= 1 and lower - 1e-7 <= y + t * (end_y - y) <= upper + 1e-7)
220
- continue
221
- a, b, c, d = calcCubicParameters(*segment)
222
- extrema = [0, 1, *solveQuadratic(3 * a[0], 2 * b[0], c[0])]
223
- critical = sorted([0, 1, *(t for t in solveQuadratic(3 * a[1], 2 * b[1], c[1]) if 0 < t < 1)])
224
- intersections = {}
225
-
226
- def vertical(t):
227
- return ((a[1] * t + b[1]) * t + c[1]) * t + d[1]
228
-
229
- def crossing(height):
230
- if height not in intersections:
231
- roots = []
232
- for low, high in zip(critical, critical[1:]):
233
- y_low, y_high = vertical(low), vertical(high)
234
- if not min(y_low, y_high) <= height <= max(y_low, y_high):
235
- continue
236
- for _ in range(45):
237
- middle = (low + high) / 2
238
- if (vertical(middle) < height) == (y_low < y_high):
239
- low = middle
240
- else:
241
- high = middle
242
- roots.append((low + high) / 2)
243
- intersections[height] = roots
244
- return intersections[height]
245
-
246
- y_min, y_max = min(point[1] for point in segment), max(point[1] for point in segment)
247
- for index, strip in enumerate(strips):
248
- lower, upper = first + index * EDGE_STEP, first + (index + 1) * EDGE_STEP
249
- if lower > y_max or upper < y_min:
250
- continue
251
- values = [*extrema, *crossing(lower), *crossing(upper)]
252
- for t in values:
253
- if 0 <= t <= 1:
254
- y = ((a[1] * t + b[1]) * t + c[1]) * t + d[1]
255
- if lower - 1e-7 <= y <= upper + 1e-7:
256
- strip.append(((a[0] * t + b[0]) * t + c[0]) * t + d[0])
257
- return [first, *([math.floor(min(strip) - 1e-7), math.ceil(max(strip) + 1e-7)] if strip else None for strip in strips)]
258
-
259
-
260
167
  PAGE_BYTES = 16384
261
168
  PAGE_STRIDE = 32768
262
169
  PARENT_DEPTH = 4
263
170
  SCALAR_MAPS = ("chars", "dotless", "flatAccents", "extendedShapes")
264
171
 
265
172
 
173
+ def unsigned(value, target):
174
+ if value < 0 or value > 2**53 - 1 or value != int(value):
175
+ raise ValueError("Font integer exceeds exact JavaScript arithmetic")
176
+ value = int(value)
177
+ while value >= 128:
178
+ target.append((value & 127) | 128)
179
+ value >>= 7
180
+ target.append(value)
181
+
182
+
183
+ def signed(value, target):
184
+ if value != int(value):
185
+ raise ValueError("Font value is not an integer")
186
+ value = int(value)
187
+ value = value * 2 if value >= 0 else -value * 2 - 1
188
+ if value > 2**53 - 1:
189
+ raise ValueError("Font integer exceeds exact JavaScript arithmetic")
190
+ if value < 240:
191
+ target.append(value)
192
+ elif value < 4080:
193
+ value -= 240
194
+ target.extend((240 + (value >> 8), value & 255))
195
+ else:
196
+ target.append(255)
197
+ unsigned(value - 4080, target)
198
+
199
+
200
+ def text(data):
201
+ """Raw DEFLATE in base64."""
202
+ return base64.b64encode(zlib.compress(data, level=9, wbits=-15)).decode("ascii")
203
+
204
+
266
205
  def pack_font(data):
267
206
  """Share translated contours and retain independently inflatable record pages."""
268
- glyphs, profiles = data["glyphs"], data["edgeProfiles"]
207
+ glyphs = data["glyphs"]
269
208
  commands = "MLHVCZ"
270
209
  lengths = (2, 2, 1, 1, 6, 0)
271
-
272
- def unsigned(value, target):
273
- if value < 0 or value > 2**53 - 1:
274
- raise ValueError("Font integer exceeds exact JavaScript arithmetic")
275
- while value >= 128:
276
- target.append((value & 127) | 128)
277
- value >>= 7
278
- target.append(value)
279
-
280
- def signed(value, target):
281
- value = value * 2 if value >= 0 else -value * 2 - 1
282
- if value > 2**53 - 1:
283
- raise ValueError("Font integer exceeds exact JavaScript arithmetic")
284
- if value < 240:
285
- target.append(value)
286
- elif value < 4080:
287
- value -= 240
288
- target.extend((240 + (value >> 8), value & 255))
289
- else:
290
- target.append(255)
291
- unsigned(value - 4080, target)
292
-
293
- paths = [re.findall(r"[MLHVCZ]|-?\d+(?:\.\d+)?", glyph[7]) for glyph in glyphs]
210
+ paths = [re.findall(r"[MLHVCZ]|-?\d+(?:\.\d+)?", glyph[3]) for glyph in glyphs]
294
211
  unit = 1
295
212
  for glyph, tokens in zip(glyphs, paths):
296
- if "".join(tokens) != re.sub(r"[ ,]", "", glyph[7]):
213
+ if "".join(tokens) != re.sub(r"[ ,]", "", glyph[3]):
297
214
  raise ValueError("Font path has an unsupported coordinate or command")
298
215
  for token in tokens:
299
216
  if "." in token:
300
217
  unit = math.lcm(unit, Fraction(token).denominator)
301
- metric_unit = math.lcm(2, *(Fraction(value).denominator for glyph in glyphs for value in glyph[:7]))
302
- metrics = [[int(value * metric_unit) for value in glyph[:7]] for glyph in glyphs]
218
+ # Derived bounds and profiles divide by the unit; a power of two keeps every coordinate exact.
219
+ if unit & (unit - 1):
220
+ raise ValueError("Font coordinates need a power-of-two unit")
221
+ metric_unit = math.lcm(2, *(Fraction(value).denominator for glyph in glyphs for value in glyph[:3]))
222
+ metrics = [[int(value * metric_unit) for value in glyph[:3]] for glyph in glyphs]
303
223
  for values in metrics:
304
- values[3] -= values[0] - values[1]
305
- values[6] -= values[0] // 2
306
- metric_bases = [sorted(values[column] for values in metrics)[len(metrics) // 2] for column in range(7)]
224
+ values[2] -= values[0] // 2
225
+ metric_bases = [sorted(values[column] for values in metrics)[len(metrics) // 2] for column in range(3)]
307
226
  contours, contour_ids, references = [], {}, []
308
227
  for tokens in paths:
309
228
  cursor, previous = 0, None
310
229
  structure, coordinates, refs = [], [], []
311
230
  first_x = first_y = x = y = 0
231
+ closing = None
312
232
 
313
233
  def keep_contour():
314
234
  if not structure:
315
235
  return
316
- key = bytes(structure), tuple(coordinates)
236
+ # A closing curve that ends at the start stores no end point; the decoder returns it to the start.
237
+ closes = structure[-2:] == [4, 5] and closing == (first_x, first_y)
238
+ key = bytes(structure), tuple(coordinates[:-2] if closes else coordinates), closes
317
239
  if key not in contour_ids:
318
240
  contour_ids[key] = len(contours)
319
241
  contours.append(key)
@@ -350,22 +272,22 @@ def pack_font(data):
350
272
  coordinates.append(value - x)
351
273
  x = value
352
274
  if command == 5:
353
- x, y = first_x, first_y
275
+ closing, x, y = (x, y), first_x, first_y
354
276
  previous = command
355
277
  keep_contour()
356
278
  references.append(refs)
357
279
 
358
280
  contour_records, shapes, depths = [], {}, []
359
- for contour_id, (structure, coordinates) in enumerate(contours):
281
+ for contour_id, (structure, coordinates, closes) in enumerate(contours):
360
282
  record = bytearray()
361
- unsigned(len(structure) * 2, record)
283
+ unsigned((len(structure) * 2 + closes) * 2, record)
362
284
  record.extend(structure)
363
285
  for value in coordinates:
364
286
  signed(value, record)
365
287
  # Small residuals compress better even when their first encoding costs another byte.
366
288
  best = (len(record) + sum(abs(value).bit_length() for value in coordinates), len(record))
367
289
  parent_depth = -1
368
- for parent, previous_coordinates in shapes.setdefault(structure, []):
290
+ for parent, previous_coordinates in shapes.setdefault((structure, closes), []):
369
291
  if depths[parent] >= PARENT_DEPTH:
370
292
  continue
371
293
  shared = bytearray()
@@ -378,60 +300,14 @@ def pack_font(data):
378
300
  best = score
379
301
  record, parent_depth = shared, depths[parent]
380
302
  depths.append(parent_depth + 1)
381
- shapes[structure].append((contour_id, coordinates))
303
+ shapes[(structure, closes)].append((contour_id, coordinates))
382
304
  contour_records.append(record)
383
305
 
384
- profile_records, profile_ids, profile_shapes, profile_depths = [], {}, {}, []
385
- profile_values = {}
386
- for glyph_id, profile in sorted(profiles.items()):
387
- key = profile[0], tuple(None if strip is None else tuple(strip) for strip in profile[1:])
388
- if key in profile_values:
389
- profile_ids[glyph_id] = profile_values[key]
390
- continue
391
- profile_id = len(profile_records)
392
- profile_ids[glyph_id] = profile_id
393
- profile_values[key] = profile_id
394
- record = bytearray()
395
- unsigned((len(profile) - 1) * 2, record)
396
- signed(profile[0], record)
397
- left = right = 0
398
- for strip in profile[1:]:
399
- if strip is None:
400
- unsigned(0, record)
401
- continue
402
- delta = strip[0] - left
403
- unsigned((delta * 2 if delta >= 0 else -delta * 2 - 1) + 1, record)
404
- signed(strip[1] - right, record)
405
- left, right = strip
406
- shape = profile[0], tuple(strip is not None for strip in profile[1:])
407
- parent_depth = -1
408
- for parent_id, parent in profile_shapes.setdefault(shape, []):
409
- if profile_depths[parent_id] >= PARENT_DEPTH:
410
- continue
411
- shared = bytearray()
412
- unsigned(parent_id * 2 + 1, shared)
413
- left = right = 0
414
- for strip, previous_strip in zip(profile[1:], parent[1:]):
415
- if strip is None:
416
- continue
417
- next_left, next_right = strip[0] - previous_strip[0], strip[1] - previous_strip[1]
418
- signed(next_left - left, shared)
419
- signed(next_right - right, shared)
420
- left, right = next_left, next_right
421
- if len(shared) >= len(record):
422
- break
423
- if len(shared) < len(record):
424
- record, parent_depth = shared, profile_depths[parent_id]
425
- profile_depths.append(parent_depth + 1)
426
- profile_shapes[shape].append((profile_id, profile))
427
- profile_records.append(record)
428
-
429
306
  glyph_records = []
430
- for glyph_id, (values, refs) in enumerate(zip(metrics, references)):
307
+ for values, refs in zip(metrics, references):
431
308
  record = bytearray()
432
309
  for value, base in zip(values, metric_bases):
433
310
  signed(value - base, record)
434
- unsigned(profile_ids.get(glyph_id, -1) + 1, record)
435
311
  unsigned(len(refs), record)
436
312
  for contour_id, x, y in refs:
437
313
  unsigned(contour_id, record)
@@ -460,7 +336,31 @@ def pack_font(data):
460
336
  for index, value in enumerate(values):
461
337
  signed(value - previous_values[index], indices)
462
338
  previous_values[index] = value
463
- for records in (glyph_records, contour_records, profile_records):
339
+ unsigned(len(data["profiled"]), indices)
340
+ previous_key = -1
341
+ for key in data["profiled"]:
342
+ unsigned(key - previous_key - 1, indices)
343
+ previous_key = key
344
+ for name in ("vertical", "horizontal"):
345
+ unsigned(len(data[name]), indices)
346
+ previous_key = 0
347
+ for key, record in sorted(data[name].items()):
348
+ unsigned(key - previous_key, indices)
349
+ previous_key = key
350
+ unsigned(len(record["variants"]), indices)
351
+ for glyph, advance in record["variants"]:
352
+ signed(glyph - key, indices)
353
+ unsigned(advance, indices)
354
+ assembly = record.get("assembly")
355
+ unsigned(len(assembly["parts"]) + 1 if assembly else 0, indices)
356
+ if assembly:
357
+ signed(assembly["italic"], indices)
358
+ for glyph, start, end, full, flags in assembly["parts"]:
359
+ signed(glyph - key, indices)
360
+ unsigned(start, indices)
361
+ unsigned(end, indices)
362
+ unsigned(full * 2 + flags, indices)
363
+ for records in (glyph_records, contour_records):
464
364
  page, offsets = bytearray(), []
465
365
  for record in records:
466
366
  if len(record) > PAGE_BYTES:
@@ -478,12 +378,9 @@ def pack_font(data):
478
378
  unsigned(offset - previous, indices)
479
379
  previous = offset
480
380
 
481
- def compressed(data):
482
- return base64.b64encode(zlib.compress(data, level=9, wbits=-15)).decode("ascii")
483
-
484
- packed = [(len(page), compressed(page)) for page in pages]
485
- return packed, compressed(indices), len(indices), {
486
- "contours": len(contours), "contourReferences": sum(map(len, references)), "profileRecords": len(profile_records),
381
+ packed = [(len(page), text(page)) for page in pages]
382
+ return packed, text(indices), len(indices), {
383
+ "contours": len(contours), "contourReferences": sum(map(len, references)), "profiledGlyphs": len(data["profiled"]),
487
384
  "pages": len(pages), "pageBytes": PAGE_BYTES, "indexBytes": len(indices),
488
385
  "recordBytes": sum(map(len, pages)), "maxParentDepth": PARENT_DEPTH,
489
386
  }
@@ -526,59 +423,91 @@ if(written!==bytes.length||position-Math.floor(available/8)!==source.length)inva
526
423
  const unsigned=r=>{let value=0,shift=0,byte;do{if(r[1]>=r[2]||shift>49)invalid();byte=r[0][r[1]++];value+=(byte&127)*2**shift;shift+=7;}while(byte&128);if(!Number.isSafeInteger(value))invalid();return value;};
527
424
  const signed=r=>{if(r[1]>=r[2])invalid();let value=r[0][r[1]++];if(value>=240){if(value===255){value=4080+unsigned(r);if(!Number.isSafeInteger(value))invalid();}else{if(r[1]>=r[2])invalid();value=240+(value-240)*256+r[0][r[1]++];}}return value%2?-(value+1)/2:value/2;};
528
425
  const complete=r=>{if(r[1]!==r[2])invalid();};
529
- const [unit,metricUnit,metricBases,glyphs,contours,profiles]=(()=>{
530
- const bytes=inflate(__INDEX__,__SIZE__),r=[bytes,0,bytes.length],unit=unsigned(r),metricUnit=unsigned(r);if(!unit||!metricUnit)invalid();const metricBases=Array.from({length:7},()=>signed(r));
426
+ const [unit,metricUnit,metricBases,profiled,glyphs,contours]=(()=>{
427
+ const bytes=inflate(__INDEX__,__SIZE__),r=[bytes,0,bytes.length],unit=unsigned(r),metricUnit=unsigned(r);if(!unit||!metricUnit)invalid();const metricBases=Array.from({length:3},()=>signed(r));
531
428
  for(const name of __MAP_FIELDS__){const count=unsigned(r),map=MATH_FONT[name]={};if(count>bytes.length)invalid();let key=0,value=0;
532
429
  for(let i=0;i<count;i++){key+=unsigned(r);value+=signed(r);map[key]=value;}}
533
430
  const scripts=MATH_FONT.scriptAlternates={},scriptCount=unsigned(r),previous=[0,0];let key=0;if(scriptCount>bytes.length)invalid();
534
431
  for(let i=0;i<scriptCount;i++){key+=unsigned(r);const count=unsigned(r);if(count<1||count>2)invalid();const values=[];for(let j=0;j<count;j++){previous[j]+=signed(r);values.push(previous[j]);}scripts[key]=values;}
535
- const tables=Array.from({length:3},()=>{const count=unsigned(r);if(count<1||count>bytes.length)invalid();const offsets=new Uint32Array(count);let previous=0;
536
- for(let i=0;i<count;i++){previous+=unsigned(r);if(previous>=pages.length*32768)invalid();offsets[i]=previous;}return offsets;});complete(r);return [unit,metricUnit,metricBases,...tables];
432
+ const profiled=new Set,profileCount=unsigned(r);key=-1;if(profileCount>bytes.length)invalid();for(let i=0;i<profileCount;i++)profiled.add(key+=unsigned(r)+1);
433
+ for(const name of ['vertical','horizontal']){const map=MATH_FONT[name]={},count=unsigned(r);key=0;if(count>bytes.length)invalid();
434
+ for(let i=0;i<count;i++){key+=unsigned(r);const variants=Array.from({length:unsigned(r)},()=>[key+signed(r),unsigned(r)]),parts=unsigned(r);if(variants.length>bytes.length||parts>bytes.length)invalid();
435
+ const record=map[key]={variants};if(parts)record.assembly={italic:signed(r),parts:Array.from({length:parts-1},()=>{const part=[key+signed(r),unsigned(r),unsigned(r)],full=unsigned(r);return [...part,Math.floor(full/2),full%2];})};}}
436
+ const tables=Array.from({length:2},()=>{const count=unsigned(r);if(count<1||count>bytes.length)invalid();const offsets=new Uint32Array(count);let previous=0;
437
+ for(let i=0;i<count;i++){previous+=unsigned(r);if(previous>=pages.length*32768)invalid();offsets[i]=previous;}return offsets;});complete(r);return [unit,metricUnit,metricBases,profiled,...tables];
537
438
  })();
538
- const pageCache=new Map(),glyphCache=new Map(),profileCache=new Map();
539
- const remember=(cache,id,value,limit)=>{if(cache.size>=limit)cache.delete(cache.keys().next().value);cache.set(id,value);return value;};
540
- const touch=(cache,id)=>{const value=cache.get(id);if(value!==undefined){cache.delete(id);cache.set(id,value);}return value;};
439
+ // Each page, glyph and profile decodes once and stays: the font itself bounds every cache.
440
+ const pageCache=[],glyphCache=new Map(),profileCache=new Map();
541
441
  const record=(offsets,id)=>{
542
442
  if(!Number.isInteger(id)||id<0||id+1>=offsets.length)return;
543
- const offset=offsets[id],page=offset>>>15,next=offsets[id+1];let bytes=touch(pageCache,page);
544
- if(!bytes){const source=pages[page];if(!source||source[0]>16384)invalid();bytes=remember(pageCache,page,inflate(source[1],source[0]),8);}
443
+ const offset=offsets[id],page=offset>>>15,next=offsets[id+1];let bytes=pageCache[page];
444
+ if(!bytes){const source=pages[page];if(!source||source[0]>16384)invalid();bytes=pageCache[page]=inflate(source[1],source[0]);}
545
445
  const begin=offset&32767,end=next>>>15===page?next&32767:bytes.length;if(begin>=end||end>bytes.length)invalid();return [bytes,begin,end];
546
446
  };
547
447
  const commandLengths=[2,2,1,1,6,0],commandNames='MLHVCZ';
548
448
  const contour=(id,local,depth=0)=>{
549
- if(local.has(id))return local.get(id);if(depth>4)invalid();const r=record(contours,id);if(!r)invalid();const header=unsigned(r);let commands,coordinates;
550
- if(header%2){const parentId=Math.floor(header/2);if(parentId>=id)invalid();const parent=contour(parentId,local,depth+1);commands=parent[0];coordinates=new Float64Array(parent[1].length);
449
+ if(local.has(id))return local.get(id);if(depth>4)invalid();const r=record(contours,id);if(!r)invalid();const header=unsigned(r);let commands,coordinates,closes;
450
+ if(header%2){const parentId=Math.floor(header/2);if(parentId>=id)invalid();const parent=contour(parentId,local,depth+1);[commands,,closes]=parent;coordinates=new Float64Array(parent[1].length);
551
451
  for(let i=0;i<coordinates.length;i++)coordinates[i]=parent[1][i]+signed(r);}
552
- else{const count=header/2;if(r[1]+count>r[2])invalid();commands=r[0].subarray(r[1],r[1]+count);r[1]+=count;let values=0;
553
- for(const command of commands){if(command<1||command>5)invalid();values+=commandLengths[command];}if(values>r[2]-r[1])invalid();coordinates=new Float64Array(values);
452
+ else{const count=Math.floor(header/4);closes=header/2%2;if(r[1]+count>r[2])invalid();commands=r[0].subarray(r[1],r[1]+count);r[1]+=count;let values=0;
453
+ for(const command of commands){if(command<1||command>5)invalid();values+=commandLengths[command];}values-=2*closes;if(values<0||values>r[2]-r[1]||closes&&(commands[count-2]!==4||commands[count-1]!==5))invalid();coordinates=new Float64Array(values);
554
454
  for(let i=0;i<values;i++)coordinates[i]=signed(r);}
555
- complete(r);const value=[commands,coordinates];local.set(id,value);return value;
455
+ complete(r);const value=[commands,coordinates,closes];local.set(id,value);return value;
556
456
  };
557
- const glyphRecord=id=>{
558
- let cached=touch(glyphCache,id);if(cached)return cached;const r=record(glyphs,id);if(!r)return;
559
- const glyph=[];for(let i=0;i<7;i++)glyph.push(signed(r)+metricBases[i]);glyph[3]+=glyph[0]-glyph[1];glyph[6]+=glyph[0]/2;for(let i=0;i<7;i++)glyph[i]/=metricUnit;const profile=unsigned(r)-1,count=unsigned(r),local=new Map();let path='';
560
- if(profile>=profiles.length-1||count>r[2]-r[1])invalid();
561
- for(let part=0;part<count;part++){const id=unsigned(r),firstX=signed(r),firstY=signed(r),[commands,coordinates]=contour(id,local);let x=firstX,y=firstY,cursor=0;
562
- path+='M'+x/unit+' '+y/unit;
563
- for(const command of commands){path+=commandNames[command];for(let index=0;index<commandLengths[command];index++){if(index)path+=' ';
564
- if(command===3||(command!==2&&command!==3&&index%2)){y+=coordinates[cursor++];path+=y/unit;}else{x+=coordinates[cursor++];path+=x/unit;}}
565
- if(command===5){x=firstX;y=firstY;}}
566
- }complete(r);glyph.push(path);cached={glyph,profile};return remember(glyphCache,id,cached,256);
457
+ // Bounds and contour profiles derive from the outline with fontTools' BoundsPen and the generator's strip
458
+ // profile, operation for operation, so each value is the one the generator would have stored.
459
+ const quadratic=(a,b,c)=>{if(Math.abs(a)<1e-10)return Math.abs(b)<1e-10?[]:[-c/b];const d=b*b-4*a*c;if(d<0)return [];const root=Math.sqrt(d);return [(-b+root)/2/a,(-b-root)/2/a];};
460
+ const cubic=s=>{const cx=(s[2]-s[0])*3,cy=(s[3]-s[1])*3,bx=(s[4]-s[2])*3-cx,by=(s[5]-s[3])*3-cy;return [s[6]-s[0]-cx-bx,s[7]-s[1]-cy-by,bx,by,cx,cy,s[0],s[1]];};
461
+ const add=(box,x,y)=>box?[Math.min(box[0],x),Math.min(box[1],y),Math.max(box[2],x),Math.max(box[3],y)]:[x,y,x,y];
462
+ const inside=(box,x,y)=>box[0]<=x&&x<=box[2]&&box[1]<=y&&y<=box[3];
463
+ const curveBox=(box,s)=>{const [ax,ay,bx,by,cx,cy,dx,dy]=cubic(s),roots=[...quadratic(ax*3,bx*2,cx).filter(t=>0<=t&&t<1),...quadratic(ay*3,by*2,cy).filter(t=>0<=t&&t<1)];
464
+ let curve=add(add(null,s[0],s[1]),s[6],s[7]);for(const t of roots)curve=add(curve,ax*t*t*t+bx*t*t+cx*t+dx,ay*t*t*t+by*t*t+cy*t+dy);
465
+ return [Math.min(box[0],curve[0]),Math.min(box[1],curve[1]),Math.max(box[2],curve[2]),Math.max(box[3],curve[3])];};
466
+ const profileOf=(segments,bottom,top)=>{
467
+ const step=__EDGE_STEP__,first=Math.floor(bottom/step)*step,strips=Array.from({length:Math.max(1,Math.ceil((top-first)/step))},()=>[]);
468
+ for(const s of segments){
469
+ if(s.length===4){const [x,y,endX,endY]=s;strips.forEach((strip,i)=>{const lower=first+i*step,upper=lower+step,values=[0,1];
470
+ if(endY!==y)values.push((lower-y)/(endY-y),(upper-y)/(endY-y));
471
+ for(const t of values){const at=y+t*(endY-y);if(0<=t&&t<=1&&lower-1e-7<=at&&at<=upper+1e-7)strip.push(x+t*(endX-x));}});continue;}
472
+ const [a0,a1,b0,b1,c0,c1,d0,d1]=cubic(s),vertical=t=>((a1*t+b1)*t+c1)*t+d1,extrema=[0,1,...quadratic(3*a0,2*b0,c0)],
473
+ critical=[0,1,...quadratic(3*a1,2*b1,c1).filter(t=>0<t&&t<1)].sort((p,q)=>p-q),crossings=new Map,
474
+ crossing=height=>{if(crossings.has(height))return crossings.get(height);const roots=[];
475
+ for(let i=1;i<critical.length;i++){let low=critical[i-1],high=critical[i];const yLow=vertical(low),yHigh=vertical(high);
476
+ if(!(Math.min(yLow,yHigh)<=height&&height<=Math.max(yLow,yHigh)))continue;
477
+ for(let k=0;k<45;k++){const middle=(low+high)/2;if((vertical(middle)<height)===(yLow<yHigh))low=middle;else high=middle;}roots.push((low+high)/2);}
478
+ crossings.set(height,roots);return roots;},ys=[s[1],s[3],s[5],s[7]],yMin=Math.min(...ys),yMax=Math.max(...ys);
479
+ strips.forEach((strip,i)=>{const lower=first+i*step,upper=lower+step;if(lower>yMax||upper<yMin)return;
480
+ for(const t of [...extrema,...crossing(lower),...crossing(upper)])if(0<=t&&t<=1){const y=((a1*t+b1)*t+c1)*t+d1;if(lower-1e-7<=y&&y<=upper+1e-7)strip.push(((a0*t+b0)*t+c0)*t+d0);}});}
481
+ return [first,...strips.map(strip=>strip.length?[Math.floor(Math.min(...strip)-1e-7),Math.ceil(Math.max(...strip)+1e-7)]:null)];
567
482
  };
568
- const profileRecord=(id,depth=0)=>{
569
- const cached=touch(profileCache,id);if(cached)return cached;if(depth>4)invalid();const r=record(profiles,id);if(!r)invalid();const header=unsigned(r);let profile,left=0,right=0;
570
- if(header%2){const parentId=Math.floor(header/2);if(parentId>=id)invalid();const parent=profileRecord(parentId,depth+1);profile=[parent[0]];
571
- for(let i=1;i<parent.length;i++){const strip=parent[i];if(!strip){profile.push(null);continue;}left+=signed(r);right+=signed(r);profile.push([strip[0]+left,strip[1]+right]);}}
572
- else{profile=[signed(r)];const count=header/2;if(count>r[2]-r[1])invalid();for(let i=0;i<count;i++){const token=unsigned(r);if(!token){profile.push(null);continue;}const value=token-1;left+=value%2?-(value+1)/2:value/2;right+=signed(r);profile.push([left,right]);}}
573
- complete(r);return remember(profileCache,id,profile,128);
483
+ const glyphRecord=id=>{
484
+ let cached=glyphCache.get(id);if(cached)return cached;const r=record(glyphs,id);if(!r)return;
485
+ const metrics=[];for(let i=0;i<3;i++)metrics.push(signed(r)+metricBases[i]);metrics[2]+=metrics[0]/2;
486
+ const count=unsigned(r),local=new Map(),keep=profiled.has(id),segments=[];let path='',box=null;
487
+ if(count>r[2]-r[1])invalid();
488
+ for(let part=0;part<count;part++){const contourId=unsigned(r),firstX=signed(r),firstY=signed(r),[commands,coordinates,closes]=contour(contourId,local);let x=firstX,y=firstY,cursor=0;
489
+ path+='M'+x/unit+' '+y/unit;box=add(box,x/unit,y/unit);
490
+ for(let c=0;c<commands.length;c++){const command=commands[c],from=[x/unit,y/unit];path+=commandNames[command];
491
+ for(let index=0;index<commandLengths[command];index++){if(index)path+=' ';
492
+ const last=closes&&c===commands.length-2&&index>3;
493
+ if(command===3||(command!==2&&command!==3&&index%2)){y=last?firstY:y+coordinates[cursor++];path+=y/unit;from.push(x/unit,y/unit);}else{x=last?firstX:x+coordinates[cursor++];path+=x/unit;if(command===2)from.push(x/unit,y/unit);}}
494
+ if(command===5){if(from[0]!==firstX/unit||from[1]!==firstY/unit)segments.push([...from,firstX/unit,firstY/unit]);x=firstX;y=firstY;continue;}
495
+ if(command===4){const end=add(box,from[6],from[7]);box=inside(end,from[2],from[3])&&inside(end,from[4],from[5])?end:curveBox(end,from);}else box=add(box,from[2],from[3]);
496
+ if(keep)segments.push(from);}
497
+ }complete(r);box??=[0,0,0,0];
498
+ const glyph=[metrics[0]/metricUnit,Math.floor(box[0]),Math.floor(box[1]),Math.ceil(box[2]),Math.ceil(box[3]),metrics[1]/metricUnit,metrics[2]/metricUnit,path];
499
+ // Keep the unrounded bounds for the derived profile; only profiled glyphs keep their segments.
500
+ cached={glyph,segments:keep?segments:null,bottom:box[1],top:box[3]};glyphCache.set(id,cached);return cached;
574
501
  };
575
502
  MATH_FONT.glyph=id=>glyphRecord(id)?.glyph;
576
- MATH_FONT.profile=id=>{const glyph=glyphRecord(id);return glyph&&glyph.profile>=0?profileRecord(glyph.profile):undefined;};
503
+ MATH_FONT.profile=id=>{
504
+ if(profileCache.has(id))return profileCache.get(id);const glyph=glyphRecord(id),profile=glyph?.segments?.length?profileOf(glyph.segments,glyph.bottom,glyph.top):undefined;
505
+ profileCache.set(id,profile);return profile;
506
+ };
577
507
  }
578
508
  """
579
509
 
580
510
 
581
-
582
511
  def main():
583
512
  parser = argparse.ArgumentParser(description=__doc__)
584
513
  parser.add_argument("--font", type=Path, help="Optional pinned source font; otherwise fetch it")
@@ -606,16 +535,14 @@ def main():
606
535
  "Conversion details: FONT-SOURCE.md.\n\n").encode("utf-8") + gust + b"\n" + lppl
607
536
  pages, index, size, packing = pack_font(data)
608
537
  glyph_count = len(data["glyphs"])
609
- profile_count = len(data["edgeProfiles"])
610
538
  character_count = len(data["chars"])
611
- del data["glyphs"], data["edgeProfiles"]
612
- for name in (*SCALAR_MAPS, "scriptAlternates"):
539
+ for name in ("glyphs", "profiled", "vertical", "horizontal", *SCALAR_MAPS, "scriptAlternates"):
613
540
  del data[name]
614
- output = (b"/*!\n" + notice + b"\n*/\nconst MATH_FONT=" + json.dumps(data, ensure_ascii=True, separators=(",", ":")).encode("utf-8") + b";\n" + PATH_DECODER.replace("__PAGES__", json.dumps(pages, separators=(",", ":"))).replace("__INDEX__", json.dumps(index)).replace("__SIZE__", str(size)).replace("__MAP_FIELDS__", json.dumps(SCALAR_MAPS, separators=(",", ":"))).encode("utf-8"))
541
+ output = (b"/*!\n" + notice + b"\n*/\nconst MATH_FONT=" + json.dumps(data, ensure_ascii=True, separators=(",", ":")).encode("utf-8") + b";\n" + PATH_DECODER.replace("__PAGES__", json.dumps(pages, separators=(",", ":"))).replace("__INDEX__", json.dumps(index)).replace("__SIZE__", str(size)).replace("__MAP_FIELDS__", json.dumps(SCALAR_MAPS, separators=(",", ":"))).replace("__EDGE_STEP__", str(EDGE_STEP)).encode("utf-8") + b"\n\nexport {MATH_FONT};\n")
615
542
  args.out.parent.mkdir(parents=True, exist_ok=True)
616
543
  args.out.write_bytes(output)
617
544
  args.out.with_name("FONT-LICENSE.txt").write_bytes(notice)
618
- print(json.dumps({"sourceSha256": hashlib.sha256(font_bytes).hexdigest(), "licenseSha256": hashlib.sha256(notice).hexdigest(), "glyphs": glyph_count, "characters": character_count, "edgeProfiles": profile_count, "packing": packing, "bytes": len(output), "gzipBytes": len(gzip.compress(output, compresslevel=9, mtime=0))}, indent=2))
545
+ print(json.dumps({"sourceSha256": hashlib.sha256(font_bytes).hexdigest(), "licenseSha256": hashlib.sha256(notice).hexdigest(), "glyphs": glyph_count, "characters": character_count, "packing": packing, "bytes": len(output), "gzipBytes": len(gzip.compress(output, compresslevel=9, mtime=0))}, indent=2))
619
546
 
620
547
 
621
548
  if __name__ == "__main__":
@@ -1,6 +1,6 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
  globalThis.RapierMath=Object.freeze({
3
- version:'2.1.0', parse:parseMathTex,
3
+ version:'2.3.0', parse:parseMathTex,
4
4
  render:renderMath, renderToString:mathRenderToString,
5
5
  fit:mathFit, observe:mathObserve,
6
6
  toMathML:mathToMathML, renderWithMathML:mathRenderWithMathML,