@holtjs/stage 0.10.3 → 0.11.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.
package/dist/flex.js CHANGED
@@ -423,4 +423,356 @@ function computeWrapLayout(container, items) {
423
423
  rects
424
424
  };
425
425
  }
426
- export { computeFlexLayout, computeWrapLayout, resolvePadding };
426
+ /**
427
+ * Solve an arbitrarily nested declarative `FlexNodeSpec` tree (2-pass bottom-up intrinsic sizing +
428
+ * top-down stretch/grow propagation) and flatten it into absolute `(x, y, w, h)` screen rectangles.
429
+ */
430
+ function flattenFlexTree(root, originX = 0, originY = 0) {
431
+ const intrinsicSizes = /* @__PURE__ */ new Map();
432
+ const measure = (node) => {
433
+ if (node.visible === false) {
434
+ const zero = {
435
+ w: 0,
436
+ h: 0
437
+ };
438
+ intrinsicSizes.set(node, zero);
439
+ return zero;
440
+ }
441
+ const children = node.children;
442
+ let natW = node.w != null && Number.isFinite(node.w) ? Math.max(0, node.w) : 0;
443
+ let natH = node.h != null && Number.isFinite(node.h) ? Math.max(0, node.h) : 0;
444
+ if (children && children.length > 0) {
445
+ const childItems = new Array(children.length);
446
+ for (let i = 0; i < children.length; i++) {
447
+ const ch = children[i];
448
+ const m = measure(ch);
449
+ childItems[i] = {
450
+ w: m.w,
451
+ h: m.h,
452
+ basis: ch.basis,
453
+ grow: ch.grow,
454
+ shrink: ch.shrink,
455
+ minW: ch.minW,
456
+ maxW: ch.maxW,
457
+ minH: ch.minH,
458
+ maxH: ch.maxH,
459
+ alignSelf: ch.alignSelf,
460
+ visible: ch.visible
461
+ };
462
+ }
463
+ const solved = computeFlexLayout({
464
+ dir: node.dir,
465
+ w: node.w,
466
+ h: node.h,
467
+ gap: node.gap,
468
+ padding: node.padding,
469
+ align: node.align,
470
+ justify: node.justify,
471
+ round: node.round
472
+ }, childItems);
473
+ natW = solved.w;
474
+ natH = solved.h;
475
+ } else if (node.w == null || node.h == null) {
476
+ const [padT, padR, padB, padL] = resolvePadding(node.padding);
477
+ let contentW = 0;
478
+ let contentH = 0;
479
+ if (node.icon) {
480
+ contentW = Math.max(contentW, node.icon.w ?? 24);
481
+ contentH = Math.max(contentH, node.icon.h ?? 24);
482
+ }
483
+ if (node.text != null) {
484
+ const str = typeof node.text === "string" ? node.text : node.text.content;
485
+ contentW = Math.max(contentW, str.length * 8);
486
+ contentH = Math.max(contentH, 16);
487
+ }
488
+ if (node.w == null) natW = contentW + padL + padR;
489
+ if (node.h == null) natH = contentH + padT + padB;
490
+ }
491
+ const res = {
492
+ w: clampSize(natW, node.minW, node.maxW),
493
+ h: clampSize(natH, node.minH, node.maxH)
494
+ };
495
+ intrinsicSizes.set(node, res);
496
+ return res;
497
+ };
498
+ const rootMeas = measure(root);
499
+ const nodes = [];
500
+ const byId = /* @__PURE__ */ new Map();
501
+ const emitAndLayout = (node, x, y, w, h, depth) => {
502
+ if (node.visible === false) return;
503
+ const flat = {
504
+ id: node.id ?? null,
505
+ trackId: node.trackId ?? node.id ?? null,
506
+ x,
507
+ y,
508
+ w,
509
+ h,
510
+ depth,
511
+ visible: true,
512
+ spec: node
513
+ };
514
+ nodes.push(flat);
515
+ if (flat.id) byId.set(flat.id, flat);
516
+ const children = node.children;
517
+ if (!children || children.length === 0) return;
518
+ const childItems = new Array(children.length);
519
+ for (let i = 0; i < children.length; i++) {
520
+ const ch = children[i];
521
+ const m = intrinsicSizes.get(ch) ?? {
522
+ w: 0,
523
+ h: 0
524
+ };
525
+ childItems[i] = {
526
+ w: m.w,
527
+ h: m.h,
528
+ basis: ch.basis,
529
+ grow: ch.grow,
530
+ shrink: ch.shrink,
531
+ minW: ch.minW,
532
+ maxW: ch.maxW,
533
+ minH: ch.minH,
534
+ maxH: ch.maxH,
535
+ alignSelf: ch.alignSelf,
536
+ visible: ch.visible
537
+ };
538
+ }
539
+ const solved = computeFlexLayout({
540
+ dir: node.dir,
541
+ w,
542
+ h,
543
+ gap: node.gap,
544
+ padding: node.padding,
545
+ align: node.align,
546
+ justify: node.justify,
547
+ round: node.round
548
+ }, childItems);
549
+ for (let i = 0; i < children.length; i++) {
550
+ const ch = children[i];
551
+ const r = solved.rects[i];
552
+ if (!r || !r.visible) continue;
553
+ emitAndLayout(ch, x + r.x, y + r.y, r.w, r.h, depth + 1);
554
+ }
555
+ };
556
+ emitAndLayout(root, originX, originY, rootMeas.w, rootMeas.h, 0);
557
+ return {
558
+ width: rootMeas.w,
559
+ height: rootMeas.h,
560
+ nodes,
561
+ byId
562
+ };
563
+ }
564
+ /**
565
+ * Flatten a nested `FlexNodeSpec` tree into a single GPU-instanced `ShapeBatch` for all panel
566
+ * backgrounds/borders + pooled `TextObject`s / `ImageObject`s + `trackId` hit regions!
567
+ */
568
+ function mountFlexUi(scene, initialRoot, options = {}) {
569
+ let rootSpec = initialRoot;
570
+ let origX = options.x ?? 0;
571
+ let origY = options.y ?? 0;
572
+ const container = scene.add.container(0, 0);
573
+ const sf = options.scrollFactor ?? 0;
574
+ container.setScrollFactor(sf, sf);
575
+ container.setDepth(options.depth ?? 6e5);
576
+ if (options.trackId) container.trackId = options.trackId;
577
+ const shapeBatch = scene.make.shapeBatch(32);
578
+ shapeBatch.setOrigin(0, 0);
579
+ shapeBatch.zIndex = 0;
580
+ container.add(shapeBatch);
581
+ let cap = 32;
582
+ let pX = new Float32Array(cap);
583
+ let pY = new Float32Array(cap);
584
+ let pW = new Float32Array(cap);
585
+ let pH = new Float32Array(cap);
586
+ let pR = new Float32Array(cap);
587
+ let pFc = new Uint32Array(cap);
588
+ let pFa = new Float32Array(cap);
589
+ let pBc = new Uint32Array(cap);
590
+ let pBa = new Float32Array(cap);
591
+ let pBw = new Float32Array(cap);
592
+ const textPool = [];
593
+ const iconPool = [];
594
+ const trackPool = [];
595
+ let currentTree = {
596
+ width: 0,
597
+ height: 0,
598
+ nodes: [],
599
+ byId: /* @__PURE__ */ new Map()
600
+ };
601
+ const ensurePanelCap = (needed) => {
602
+ if (needed <= cap) return;
603
+ while (cap < needed) cap *= 2;
604
+ pX = new Float32Array(cap);
605
+ pY = new Float32Array(cap);
606
+ pW = new Float32Array(cap);
607
+ pH = new Float32Array(cap);
608
+ pR = new Float32Array(cap);
609
+ pFc = new Uint32Array(cap);
610
+ pFa = new Float32Array(cap);
611
+ pBc = new Uint32Array(cap);
612
+ pBa = new Float32Array(cap);
613
+ pBw = new Float32Array(cap);
614
+ shapeBatch.maxCount = cap;
615
+ };
616
+ const applyTree = (tree) => {
617
+ currentTree = tree;
618
+ const nodes = tree.nodes;
619
+ let panelCount = 0;
620
+ for (let i = 0; i < nodes.length; i++) if (nodes[i].spec.panel) panelCount++;
621
+ ensurePanelCap(Math.max(1, panelCount));
622
+ let pi = 0;
623
+ let ti = 0;
624
+ let ii = 0;
625
+ let ki = 0;
626
+ for (let i = 0; i < nodes.length; i++) {
627
+ const n = nodes[i];
628
+ const sp = n.spec;
629
+ if (sp.panel && n.w > 0 && n.h > 0) {
630
+ const pnl = sp.panel;
631
+ pX[pi] = n.x;
632
+ pY[pi] = n.y;
633
+ pW[pi] = n.w;
634
+ pH[pi] = n.h;
635
+ pR[pi] = pnl.radius ?? 0;
636
+ pFc[pi] = pnl.fillColor ?? 1976635;
637
+ pFa[pi] = pnl.fillAlpha ?? 1;
638
+ pBc[pi] = pnl.borderColor ?? 0xffffff;
639
+ pBa[pi] = pnl.borderAlpha ?? (pnl.borderWidth ? 1 : 0);
640
+ pBw[pi] = pnl.borderWidth ?? 0;
641
+ pi++;
642
+ }
643
+ if (sp.icon && n.w > 0 && n.h > 0) {
644
+ const ic = sp.icon;
645
+ let img = iconPool[ii];
646
+ if (!img) {
647
+ img = scene.make.image(0, 0, ic.texture, ic.frame);
648
+ img.zIndex = 1;
649
+ container.add(img);
650
+ iconPool.push(img);
651
+ } else img.setTexture(ic.texture, ic.frame);
652
+ const iw = ic.w ?? n.w;
653
+ const ih = ic.h ?? n.h;
654
+ img.visible = true;
655
+ img.alpha = ic.alpha ?? 1;
656
+ img.setOrigin(.5, .5);
657
+ img.setDisplaySize(iw, ih);
658
+ if (ic.tint !== void 0) img.setTint(ic.tint);
659
+ img.x = n.x + n.w * .5;
660
+ img.y = n.y + n.h * .5;
661
+ img.trackId = null;
662
+ ii++;
663
+ }
664
+ if (sp.text != null && n.w > 0 && n.h > 0) {
665
+ const tSpec = typeof sp.text === "string" ? { content: sp.text } : sp.text;
666
+ let txt = textPool[ti];
667
+ if (!txt) {
668
+ txt = scene.make.text(0, 0, tSpec.content, tSpec.style);
669
+ txt.zIndex = 2;
670
+ container.add(txt);
671
+ textPool.push(txt);
672
+ } else {
673
+ if (tSpec.style && typeof txt.setStyle === "function") txt.setStyle(tSpec.style);
674
+ txt.setText(tSpec.content);
675
+ }
676
+ txt.visible = true;
677
+ const hAlign = tSpec.align ?? "center";
678
+ const vAlign = tSpec.vAlign ?? "center";
679
+ const ox = hAlign === "left" ? 0 : hAlign === "right" ? 1 : .5;
680
+ const oy = vAlign === "top" ? 0 : vAlign === "bottom" ? 1 : .5;
681
+ txt.setOrigin(ox, oy);
682
+ const [padT, padR, padB, padL] = resolvePadding(sp.padding);
683
+ const baseX = hAlign === "left" ? n.x + padL : hAlign === "right" ? n.x + n.w - padR : n.x + n.w * .5;
684
+ const baseY = vAlign === "top" ? n.y + padT : vAlign === "bottom" ? n.y + n.h - padB : n.y + n.h * .5;
685
+ txt.x = Math.round(baseX + (tSpec.offsetX ?? 0));
686
+ txt.y = Math.round(baseY + (tSpec.offsetY ?? 0));
687
+ txt.trackId = null;
688
+ ti++;
689
+ }
690
+ if (n.trackId && typeof scene.make.rectangle === "function" && n.w > 0 && n.h > 0) {
691
+ let hit = trackPool[ki];
692
+ if (!hit) {
693
+ hit = scene.make.rectangle(n.x, n.y, n.w, n.h, 0, 0);
694
+ hit.setOrigin(0, 0);
695
+ container.add(hit);
696
+ trackPool.push(hit);
697
+ }
698
+ hit.visible = true;
699
+ hit.x = n.x;
700
+ hit.y = n.y;
701
+ hit.width = n.w;
702
+ hit.height = n.h;
703
+ hit.trackId = n.trackId;
704
+ ki++;
705
+ }
706
+ }
707
+ for (let j = ti; j < textPool.length; j++) textPool[j].visible = false;
708
+ for (let j = ii; j < iconPool.length; j++) iconPool[j].visible = false;
709
+ for (let j = ki; j < trackPool.length; j++) {
710
+ trackPool[j].visible = false;
711
+ trackPool[j].trackId = null;
712
+ }
713
+ shapeBatch.setColumns({
714
+ count: pi,
715
+ x: pX,
716
+ y: pY,
717
+ width: pW,
718
+ height: pH,
719
+ radius: pR,
720
+ fillColor: pFc,
721
+ fillAlpha: pFa,
722
+ borderColor: pBc,
723
+ borderAlpha: pBa,
724
+ borderWidth: pBw
725
+ });
726
+ };
727
+ const hitTest = (x, y, interactiveOnly = false) => {
728
+ if (!container.visible) return null;
729
+ const nodes = currentTree.nodes;
730
+ for (let i = nodes.length - 1; i >= 0; i--) {
731
+ const n = nodes[i];
732
+ if (!n.visible || n.w <= 0 || n.h <= 0) continue;
733
+ if (interactiveOnly && typeof n.spec.onClick !== "function") continue;
734
+ if (x >= n.x && x <= n.x + n.w && y >= n.y && y <= n.y + n.h) return n;
735
+ }
736
+ return null;
737
+ };
738
+ const dispatchClick = (x, y, button = 0) => {
739
+ if (!container.visible) return false;
740
+ if (options.canInteract && !options.canInteract()) return false;
741
+ const hit = hitTest(x, y, true);
742
+ if (!hit || typeof hit.spec.onClick !== "function") return false;
743
+ hit.spec.onClick(hit, {
744
+ x,
745
+ y,
746
+ button
747
+ });
748
+ return true;
749
+ };
750
+ const onPointerDown = (p) => {
751
+ dispatchClick(p.x, p.y, p.button ?? 0);
752
+ };
753
+ if (options.interactive !== false && scene.input) scene.input.on("pointerdown", onPointerDown);
754
+ const relayout = (nextRoot = rootSpec, nextX = origX, nextY = origY) => {
755
+ rootSpec = nextRoot;
756
+ origX = nextX;
757
+ origY = nextY;
758
+ const tree = flattenFlexTree(rootSpec, origX, origY);
759
+ applyTree(tree);
760
+ return tree;
761
+ };
762
+ relayout(initialRoot, origX, origY);
763
+ return {
764
+ container,
765
+ get tree() {
766
+ return currentTree;
767
+ },
768
+ rectOf: (id) => currentTree.byId.get(id),
769
+ hitTest,
770
+ dispatchClick,
771
+ relayout,
772
+ destroy: () => {
773
+ if (options.interactive !== false && scene.input) scene.input.off("pointerdown", onPointerDown);
774
+ container.destroy(true);
775
+ }
776
+ };
777
+ }
778
+ export { computeFlexLayout, computeWrapLayout, flattenFlexTree, mountFlexUi, resolvePadding };
@@ -1,8 +1,9 @@
1
1
  import { _ as rgbToCss, a as EventEmitter, c as Scale, h as packColorAbgr, l as Scenes, m as createMatrix2D, o as FilterMode, p as WHITE_RGB, r as BlendModes, u as TintModes } from "./types-CXsCvp1p.js";
2
2
  import { AnimationManager } from "./anims.js";
3
3
  import { i as Camera, r as Renderer2D, t as RendererWebGpu } from "./renderer-webgpu-CHJxmCvR.js";
4
- import { c as InstancedBatchObject, d as PanelObject, f as RectangleObject, g as TileSpriteObject, h as TextObject, i as DisplayList, l as MsdfIconObject, m as SpriteObject, n as Container, o as Graphics, p as ShapeBatchObject, r as CustomPassObject, s as ImageObject, t as BlitterObject, u as NineSliceObject } from "./display-DU4edtH-.js";
4
+ import { _ as TileSpriteObject, c as ImageObject, d as NineSliceObject, f as PanelObject, g as TextObject, h as SpriteObject, i as DisplayList, l as InstancedBatchObject, m as ShapeBatchObject, n as Container, o as DrawStreamObject, p as RectangleObject, r as CustomPassObject, s as Graphics, t as BlitterObject, u as MsdfIconObject } from "./display-CuyQc8oE.js";
5
5
  import { TweenManager } from "./tween.js";
6
+ import { ScriptScheduler } from "./coroutine.js";
6
7
  import { StageKernel } from "./kernel.js";
7
8
  // src/texture.ts
8
9
  var TextureSource = class TextureSource {
@@ -77,6 +78,8 @@ var Frame = class {
77
78
  name;
78
79
  sourceIndex;
79
80
  source;
81
+ /** Dense 0-based registration index inside `texture.frameList` (enables O(1) numeric IDs via `texture.frameIdOf(name)`). */
82
+ index = 0;
80
83
  cutX = 0;
81
84
  cutY = 0;
82
85
  cutWidth = 0;
@@ -210,6 +213,7 @@ var Texture = class {
210
213
  key;
211
214
  source;
212
215
  frames = Object.create(null);
216
+ frameList = [];
213
217
  /** Optional isometric camera azimuth (`yaw` in radians, e.g. `Math.PI / 4` from `@holtjs/craft/three`) used by `SpriteObject.playDirectional()`. */
214
218
  atlasYaw = null;
215
219
  atlasPitch = null;
@@ -223,13 +227,35 @@ var Texture = class {
223
227
  }
224
228
  add(name, sourceIndex, x, y, width, height, meta) {
225
229
  const frame = new Frame(this, name, sourceIndex, x, y, width, height, meta);
226
- this.frames[String(name)] = frame;
230
+ const key = String(name);
231
+ const prev = this.frames[key];
232
+ if (prev) {
233
+ frame.index = prev.index;
234
+ this.frameList[prev.index] = frame;
235
+ } else {
236
+ frame.index = this.frameList.length;
237
+ this.frameList.push(frame);
238
+ }
239
+ this.frames[key] = frame;
227
240
  return frame;
228
241
  }
242
+ /**
243
+ * Resolve a stable negative integer frame handle (`-1 - frame.index`) usable directly in
244
+ * `InstancedColumns.frameIndex` and `DrawStreamObject` across WebGL2, WebGPU, and Canvas2D!
245
+ */
246
+ frameIdOf(name = "__BASE") {
247
+ if (typeof name === "number" && name < 0) return name;
248
+ return -1 - this.get(name).index;
249
+ }
229
250
  has(name) {
251
+ if (typeof name === "number" && name < 0) {
252
+ const idx = -1 - name;
253
+ return idx >= 0 && idx < this.frameList.length;
254
+ }
230
255
  return Object.prototype.hasOwnProperty.call(this.frames, String(name));
231
256
  }
232
257
  get(name = "__BASE") {
258
+ if (typeof name === "number" && name < 0) return this.frameList[-1 - name] ?? this.frames["__BASE"];
233
259
  const key = String(name);
234
260
  return this.frames[key] ?? this.frames["__BASE"];
235
261
  }
@@ -5170,6 +5196,10 @@ var GameObjectFactory = class {
5170
5196
  instancedBatch(key, maxCount = 1024, frame) {
5171
5197
  return this.register(new InstancedBatchObject(this.scene, key, maxCount, frame));
5172
5198
  }
5199
+ /** Create an immediate-mode per-frame `DrawStreamObject` (`sprite()` / `writeBulk()`). */
5200
+ drawStream(key, options) {
5201
+ return this.register(new DrawStreamObject(this.scene, key, options));
5202
+ }
5173
5203
  /** Create a zero-texture GPU analytical SDF shape batch (`circles`, `rings`, `pills`, `rounded rects`). */
5174
5204
  shapeBatch(maxCount = 1024, defaults) {
5175
5205
  return this.register(new ShapeBatchObject(this.scene, maxCount, defaults));
@@ -5272,6 +5302,9 @@ var Scene = class {
5272
5302
  events = new EventEmitter();
5273
5303
  /** Deterministic EngineClock-driven tween & spring manager (auto-stepped in `Game.step()`). */
5274
5304
  tweens = new TweenManager();
5305
+ /** Deterministic EngineClock-driven generator coroutine scheduler (`scene.script(function* (co) { ... })`). */
5306
+ scripts = new ScriptScheduler(this.tweens);
5307
+ _drawStreams = /* @__PURE__ */ new Map();
5275
5308
  _animatedSprites = /* @__PURE__ */ new Set();
5276
5309
  _equippedSprites = /* @__PURE__ */ new Set();
5277
5310
  _nodesCreated = 0;
@@ -5356,6 +5389,27 @@ var Scene = class {
5356
5389
  tweenStats() {
5357
5390
  return this.tweens.stats();
5358
5391
  }
5392
+ /** Launch a deterministic EngineClock-driven generator coroutine (`function* (co) { yield* co.wait(0.35); ... }`). */
5393
+ script(fn, options) {
5394
+ return this.scripts.run(fn, options);
5395
+ }
5396
+ /** Lightweight active/completed/cancelled coroutine counters. */
5397
+ scriptStats() {
5398
+ return this.scripts.stats();
5399
+ }
5400
+ /**
5401
+ * Acquire (or lazily create) a memoized immediate-mode `DrawStreamObject` keyed by `(textureKey, opts?.streamId ?? 'default')`.
5402
+ * Safe to call directly inside `update()` or `preRender()` every frame with zero node allocation!
5403
+ */
5404
+ drawStream(key, options) {
5405
+ const mapKey = `${key}::${options?.streamId ?? "default"}`;
5406
+ let stream = this._drawStreams.get(mapKey);
5407
+ if (!stream || !stream.active) {
5408
+ stream = this.add.drawStream(key, options);
5409
+ this._drawStreams.set(mapKey, stream);
5410
+ }
5411
+ return stream;
5412
+ }
5359
5413
  _registerAnimatedSprite(sprite) {
5360
5414
  this._animatedSprites.add(sprite);
5361
5415
  }
@@ -5404,6 +5458,8 @@ var Scene = class {
5404
5458
  } catch {}
5405
5459
  this._animatedSprites.clear();
5406
5460
  this._equippedSprites.clear();
5461
+ this._drawStreams.clear();
5462
+ this.scripts.clear();
5407
5463
  this.tweens.clear();
5408
5464
  }
5409
5465
  };
@@ -5662,6 +5718,7 @@ var Game = class {
5662
5718
  if (sc.sys.settings.status === Scenes.RUNNING) {
5663
5719
  sc.events.emit("preupdate", time, delta);
5664
5720
  if (sc.tweens.hasActive) sc.tweens.step(this.clock.lastDeltaMs);
5721
+ if (sc.scripts.hasActive) sc.scripts.step(this.clock.lastDeltaMs);
5665
5722
  sc._stepAnimations(this.clock.lastDeltaMs);
5666
5723
  sc.update?.(time, delta);
5667
5724
  this.kernel._updateScene(sc, time, delta);