@beff/aula 0.5.1 → 0.6.1

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.
@@ -7,6 +7,10 @@ export function tex(name: string, parts: Array<Array<Glyph>>, color: Color): Mob
7
7
  * @throws {Error & { payload: Diagnostic }} The error of the result, as the `payload` of the thrown error.
8
8
  */
9
9
  export function text(content: string, settings: TextSettings): Mobject;
10
+ /**
11
+ * @throws {Error & { payload: Diagnostic }} The error of the result, as the `payload` of the thrown error.
12
+ */
13
+ export function image(path: string, mime: string, width: number, height: number, bytes: Uint8Array): Mobject;
10
14
  /**
11
15
  * @throws {Error & { payload: Diagnostic }} The error of the result, as the `payload` of the thrown error.
12
16
  */
package/dist/manim.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  export type { Card, Color, Heading, Location } from "./engine.ts";
2
2
  export { card, chapterCard, dockedHeading, NUMBER_GAP } from "./card.ts";
3
3
  export { theme, type Theme } from "./theme.ts";
4
- export type { AboutOptions, StyleSettings, VMobjectOptions, BackgroundRectangleOptions, GridOptions, MobjectAttributes, MobjectOptions, RadialGradientOptions, UpdaterBuilder, AnimationBuilder, BoundMethod, PathFunc, AnimationOptions, Animations, DecimalNumberMobject, DecimalNumberOptions, IntegerMobject, CodeBackgroundConfig, CodeMobject, CodeOptions, CodeParagraphConfig, Mobjects, Points, RateFunc, StyleOptions, TexMatch, TexOptions, TextOptions, DashedVMobjectOptions, Weight, Slant, TrackerBuilder, } from "./engine.ts";
5
- export { BLACK, BOLD, DEGREES, DL, DOWN, DR, FRAME_HEIGHT, FRAME_WIDTH, LARGE_BUFF, LEFT, MED_LARGE_BUFF, MED_SMALL_BUFF, NORMAL, ORIGIN, PI, RIGHT, SMALL_BUFF, TAU, UL, UP, UR, WHITE, YELLOW, PURE_YELLOW, doubleSmooth, linear, rushFrom, rushInto, slowInto, smooth, thereAndBack, thereAndBackWithPause, easeInSine, easeOutSine, easeInOutSine, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInBack, easeOutBack, easeInOutBack, easeInElastic, easeOutElastic, easeInOutElastic, easeInBounce, easeOutBounce, easeInOutBounce, add, lerp, mul, norm, sub, Animation, Mobject, ValueTracker, MathTex, Code, CubicBezier, DecimalNumber, DashedVMobject, Integer, Polyline, Tex, Text, VGroup, VMobject, alwaysRedraw, Scene, } from "./engine.ts";
4
+ export type { AboutOptions, StyleSettings, VMobjectOptions, BackgroundRectangleOptions, GridOptions, ImageOptions, MobjectAttributes, MobjectOptions, RadialGradientOptions, UpdaterBuilder, AnimationBuilder, BoundMethod, PathFunc, AnimationOptions, Animations, DecimalNumberMobject, DecimalNumberOptions, IntegerMobject, CodeBackgroundConfig, CodeMobject, CodeOptions, CodeParagraphConfig, Mobjects, Points, RateFunc, StyleOptions, TexMatch, TexOptions, TextOptions, DashedVMobjectOptions, Weight, Slant, TrackerBuilder, } from "./engine.ts";
5
+ export { BLACK, BOLD, DEGREES, DL, DOWN, DR, FRAME_HEIGHT, FRAME_WIDTH, LARGE_BUFF, LEFT, MED_LARGE_BUFF, MED_SMALL_BUFF, NORMAL, ORIGIN, PI, RIGHT, SMALL_BUFF, TAU, UL, UP, UR, WHITE, YELLOW, PURE_YELLOW, doubleSmooth, linear, rushFrom, rushInto, slowInto, smooth, thereAndBack, thereAndBackWithPause, easeInSine, easeOutSine, easeInOutSine, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInBack, easeOutBack, easeInOutBack, easeInElastic, easeOutElastic, easeInOutElastic, easeInBounce, easeOutBounce, easeInOutBounce, add, lerp, mul, norm, sub, Animation, Mobject, ValueTracker, MathTex, Code, CubicBezier, DecimalNumber, DashedVMobject, Integer, Polyline, Tex, Text, Image, VGroup, VMobject, alwaysRedraw, Scene, } from "./engine.ts";
6
6
  export type { AddTipOptions, AngleMobject, AngleOptions, AnnularSectorOptions, ArcBetweenPointsOptions, ArcMobject, ArcOptions, ArcPolygonMobject, ArcPolygonOptions, ArrowMobject, ArrowSettings, ArrowTipMobject, BackgroundRectangleMobject, CircleMobject, CurvedArrowOptions, DashedLineMobject, DashedLineOptions, FunctionGraphMobject, LabelOptions, LabeledLineOptions, LineMobject, LineOptions, ParametricFunctionMobject, ParametricFunctionOptions, PolygramMobject, RectangleOptions, RegularPolygramOptions, Scaling, SquareMobject, StarOptions, StealthTipMobject, TRange, TipOptions, TipShape, TipableOptions, TipableVMobjectMobject, VectorMobject, } from "./geometry.ts";
7
7
  export { Angle, AnnotationDot, AnnularSector, Annulus, Arc, ArcBetweenPoints, ArcPolygon, ArcPolygonFromArcs, Arrow, ArrowCircleFilledTip, ArrowCircleTip, ArrowSquareFilledTip, ArrowSquareTip, ArrowTip, ArrowTriangleFilledTip, ArrowTriangleTip, BackgroundRectangle, Circle, ConvexHull, Cross, CurvedArrow, CurvedDoubleArrow, Cutout, DashedLine, Difference, Dot, DoubleArrow, Elbow, Ellipse, Exclusion, FunctionGraph, ImplicitFunction, Intersection, Label, LabeledArrow, LabeledDot, LabeledLine, LabeledPolygram, Line, ParametricFunction, Polygon, Polygram, Rectangle, RegularPolygon, RegularPolygram, RightAngle, RoundedRectangle, Sector, Square, Star, StealthTip, SurroundingRectangle, TangentLine, TangentialArc, TipableVMobject, Triangle, Underline, Union, Vector, } from "./geometry.ts";
8
8
  export * from "./colors-palette.ts";
package/dist/manim.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // The chapter card, the docked heading and the theme: the defaults of every project.
2
2
  export { card, chapterCard, dockedHeading, NUMBER_GAP } from "./card.js";
3
3
  export { theme } from "./theme.js";
4
- export { BLACK, BOLD, DEGREES, DL, DOWN, DR, FRAME_HEIGHT, FRAME_WIDTH, LARGE_BUFF, LEFT, MED_LARGE_BUFF, MED_SMALL_BUFF, NORMAL, ORIGIN, PI, RIGHT, SMALL_BUFF, TAU, UL, UP, UR, WHITE, YELLOW, PURE_YELLOW, doubleSmooth, linear, rushFrom, rushInto, slowInto, smooth, thereAndBack, thereAndBackWithPause, easeInSine, easeOutSine, easeInOutSine, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInBack, easeOutBack, easeInOutBack, easeInElastic, easeOutElastic, easeInOutElastic, easeInBounce, easeOutBounce, easeInOutBounce, add, lerp, mul, norm, sub, Animation, Mobject, ValueTracker, MathTex, Code, CubicBezier, DecimalNumber, DashedVMobject, Integer, Polyline, Tex, Text, VGroup, VMobject, alwaysRedraw, Scene, } from "./engine.js";
4
+ export { BLACK, BOLD, DEGREES, DL, DOWN, DR, FRAME_HEIGHT, FRAME_WIDTH, LARGE_BUFF, LEFT, MED_LARGE_BUFF, MED_SMALL_BUFF, NORMAL, ORIGIN, PI, RIGHT, SMALL_BUFF, TAU, UL, UP, UR, WHITE, YELLOW, PURE_YELLOW, doubleSmooth, linear, rushFrom, rushInto, slowInto, smooth, thereAndBack, thereAndBackWithPause, easeInSine, easeOutSine, easeInOutSine, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInBack, easeOutBack, easeInOutBack, easeInElastic, easeOutElastic, easeInOutElastic, easeInBounce, easeOutBounce, easeInOutBounce, add, lerp, mul, norm, sub, Animation, Mobject, ValueTracker, MathTex, Code, CubicBezier, DecimalNumber, DashedVMobject, Integer, Polyline, Tex, Text, Image, VGroup, VMobject, alwaysRedraw, Scene, } from "./engine.js";
5
5
  export { Angle, AnnotationDot, AnnularSector, Annulus, Arc, ArcBetweenPoints, ArcPolygon, ArcPolygonFromArcs, Arrow, ArrowCircleFilledTip, ArrowCircleTip, ArrowSquareFilledTip, ArrowSquareTip, ArrowTip, ArrowTriangleFilledTip, ArrowTriangleTip, BackgroundRectangle, Circle, ConvexHull, Cross, CurvedArrow, CurvedDoubleArrow, Cutout, DashedLine, Difference, Dot, DoubleArrow, Elbow, Ellipse, Exclusion, FunctionGraph, ImplicitFunction, Intersection, Label, LabeledArrow, LabeledDot, LabeledLine, LabeledPolygram, Line, ParametricFunction, Polygon, Polygram, Rectangle, RegularPolygon, RegularPolygram, RightAngle, RoundedRectangle, Sector, Square, Star, StealthTip, SurroundingRectangle, TangentLine, TangentialArc, TipableVMobject, Triangle, Underline, Union, Vector, } from "./geometry.js";
6
6
  export * from "./colors-palette.js";
7
7
  export { HSV, ManimColor, RGBA, RandomColorGenerator, averageColor, colorGradient, colorToIntRgb, colorToIntRgba, colorToRgb, colorToRgba, hexToRgb, interpolateColor, invertColor, randomBrightColor, randomColor, rgbToColor, rgbToHex, rgbaToColor, } from "./colors.js";
package/dist/media.d.ts CHANGED
@@ -24,9 +24,10 @@ export declare const MEDIA_FORMATS = "MP4 (H.264, AAC) or WebM (VP8 or VP9, Opus
24
24
  /** What the file `source` is, or why aula cannot play it (a problem that fits after the path of
25
25
  * the file). The size is checked before the read. */
26
26
  export declare function probeMedia(source: MediaSource): MediaInfo | string;
27
- /** The path `given` of a file of the project, with no `.` and no `..` (from the project folder),
28
- * or the problem with it: a URL, an absolute path, or a path outside the project folder. */
29
- export declare function projectPath(given: string): {
27
+ /** The path `given` of a file of the project, from the folder `from` of the project (default: the
28
+ * project folder), as a path from the project folder with no `.` and no `..`, or the problem with
29
+ * it: a URL, an absolute path, or a path outside the project folder. */
30
+ export declare function projectPath(given: string, from?: string): {
30
31
  path: string;
31
32
  } | {
32
33
  problem: string;
package/dist/media.js CHANGED
@@ -363,9 +363,10 @@ function probeWebm(bytes) {
363
363
  return typeof length === "string" ? length : { kind: "video", format: "webm", seconds: length };
364
364
  }
365
365
  // --- paths ----------------------------------------------------------------------------------
366
- /** The path `given` of a file of the project, with no `.` and no `..` (from the project folder),
367
- * or the problem with it: a URL, an absolute path, or a path outside the project folder. */
368
- export function projectPath(given) {
366
+ /** The path `given` of a file of the project, from the folder `from` of the project (default: the
367
+ * project folder), as a path from the project folder with no `.` and no `..`, or the problem with
368
+ * it: a URL, an absolute path, or a path outside the project folder. */
369
+ export function projectPath(given, from = "") {
369
370
  if (given.trim() === "")
370
371
  return { problem: "has an empty path" };
371
372
  if (/^[a-z][a-z0-9+.-]*:/i.test(given)) {
@@ -374,7 +375,7 @@ export function projectPath(given) {
374
375
  if (given.startsWith("/") || given.includes("\\")) {
375
376
  return { problem: `is not a path from the project folder with "/" (${JSON.stringify(given)})` };
376
377
  }
377
- const parts = [];
378
+ const parts = from.split("/").filter((part) => part !== "");
378
379
  for (const part of given.split("/")) {
379
380
  if (part === "" || part === ".")
380
381
  continue;
@@ -0,0 +1,23 @@
1
+ import type { MediaSource } from "./media.ts";
2
+ /** The most bytes of one picture file. */
3
+ export declare const MAX_PICTURE_BYTES: number;
4
+ /** The most pixels of one picture (its width times its height). */
5
+ export declare const MAX_PICTURE_PIXELS = 36000000;
6
+ /** A picture that the engine draws: the media type, the size in pixels (for an SVG, the size
7
+ * that it says), and the bytes of the still. */
8
+ export interface Picture {
9
+ readonly mime: string;
10
+ readonly width: number;
11
+ readonly height: number;
12
+ readonly bytes: Uint8Array;
13
+ }
14
+ /** A picture of the project: its path from the project folder, as the engine tells two files
15
+ * apart, and the picture. */
16
+ export interface PlacedPicture extends Picture {
17
+ readonly path: string;
18
+ }
19
+ type Found = Picture | string;
20
+ /** The picture that the file `source` is, or why aula cannot draw it (a problem that fits after
21
+ * the path of the file). The size is checked before the read. */
22
+ export declare function probePicture(source: MediaSource): Found;
23
+ export {};
@@ -0,0 +1,291 @@
1
+ // The pictures of a scene (`m.Image`): what a file is and how big, read from its header. Pure:
2
+ // the host gives the bytes (`Host.media`), the same for the CLI and the web app. A picture is
3
+ // one still, so the file that goes to the engine has what every viewer shows the same way: a GIF
4
+ // is cut after its first frame and a PNG loses its animation chunks; an animated WebP, a JPEG
5
+ // with an EXIF rotation, and an SVG whose picture depends on the viewer (scripts, animation,
6
+ // text, other files) are refused, with the fix.
7
+ /** The most bytes of one picture file. */
8
+ export const MAX_PICTURE_BYTES = 10 * 1024 * 1024;
9
+ /** The most pixels of one picture (its width times its height). */
10
+ export const MAX_PICTURE_PIXELS = 36_000_000;
11
+ /** The formats of a picture, for the messages. */
12
+ const PICTURE_FORMATS = "PNG, JPEG, WebP, GIF (its first frame) or SVG";
13
+ const megabytes = (bytes) => (bytes / (1024 * 1024)).toFixed(1);
14
+ const byteAt = (bytes, at) => bytes[at] ?? 0;
15
+ const ascii = (bytes, at, length) => String.fromCharCode(...bytes.subarray(at, at + length));
16
+ const be16 = (bytes, at) => (byteAt(bytes, at) << 8) | byteAt(bytes, at + 1);
17
+ const be32 = (bytes, at) => be16(bytes, at) * 65536 + be16(bytes, at + 2);
18
+ const le16 = (bytes, at) => byteAt(bytes, at) | (byteAt(bytes, at + 1) << 8);
19
+ const le24 = (bytes, at) => le16(bytes, at) | (byteAt(bytes, at + 2) << 16);
20
+ const startsWith = (bytes, head) => bytes.length >= head.length && head.every((b, i) => bytes[i] === b);
21
+ const join = (...parts) => {
22
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
23
+ let at = 0;
24
+ for (const part of parts) {
25
+ out.set(part, at);
26
+ at += part.length;
27
+ }
28
+ return out;
29
+ };
30
+ /** The picture that the file `source` is, or why aula cannot draw it (a problem that fits after
31
+ * the path of the file). The size is checked before the read. */
32
+ export function probePicture(source) {
33
+ if (source.size > MAX_PICTURE_BYTES) {
34
+ return `is ${megabytes(source.size)} MB, and the limit is ${megabytes(MAX_PICTURE_BYTES)} MB`;
35
+ }
36
+ const bytes = source.read();
37
+ const found = probeFormat(bytes);
38
+ if (typeof found === "string")
39
+ return found;
40
+ if (found.width < 1 || found.height < 1)
41
+ return "has no size";
42
+ if (found.width * found.height > MAX_PICTURE_PIXELS) {
43
+ return `is ${String(found.width)}×${String(found.height)} pixels, and the limit is ${String(MAX_PICTURE_PIXELS / 1_000_000)} million`;
44
+ }
45
+ return found;
46
+ }
47
+ function probeFormat(bytes) {
48
+ if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
49
+ return probePng(bytes);
50
+ if (startsWith(bytes, [0xff, 0xd8, 0xff]))
51
+ return probeJpeg(bytes);
52
+ if (bytes.length >= 12 && ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 4) === "WEBP")
53
+ return probeWebp(bytes);
54
+ if (bytes.length >= 10 && (ascii(bytes, 0, 6) === "GIF87a" || ascii(bytes, 0, 6) === "GIF89a")) {
55
+ return probeGif(bytes);
56
+ }
57
+ const svg = probeSvg(bytes);
58
+ if (svg !== undefined)
59
+ return svg;
60
+ return `has an unknown format: aula draws ${PICTURE_FORMATS}`;
61
+ }
62
+ // --- PNG ------------------------------------------------------------------------------------
63
+ const APNG_CHUNKS = new Set(["acTL", "fcTL", "fdAT"]);
64
+ function probePng(bytes) {
65
+ if (bytes.length < 33 || ascii(bytes, 12, 4) !== "IHDR")
66
+ return "is not a complete PNG file";
67
+ const kept = [];
68
+ let at = 8;
69
+ let ended = false;
70
+ let animated = false;
71
+ while (at + 12 <= bytes.length) {
72
+ const end = at + 12 + be32(bytes, at);
73
+ if (end > bytes.length)
74
+ break;
75
+ const type = ascii(bytes, at + 4, 4);
76
+ if (APNG_CHUNKS.has(type)) {
77
+ animated = true;
78
+ }
79
+ else {
80
+ kept.push(bytes.subarray(at, end));
81
+ }
82
+ at = end;
83
+ if (type === "IEND") {
84
+ ended = true;
85
+ break;
86
+ }
87
+ }
88
+ if (!ended)
89
+ return "is cut short: it is not a complete PNG file";
90
+ return {
91
+ mime: "image/png",
92
+ width: be32(bytes, 16),
93
+ height: be32(bytes, 20),
94
+ bytes: animated ? join(bytes.subarray(0, 8), ...kept) : bytes,
95
+ };
96
+ }
97
+ // --- JPEG -----------------------------------------------------------------------------------
98
+ const JPEG_SOF = new Set([0xc0, 0xc1, 0xc2]);
99
+ const JPEG_OTHER_SOF = new Set([0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf]);
100
+ /** The EXIF orientation of the APP1 segment at `data` (1 when it says none). */
101
+ function exifOrientation(bytes, data, end) {
102
+ if (ascii(bytes, data, 6) !== "Exif\0\0")
103
+ return 1;
104
+ const tiff = data + 6;
105
+ const little = ascii(bytes, tiff, 2) === "II";
106
+ const u16 = (at) => (little ? le16(bytes, at) : be16(bytes, at));
107
+ const u32 = (at) => (little ? u16(at) + u16(at + 2) * 65536 : u16(at) * 65536 + u16(at + 2));
108
+ const ifd = tiff + u32(tiff + 4);
109
+ if (ifd + 2 > end)
110
+ return 1;
111
+ const count = u16(ifd);
112
+ for (let i = 0; i < count; i += 1) {
113
+ const entry = ifd + 2 + i * 12;
114
+ if (entry + 12 > end)
115
+ return 1;
116
+ if (u16(entry) === 0x0112)
117
+ return u16(entry + 8);
118
+ }
119
+ return 1;
120
+ }
121
+ function probeJpeg(bytes) {
122
+ let at = 2;
123
+ let orientation = 1;
124
+ while (at + 4 <= bytes.length) {
125
+ if (byteAt(bytes, at) !== 0xff)
126
+ return "is not a complete JPEG file";
127
+ const marker = byteAt(bytes, at + 1);
128
+ if (marker === 0xff) {
129
+ at += 1;
130
+ continue;
131
+ }
132
+ if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
133
+ at += 2;
134
+ continue;
135
+ }
136
+ const length = be16(bytes, at + 2);
137
+ const end = at + 2 + length;
138
+ if (end > bytes.length)
139
+ return "is cut short: it is not a complete JPEG file";
140
+ if (marker === 0xe1 && orientation === 1)
141
+ orientation = exifOrientation(bytes, at + 4, end);
142
+ if (JPEG_OTHER_SOF.has(marker))
143
+ return "is a kind of JPEG that aula does not draw (lossless or arithmetic): save it as a normal JPEG";
144
+ if (JPEG_SOF.has(marker)) {
145
+ if (byteAt(bytes, at + 4) !== 8)
146
+ return "has more than 8 bits for each color: save it as a normal JPEG";
147
+ const components = byteAt(bytes, at + 9);
148
+ if (components !== 1 && components !== 3) {
149
+ return "is not RGB or gray (a CMYK file): save it as RGB, so every viewer shows the same colors";
150
+ }
151
+ if (orientation !== 1) {
152
+ return `has an EXIF orientation (${String(orientation)}): turn the picture upright and save it again, so every viewer shows it the same way`;
153
+ }
154
+ return { mime: "image/jpeg", width: be16(bytes, at + 7), height: be16(bytes, at + 5), bytes };
155
+ }
156
+ if (marker === 0xda)
157
+ break;
158
+ at = end;
159
+ }
160
+ return "is cut short: it is not a complete JPEG file";
161
+ }
162
+ // --- WebP -----------------------------------------------------------------------------------
163
+ function probeWebp(bytes) {
164
+ const kind = ascii(bytes, 12, 4);
165
+ const mime = "image/webp";
166
+ if (kind === "VP8X" && bytes.length >= 30) {
167
+ if ((byteAt(bytes, 20) & 0x02) !== 0) {
168
+ return "is an animated WebP: aula draws one still, so save a still WebP (or a PNG)";
169
+ }
170
+ return { mime, width: le24(bytes, 24) + 1, height: le24(bytes, 27) + 1, bytes };
171
+ }
172
+ if (kind === "VP8L" && bytes.length >= 25 && byteAt(bytes, 20) === 0x2f) {
173
+ const bits = le16(bytes, 21) | (le16(bytes, 23) << 16);
174
+ return { mime, width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1, bytes };
175
+ }
176
+ if (kind === "VP8 " && bytes.length >= 30 && byteAt(bytes, 23) === 0x9d && byteAt(bytes, 24) === 0x01) {
177
+ return { mime, width: le16(bytes, 26) & 0x3fff, height: le16(bytes, 28) & 0x3fff, bytes };
178
+ }
179
+ return "is not a complete WebP file";
180
+ }
181
+ // --- GIF ------------------------------------------------------------------------------------
182
+ /** The offset after the sub-blocks that start at `at`. */
183
+ function afterBlocks(bytes, start) {
184
+ let at = start;
185
+ while (at < bytes.length) {
186
+ const size = byteAt(bytes, at);
187
+ at += 1 + size;
188
+ if (size === 0)
189
+ return at;
190
+ }
191
+ return bytes.length + 1;
192
+ }
193
+ function probeGif(bytes) {
194
+ const flags = byteAt(bytes, 10);
195
+ let at = 13 + (flags & 0x80 ? 3 * 2 ** ((flags & 7) + 1) : 0);
196
+ while (at < bytes.length) {
197
+ const block = byteAt(bytes, at);
198
+ if (block === 0x21) {
199
+ at = afterBlocks(bytes, at + 2);
200
+ }
201
+ else if (block === 0x2c) {
202
+ const local = byteAt(bytes, at + 9);
203
+ at += 10 + (local & 0x80 ? 3 * 2 ** ((local & 7) + 1) : 0) + 1;
204
+ at = afterBlocks(bytes, at);
205
+ if (at > bytes.length)
206
+ break;
207
+ return {
208
+ mime: "image/gif",
209
+ width: le16(bytes, 6),
210
+ height: le16(bytes, 8),
211
+ bytes: join(bytes.subarray(0, at), Uint8Array.of(0x3b)),
212
+ };
213
+ }
214
+ else {
215
+ break;
216
+ }
217
+ }
218
+ return "is cut short: it has no complete first frame";
219
+ }
220
+ // --- SVG ------------------------------------------------------------------------------------
221
+ /** What makes the picture of an SVG file depend on the viewer: a pattern, and the fix. */
222
+ const SVG_REFUSED = [
223
+ [/<script\b/i, "has a <script>: aula draws a picture, not a program"],
224
+ [/<foreignObject\b/i, "has a <foreignObject>: its content is not drawn the same way everywhere"],
225
+ [/<(?:animate\w*|set)\b/i, "has an animation (<animate>, <set>): aula draws one still"],
226
+ [/@keyframes\b/i, "has a CSS animation (@keyframes): aula draws one still"],
227
+ [/<image\b/i, "has an <image>: put the picture in the scene as its own m.Image"],
228
+ [
229
+ /<(?:text|tspan|textPath)\b/i,
230
+ "has text: turn the text into paths in the editor, so every viewer draws the same letters",
231
+ ],
232
+ [
233
+ /(?:xlink:)?href\s*=\s*["'](?!#)/i,
234
+ "refers to another file or URL (href): the SVG file must hold all of its picture",
235
+ ],
236
+ [/@import\b|url\(\s*(?!["']?#)/i, "refers to another file or URL: the SVG file must hold all of its picture"],
237
+ ];
238
+ const LENGTH = /^\s*([0-9]*\.?[0-9]+(?:e[+-]?[0-9]+)?)\s*(?:px)?\s*$/i;
239
+ /** The value of the attribute `name` of the tag `tag`, if it has it. */
240
+ function attribute(tag, name) {
241
+ return new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`)
242
+ .exec(tag)
243
+ ?.slice(1)
244
+ .find((v) => v !== undefined);
245
+ }
246
+ function svgSize(root) {
247
+ const box = attribute(root, "viewBox");
248
+ const given = [attribute(root, "width"), attribute(root, "height")];
249
+ if (given[0] === undefined && given[1] === undefined) {
250
+ const numbers = (box ?? "")
251
+ .trim()
252
+ .split(/[\s,]+/)
253
+ .map(Number);
254
+ const [, , width, height] = numbers;
255
+ if (numbers.length !== 4 || !(width !== undefined && width > 0) || !(height !== undefined && height > 0)) {
256
+ return "has no size: give the <svg> a width and a height, or a viewBox";
257
+ }
258
+ return { width, height };
259
+ }
260
+ const [width, height] = given.map((value) => {
261
+ const found = value === undefined ? null : LENGTH.exec(value);
262
+ return found?.[1] === undefined ? Number.NaN : Number(found[1]);
263
+ });
264
+ if (width === undefined || height === undefined || !(width > 0) || !(height > 0)) {
265
+ return 'has a width and a height that are not both a number of pixels (50% and 2cm change with the viewer): write width="200" height="100"';
266
+ }
267
+ return { width, height };
268
+ }
269
+ /** The picture of an SVG file, or undefined when the bytes are not one. */
270
+ function probeSvg(bytes) {
271
+ const text = new TextDecoder().decode(bytes);
272
+ if (text.includes("\uFFFD"))
273
+ return undefined;
274
+ const plain = text.replace(/^\uFEFF/, "").replace(/<!--[\s\S]*?-->/g, "");
275
+ const root = /<svg(\s[^>]*)?>/i.exec(plain);
276
+ if (root === null)
277
+ return undefined;
278
+ for (const [pattern, problem] of SVG_REFUSED) {
279
+ if (pattern.test(plain))
280
+ return problem;
281
+ }
282
+ const size = svgSize(root[1] ?? "");
283
+ if (typeof size === "string")
284
+ return size;
285
+ return {
286
+ mime: "image/svg+xml",
287
+ width: Math.max(1, Math.round(size.width)),
288
+ height: Math.max(1, Math.round(size.height)),
289
+ bytes,
290
+ };
291
+ }
package/dist/run.d.ts CHANGED
@@ -25,7 +25,7 @@ export interface Host {
25
25
  }
26
26
  /** Frames per second of the Lottie files: the engine's rate (`engine.fps()`, which
27
27
  * `constants.test.ts` checks), as a value here: an import does not load the engine. */
28
- export declare const FPS = 15;
28
+ export declare const FPS = 60;
29
29
  /** `tts`: the narrator engine (tokens to audio), after `loadEngine()`. */
30
30
  export { loadEngine, tts } from "./load.ts";
31
31
  /** The name of chapter 0, the title card. */
package/dist/run.js CHANGED
@@ -7,12 +7,13 @@ import { hasPending, takePending } from "./host.js";
7
7
  import { runUserCode } from "./user-code.js";
8
8
  import { badReadings, lexiconEntries } from "./lexicon.js";
9
9
  import { probeMedia, projectPath } from "./media.js";
10
+ import { probePicture } from "./picture.js";
10
11
  export { importUserModule } from "./user-code.js";
11
12
  export { renderScene } from "./engine.js";
12
13
  export { MAX_CLIP_BYTES, MEDIA_FORMATS, probeMedia } from "./media.js";
13
14
  /** Frames per second of the Lottie files: the engine's rate (`engine.fps()`, which
14
15
  * `constants.test.ts` checks), as a value here: an import does not load the engine. */
15
- export const FPS = 15;
16
+ export const FPS = 60;
16
17
  /** `tts`: the narrator engine (tokens to audio), after `loadEngine()`. */
17
18
  export { loadEngine, tts } from "./load.js";
18
19
  /** The name of chapter 0, the title card. */
@@ -206,6 +207,29 @@ function clipOf(host, folder, given) {
206
207
  const probed = probeMedia(source);
207
208
  return typeof probed === "string" ? `embed: ${JSON.stringify(given)} ${probed}` : probed;
208
209
  }
210
+ /** The folder of the chapter file `file`, from the project folder ("" for the project folder). */
211
+ function chapterFolder(project, file, host) {
212
+ const folder = projectFolder(project, host);
213
+ const name = host.name(file) ?? file;
214
+ const slash = name.lastIndexOf("/");
215
+ const dir = slash === -1 ? "." : name.slice(0, slash);
216
+ if (dir === folder)
217
+ return "";
218
+ return dir.startsWith(`${folder}/`) ? dir.slice(folder.length + 1) : "";
219
+ }
220
+ /** The file `given` of an `m.Image` (a path from the chapter file, in the folder `from` of the
221
+ * project): its picture, or why it cannot be drawn. */
222
+ function pictureOf(host, folder, from, given) {
223
+ const found = projectPath(given, from);
224
+ if ("problem" in found)
225
+ return `m.Image: ${JSON.stringify(given)} ${found.problem}`;
226
+ const source = host.media?.(folder === "." ? found.path : `${folder}/${found.path}`);
227
+ if (source === undefined) {
228
+ return `m.Image: no file ${JSON.stringify(given)} in the project folder (the path starts at the chapter file)`;
229
+ }
230
+ const probed = probePicture(source);
231
+ return typeof probed === "string" ? `m.Image: ${JSON.stringify(given)} ${probed}` : { ...probed, path: found.path };
232
+ }
209
233
  /** The slot of chapter `index` (from 1) of `project`. */
210
234
  function slotOf(project, chapter, index, host) {
211
235
  const source = definedAt(chapter, host).file;
@@ -217,6 +241,7 @@ function slotOf(project, chapter, index, host) {
217
241
  frames: (e) => host.frames(e),
218
242
  lexicon: lexiconEntries(project.lexicon),
219
243
  clip: (given) => clipOf(host, projectFolder(project, host), given),
244
+ picture: (given) => pictureOf(host, projectFolder(project, host), chapterFolder(project, source, host), given),
220
245
  };
221
246
  }
222
247
  /** Reads chapter `index` (from 1) of `project`: its text and its text problems, with no move
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@beff/aula",
3
- "version": "0.5.1",
3
+ "version": "0.6.1",
4
4
  "type": "module",
5
5
  "description": "The aula engine for narrated explainer videos: the Manim CE API, defineChapter, its rows, readChapter and renderChapter over a Rust WebAssembly component. Chapters and kits import it; the aula command is @beff/aula-cli.",
6
6
  "license": "MIT AND GPL-3.0-or-later",