@flare-engine/react 0.2.0 → 0.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.
package/dist/index.js CHANGED
@@ -1,549 +1,761 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- GameContext: () => GameContext,
24
- GameView: () => GameView,
25
- LoadingScreen: () => LoadingScreen,
26
- SafeAreaContext: () => SafeAreaContext,
27
- VirtualButton: () => VirtualButton,
28
- VirtualJoystick: () => VirtualJoystick,
29
- createSkiaFrameRenderer: () => createSkiaFrameRenderer,
30
- renderShapesToImage: () => renderShapesToImage,
31
- useCountUp: () => useCountUp,
32
- useEntity: () => useEntity,
33
- useGame: () => useGame,
34
- useGameLoop: () => useGameLoop,
35
- useOverlayFade: () => useOverlayFade,
36
- useSafeArea: () => useSafeArea,
37
- useSignalState: () => useSignalState
38
- });
39
- module.exports = __toCommonJS(index_exports);
40
-
41
- // src/game-context.ts
42
- var import_react = require("react");
43
- var GameContext = (0, import_react.createContext)(null);
44
-
45
- // src/game-view.tsx
46
- var import_assets = require("@flare-engine/assets");
47
- var import_audio = require("@flare-engine/audio");
48
- var import_core = require("@flare-engine/core");
49
- var import_ecs = require("@flare-engine/ecs");
50
- var import_input = require("@flare-engine/input");
51
- var import_render2 = require("@flare-engine/render");
52
- var import_scene = require("@flare-engine/scene");
53
- var import_react_native_skia = require("@shopify/react-native-skia");
54
- var import_react3 = require("react");
55
- var import_react_native = require("react-native");
56
- var import_react_native_safe_area_context = require("react-native-safe-area-context");
57
-
58
- // src/safe-area.ts
59
- var import_react2 = require("react");
60
- var SafeAreaContext = (0, import_react2.createContext)(null);
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let react = require("react");
3
+ let _flare_engine_assets = require("@flare-engine/assets");
4
+ let _flare_engine_audio = require("@flare-engine/audio");
5
+ let _flare_engine_core = require("@flare-engine/core");
6
+ let _flare_engine_ecs = require("@flare-engine/ecs");
7
+ let _flare_engine_input = require("@flare-engine/input");
8
+ let _flare_engine_render = require("@flare-engine/render");
9
+ let _flare_engine_scene = require("@flare-engine/scene");
10
+ let _shopify_react_native_skia = require("@shopify/react-native-skia");
11
+ let react_native = require("react-native");
12
+ let react_native_safe_area_context = require("react-native-safe-area-context");
13
+ let react_jsx_runtime = require("react/jsx-runtime");
14
+ let _flare_engine_math = require("@flare-engine/math");
15
+ //#region src/game-context.ts
16
+ /**
17
+ * React context that provides access to core game objects.
18
+ * Null if accessed outside a <GameView>.
19
+ */
20
+ const GameContext = (0, react.createContext)(null);
21
+ //#endregion
22
+ //#region src/safe-area.ts
23
+ const SafeAreaContext = (0, react.createContext)(null);
61
24
  function useSafeArea() {
62
- const value = (0, import_react2.useContext)(SafeAreaContext);
63
- if (value === null) {
64
- throw new Error("useSafeArea must be used inside a <GameView>");
65
- }
66
- return value;
25
+ const value = (0, react.useContext)(SafeAreaContext);
26
+ if (value === null) throw new Error("useSafeArea must be used inside a <GameView>");
27
+ return value;
67
28
  }
68
-
69
- // src/skia-bridge.ts
70
- var import_render = require("@flare-engine/render");
29
+ //#endregion
30
+ //#region src/scene-texture.ts
31
+ /**
32
+ * `Symbol.dispose` is not in this project's ES2022 lib, so the well-known
33
+ * symbol is looked up at runtime instead of written as a computed key.
34
+ */
35
+ const DISPOSE = Symbol.dispose;
36
+ function releaseSkiaObject(target) {
37
+ if (DISPOSE === void 0 || target === null || target === void 0) return;
38
+ const disposer = target[DISPOSE];
39
+ if (typeof disposer === "function") disposer.call(target);
40
+ }
41
+ /**
42
+ * Reuse one offscreen surface across frames instead of allocating per frame.
43
+ *
44
+ * On **web** this is a correctness requirement, not an optimisation. RN-Skia's
45
+ * web `MakeOffscreen` builds a fresh `OffscreenCanvas` and a fresh WebGL
46
+ * context on every call and releases neither; Chrome caps a page at 16 live
47
+ * WebGL contexts and evicts the oldest, which is the on-screen `<Canvas>`.
48
+ * A per-frame allocation therefore kills the visible canvas within ~16 frames
49
+ * while the game loop keeps running — the app looks alive and paints nothing.
50
+ * Measured and written up in docs/plans/web-target-2026-08.md §12.
51
+ */
52
+ function createSceneSurfaceCache(Skia) {
53
+ let surface = null;
54
+ let currentWidth = 0;
55
+ let currentHeight = 0;
56
+ const dispose = () => {
57
+ if (surface === null) return;
58
+ releaseSkiaObject(surface);
59
+ surface = null;
60
+ currentWidth = 0;
61
+ currentHeight = 0;
62
+ };
63
+ return {
64
+ acquire(width, height) {
65
+ if (width <= 0 || height <= 0) return null;
66
+ if (surface !== null && currentWidth === width && currentHeight === height) return surface;
67
+ dispose();
68
+ const next = Skia.Surface.MakeOffscreen(width, height);
69
+ if (next === null) return null;
70
+ surface = next;
71
+ currentWidth = width;
72
+ currentHeight = height;
73
+ return surface;
74
+ },
75
+ dispose
76
+ };
77
+ }
78
+ /**
79
+ * Capture the scene into a reused offscreen surface, releasing Skia objects as
80
+ * it goes.
81
+ *
82
+ * Two leaks have to be avoided here, and both were measured in a browser
83
+ * (docs/plans/web-target-2026-08.md §12):
84
+ *
85
+ * 1. **Per-frame surfaces.** RN-Skia's web `MakeOffscreen` builds an
86
+ * `OffscreenCanvas` + WebGL context per call and releases neither; Chrome
87
+ * caps a page at 16 live contexts and evicts the on-screen canvas. Hence the
88
+ * surface cache.
89
+ * 2. **Per-frame images.** `makeNonTextureImage()` reads the whole viewport back
90
+ * into the wasm heap. Leaving old CPU images unreleased exhausts that heap.
91
+ * A single-slot release strategy is not enough: RN-Skia's web `<Canvas>`
92
+ * paints on its own rAF, which fires *after* the capture, so the image handed
93
+ * to React on frame N is still in use when frame N+1 runs. Releasing it
94
+ * immediately causes `BindingError: Cannot pass deleted object as a pointer of
95
+ * type Image const*` from `JsiSkImage.width` every frame and a blank canvas.
96
+ * Measured at 2560×1215 / Chrome (WEB-3):
97
+ * hold=1 (one slot — what shipped at WEB-2) → blank, BindingError every frame
98
+ * hold=2 → blank
99
+ * hold=3 → 1378 frames, zero errors
100
+ * A FIFO ring of depth 3 is the measured minimum.
101
+ *
102
+ * The snapshot is released as soon as it has been copied. Frame images are
103
+ * released once the ring exceeds depth 3, ensuring the canvas's rAF always has
104
+ * a live image to paint from.
105
+ */
106
+ const RETENTION_DEPTH = 3;
107
+ function createSceneCapture(Skia) {
108
+ const surfaces = createSceneSurfaceCache(Skia);
109
+ const ring = [];
110
+ return {
111
+ capture(picture, width, height) {
112
+ const surface = surfaces.acquire(width, height);
113
+ if (surface === null) return null;
114
+ surface.getCanvas().drawPicture(picture);
115
+ surface.flush();
116
+ const snapshot = surface.makeImageSnapshot();
117
+ const detachable = snapshot;
118
+ const detached = detachable.makeNonTextureImage ? detachable.makeNonTextureImage() : snapshot;
119
+ if (detached !== snapshot) releaseSkiaObject(snapshot);
120
+ ring.push(detached);
121
+ if (ring.length > RETENTION_DEPTH) releaseSkiaObject(ring.shift());
122
+ return detached;
123
+ },
124
+ dispose() {
125
+ for (const img of ring) releaseSkiaObject(img);
126
+ ring.length = 0;
127
+ surfaces.dispose();
128
+ }
129
+ };
130
+ }
131
+ /**
132
+ * Web scene texture (imperative form): expose a `capture` callback that
133
+ * `GameView`'s `onPreRender` frame callback invokes directly instead of pushing
134
+ * a picture through React state.
135
+ *
136
+ * The previous reactive form called `setImage` from a `useEffect` keyed on
137
+ * `[Skia, picture, width, height]`. `onPreRender` would call `setPicture`,
138
+ * React would re-render, the effect would re-run, `setImage` would re-render
139
+ * again. That is a setState-in-a-passive-effect cascade; React's
140
+ * NESTED_PASSIVE_UPDATE_LIMIT (50) trips and logs `Maximum update depth
141
+ * exceeded` on every web load. It also costs two React renders per frame and
142
+ * delays the captured image by two hops.
143
+ *
144
+ * `GameLoop` schedules via `requestAnimationFrame`, so calling `setImage`
145
+ * directly from `onPreRender` is an ordinary root update that never touches the
146
+ * passive-update counter. Both hooks still run on both platforms so hook order
147
+ * never varies, but this hook is now inert on native simply because nothing
148
+ * calls `capture` on that platform.
149
+ *
150
+ * `makeNonTextureImage()` is required regardless of reuse: the offscreen surface
151
+ * has its own WebGL context, and a texture-backed image cannot be sampled by the
152
+ * on-screen canvas's context. It also makes reuse safe — the snapshot is copied
153
+ * off the GPU so next frame's draw into the same surface cannot disturb the image
154
+ * React still holds.
155
+ *
156
+ * The surface is never cleared here: `Renderer.begin()` records
157
+ * `canvas.clear(clearColor)` into the picture itself (packages/render
158
+ * `renderer.ts:75`), so replaying the picture repaints the full surface.
159
+ */
160
+ function useWebSceneTexture(Skia) {
161
+ const captureRef = (0, react.useRef)(null);
162
+ const [image, setImage] = (0, react.useState)(null);
163
+ (0, react.useEffect)(() => {
164
+ return () => {
165
+ captureRef.current?.dispose();
166
+ captureRef.current = null;
167
+ };
168
+ }, []);
169
+ return {
170
+ image,
171
+ capture: (0, react.useCallback)((picture, width, height) => {
172
+ if (picture === null || picture === void 0) return;
173
+ if (captureRef.current === null) captureRef.current = createSceneCapture(Skia);
174
+ const next = captureRef.current.capture(picture, width, height);
175
+ if (next !== null) setImage(next);
176
+ }, [Skia])
177
+ };
178
+ }
179
+ //#endregion
180
+ //#region src/skia-bridge.ts
181
+ /**
182
+ * Take a snapshot of `surface` and detach it from the GPU context so it can
183
+ * be safely sampled from a different GrDirectContext (e.g. the on-screen
184
+ * Canvas). RN-Skia's MakeOffscreen allocates a private Gr context per
185
+ * surface; without this step Skia silently renders black when the texture is
186
+ * read from any other context.
187
+ *
188
+ * Calls `makeNonTextureImage()` when available (RN-Skia ≥ 0.1 on device).
189
+ * Falls back to the raw snapshot when the method is absent (CPU surfaces,
190
+ * test mocks) — no behavioural change in those paths.
191
+ */
71
192
  function detachSnapshot(surface) {
72
- const snap = surface.makeImageSnapshot();
73
- if (typeof snap.makeNonTextureImage === "function") {
74
- return snap.makeNonTextureImage();
75
- }
76
- return snap;
193
+ const snap = surface.makeImageSnapshot();
194
+ if (typeof snap.makeNonTextureImage === "function") return snap.makeNonTextureImage();
195
+ return snap;
77
196
  }
78
- function createSkiaFrameRenderer(Skia2) {
79
- return (0, import_render.createFrameRenderer)(Skia2);
197
+ /**
198
+ * Create a `SkiaFrameRenderer`.
199
+ *
200
+ * `Skia` is passed in (rather than imported) so unit tests can supply a
201
+ * mock. Production code constructs this once inside `<GameView>` using the
202
+ * real `Skia` import from `@shopify/react-native-skia`.
203
+ *
204
+ * Delegates to `createFrameRenderer` from `@flare-engine/render` — the
205
+ * frame-renderer body is backend-neutral and shared with render-web.
206
+ */
207
+ function createSkiaFrameRenderer(Skia) {
208
+ return (0, _flare_engine_render.createFrameRenderer)(Skia);
80
209
  }
210
+ /**
211
+ * Render a list of solid rectangles into a fresh offscreen surface and return
212
+ * the resulting image snapshot. Returns `null` if `Surface` factory is absent or
213
+ * fails. The surface is not cached — callers that need reuse should cache the
214
+ * returned image themselves.
215
+ */
81
216
  function renderShapesToImage(skia, opts) {
82
- if (skia.Surface === void 0) return null;
83
- const surface = skia.Surface.Make(opts.width, opts.height);
84
- if (surface === null) return null;
85
- const scratch = new Float32Array(4);
86
- const canvas = surface.getCanvas();
87
- unpackArgb(scratch, opts.clearColor);
88
- canvas.clear(scratch);
89
- const paint = skia.Paint();
90
- for (const shape of opts.shapes) {
91
- unpackArgb(scratch, shape.color);
92
- if (paint.setColor) paint.setColor(scratch);
93
- const rect = skia.XYWHRect(shape.x, shape.y, shape.w, shape.h);
94
- canvas.drawRect(rect, paint);
95
- }
96
- return detachSnapshot(surface);
217
+ if (skia.Surface === void 0) return null;
218
+ const surface = skia.Surface.Make(opts.width, opts.height);
219
+ if (surface === null) return null;
220
+ const scratch = /* @__PURE__ */ new Float32Array(4);
221
+ const canvas = surface.getCanvas();
222
+ unpackArgb(scratch, opts.clearColor);
223
+ canvas.clear(scratch);
224
+ const paint = skia.Paint();
225
+ for (const shape of opts.shapes) {
226
+ unpackArgb(scratch, shape.color);
227
+ if (paint.setColor) paint.setColor(scratch);
228
+ const rect = skia.XYWHRect(shape.x, shape.y, shape.w, shape.h);
229
+ canvas.drawRect(rect, paint);
230
+ }
231
+ return detachSnapshot(surface);
97
232
  }
233
+ /** Unpack a 0xAARRGGBB integer into a Float32Array [r, g, b, a] in 0..1 range. */
98
234
  function unpackArgb(out, argb) {
99
- out[0] = (argb >>> 16 & 255) / 255;
100
- out[1] = (argb >>> 8 & 255) / 255;
101
- out[2] = (argb & 255) / 255;
102
- out[3] = (argb >>> 24 & 255) / 255;
235
+ out[0] = (argb >>> 16 & 255) / 255;
236
+ out[1] = (argb >>> 8 & 255) / 255;
237
+ out[2] = (argb & 255) / 255;
238
+ out[3] = (argb >>> 24 & 255) / 255;
103
239
  }
104
-
105
- // src/game-view.tsx
106
- var import_jsx_runtime = require("react/jsx-runtime");
107
- function GameView({
108
- config,
109
- onReady,
110
- style,
111
- children,
112
- safeArea
113
- }) {
114
- const insets = (0, import_react_native_safe_area_context.useSafeAreaInsets)();
115
- const resolvedSafeArea = safeArea ?? insets;
116
- const canvasRef = (0, import_react_native_skia.useCanvasRef)();
117
- const [picture, setPicture] = (0, import_react3.useState)(null);
118
- const [passes, setPasses] = (0, import_react3.useState)([]);
119
- const [viewportSize, setViewportSize] = (0, import_react3.useState)({ w: 0, h: 0 });
120
- const pd = import_react_native.PixelRatio.get();
121
- const sceneSize = (0, import_react3.useMemo)(
122
- () => ({ width: viewportSize.w * pd, height: viewportSize.h * pd }),
123
- [viewportSize.w, viewportSize.h, pd]
124
- );
125
- const sceneTexture = (0, import_react_native_skia.usePictureAsTexture)(picture, sceneSize);
126
- const ctx = (0, import_react3.useMemo)(() => {
127
- const loop = new import_core.GameLoop({
128
- fixedDt: config?.fixedDt,
129
- maxDt: config?.maxDt
130
- });
131
- const world = new import_ecs.World();
132
- const camera = new import_render2.Camera2D();
133
- const input = new import_input.InputManager();
134
- const audio = new import_audio.AudioManager();
135
- const noop = () => Promise.resolve(null);
136
- const assets = new import_assets.AssetManager(config?.assetLoader ?? noop);
137
- const scenes = new import_scene.SceneManager();
138
- const renderer = new import_render2.Renderer();
139
- const batch = new import_render2.SpriteBatch();
140
- return { world, camera, input, audio, assets, scenes, loop, renderer, batch };
141
- }, []);
142
- (0, import_react3.useEffect)(() => {
143
- const bridge = createSkiaFrameRenderer(import_react_native_skia.Skia);
144
- ctx.renderer.setCanvas(bridge.canvas);
145
- const clearColor = config?.clearColor ?? 4278190080;
146
- const onRenderBackground = config?.onRenderBackground;
147
- const onRenderPostFx = config?.onRenderPostFx;
148
- const spriteQuery = ctx.world.query(import_ecs.Position, import_render2.Sprite);
149
- const renderSystem = (0, import_render2.createRenderSystem)(ctx.world, spriteQuery, import_ecs.Position, import_render2.Sprite, ctx.batch);
150
- const unsubscribeLate = ctx.loop.onLateUpdate.add((dt) => {
151
- ctx.camera.update(dt);
152
- ctx.input.update();
153
- });
154
- const unsubscribePre = ctx.loop.onPreRender.add(() => {
155
- const w = ctx.camera.viewportWidth;
156
- const h = ctx.camera.viewportHeight;
157
- bridge.beginFrame(w, h, 0, pd);
158
- ctx.renderer.begin(clearColor);
159
- ctx.renderer.applyCamera(
160
- ctx.camera.effectiveX,
161
- ctx.camera.effectiveY,
162
- ctx.camera.zoom,
163
- ctx.camera.rotation,
164
- w,
165
- h
166
- );
167
- if (onRenderBackground) onRenderBackground(ctx, ctx.renderer.canvas);
168
- renderSystem();
169
- ctx.batch.flush(bridge.drawAtlas, ctx.renderer);
170
- if (onRenderPostFx) onRenderPostFx(ctx, ctx.renderer.canvas, bridge);
171
- ctx.renderer.end();
172
- const pic = bridge.endFrame();
173
- if (pic !== null) setPicture(pic);
174
- const built = bridge.buildPostFxPasses(null, null, w, h);
175
- setPasses(built);
176
- canvasRef.current?.redraw();
177
- });
178
- onReady?.(ctx);
179
- ctx.loop.start();
180
- return () => {
181
- unsubscribeLate();
182
- unsubscribePre();
183
- ctx.loop.stop();
184
- };
185
- }, []);
186
- const handleLayout = (event) => {
187
- const { width, height } = event.nativeEvent.layout;
188
- ctx.camera.setViewport(width, height);
189
- setViewportSize({ w: width, h: height });
190
- };
191
- const onGrant = (e) => {
192
- ctx.input.onPointerDown(0, e.nativeEvent.locationX, e.nativeEvent.locationY);
193
- };
194
- const onMove = (e) => {
195
- ctx.input.onPointerMove(0, e.nativeEvent.locationX, e.nativeEvent.locationY);
196
- };
197
- const onRelease = (e) => {
198
- ctx.input.onPointerUp(0, e.nativeEvent.locationX, e.nativeEvent.locationY);
199
- };
200
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SafeAreaContext.Provider, { value: resolvedSafeArea, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(GameContext.Provider, { value: ctx, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
201
- import_react_native.View,
202
- {
203
- style: [styles.container, style],
204
- onLayout: handleLayout,
205
- onStartShouldSetResponder: returnTrue,
206
- onResponderGrant: onGrant,
207
- onResponderMove: onMove,
208
- onResponderRelease: onRelease,
209
- onResponderTerminate: onRelease,
210
- children: [
211
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
212
- import_react_native_skia.Canvas,
213
- {
214
- ref: canvasRef,
215
- style: import_react_native.StyleSheet.absoluteFill,
216
- pointerEvents: "none",
217
- opaque: config?.opaque ?? false,
218
- children: viewportSize.w === 0 || sceneTexture == null ? null : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
219
- import_react_native_skia.Image,
220
- {
221
- image: sceneTexture,
222
- x: 0,
223
- y: 0,
224
- width: viewportSize.w,
225
- height: viewportSize.h,
226
- fit: "cover",
227
- children: passes.map((p) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_native_skia.RuntimeShader, { source: p.source, uniforms: p.uniforms }, p.id))
228
- }
229
- )
230
- }
231
- ),
232
- children
233
- ]
234
- }
235
- ) }) });
240
+ //#endregion
241
+ //#region src/game-view.tsx
242
+ /**
243
+ * GameView — root component that sets up the Skia canvas, game loop,
244
+ * and all core game systems. Provides GameContext to descendants.
245
+ *
246
+ * Overlay controls (VirtualJoystick, VirtualButton) should be placed
247
+ * as children; they render on top of the Skia canvas.
248
+ */
249
+ function GameView({ config, onReady, style, children, safeArea }) {
250
+ const insets = (0, react_native_safe_area_context.useSafeAreaInsets)();
251
+ const resolvedSafeArea = safeArea ?? insets;
252
+ const canvasRef = (0, _shopify_react_native_skia.useCanvasRef)();
253
+ const [picture, setPicture] = (0, react.useState)(null);
254
+ const [passes, setPasses] = (0, react.useState)(EMPTY_PASSES);
255
+ const [viewportSize, setViewportSize] = (0, react.useState)({
256
+ w: 0,
257
+ h: 0
258
+ });
259
+ const pd = react_native.PixelRatio.get();
260
+ const sceneSize = (0, react.useMemo)(() => ({
261
+ width: viewportSize.w * pd,
262
+ height: viewportSize.h * pd
263
+ }), [
264
+ viewportSize.w,
265
+ viewportSize.h,
266
+ pd
267
+ ]);
268
+ const isWeb = react_native.Platform.OS === "web";
269
+ const nativeTexture = (0, _shopify_react_native_skia.usePictureAsTexture)(isWeb ? null : picture, sceneSize);
270
+ const { image: webTexture, capture: captureWebScene } = useWebSceneTexture(_shopify_react_native_skia.Skia);
271
+ const sceneTexture = isWeb ? webTexture : nativeTexture;
272
+ const ctx = (0, react.useMemo)(() => {
273
+ const loop = new _flare_engine_core.GameLoop({
274
+ fixedDt: config?.fixedDt,
275
+ maxDt: config?.maxDt
276
+ });
277
+ const world = new _flare_engine_ecs.World();
278
+ const camera = new _flare_engine_render.Camera2D();
279
+ const input = new _flare_engine_input.InputManager();
280
+ const audio = new _flare_engine_audio.AudioManager();
281
+ const noop = () => Promise.resolve(null);
282
+ return {
283
+ world,
284
+ camera,
285
+ input,
286
+ audio,
287
+ assets: new _flare_engine_assets.AssetManager(config?.assetLoader ?? noop),
288
+ scenes: new _flare_engine_scene.SceneManager(),
289
+ loop,
290
+ renderer: new _flare_engine_render.Renderer(),
291
+ batch: new _flare_engine_render.SpriteBatch()
292
+ };
293
+ }, []);
294
+ const webPostFxWarnedRef = (0, react.useRef)(false);
295
+ (0, react.useEffect)(() => {
296
+ const bridge = createSkiaFrameRenderer(_shopify_react_native_skia.Skia);
297
+ ctx.renderer.setCanvas(bridge.canvas);
298
+ const clearColor = config?.clearColor ?? 4278190080;
299
+ const onRenderBackground = config?.onRenderBackground;
300
+ const onRenderPostFx = config?.onRenderPostFx;
301
+ const spriteQuery = ctx.world.query(_flare_engine_ecs.Position, _flare_engine_render.Sprite);
302
+ const renderSystem = (0, _flare_engine_render.createRenderSystem)(ctx.world, spriteQuery, _flare_engine_ecs.Position, _flare_engine_render.Sprite, ctx.batch);
303
+ let prevBuilt = EMPTY_PASSES;
304
+ const unsubscribeLate = ctx.loop.onLateUpdate.add((dt) => {
305
+ ctx.camera.update(dt);
306
+ ctx.input.update();
307
+ });
308
+ const unsubscribePre = ctx.loop.onPreRender.add(() => {
309
+ const w = ctx.camera.viewportWidth;
310
+ const h = ctx.camera.viewportHeight;
311
+ bridge.beginFrame(w, h, ctx.loop.clock.elapsed, pd);
312
+ ctx.renderer.begin(clearColor);
313
+ ctx.renderer.applyCamera(ctx.camera.effectiveX, ctx.camera.effectiveY, ctx.camera.zoom, ctx.camera.rotation, w, h);
314
+ if (onRenderBackground) onRenderBackground(ctx, ctx.renderer.canvas);
315
+ renderSystem();
316
+ ctx.batch.flush(bridge.drawAtlas, ctx.renderer);
317
+ if (onRenderPostFx) onRenderPostFx(ctx, ctx.renderer.canvas, bridge);
318
+ ctx.renderer.end();
319
+ const pic = bridge.endFrame();
320
+ if (pic !== null) if (isWeb) captureWebScene(pic, w * pd, h * pd);
321
+ else setPicture(pic);
322
+ if (!isWeb) {
323
+ const built = bridge.buildPostFxPasses(null, null, w, h);
324
+ if (!samePasses(prevBuilt, built)) {
325
+ prevBuilt = built.length === 0 ? EMPTY_PASSES : built;
326
+ setPasses(prevBuilt);
327
+ }
328
+ } else if (bridge.hasPostFxBinding() && !webPostFxWarnedRef.current) {
329
+ console.warn("postfx chain skipped: Skia.RuntimeShaderBuilder and ImageFilter.MakeRuntimeShaderWithChildren both throw \"Not implemented on React Native Web\".");
330
+ webPostFxWarnedRef.current = true;
331
+ }
332
+ canvasRef.current?.redraw();
333
+ });
334
+ onReady?.(ctx);
335
+ ctx.loop.start();
336
+ return () => {
337
+ unsubscribeLate();
338
+ unsubscribePre();
339
+ ctx.loop.stop();
340
+ };
341
+ }, []);
342
+ const handleLayout = (0, react.useCallback)((event) => {
343
+ const { width, height } = event.nativeEvent.layout;
344
+ ctx.camera.setViewport(width, height);
345
+ setViewportSize({
346
+ w: width,
347
+ h: height
348
+ });
349
+ }, [ctx]);
350
+ const onGrant = (0, react.useCallback)((e) => {
351
+ ctx.input.onPointerDown(0, e.nativeEvent.locationX, e.nativeEvent.locationY);
352
+ }, [ctx]);
353
+ const onMove = (0, react.useCallback)((e) => {
354
+ ctx.input.onPointerMove(0, e.nativeEvent.locationX, e.nativeEvent.locationY);
355
+ }, [ctx]);
356
+ const onRelease = (0, react.useCallback)((e) => {
357
+ ctx.input.onPointerUp(0, e.nativeEvent.locationX, e.nativeEvent.locationY);
358
+ }, [ctx]);
359
+ const containerStyle = (0, react.useMemo)(() => [styles$3.container, style], [style]);
360
+ const passElements = (0, react.useMemo)(() => passes.map((p) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_shopify_react_native_skia.RuntimeShader, {
361
+ source: p.source,
362
+ uniforms: p.uniforms
363
+ }, p.id)), [passes]);
364
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SafeAreaContext.Provider, {
365
+ value: resolvedSafeArea,
366
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GameContext.Provider, {
367
+ value: ctx,
368
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_native.View, {
369
+ style: containerStyle,
370
+ onLayout: handleLayout,
371
+ onStartShouldSetResponder: returnTrue$2,
372
+ onResponderGrant: onGrant,
373
+ onResponderMove: onMove,
374
+ onResponderRelease: onRelease,
375
+ onResponderTerminate: onRelease,
376
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_shopify_react_native_skia.Canvas, {
377
+ ref: canvasRef,
378
+ style: react_native.StyleSheet.absoluteFill,
379
+ pointerEvents: "none",
380
+ opaque: config?.opaque ?? false,
381
+ children: viewportSize.w === 0 || sceneTexture == null ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_shopify_react_native_skia.Image, {
382
+ image: sceneTexture,
383
+ x: 0,
384
+ y: 0,
385
+ width: viewportSize.w,
386
+ height: viewportSize.h,
387
+ fit: "cover",
388
+ children: passElements
389
+ })
390
+ }), children]
391
+ })
392
+ })
393
+ });
236
394
  }
237
- function returnTrue() {
238
- return true;
395
+ function returnTrue$2() {
396
+ return true;
239
397
  }
240
- var styles = import_react_native.StyleSheet.create({
241
- container: { flex: 1 }
242
- });
243
-
244
- // src/hooks.ts
245
- var import_react4 = require("react");
246
- function useGame() {
247
- const ctx = (0, import_react4.useContext)(GameContext);
248
- if (!ctx) {
249
- throw new Error("useGame must be used inside a <GameView>");
250
- }
251
- return ctx;
398
+ /** Stable empty-chain reference — an empty `buildPostFxPasses` result collapses
399
+ * to this so the `passes` state never changes for a postfx-free GameView. */
400
+ const EMPTY_PASSES = [];
401
+ /**
402
+ * Shallow structural equality of two pass lists. The signature is length +
403
+ * per-pass `id` + shader ref + child-image refs + uniform values. Uniforms are
404
+ * compared (not just `id`/`source`) because animating effects — the hit-flash
405
+ * decay and timed triggers — keep a constant `id`/`source` while only their
406
+ * uniform values change frame to frame; excluding them would freeze those
407
+ * animations. Cost is trivial: postfx chains hold a handful of scalar/short-vec
408
+ * uniforms.
409
+ */
410
+ function samePasses(a, b) {
411
+ if (a.length !== b.length) return false;
412
+ for (let i = 0; i < a.length; i++) {
413
+ const pa = a[i];
414
+ const pb = b[i];
415
+ if (pa === void 0 || pb === void 0) return false;
416
+ if (pa.id !== pb.id || pa.source !== pb.source) return false;
417
+ if (!sameChildren(pa.children, pb.children)) return false;
418
+ if (!sameUniforms(pa.uniforms, pb.uniforms)) return false;
419
+ }
420
+ return true;
252
421
  }
253
- function useEntity(query) {
254
- const [entities, setEntities] = (0, import_react4.useState)(() => Array.from(query));
255
- (0, import_react4.useEffect)(() => {
256
- const refresh = () => setEntities(Array.from(query));
257
- const unsubAdd = query.onEntityAdded.add(refresh);
258
- const unsubRemove = query.onEntityRemoved.add(refresh);
259
- refresh();
260
- return () => {
261
- unsubAdd();
262
- unsubRemove();
263
- };
264
- }, [query]);
265
- return entities;
422
+ function sameChildren(a, b) {
423
+ if (a.length !== b.length) return false;
424
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
425
+ return true;
266
426
  }
267
- function useGameLoop(callback) {
268
- const { loop } = useGame();
269
- const callbackRef = (0, import_react4.useRef)(callback);
270
- callbackRef.current = callback;
271
- const stable = (0, import_react4.useCallback)((dt) => {
272
- callbackRef.current(dt);
273
- }, []);
274
- (0, import_react4.useEffect)(() => {
275
- const unsub = loop.onUpdate.add(stable);
276
- return () => {
277
- unsub();
278
- };
279
- }, [loop, stable]);
427
+ function sameUniforms(a, b) {
428
+ const aKeys = Object.keys(a);
429
+ if (aKeys.length !== Object.keys(b).length) return false;
430
+ for (const key of aKeys) {
431
+ const va = a[key];
432
+ const vb = b[key];
433
+ if (va === void 0 || vb === void 0) return false;
434
+ if (typeof va === "number") {
435
+ if (va !== vb) return false;
436
+ } else {
437
+ if (typeof vb === "number" || va.length !== vb.length) return false;
438
+ for (let i = 0; i < va.length; i++) if (va[i] !== vb[i]) return false;
439
+ }
440
+ }
441
+ return true;
280
442
  }
281
-
282
- // src/virtual-joystick.tsx
283
- var import_input2 = require("@flare-engine/input");
284
- var import_react5 = require("react");
285
- var import_react_native2 = require("react-native");
286
- var import_jsx_runtime2 = require("react/jsx-runtime");
287
- function VirtualJoystick({
288
- config,
289
- onStateChange,
290
- style,
291
- base,
292
- thumb
293
- }) {
294
- const stateRef = (0, import_react5.useRef)((0, import_input2.createJoystickState)());
295
- const sizeRef = (0, import_react5.useRef)({ w: 0, h: 0 });
296
- const [knob, setKnob] = (0, import_react5.useState)({ x: 0, y: 0 });
297
- const handleLayout = (0, import_react5.useCallback)(
298
- (e) => {
299
- sizeRef.current = { w: e.nativeEvent.layout.width, h: e.nativeEvent.layout.height };
300
- },
301
- []
302
- );
303
- const handleTouch = (0, import_react5.useCallback)(
304
- (e) => {
305
- const { locationX, locationY } = e.nativeEvent;
306
- const { w, h } = sizeRef.current;
307
- (0, import_input2.updateJoystick)(stateRef.current, w / 2, h / 2, locationX, locationY, config);
308
- onStateChange?.(stateRef.current);
309
- const { x, y } = stateRef.current.offset;
310
- setKnob((prev) => prev.x === x && prev.y === y ? prev : { x, y });
311
- },
312
- [config, onStateChange]
313
- );
314
- const handleRelease = (0, import_react5.useCallback)(() => {
315
- (0, import_input2.releaseJoystick)(stateRef.current);
316
- onStateChange?.(stateRef.current);
317
- setKnob((prev) => prev.x === 0 && prev.y === 0 ? prev : { x: 0, y: 0 });
318
- }, [onStateChange]);
319
- const maxRadius = config?.maxRadius ?? 50;
320
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
321
- import_react_native2.View,
322
- {
323
- style: [
324
- styles2.center,
325
- ...base ? [] : [styles2.baseBg],
326
- {
327
- width: maxRadius * 2,
328
- height: maxRadius * 2,
329
- borderRadius: maxRadius
330
- },
331
- style
332
- ],
333
- onLayout: handleLayout,
334
- onStartShouldSetResponder: returnTrue2,
335
- onMoveShouldSetResponder: returnTrue2,
336
- onResponderGrant: handleTouch,
337
- onResponderMove: handleTouch,
338
- onResponderRelease: handleRelease,
339
- onResponderTerminate: handleRelease,
340
- children: [
341
- base ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_native2.View, { style: import_react_native2.StyleSheet.absoluteFill, pointerEvents: "none", children: base }) : null,
342
- thumb ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
343
- import_react_native2.View,
344
- {
345
- style: { transform: [{ translateX: knob.x }, { translateY: knob.y }] },
346
- pointerEvents: "none",
347
- children: thumb
348
- }
349
- ) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
350
- import_react_native2.View,
351
- {
352
- style: [styles2.knob, { transform: [{ translateX: knob.x }, { translateY: knob.y }] }]
353
- }
354
- )
355
- ]
356
- }
357
- );
358
- }
359
- function returnTrue2() {
360
- return true;
443
+ const styles$3 = react_native.StyleSheet.create({ container: { flex: 1 } });
444
+ //#endregion
445
+ //#region src/hooks.ts
446
+ /**
447
+ * useGame — returns the GameContextValue from the nearest <GameView>.
448
+ * Throws if called outside a <GameView>.
449
+ */
450
+ function useGame() {
451
+ const ctx = (0, react.useContext)(GameContext);
452
+ if (!ctx) throw new Error("useGame must be used inside a <GameView>");
453
+ return ctx;
361
454
  }
362
- var styles2 = import_react_native2.StyleSheet.create({
363
- center: {
364
- alignItems: "center",
365
- justifyContent: "center"
366
- },
367
- baseBg: {
368
- backgroundColor: "rgba(255,255,255,0.2)"
369
- },
370
- knob: {
371
- width: 40,
372
- height: 40,
373
- borderRadius: 20,
374
- backgroundColor: "rgba(255,255,255,0.6)"
375
- }
376
- });
377
-
378
- // src/virtual-button.tsx
379
- var import_input3 = require("@flare-engine/input");
380
- var import_react6 = require("react");
381
- var import_react_native3 = require("react-native");
382
- var import_jsx_runtime3 = require("react/jsx-runtime");
383
- function VirtualButton({
384
- onStateChange,
385
- style,
386
- children
387
- }) {
388
- const stateRef = (0, import_react6.useRef)((0, import_input3.createButtonState)());
389
- const handlePress = (0, import_react6.useCallback)(() => {
390
- (0, import_input3.resetButtonFrame)(stateRef.current);
391
- (0, import_input3.pressButton)(stateRef.current);
392
- onStateChange?.(stateRef.current);
393
- }, [onStateChange]);
394
- const handleRelease = (0, import_react6.useCallback)(() => {
395
- (0, import_input3.resetButtonFrame)(stateRef.current);
396
- (0, import_input3.releaseButton)(stateRef.current);
397
- onStateChange?.(stateRef.current);
398
- }, [onStateChange]);
399
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
400
- import_react_native3.View,
401
- {
402
- style: [styles3.button, style],
403
- onStartShouldSetResponder: returnTrue3,
404
- onResponderGrant: handlePress,
405
- onResponderRelease: handleRelease,
406
- onResponderTerminate: handleRelease,
407
- children
408
- }
409
- );
455
+ /**
456
+ * useEntity — subscribes to an ECS Query and returns the current entity list.
457
+ * Re-renders when entities are added to or removed from the query.
458
+ *
459
+ * @param query An active Query obtained from world.query(...)
460
+ */
461
+ function useEntity(query) {
462
+ const [entities, setEntities] = (0, react.useState)(() => Array.from(query));
463
+ (0, react.useEffect)(() => {
464
+ const refresh = () => setEntities(Array.from(query));
465
+ const unsubAdd = query.onEntityAdded.add(refresh);
466
+ const unsubRemove = query.onEntityRemoved.add(refresh);
467
+ refresh();
468
+ return () => {
469
+ unsubAdd();
470
+ unsubRemove();
471
+ };
472
+ }, [query]);
473
+ return entities;
410
474
  }
411
- function returnTrue3() {
412
- return true;
475
+ /**
476
+ * useGameLoop — registers a per-frame callback on the game loop's onUpdate signal.
477
+ * The callback is called each frame with delta time in seconds.
478
+ * Automatically unregisters on unmount.
479
+ *
480
+ * @param callback Function called each frame with dt in seconds.
481
+ */
482
+ function useGameLoop(callback) {
483
+ const { loop } = useGame();
484
+ const callbackRef = (0, react.useRef)(callback);
485
+ callbackRef.current = callback;
486
+ const stable = (0, react.useCallback)((dt) => {
487
+ callbackRef.current(dt);
488
+ }, []);
489
+ (0, react.useEffect)(() => {
490
+ const unsub = loop.onUpdate.add(stable);
491
+ return () => {
492
+ unsub();
493
+ };
494
+ }, [loop, stable]);
413
495
  }
414
- var styles3 = import_react_native3.StyleSheet.create({
415
- button: {
416
- width: 60,
417
- height: 60,
418
- borderRadius: 30,
419
- backgroundColor: "rgba(255,255,255,0.3)",
420
- alignItems: "center",
421
- justifyContent: "center"
422
- }
423
- });
424
-
425
- // src/loading-screen.tsx
426
- var import_react_native4 = require("react-native");
427
- var import_jsx_runtime4 = require("react/jsx-runtime");
428
- function LoadingScreen({
429
- progress,
430
- style,
431
- barColor = "#ffffff",
432
- trackColor = "rgba(255,255,255,0.2)",
433
- backgroundColor = "#000000"
434
- }) {
435
- const clamped = progress < 0 ? 0 : progress > 1 ? 1 : progress;
436
- const percent = `${Math.round(clamped * 100)}%`;
437
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_react_native4.View, { style: [styles4.container, { backgroundColor }, style], children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_react_native4.View, { style: [styles4.track, { backgroundColor: trackColor }], children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_react_native4.View, { style: [styles4.bar, { width: percent, backgroundColor: barColor }] }) }) });
496
+ //#endregion
497
+ //#region src/loading-screen.tsx
498
+ /**
499
+ * LoadingScreen — full-screen asset-load overlay.
500
+ *
501
+ * Renders before `<GameView>` mounts its Skia canvas (or alongside it
502
+ * while `AssetManager.load()` resolves). Pure RN Views so it works
503
+ * without a live Skia context. Consumers drive `progress` from the
504
+ * AssetManager progress callback.
505
+ */
506
+ function LoadingScreen({ progress, style, barColor = "#ffffff", trackColor = "rgba(255,255,255,0.2)", backgroundColor = "#000000" }) {
507
+ const percent = `${Math.round((progress < 0 ? 0 : progress > 1 ? 1 : progress) * 100)}%`;
508
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
509
+ style: [
510
+ styles$2.container,
511
+ { backgroundColor },
512
+ style
513
+ ],
514
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
515
+ style: [styles$2.track, { backgroundColor: trackColor }],
516
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, { style: [styles$2.bar, {
517
+ width: percent,
518
+ backgroundColor: barColor
519
+ }] })
520
+ })
521
+ });
438
522
  }
439
- var styles4 = import_react_native4.StyleSheet.create({
440
- container: {
441
- position: "absolute",
442
- top: 0,
443
- left: 0,
444
- right: 0,
445
- bottom: 0,
446
- alignItems: "center",
447
- justifyContent: "center",
448
- padding: 32
449
- },
450
- track: {
451
- width: "80%",
452
- height: 6,
453
- borderRadius: 3,
454
- overflow: "hidden"
455
- },
456
- bar: {
457
- height: "100%"
458
- }
523
+ const styles$2 = react_native.StyleSheet.create({
524
+ container: {
525
+ position: "absolute",
526
+ top: 0,
527
+ left: 0,
528
+ right: 0,
529
+ bottom: 0,
530
+ alignItems: "center",
531
+ justifyContent: "center",
532
+ padding: 32
533
+ },
534
+ track: {
535
+ width: "80%",
536
+ height: 6,
537
+ borderRadius: 3,
538
+ overflow: "hidden"
539
+ },
540
+ bar: { height: "100%" }
459
541
  });
460
-
461
- // src/overlay-hooks.ts
462
- var import_math = require("@flare-engine/math");
463
- var import_react7 = require("react");
542
+ //#endregion
543
+ //#region src/overlay-hooks.ts
464
544
  function useOverlayFade(visible, durationMs = 300) {
465
- const target = visible ? 1 : 0;
466
- const [opacity, setOpacity] = (0, import_react7.useState)(target);
467
- const opacityRef = (0, import_react7.useRef)(opacity);
468
- const startRef = (0, import_react7.useRef)(null);
469
- const rafRef = (0, import_react7.useRef)(null);
470
- opacityRef.current = opacity;
471
- (0, import_react7.useEffect)(() => {
472
- if (typeof requestAnimationFrame === "undefined") {
473
- setOpacity(target);
474
- return;
475
- }
476
- const from = opacityRef.current;
477
- startRef.current = null;
478
- if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
479
- const step = (now) => {
480
- if (startRef.current === null) startRef.current = now;
481
- const t = Math.min((now - startRef.current) / durationMs, 1);
482
- setOpacity(from + (target - from) * t);
483
- if (t < 1) {
484
- rafRef.current = requestAnimationFrame(step);
485
- }
486
- };
487
- rafRef.current = requestAnimationFrame(step);
488
- return () => {
489
- if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
490
- };
491
- }, [target, durationMs]);
492
- return opacity;
545
+ const target = visible ? 1 : 0;
546
+ const [opacity, setOpacity] = (0, react.useState)(target);
547
+ const opacityRef = (0, react.useRef)(opacity);
548
+ const startRef = (0, react.useRef)(null);
549
+ const rafRef = (0, react.useRef)(null);
550
+ opacityRef.current = opacity;
551
+ (0, react.useEffect)(() => {
552
+ if (typeof requestAnimationFrame === "undefined") {
553
+ setOpacity(target);
554
+ return;
555
+ }
556
+ const from = opacityRef.current;
557
+ startRef.current = null;
558
+ if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
559
+ const step = (now) => {
560
+ if (startRef.current === null) startRef.current = now;
561
+ const t = Math.min((now - startRef.current) / durationMs, 1);
562
+ setOpacity(from + (target - from) * t);
563
+ if (t < 1) rafRef.current = requestAnimationFrame(step);
564
+ };
565
+ rafRef.current = requestAnimationFrame(step);
566
+ return () => {
567
+ if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
568
+ };
569
+ }, [target, durationMs]);
570
+ return opacity;
493
571
  }
494
572
  function useCountUp(target, durationMs = 600) {
495
- const [value, setValue] = (0, import_react7.useState)(target);
496
- const valueRef = (0, import_react7.useRef)(value);
497
- const startRef = (0, import_react7.useRef)(null);
498
- const rafRef = (0, import_react7.useRef)(null);
499
- valueRef.current = value;
500
- (0, import_react7.useEffect)(() => {
501
- if (typeof requestAnimationFrame === "undefined") {
502
- setValue(target);
503
- return;
504
- }
505
- const from = valueRef.current;
506
- startRef.current = null;
507
- if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
508
- const step = (now) => {
509
- if (startRef.current === null) startRef.current = now;
510
- const t = Math.min((now - startRef.current) / durationMs, 1);
511
- setValue(from + (target - from) * (0, import_math.easeOutCubic)(t));
512
- if (t < 1) {
513
- rafRef.current = requestAnimationFrame(step);
514
- }
515
- };
516
- rafRef.current = requestAnimationFrame(step);
517
- return () => {
518
- if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
519
- };
520
- }, [target, durationMs]);
521
- return value;
573
+ const [value, setValue] = (0, react.useState)(target);
574
+ const valueRef = (0, react.useRef)(value);
575
+ const startRef = (0, react.useRef)(null);
576
+ const rafRef = (0, react.useRef)(null);
577
+ valueRef.current = value;
578
+ (0, react.useEffect)(() => {
579
+ if (typeof requestAnimationFrame === "undefined") {
580
+ setValue(target);
581
+ return;
582
+ }
583
+ const from = valueRef.current;
584
+ startRef.current = null;
585
+ if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
586
+ const step = (now) => {
587
+ if (startRef.current === null) startRef.current = now;
588
+ const t = Math.min((now - startRef.current) / durationMs, 1);
589
+ setValue(from + (target - from) * (0, _flare_engine_math.easeOutCubic)(t));
590
+ if (t < 1) rafRef.current = requestAnimationFrame(step);
591
+ };
592
+ rafRef.current = requestAnimationFrame(step);
593
+ return () => {
594
+ if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
595
+ };
596
+ }, [target, durationMs]);
597
+ return value;
522
598
  }
523
599
  function useSignalState(signal, initial) {
524
- const [state, setState] = (0, import_react7.useState)(initial);
525
- (0, import_react7.useEffect)(() => {
526
- const disposer = signal.add(setState);
527
- return disposer;
528
- }, [signal]);
529
- return state;
600
+ const [state, setState] = (0, react.useState)(initial);
601
+ (0, react.useEffect)(() => {
602
+ return signal.add(setState);
603
+ }, [signal]);
604
+ return state;
605
+ }
606
+ //#endregion
607
+ //#region src/skia-atlas.ts
608
+ /**
609
+ * The RN-Skia module adapted to the engine's structural atlas interface.
610
+ * Centralises the one boundary assertion so template code stays cast-free.
611
+ */
612
+ const skiaAtlasModule = _shopify_react_native_skia.Skia;
613
+ //#endregion
614
+ //#region src/virtual-button.tsx
615
+ /**
616
+ * VirtualButton — an on-screen button overlay component.
617
+ *
618
+ * Claims the React Native touch responder so press/release fire reliably
619
+ * even when an ancestor (e.g. <GameView>) also claims the responder.
620
+ */
621
+ function VirtualButton({ onStateChange, style, children }) {
622
+ const stateRef = (0, react.useRef)((0, _flare_engine_input.createButtonState)());
623
+ const handlePress = (0, react.useCallback)(() => {
624
+ (0, _flare_engine_input.resetButtonFrame)(stateRef.current);
625
+ (0, _flare_engine_input.pressButton)(stateRef.current);
626
+ onStateChange?.(stateRef.current);
627
+ }, [onStateChange]);
628
+ const handleRelease = (0, react.useCallback)(() => {
629
+ (0, _flare_engine_input.resetButtonFrame)(stateRef.current);
630
+ (0, _flare_engine_input.releaseButton)(stateRef.current);
631
+ onStateChange?.(stateRef.current);
632
+ }, [onStateChange]);
633
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
634
+ style: [styles$1.button, style],
635
+ onStartShouldSetResponder: returnTrue$1,
636
+ onResponderGrant: handlePress,
637
+ onResponderRelease: handleRelease,
638
+ onResponderTerminate: handleRelease,
639
+ children
640
+ });
641
+ }
642
+ function returnTrue$1() {
643
+ return true;
530
644
  }
531
- // Annotate the CommonJS export names for ESM import in node:
532
- 0 && (module.exports = {
533
- GameContext,
534
- GameView,
535
- LoadingScreen,
536
- SafeAreaContext,
537
- VirtualButton,
538
- VirtualJoystick,
539
- createSkiaFrameRenderer,
540
- renderShapesToImage,
541
- useCountUp,
542
- useEntity,
543
- useGame,
544
- useGameLoop,
545
- useOverlayFade,
546
- useSafeArea,
547
- useSignalState
645
+ const styles$1 = react_native.StyleSheet.create({ button: {
646
+ width: 60,
647
+ height: 60,
648
+ borderRadius: 30,
649
+ backgroundColor: "rgba(255,255,255,0.3)",
650
+ alignItems: "center",
651
+ justifyContent: "center"
652
+ } });
653
+ //#endregion
654
+ //#region src/virtual-joystick.tsx
655
+ /**
656
+ * VirtualJoystick — an on-screen joystick overlay component.
657
+ *
658
+ * Renders a base circle and a knob that follows the user's touch.
659
+ * Claims the React Native touch responder so children of a parent that
660
+ * also claims the responder (e.g. <GameView>) still receive move/end events.
661
+ */
662
+ function VirtualJoystick({ config, onStateChange, style, base, thumb }) {
663
+ const stateRef = (0, react.useRef)((0, _flare_engine_input.createJoystickState)());
664
+ const sizeRef = (0, react.useRef)({
665
+ w: 0,
666
+ h: 0
667
+ });
668
+ const [knob, setKnob] = (0, react.useState)({
669
+ x: 0,
670
+ y: 0
671
+ });
672
+ const handleLayout = (0, react.useCallback)((e) => {
673
+ sizeRef.current = {
674
+ w: e.nativeEvent.layout.width,
675
+ h: e.nativeEvent.layout.height
676
+ };
677
+ }, []);
678
+ const handleTouch = (0, react.useCallback)((e) => {
679
+ const { locationX, locationY } = e.nativeEvent;
680
+ const { w, h } = sizeRef.current;
681
+ (0, _flare_engine_input.updateJoystick)(stateRef.current, w / 2, h / 2, locationX, locationY, config);
682
+ onStateChange?.(stateRef.current);
683
+ const { x, y } = stateRef.current.offset;
684
+ setKnob((prev) => prev.x === x && prev.y === y ? prev : {
685
+ x,
686
+ y
687
+ });
688
+ }, [config, onStateChange]);
689
+ const handleRelease = (0, react.useCallback)(() => {
690
+ (0, _flare_engine_input.releaseJoystick)(stateRef.current);
691
+ onStateChange?.(stateRef.current);
692
+ setKnob((prev) => prev.x === 0 && prev.y === 0 ? prev : {
693
+ x: 0,
694
+ y: 0
695
+ });
696
+ }, [onStateChange]);
697
+ const maxRadius = config?.maxRadius ?? 50;
698
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_native.View, {
699
+ style: [
700
+ styles.center,
701
+ ...base ? [] : [styles.baseBg],
702
+ {
703
+ width: maxRadius * 2,
704
+ height: maxRadius * 2,
705
+ borderRadius: maxRadius
706
+ },
707
+ style
708
+ ],
709
+ onLayout: handleLayout,
710
+ onStartShouldSetResponder: returnTrue,
711
+ onMoveShouldSetResponder: returnTrue,
712
+ onResponderGrant: handleTouch,
713
+ onResponderMove: handleTouch,
714
+ onResponderRelease: handleRelease,
715
+ onResponderTerminate: handleRelease,
716
+ children: [base ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
717
+ style: react_native.StyleSheet.absoluteFill,
718
+ pointerEvents: "none",
719
+ children: base
720
+ }) : null, thumb ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, {
721
+ style: { transform: [{ translateX: knob.x }, { translateY: knob.y }] },
722
+ pointerEvents: "none",
723
+ children: thumb
724
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_native.View, { style: [styles.knob, { transform: [{ translateX: knob.x }, { translateY: knob.y }] }] })]
725
+ });
726
+ }
727
+ function returnTrue() {
728
+ return true;
729
+ }
730
+ const styles = react_native.StyleSheet.create({
731
+ center: {
732
+ alignItems: "center",
733
+ justifyContent: "center"
734
+ },
735
+ baseBg: { backgroundColor: "rgba(255,255,255,0.2)" },
736
+ knob: {
737
+ width: 40,
738
+ height: 40,
739
+ borderRadius: 20,
740
+ backgroundColor: "rgba(255,255,255,0.6)"
741
+ }
548
742
  });
743
+ //#endregion
744
+ exports.GameContext = GameContext;
745
+ exports.GameView = GameView;
746
+ exports.LoadingScreen = LoadingScreen;
747
+ exports.SafeAreaContext = SafeAreaContext;
748
+ exports.VirtualButton = VirtualButton;
749
+ exports.VirtualJoystick = VirtualJoystick;
750
+ exports.createSkiaFrameRenderer = createSkiaFrameRenderer;
751
+ exports.renderShapesToImage = renderShapesToImage;
752
+ exports.skiaAtlasModule = skiaAtlasModule;
753
+ exports.useCountUp = useCountUp;
754
+ exports.useEntity = useEntity;
755
+ exports.useGame = useGame;
756
+ exports.useGameLoop = useGameLoop;
757
+ exports.useOverlayFade = useOverlayFade;
758
+ exports.useSafeArea = useSafeArea;
759
+ exports.useSignalState = useSignalState;
760
+
549
761
  //# sourceMappingURL=index.js.map