@egret/runtime 7.0.1-rc.3 → 7.0.2

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.
@@ -505,11 +505,20 @@ function strokeSolid(target, points, loop, style) {
505
505
  }
506
506
  for (let i = 0; i < segments; i++)
507
507
  triangles.push(startPlus[i], startMinus[i], endMinus[i], startPlus[i], endMinus[i], endPlus[i]);
508
- const first = paint(target, out, style), from = target.indices.length;
508
+ const vertices = target.positions.length / 2, first = paint(target, out, style), from = target.indices.length;
509
509
  for (const index of triangles)
510
510
  target.indices.push(first + index);
511
- if (style.bitmap === undefined && style.feather !== undefined && style.feather > 0)
512
- featherEdges(target, from, style.feather);
511
+ const feather = style.bitmap === undefined && style.feather !== undefined && style.feather > 0 ? style.feather : 0;
512
+ // A line of a gradient is cut, as a fill of one is, until the colours of its corners are close enough to it.
513
+ let boundary;
514
+ if (style.gradient !== undefined) {
515
+ if (feather > 0)
516
+ boundary = originalBoundary(target, from);
517
+ const refined = refineForGradient(takeTriangles(target, vertices, from), style.gradient, GRAPHICS_SHAPE_LIMITS.maxFillTriangles, boundary);
518
+ addTriangles(target, refined, style, boundary);
519
+ }
520
+ if (feather > 0)
521
+ featherEdges(target, from, feather, boundary);
513
522
  }
514
523
  /** How many straight pieces a curve of this radius is drawn with: each is within a quarter unit of the curve. */
515
524
  export function curveSegments(radius) {
@@ -752,4 +761,201 @@ export function resolveShape(shape) {
752
761
  }
753
762
  return (shape.resolved = resolved);
754
763
  }
764
+ /** The most pixels a side of a mask's image has, and how many samples a pixel takes on each side. */
765
+ export const SHAPE_MASK_LIMITS = Object.freeze({ maxEdge: 2048, samples: 4 });
766
+ const keptMasks = new WeakMap();
767
+ /** How far an even change of size may go before the image is drawn again: an eighth of an octave either way. */
768
+ const STRETCH = 2 ** (1 / 8);
769
+ /**
770
+ * The image kept for a mask placed by `matrix` instead of the matrix it was drawn at: the same when nothing changed, moved
771
+ * when only the place changed, and moved and stretched when the size changed evenly and a little. Undefined otherwise.
772
+ */
773
+ function reuse(kept, matrix) {
774
+ const old = kept.matrix;
775
+ if (old.a === matrix.a &&
776
+ old.b === matrix.b &&
777
+ old.c === matrix.c &&
778
+ old.d === matrix.d &&
779
+ old.tx === matrix.tx &&
780
+ old.ty === matrix.ty)
781
+ return kept.value;
782
+ // A mask that covers nothing covers nothing wherever it is.
783
+ if (kept.value === EMPTY)
784
+ return EMPTY;
785
+ // The new linear part must be the old one times one ratio.
786
+ const pick = Math.abs(old.a) >= Math.abs(old.b) ? 'a' : 'b', ratio = old[pick] === 0 ? NaN : matrix[pick] / old[pick];
787
+ if (!(ratio >= 1 / STRETCH && ratio <= STRETCH))
788
+ return undefined;
789
+ const near = (x, y) => Math.abs(x - y) <= 1e-9 * Math.max(1, Math.abs(x), Math.abs(y));
790
+ if (!near(matrix.a, ratio * old.a) ||
791
+ !near(matrix.b, ratio * old.b) ||
792
+ !near(matrix.c, ratio * old.c) ||
793
+ !near(matrix.d, ratio * old.d))
794
+ return undefined;
795
+ const rect = kept.value.rect;
796
+ // A point drawn at p = L q + t is now at r L q + t' = r (p - t) + t'.
797
+ return Object.freeze({
798
+ image: kept.value.image,
799
+ region: kept.value.region,
800
+ rect: Object.freeze({
801
+ x: ratio * (rect.x - old.tx) + matrix.tx,
802
+ y: ratio * (rect.y - old.ty) + matrix.ty,
803
+ width: ratio * rect.width,
804
+ height: ratio * rect.height
805
+ })
806
+ });
807
+ }
808
+ // A drawing resolved once is one object for as long as it is the same; its number stands for it in a key.
809
+ const drawings = new WeakMap();
810
+ let nextDrawing = 1;
811
+ const drawingNumber = (drawing) => {
812
+ if (drawing === undefined)
813
+ return 0;
814
+ let number = drawings.get(drawing);
815
+ if (number === undefined)
816
+ drawings.set(drawing, (number = nextDrawing++));
817
+ return number;
818
+ };
819
+ function regionOf(width, height) {
820
+ return Object.freeze({
821
+ packed: Object.freeze({ x: 0, y: 0, width, height }),
822
+ logicalWidth: width,
823
+ logicalHeight: height,
824
+ trimX: 0,
825
+ trimY: 0,
826
+ quarterTurn: 0
827
+ });
828
+ }
829
+ /** A mask that covers nothing: everything under it is hidden. */
830
+ const EMPTY = Object.freeze({
831
+ image: createImageData2D({ width: 1, height: 1, pixels: new Uint8Array([255, 255, 255, 0]) }),
832
+ region: regionOf(1, 1),
833
+ rect: Object.freeze({ x: 0, y: 0, width: 1, height: 1 })
834
+ });
835
+ /**
836
+ * The image of what a mask draws, its filled rectangles and its drawing placed by `matrix` in the masked node's units,
837
+ * at `scale` pixels to a unit of that node. `mask` is what the image is kept for.
838
+ */
839
+ export function shapeMaskImage(mask, primitives, shape, matrix, scale) {
840
+ // A size that changes a little keeps its image: it is taken in steps of a quarter of a power of two.
841
+ const wanted = Math.max(1e-6, Number.isFinite(scale) && scale > 0 ? scale : 1), step = 2 ** (Math.round(4 * Math.log2(wanted)) / 4);
842
+ const key = [
843
+ drawingNumber(shape),
844
+ step,
845
+ ...primitives.flatMap(({ rect, alpha }) => [rect.x, rect.y, rect.width, rect.height, alpha])
846
+ ].join(',');
847
+ const before = keptMasks.get(mask);
848
+ if (before !== undefined && before.key === key) {
849
+ const kept = reuse(before, matrix);
850
+ if (kept !== undefined)
851
+ return kept;
852
+ }
853
+ // Each triangle as x, y of its corners in the masked node's units, and the alpha of each corner.
854
+ const points = [], alphas = [];
855
+ const place = (x, y, alpha) => {
856
+ points.push(matrix.a * x + matrix.c * y + matrix.tx, matrix.b * x + matrix.d * y + matrix.ty);
857
+ alphas.push(alpha);
858
+ };
859
+ for (const { rect, alpha } of primitives) {
860
+ const right = rect.x + rect.width, bottom = rect.y + rect.height;
861
+ for (const [x, y] of [
862
+ [rect.x, rect.y],
863
+ [right, rect.y],
864
+ [right, bottom],
865
+ [rect.x, rect.y],
866
+ [right, bottom],
867
+ [rect.x, bottom]
868
+ ])
869
+ place(x, y, alpha);
870
+ }
871
+ for (const part of shape?.parts ?? []) {
872
+ const { positions, lightColors, indices } = part.geometry;
873
+ // A part over an image covers where it is drawn; the image's own alpha does not count.
874
+ for (const index of indices)
875
+ place(positions[2 * index], positions[2 * index + 1], part.bitmap === undefined ? lightColors[4 * index + 3] : 1);
876
+ }
877
+ if (points.length === 0)
878
+ return remember(mask, key, matrix, EMPTY);
879
+ let left = Infinity, top = Infinity, right = -Infinity, bottom = -Infinity;
880
+ for (let i = 0; i < points.length; i += 2) {
881
+ left = Math.min(left, points[i]);
882
+ right = Math.max(right, points[i]);
883
+ top = Math.min(top, points[i + 1]);
884
+ bottom = Math.max(bottom, points[i + 1]);
885
+ }
886
+ const width = right - left, height = bottom - top;
887
+ if (!(width > 0) || !(height > 0))
888
+ return remember(mask, key, matrix, EMPTY);
889
+ const fit = Math.min(step, SHAPE_MASK_LIMITS.maxEdge / width, SHAPE_MASK_LIMITS.maxEdge / height), columns = Math.max(1, Math.ceil(width * fit)), rows = Math.max(1, Math.ceil(height * fit));
890
+ const value = Object.freeze({
891
+ image: createImageData2D({
892
+ width: columns,
893
+ height: rows,
894
+ pixels: rasterize(points, alphas, left, top, width, height, columns, rows)
895
+ }),
896
+ region: regionOf(columns, rows),
897
+ rect: Object.freeze({ x: left, y: top, width, height })
898
+ });
899
+ return remember(mask, key, matrix, value);
900
+ }
901
+ function remember(mask, key, matrix, value) {
902
+ keptMasks.set(mask, {
903
+ key,
904
+ matrix: Object.freeze({ a: matrix.a, b: matrix.b, c: matrix.c, d: matrix.d, tx: matrix.tx, ty: matrix.ty }),
905
+ value
906
+ });
907
+ return value;
908
+ }
909
+ /**
910
+ * The alpha the triangles cover in each pixel of a grid over a rectangle: each pixel is sampled at a grid of points,
911
+ * each sample takes the triangles over it one upon another, and the pixel is the mean of its samples. Red, green
912
+ * and blue are white.
913
+ */
914
+ function rasterize(points, alphas, left, top, width, height, columns, rows) {
915
+ const n = SHAPE_MASK_LIMITS.samples, across = columns * n, down = rows * n, sx = across / width, sy = down / height;
916
+ const cover = new Float32Array(across * down);
917
+ for (let t = 0; t < points.length; t += 6) {
918
+ const ax = (points[t] - left) * sx, ay = (points[t + 1] - top) * sy, bx = (points[t + 2] - left) * sx, by = (points[t + 3] - top) * sy, cx = (points[t + 4] - left) * sx, cy = (points[t + 5] - top) * sy, alphaA = alphas[t / 2], alphaB = alphas[t / 2 + 1], alphaC = alphas[t / 2 + 2];
919
+ const area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
920
+ if (area === 0 || !Number.isFinite(area))
921
+ continue;
922
+ const x0 = Math.max(0, Math.floor(Math.min(ax, bx, cx))), x1 = Math.min(across - 1, Math.ceil(Math.max(ax, bx, cx))), y0 = Math.max(0, Math.floor(Math.min(ay, by, cy))), y1 = Math.min(down - 1, Math.ceil(Math.max(ay, by, cy)));
923
+ for (let y = y0; y <= y1; y++) {
924
+ const py = y + 0.5;
925
+ for (let x = x0; x <= x1; x++) {
926
+ const px = x + 0.5;
927
+ // Where the sample is between the corners; a sample on a side shared by two triangles is in one of them.
928
+ const wa = ((bx - px) * (cy - py) - (by - py) * (cx - px)) / area, wb = ((cx - px) * (ay - py) - (cy - py) * (ax - px)) / area;
929
+ const wc = 1 - wa - wb;
930
+ if (wa < 0 || wb < 0 || wc < 0)
931
+ continue;
932
+ if ((wa === 0 && !edgeOwns(bx, by, cx, cy, area)) || (wb === 0 && !edgeOwns(cx, cy, ax, ay, area)))
933
+ continue;
934
+ if (wc === 0 && !edgeOwns(ax, ay, bx, by, area))
935
+ continue;
936
+ const alpha = Math.max(0, Math.min(1, wa * alphaA + wb * alphaB + wc * alphaC)), at = y * across + x;
937
+ cover[at] = cover[at] + alpha * (1 - cover[at]);
938
+ }
939
+ }
940
+ }
941
+ const pixels = new Uint8Array(4 * columns * rows);
942
+ for (let row = 0; row < rows; row++)
943
+ for (let column = 0; column < columns; column++) {
944
+ let sum = 0;
945
+ for (let j = 0; j < n; j++)
946
+ for (let i = 0; i < n; i++)
947
+ sum += cover[(row * n + j) * across + column * n + i];
948
+ const at = 4 * (row * columns + column);
949
+ pixels[at] = pixels[at + 1] = pixels[at + 2] = 255;
950
+ pixels[at + 3] = Math.round((255 * sum) / (n * n));
951
+ }
952
+ return pixels;
953
+ }
954
+ /** The top-left rule: a sample exactly on a side belongs to the triangle on one side of it only. */
955
+ function edgeOwns(fromX, fromY, toX, toY, area) {
956
+ const dx = toX - fromX, dy = toY - fromY;
957
+ // With the corners made to run one way, a top side runs along x and a left side runs down.
958
+ const sign = area > 0 ? 1 : -1;
959
+ return sign * dy < 0 || (dy === 0 && sign * dx > 0);
960
+ }
755
961
  //# sourceMappingURL=graphicsShape.js.map
package/dist/index.d.ts CHANGED
@@ -24,6 +24,9 @@ export { AssetLease } from "./AssetLease.js";
24
24
  export { createAssetType, createAssetRef } from "./AssetRef.js";
25
25
  export type { AssetType, AssetRef } from "./AssetRef.js";
26
26
  export { Sprite } from "./Sprite.js";
27
+ export { Sprite as Shape } from "./Sprite.js";
28
+ export { Point, Rectangle, Matrix } from "./geometry.js";
29
+ export type { RectangleLike, MatrixLike } from "./geometry.js";
27
30
  export { Graphics } from "./Graphics.js";
28
31
  export type { LineStyleOptions, GradientColorStop, GradientBoxMatrix } from "./Graphics.js";
29
32
  export { collectSharedFrameContent } from "./sharedFrameCapture.js";
package/dist/index.js CHANGED
@@ -12,6 +12,9 @@ export { AssetManager, createAssetManager } from "./AssetManager.js";
12
12
  export { AssetLease } from "./AssetLease.js";
13
13
  export { createAssetType, createAssetRef } from "./AssetRef.js";
14
14
  export { Sprite } from "./Sprite.js";
15
+ // Egret 5's Shape is a Sprite here: it has graphics, and may hold children too.
16
+ export { Sprite as Shape } from "./Sprite.js";
17
+ export { Point, Rectangle, Matrix } from "./geometry.js";
15
18
  export { Graphics } from "./Graphics.js";
16
19
  export { collectSharedFrameContent } from "./sharedFrameCapture.js";
17
20
  export { Texture, createTexture, createTextureView, isTexture } from "./Texture.js";
@@ -1,6 +1,10 @@
1
+ /** What made a pointer: a mouse, a finger or a pen. */
1
2
  export type PointerType = "mouse" | "touch" | "pen";
3
+ /** What happened to a pointer: it went down, moved, went up or was cancelled. */
2
4
  export type PointerEventKind = "begin" | "move" | "end" | "cancel";
5
+ /** Whether a pointer router passes input on, holds it, or has closed. */
3
6
  export type PointerRouterState = "active" | "suspended" | "closed";
7
+ /** Why a pointer was cancelled. */
4
8
  export type PointerCancelReason = "pointercancel" | "lostcapture" | "blur" | "hidden" | "pagehide" | "viewport" | "owner" | "suspended" | "dispose" | "error";
5
9
  declare const sessionIdentity: unique symbol;
6
10
  /** Only the creating router admits this frozen identity; host IDs may be reused. */
@@ -11,6 +15,7 @@ export interface PointerSession {
11
15
  readonly pointerId: number;
12
16
  readonly pointerType: PointerType;
13
17
  }
18
+ /** Where a pointer is on the stage, which buttons it holds, and when, with its pressure and size where the device gives them. */
14
19
  export interface PointerUpdate {
15
20
  readonly globalX: number;
16
21
  readonly globalY: number;
@@ -20,6 +25,7 @@ export interface PointerUpdate {
20
25
  readonly width?: number;
21
26
  readonly height?: number;
22
27
  }
28
+ /** One pointer's state at one moment: which pointer it is, what made it and where it is. */
23
29
  export interface PointerSample extends PointerUpdate {
24
30
  readonly pointerId: number;
25
31
  readonly pointerType: PointerType;
@@ -8,6 +8,14 @@ export interface RenderEffect2D {
8
8
  readonly blurRadius?: number;
9
9
  readonly alphaMask?: Bitmap;
10
10
  readonly maskRect?: Rectangle2D;
11
+ /**
12
+ * A mask of vector shapes, as Egret's `mask = displayObject`: what the node draws shows only where this Sprite's
13
+ * Graphics covers, faded where they are translucent. On the stage with the node it masks where it is, as in Egret;
14
+ * off the stage it is placed as if it were a child of the node. Only its own drawing counts, not its children's, and
15
+ * its alpha and visibility do not. On the stage it is not drawn while it masks, as in Egret. One effect has an alpha
16
+ * mask or a shape mask.
17
+ */
18
+ readonly shapeMask?: DisplayObject;
11
19
  /**
12
20
  * Twenty numbers, as Egret's ColorMatrixFilter: four rows of red, green, blue and alpha, each four factors and an
13
21
  * offset from 0 to 255. Applied to colour as it is seen, without its alpha multiplied in, after the blur.
@@ -18,6 +26,7 @@ export interface RenderEffect2D {
18
26
  /** A hard line of a colour around what is drawn, a few pixels wide. One effect has a glow or an outline. */
19
27
  readonly outline?: RenderOutline2D;
20
28
  }
29
+ /** A glow around a node's picture, or, moved by an offset, a drop shadow. */
21
30
  export interface RenderGlow2D {
22
31
  /** 0xRRGGBB. */
23
32
  readonly color: number;
@@ -35,6 +44,7 @@ export interface RenderGlow2D {
35
44
  readonly offsetX?: number;
36
45
  readonly offsetY?: number;
37
46
  }
47
+ /** An outline around a node's picture: its color, width and alpha. */
38
48
  export interface RenderOutline2D {
39
49
  /** 0xRRGGBB. */
40
50
  readonly color: number;
@@ -1,5 +1,5 @@
1
1
  import { readBitmapState as bitmapCaptureState } from './bitmapDisplayState.js';
2
- import { assertLive } from './displayTreeState.js';
2
+ import { assertLive, isDisplayNode } from './displayTreeState.js';
3
3
  import { engineOf } from './ownership.js';
4
4
  import { assertVisualMutable, copyRect, visualOf, recordVisualChange, VISUAL_APPEARANCE } from './displayVisualState.js';
5
5
  import { EgretError } from './EgretError.js';
@@ -49,7 +49,7 @@ export function setRenderEffect(node, input) {
49
49
  if (input !== undefined) {
50
50
  if (input === null || typeof input !== 'object')
51
51
  throw new EgretError('DISPLAY_EFFECT_INVALID');
52
- const radius = input.blurRadius ?? 0, mask = input.alphaMask, rect = input.maskRect;
52
+ const radius = input.blurRadius ?? 0, mask = input.alphaMask, rect = input.maskRect, shapeMask = input.shapeMask;
53
53
  if (!Number.isInteger(radius) || radius < 0 || radius > 8)
54
54
  throw new EgretError('DISPLAY_EFFECT_INVALID');
55
55
  let bounds;
@@ -67,6 +67,15 @@ export function setRenderEffect(node, input) {
67
67
  }
68
68
  else if (rect !== undefined)
69
69
  throw new EgretError('DISPLAY_EFFECT_INVALID');
70
+ if (shapeMask !== undefined) {
71
+ if (mask !== undefined || shapeMask === null || typeof shapeMask !== 'object' || !isDisplayNode(shapeMask))
72
+ throw new EgretError('DISPLAY_EFFECT_MASK_INVALID');
73
+ assertLive(shapeMask);
74
+ if (engineOf(shapeMask) !== engineOf(node))
75
+ throw new EgretError('ENGINE_MISMATCH');
76
+ if (shapeMask === node)
77
+ throw new EgretError('DISPLAY_EFFECT_MASK_INVALID');
78
+ }
70
79
  const matrix = input.colorMatrix === undefined ? undefined : readMatrix(input.colorMatrix);
71
80
  const glow = input.glow === undefined ? undefined : readGlow(input.glow), outline = input.outline === undefined ? undefined : readOutline(input.outline);
72
81
  if (glow !== undefined && outline !== undefined)
@@ -74,6 +83,7 @@ export function setRenderEffect(node, input) {
74
83
  value = Object.freeze({
75
84
  blurRadius: radius,
76
85
  ...(mask === undefined ? {} : { alphaMask: mask, maskRect: bounds }),
86
+ ...(shapeMask === undefined ? {} : { shapeMask }),
77
87
  ...(matrix === undefined ? {} : { colorMatrix: matrix }),
78
88
  ...(glow === undefined ? {} : { glow }),
79
89
  ...(outline === undefined ? {} : { outline })
@@ -81,7 +91,19 @@ export function setRenderEffect(node, input) {
81
91
  }
82
92
  // Descriptor reads may execute application getters; publish only after life recheck.
83
93
  assertVisualMutable(node);
84
- visualOf(node).renderEffect = value;
94
+ const state = visualOf(node), before = state.renderEffect?.shapeMask, after = value?.shapeMask;
95
+ state.renderEffect = value;
85
96
  recordVisualChange(node, VISUAL_APPEARANCE);
97
+ // A node that becomes a mask stops being drawn; one no longer a mask of anything is drawn again.
98
+ if (before !== after) {
99
+ if (before !== undefined && !before.isDisposed) {
100
+ visualOf(before).maskUses--;
101
+ recordVisualChange(before, VISUAL_APPEARANCE);
102
+ }
103
+ if (after !== undefined) {
104
+ visualOf(after).maskUses++;
105
+ recordVisualChange(after, VISUAL_APPEARANCE);
106
+ }
107
+ }
86
108
  }
87
109
  //# sourceMappingURL=renderEffect.js.map
@@ -1,4 +1,5 @@
1
1
  import type { AtlasFrameLayout } from './atlasFrameLayout.js';
2
+ /** One frame of a sequence to make: its rectangle on the atlas, how long it shows, and its trim and rotation. */
2
3
  export interface SequenceFrameInput {
3
4
  readonly layout?: AtlasFrameLayout;
4
5
  readonly x: number;
@@ -7,11 +8,13 @@ export interface SequenceFrameInput {
7
8
  readonly height: number;
8
9
  readonly durationSeconds: number;
9
10
  }
11
+ /** The atlas size and the frames of a sequence to make. */
10
12
  export interface SequenceClipInput {
11
13
  readonly atlasWidth: number;
12
14
  readonly atlasHeight: number;
13
15
  readonly frames: readonly SequenceFrameInput[];
14
16
  }
17
+ /** Whether a sequence plays once and stops on its last frame, or loops. */
15
18
  export type SequencePlaybackMode = 'once' | 'loop';
16
19
  /** Public immutable sequence metadata; authentic values come from createSequenceClip. */
17
20
  export interface SequenceClip {
@@ -20,6 +23,7 @@ export interface SequenceClip {
20
23
  readonly frameCount: number;
21
24
  readonly durationSeconds: number;
22
25
  }
26
+ /** The rectangle of the atlas a sequence shows at one moment, with its trim and rotation. */
23
27
  export interface SequenceRegion {
24
28
  readonly layout?: AtlasFrameLayout;
25
29
  readonly x: number;
@@ -27,6 +31,7 @@ export interface SequenceRegion {
27
31
  readonly width: number;
28
32
  readonly height: number;
29
33
  }
34
+ /** What a sequence shows at a position: its frame and region, and whether it has reached its end or stopped. */
30
35
  export interface SequenceSample {
31
36
  readonly frameIndex: number;
32
37
  readonly region: SequenceRegion;
@@ -34,6 +39,7 @@ export interface SequenceSample {
34
39
  readonly atEnd: boolean;
35
40
  readonly stopped: boolean;
36
41
  }
42
+ /** Checks and freezes a sequence from its atlas size and frames; malformed input is refused. */
37
43
  export declare function createSequenceClip(input: unknown, profile?: 'trim-rotation-v1'): SequenceClip;
38
44
  export declare function sampleSequenceClip(clip: SequenceClip, elapsedSeconds: number, options: {
39
45
  readonly mode: 'once' | 'loop';
@@ -65,6 +65,7 @@ function nonnegativeFinite(value) {
65
65
  function positiveZero(value) {
66
66
  return value === 0 ? 0 : value;
67
67
  }
68
+ /** Checks and freezes a sequence from its atlas size and frames; malformed input is refused. */
68
69
  export function createSequenceClip(input, profile) {
69
70
  const source = admitObject(input);
70
71
  if (profile !== undefined && profile !== 'trim-rotation-v1')
@@ -5,7 +5,7 @@ import { finite, visualOf } from './displayVisualState.js';
5
5
  import { composeDisplayTransform } from './displayTransform.js';
6
6
  import { bitmapCaptureState, readBitmapImage, readBitmapSource } from './Bitmap.js';
7
7
  import { readMeshState } from './meshDisplayState.js';
8
- import { SHAPE_PAGE, SHAPE_REGION, resolveShape } from './graphicsShape.js';
8
+ import { SHAPE_PAGE, SHAPE_REGION, resolveShape, shapeMaskImage } from './graphicsShape.js';
9
9
  import { readMeshCaptureImage } from './meshCaptureSnapshot.js';
10
10
  import { assertTextFieldScope, readTextFieldState } from './textDisplayState.js';
11
11
  import { EgretError } from './EgretError.js';
@@ -73,7 +73,8 @@ function shapeFillMaterial(base, repeat) {
73
73
  addressU: address,
74
74
  addressV: address,
75
75
  minFilter: base.minFilter,
76
- magFilter: base.magFilter
76
+ magFilter: base.magFilter,
77
+ mipmapFilter: base.mipmapFilter
77
78
  }));
78
79
  }
79
80
  const glows = new WeakMap();
@@ -110,6 +111,43 @@ function effectGlow(settings) {
110
111
  return value;
111
112
  }
112
113
  const identity = freeze({ a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0 });
114
+ /** Where a node is on the stage, or undefined when it is not on one. */
115
+ function stagePlacement(node) {
116
+ const chain = [];
117
+ let at = node;
118
+ while (at !== undefined && !isStageRoot(at)) {
119
+ chain.push(at);
120
+ at = parentOf(at);
121
+ }
122
+ if (at === undefined)
123
+ return undefined;
124
+ let matrix = composeDisplayTransform(identity, visualOf(at));
125
+ for (let i = chain.length - 1; i >= 0; i--)
126
+ matrix = composeDisplayTransform(matrix, visualOf(chain[i]));
127
+ return matrix;
128
+ }
129
+ /**
130
+ * Where a shape mask is in the masked node's units: where it is on the stage when both are on it, as Egret places a
131
+ * mask on the display list, and otherwise as if it were a child of the node.
132
+ */
133
+ function maskPlacement(node, mask, maskState) {
134
+ const own = stagePlacement(mask), of = own === undefined ? undefined : stagePlacement(node);
135
+ if (own === undefined || of === undefined)
136
+ return composeDisplayTransform(identity, maskState);
137
+ const det = of.a * of.d - of.b * of.c;
138
+ if (det === 0 || !Number.isFinite(det))
139
+ return composeDisplayTransform(identity, maskState);
140
+ // The inverse of the node's placement, times the mask's.
141
+ const a = of.d / det, b = -of.b / det, c = -of.c / det, d = of.a / det, tx = (of.c * of.ty - of.d * of.tx) / det, ty = (of.b * of.tx - of.a * of.ty) / det;
142
+ return {
143
+ a: a * own.a + c * own.b,
144
+ b: b * own.a + d * own.b,
145
+ c: a * own.c + c * own.d,
146
+ d: b * own.c + d * own.d,
147
+ tx: a * own.tx + c * own.ty + tx,
148
+ ty: b * own.tx + d * own.ty + ty
149
+ };
150
+ }
113
151
  function debit(used, count, limit, code = 'FRAME_BUDGET_EXCEEDED') {
114
152
  if (!Number.isSafeInteger(count) || count < 0 || count > limit - used)
115
153
  throw new EgretError(code);
@@ -321,7 +359,9 @@ function materialKey(material) {
321
359
  ';' +
322
360
  material.magFilter +
323
361
  ';' +
324
- material.maxAnisotropy);
362
+ material.maxAnisotropy +
363
+ ';' +
364
+ material.mipmapFilter);
325
365
  }
326
366
  /** Two numbers that print the same: equal, or both not a number. Either zero prints as "0". */
327
367
  function sameNumber(a, b) {
@@ -476,6 +516,7 @@ function captureSharedContent(stage, readBitmap, tree = liveTree, keeping = fals
476
516
  pageIndex = pages.length;
477
517
  pages.push(freeze({
478
518
  source: image,
519
+ ...(image === SHAPE_PAGE ? { builtin: 'solid-white' } : {}),
479
520
  sourceRepresentation: 'egret.srgb-straight-rgba8/1',
480
521
  canonicalRepresentation: 'egret.alpha8-capped-srgb-pma8/1'
481
522
  }));
@@ -564,7 +605,8 @@ function captureSharedContent(stage, readBitmap, tree = liveTree, keeping = fals
564
605
  const firstOrdinal = commands.length, firstOccurrence = nextOccurrence;
565
606
  const explicit = state.renderBoundary === 'isolate' ? open('explicit-enter') : undefined;
566
607
  const alpha = parentAlpha * state.alpha;
567
- if (!state.visible || state.alpha === 0 || alpha === 0) {
608
+ // A node that is some node's shape mask is not drawn itself, as Egret hid a mask.
609
+ if (!state.visible || state.maskUses > 0 || state.alpha === 0 || alpha === 0) {
568
610
  close(explicit, undefined);
569
611
  return false;
570
612
  }
@@ -662,6 +704,21 @@ function captureSharedContent(stage, readBitmap, tree = liveTree, keeping = fals
662
704
  budget.source(image);
663
705
  maskPageIndex = regions[regionIndex(image, region)].pageIndex;
664
706
  }
707
+ // A mask of shapes is drawn as an image of its alpha at the size the node is seen at, twice over for a dense
708
+ // screen, and then masks as an image does.
709
+ let maskRect = settings.maskRect;
710
+ const shapeMask = settings.shapeMask;
711
+ if (shapeMask !== undefined) {
712
+ assertLive(shapeMask);
713
+ if (engineOf(shapeMask) !== engine)
714
+ throw new EgretError('ENGINE_MISMATCH');
715
+ // On the stage it masks where it is, as in Egret; off it, it is placed as if it were a child of the node. Only
716
+ // its own drawing counts, not its alpha or visibility.
717
+ const maskState = visualOf(shapeMask), drawn = shapeMaskImage(shapeMask, maskState.primitives, maskState.shape === undefined ? undefined : resolveShape(maskState.shape), maskPlacement(node, shapeMask, maskState), 2 * Math.sqrt(Math.abs(matrix.a * matrix.d - matrix.b * matrix.c)));
718
+ budget.source(drawn.image);
719
+ maskPageIndex = regions[regionIndex(drawn.image, drawn.region)].pageIndex;
720
+ maskRect = drawn.rect;
721
+ }
665
722
  effect = { occurrenceId: nextOccurrence++, boundaryId: nextBoundary++ };
666
723
  const glow = effectGlow(settings);
667
724
  budget.emission(undefined, true);
@@ -674,7 +731,7 @@ function captureSharedContent(stage, readBitmap, tree = liveTree, keeping = fals
674
731
  effect: freeze({
675
732
  blurRadius: settings.blurRadius ?? 0,
676
733
  maskPageIndex,
677
- maskRect: settings.maskRect,
734
+ maskRect,
678
735
  matrix,
679
736
  clips: flattenClips(clips),
680
737
  ...(settings.colorMatrix === undefined ? {} : { colorMatrix: settings.colorMatrix }),
@@ -988,7 +1045,9 @@ function captureSharedContent(stage, readBitmap, tree = liveTree, keeping = fals
988
1045
  const state = checkNode(node, parent, engine, capture, tree);
989
1046
  const kept = keeping && drawn && !refused ? state.sharedCapture : undefined;
990
1047
  // At rest, the node is a sprite or a bitmap as it was, with as many primitives: its units are those it had.
1048
+ // A node masked by shapes is captured anew: its mask may have changed without it.
991
1049
  const resting = kept !== undefined &&
1050
+ state.renderEffect?.shapeMask === undefined &&
992
1051
  kept.restChanges === state.changes &&
993
1052
  kept.parentMatrix === parentMatrix &&
994
1053
  is(kept.restParentAlpha, parentAlpha) &&
@@ -11,8 +11,8 @@ const scopeState = Object.getOwnPropertyDescriptor(Scope.prototype, 'state').get
11
11
  const containerDispose = DisplayObjectContainer.prototype.dispose;
12
12
  const own = Object.prototype.hasOwnProperty;
13
13
  const MAX_UPDATES = 8192;
14
- function refuse(code = 'UI_CONTENT_INVALID') {
15
- throw new EgretError(code);
14
+ function refuse(code = 'UI_CONTENT_INVALID', reason) {
15
+ throw new EgretError(code, reason === undefined ? {} : { cause: new Error(reason) });
16
16
  }
17
17
  /** A callback-capable array exposes exactly one admitted finite capture boundary. */
18
18
  function captureArrayCount(value) {
@@ -66,30 +66,38 @@ export function createUiDisplayOperations(stage) {
66
66
  }
67
67
  function validateContent(content, scope) {
68
68
  if (scopeState.call(scope) !== 'open')
69
- refuse('UI_CONTENT_INVALID');
69
+ refuse('UI_CONTENT_INVALID', 'the scope of the leaf is closed');
70
70
  const pending = [{ node: content, depth: 1 }];
71
71
  const seen = new Set();
72
72
  while (pending.length !== 0) {
73
73
  const { node, depth } = pending.pop();
74
- if (!isDisplayNode(node) ||
75
- isTerminated(node) ||
76
- isStageRoot(node) ||
77
- seen.has(node) ||
78
- depth > 8 ||
79
- seen.size >= 32 ||
80
- ownerOf(node) !== scope ||
81
- engineOf(node) !== engine ||
82
- isManagedWrapper(node) ||
83
- managedTerminal(node))
84
- refuse();
74
+ const what = node === content ? 'the content' : 'a display object inside the content';
75
+ if (!isDisplayNode(node))
76
+ refuse('UI_CONTENT_INVALID', what + ' is not a display object');
77
+ if (isTerminated(node) || managedTerminal(node))
78
+ refuse('UI_CONTENT_INVALID', what + ' is disposed');
79
+ if (isStageRoot(node))
80
+ refuse('UI_CONTENT_INVALID', what + ' is the stage');
81
+ if (seen.has(node))
82
+ refuse('UI_CONTENT_INVALID', what + ' appears twice');
83
+ if (depth > 8 || seen.size >= 32)
84
+ refuse('UI_CONTENT_INVALID', 'the content has more than 32 display objects, or is deeper than 8');
85
+ if (ownerOf(node) !== scope)
86
+ refuse('UI_CONTENT_INVALID', what +
87
+ ' does not belong to the scope of the leaf: make it with `context.scope.use(...)` in `prepare`, ' +
88
+ 'or give that scope to whatever makes it (such as `createLabel({ scope })`)');
89
+ if (engineOf(node) !== engine)
90
+ refuse('UI_CONTENT_INVALID', what + ' belongs to another Engine');
91
+ if (isManagedWrapper(node))
92
+ refuse('UI_CONTENT_INVALID', what + ' is a node the UI made itself');
85
93
  seen.add(node);
86
94
  const parent = parentOf(node);
87
95
  if (node === content && parent !== undefined && !managedBy(parent, authority))
88
- refuse();
96
+ refuse('UI_CONTENT_INVALID', 'the content is already a child of another display object: remove it first');
89
97
  const childCount = childCountOf(node);
90
98
  // Refuse before allocating a frontier wider than the remaining subtree budget.
91
99
  if (childCount > 32 - seen.size - pending.length || (depth === 8 && childCount !== 0))
92
- refuse();
100
+ refuse('UI_CONTENT_INVALID', 'the content has more than 32 display objects, or is deeper than 8');
93
101
  for (let index = 0; index < childCount; index++) {
94
102
  const child = childAtOf(node, index);
95
103
  if (parentOf(child) !== node)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egret/runtime",
3
- "version": "7.0.1-rc.3",
3
+ "version": "7.0.2",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -29,7 +29,7 @@
29
29
  }
30
30
  },
31
31
  "dependencies": {
32
- "@egret/contracts": "7.0.1-rc.3"
32
+ "@egret/contracts": "7.0.2"
33
33
  },
34
34
  "license": "Apache-2.0",
35
35
  "files": [