@flare-engine/react 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Grzegorz Otto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,36 @@
1
+ # @flare-engine/react
2
+
3
+ React Native integration — `<GameView>` (Skia Canvas + game loop + input), `<VirtualJoystick>` / `<VirtualButton>` / `<LoadingScreen>` overlays, `useGame` / `useEntity` / `useGameLoop` hooks. `createSkiaFrameRenderer` adapts a `@flare-engine/render` `Renderer` to Skia's frame callback.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ bun add @flare-engine/react @shopify/react-native-skia
9
+ ```
10
+
11
+ Peer deps: `react`, `react-native`.
12
+
13
+ ## Usage
14
+
15
+ ```tsx
16
+ import { GameView, VirtualJoystick, useGameLoop } from '@flare-engine/react';
17
+
18
+ function HUD() {
19
+ useGameLoop((dt) => { /* ...frame logic... */ });
20
+ return null;
21
+ }
22
+
23
+ <GameView
24
+ config={{ designResolution: { width: 1080, height: 1920 }, fixedDt: 1 / 60 }}
25
+ onReady={(ctx) => bootstrap(ctx)}
26
+ >
27
+ <HUD />
28
+ <VirtualJoystick onChange={(v) => /* ... */} />
29
+ </GameView>
30
+ ```
31
+
32
+ See [API spec](../../docs/design/api-specs.md#flare-enginereact--10kb-gzip) and [skill reference](../../.github/skills/flare-react/SKILL.md).
33
+
34
+ ## License
35
+
36
+ MIT
@@ -0,0 +1,379 @@
1
+ import * as React from 'react';
2
+ import React__default from 'react';
3
+ import { AssetManager, SkImageLike, AssetLoader } from '@flare-engine/assets';
4
+ import { AudioManager } from '@flare-engine/audio';
5
+ import { GameLoop } from '@flare-engine/core';
6
+ import { World, Query } from '@flare-engine/ecs';
7
+ import { InputManager, VirtualJoystickConfig, VirtualJoystickState, VirtualButtonState } from '@flare-engine/input';
8
+ import { Camera2D, Renderer, SpriteBatch, CanvasLike, SpriteDrawCommand } from '@flare-engine/render';
9
+ import { SceneManager } from '@flare-engine/scene';
10
+ import { SkRuntimeEffect, SkImage, SkPicture, Skia } from '@shopify/react-native-skia';
11
+ import { ViewStyle } from 'react-native';
12
+
13
+ /** The value exposed via GameContext. */
14
+ interface GameContextValue {
15
+ /** ECS world. */
16
+ world: World;
17
+ /** Primary 2D camera. */
18
+ camera: Camera2D;
19
+ /** Input manager (pointer, touches). */
20
+ input: InputManager;
21
+ /** Audio manager. */
22
+ audio: AudioManager;
23
+ /** Asset manager. */
24
+ assets: AssetManager;
25
+ /** Scene manager. */
26
+ scenes: SceneManager;
27
+ /** Game loop. */
28
+ loop: GameLoop;
29
+ /** Frame renderer (owns the draw phase). */
30
+ renderer: Renderer;
31
+ /** Sprite batch — queue `draw()` calls from systems or custom logic. */
32
+ batch: SpriteBatch;
33
+ }
34
+ /**
35
+ * React context that provides access to core game objects.
36
+ * Null if accessed outside a <GameView>.
37
+ */
38
+ declare const GameContext: React.Context<GameContextValue | null>;
39
+
40
+ /** Structural canvas — minimal subset needed for offscreen rendering. */
41
+ interface SkOffscreenCanvasLike {
42
+ drawPicture(picture: unknown): void;
43
+ drawImageRect(image: unknown, src: unknown, dst: unknown, paint: unknown): void;
44
+ drawRect(rect: unknown, paint: unknown): void;
45
+ clear(color: unknown): void;
46
+ }
47
+ /** Structural canvas surface — minimal subset needed for offscreen capture. */
48
+ interface SkSurfaceLike {
49
+ getCanvas(): SkOffscreenCanvasLike;
50
+ makeImageSnapshot(): SkImageLike;
51
+ /** Force queued draws to execute. Required for GPU-backed surfaces before
52
+ * makeImageSnapshot is called, otherwise the snapshot may capture
53
+ * uninitialized texture content. See Skia's SkSurface.flush docs. */
54
+ flush(): void;
55
+ }
56
+ /**
57
+ * A single post-processing pass descriptor built by `buildPostFxPasses`.
58
+ * GameView maps each descriptor to a `<RuntimeShader>` child of `<Image>`.
59
+ */
60
+ interface PostFxPassDescriptor {
61
+ /** Stable id, used as React key. */
62
+ readonly id: string;
63
+ /** The compiled SkRuntimeEffect passed as `<RuntimeShader source={…}/>`. */
64
+ readonly source: SkRuntimeEffect;
65
+ /**
66
+ * Uniform map keyed by SkSL uniform name. Vector uniforms are `number[]`
67
+ * whose length equals `columns * rows`; scalar uniforms are `number`.
68
+ * Built by zipping `shader.getUniformName(i)` → sliced Float32Array values.
69
+ */
70
+ readonly uniforms: Record<string, number | readonly number[]>;
71
+ /**
72
+ * Extra child shader slots beyond the implicit scene sampler. Empty for every
73
+ * built-in PT effect; only color-grading-lut would populate it. Each entry
74
+ * is an SkImage that GameView wraps in `<ImageShader>`.
75
+ */
76
+ readonly children: readonly SkImage[];
77
+ }
78
+ /** A single axis-aligned rectangle shape to draw into an offscreen surface. */
79
+ interface ShapeRect {
80
+ readonly x: number;
81
+ readonly y: number;
82
+ readonly w: number;
83
+ readonly h: number;
84
+ /** ARGB packed integer: 0xAARRGGBB */
85
+ readonly color: number;
86
+ }
87
+ /** Options for `renderShapesToImage`. */
88
+ interface RenderShapesOpts {
89
+ readonly width: number;
90
+ readonly height: number;
91
+ /** ARGB packed integer: 0xAARRGGBB */
92
+ readonly clearColor: number;
93
+ readonly shapes: readonly ShapeRect[];
94
+ }
95
+ /**
96
+ * Narrow view of the Skia module — only the factories the bridge needs.
97
+ * Declared as its own type so tests can pass a plain mock without pulling
98
+ * in the full `@shopify/react-native-skia` surface.
99
+ */
100
+ type SkiaModuleLike = Pick<typeof Skia, 'XYWHRect' | 'RSXform' | 'Paint' | 'PictureRecorder' | 'ColorFilter'> & {
101
+ RuntimeEffect?: {
102
+ Make(sksl: string): SkRuntimeEffect | null;
103
+ };
104
+ Surface?: {
105
+ Make(width: number, height: number): SkSurfaceLike | null;
106
+ MakeOffscreen?(width: number, height: number): SkSurfaceLike | null;
107
+ };
108
+ };
109
+ /**
110
+ * A single compiled postfx pass descriptor produced by the runtime.
111
+ * The bridge owns the actual rendering; the runtime just produces these.
112
+ */
113
+ interface CompiledPassLike {
114
+ readonly id: string;
115
+ readonly shader: {
116
+ makeShaderWithChildren(uniforms: number[], children: unknown[]): unknown | null;
117
+ /** Required for buildPostFxPasses uniform-name mapping. */
118
+ getUniformCount?(): number;
119
+ getUniformName?(index: number): string;
120
+ getUniform?(index: number): {
121
+ columns: number;
122
+ rows: number;
123
+ slot: number;
124
+ };
125
+ };
126
+ readonly uniforms: Float32Array;
127
+ readonly children: readonly unknown[];
128
+ }
129
+ /**
130
+ * Minimal structural view of a PostFxRuntime that the bridge needs.
131
+ * Declared locally so `@flare-engine/react` does not take a hard dep on
132
+ * `@flare-engine/postfx`; interfaces are compatible structurally.
133
+ *
134
+ * Runtimes that expose `buildPass` are fully managed by the bridge via the
135
+ * JSX `<Image><RuntimeShader/></Image>` chain in GameView.
136
+ */
137
+ interface PostFxRuntimeLike {
138
+ readonly supported: boolean;
139
+ buildPass?(chain: PostFxChainLike, width: number, height: number): readonly CompiledPassLike[];
140
+ }
141
+ /** Minimal structural view of an EffectChain the bridge needs. */
142
+ interface PostFxChainLike {
143
+ enabled(): Iterable<unknown>;
144
+ }
145
+ /**
146
+ * Frame renderer that bridges a `SpriteBatch` to a Skia `<Picture>`.
147
+ *
148
+ * Each frame:
149
+ * 1. Call `beginFrame(viewportWidth, viewportHeight)` — opens a fresh
150
+ * picture recording bounded to the viewport. If either dimension is 0
151
+ * (layout not yet resolved) the call is a no-op and `endFrame` returns
152
+ * null for that frame.
153
+ * 2. Call `drawAtlas(image, commands)` one or more times (typically via
154
+ * `batch.flush(bridge.drawAtlas, renderer)`).
155
+ * 3. Call `endFrame()` — returns the recorded `SkPicture` to hand to a
156
+ * `<Picture>` component inside a `<Canvas>`.
157
+ *
158
+ * The `canvas` field is a `CanvasLike` adapter the frame owner installs on
159
+ * the `Renderer` via `renderer.setCanvas(bridge.canvas)`. It forwards to
160
+ * the live recording canvas between `beginFrame` and `endFrame`, and is a
161
+ * no-op otherwise.
162
+ */
163
+ interface SkiaFrameRenderer {
164
+ readonly canvas: CanvasLike;
165
+ /**
166
+ * Open a fresh picture recording for this frame.
167
+ * @param viewportWidth Logical viewport width (CSS pixels).
168
+ * @param viewportHeight Logical viewport height (CSS pixels).
169
+ * @param time Frame timestamp in seconds (default 0).
170
+ * @param pixelDensity Logical→physical recording scale (default 1). When
171
+ * > 1 the recording bounds are expanded to physical
172
+ * resolution and a matching scale() is baked in so
173
+ * `usePictureAsTexture` fills a physical-size backing.
174
+ */
175
+ beginFrame(viewportWidth: number, viewportHeight: number, time?: number, pixelDensity?: number): void;
176
+ /**
177
+ * drawAtlas callback compatible with `SpriteBatch.flush`. Accepts
178
+ * `SkImageLike` (the narrow `@flare-engine/assets` type used by the batch) and
179
+ * upcasts to a full Skia `SkImage` at the boundary — in practice callers
180
+ * always supply a real `SkImage`.
181
+ */
182
+ drawAtlas(image: SkImageLike, commands: SpriteDrawCommand[]): void;
183
+ /**
184
+ * Build the list of postfx pass descriptors for this frame. Called by
185
+ * GameView AFTER endFrame() (picture is final) and BEFORE Canvas commits.
186
+ * Returns an empty array when runtime is null, unsupported, has no buildPass,
187
+ * or the chain has no enabled effects.
188
+ *
189
+ * Uniforms are keyed by SkSL uniform NAME via shader.getUniformName(i).
190
+ * Vector uniforms (columns*rows > 1) become readonly number[].
191
+ */
192
+ buildPostFxPasses(runtime: PostFxRuntimeLike | null, chain: PostFxChainLike | null, width: number, height: number): readonly PostFxPassDescriptor[];
193
+ /**
194
+ * Publish a (runtime, chain) pair for this frame. Called by the
195
+ * onRenderPostFx hook so GameView can drive buildPostFxPasses after
196
+ * endFrame without changing the PostFxRenderHook signature.
197
+ */
198
+ setPostFxBinding(runtime: PostFxRuntimeLike | null, chain: PostFxChainLike | null): void;
199
+ endFrame(): SkPicture | null;
200
+ }
201
+ /**
202
+ * Create a `SkiaFrameRenderer`.
203
+ *
204
+ * `Skia` is passed in (rather than imported) so unit tests can supply a
205
+ * mock. Production code constructs this once inside `<GameView>` using the
206
+ * real `Skia` import from `@shopify/react-native-skia`.
207
+ */
208
+ declare function createSkiaFrameRenderer(Skia: SkiaModuleLike): SkiaFrameRenderer;
209
+ /**
210
+ * Render a list of solid rectangles into a fresh offscreen surface and return
211
+ * the resulting image snapshot. Returns `null` if `Surface` factory is absent or
212
+ * fails. The surface is not cached — callers that need reuse should cache the
213
+ * returned image themselves.
214
+ */
215
+ declare function renderShapesToImage(skia: SkiaModuleLike, opts: RenderShapesOpts): SkImageLike | null;
216
+
217
+ interface SafeArea {
218
+ top: number;
219
+ right: number;
220
+ bottom: number;
221
+ left: number;
222
+ }
223
+ declare const SafeAreaContext: React.Context<SafeArea | null>;
224
+ declare function useSafeArea(): SafeArea;
225
+
226
+ /** Render hook invoked during the frame — receives the game context and
227
+ * the active Skia canvas for direct draw calls. Hooks run between
228
+ * `renderer.applyCamera()` and `renderer.end()`, so the camera transform
229
+ * is already applied. */
230
+ type RenderHook = (ctx: GameContextValue, canvas: unknown) => void;
231
+ /** Render hook for post-processing passes. Receives the game context, the
232
+ * active Skia canvas, and the `SkiaFrameRenderer` bridge so the hook can
233
+ * call `bridge.setPostFxBinding(runtime, chain)` to register the runtime
234
+ * and chain for the current frame.
235
+ * `bridge` is `null` only on platforms where no Skia renderer was created
236
+ * (future web fallback). */
237
+ type PostFxRenderHook = (ctx: GameContextValue, canvas: unknown, bridge: SkiaFrameRenderer | null) => void;
238
+ /** Configuration passed to <GameView>. */
239
+ interface GameConfig {
240
+ /** Fixed timestep in seconds (default 1/60). */
241
+ fixedDt?: number;
242
+ /** Maximum dt cap in seconds (default 0.25). */
243
+ maxDt?: number;
244
+ /** Background clear color as 32-bit ARGB int (default 0xFF000000). */
245
+ clearColor?: number;
246
+ /** Asset loader function — injected into AssetManager at construction. */
247
+ assetLoader?: AssetLoader;
248
+ /** Called after camera transform and before the sprite render system.
249
+ * Intended for tilemap / background layer rendering. */
250
+ onRenderBackground?: RenderHook;
251
+ /** Called after the sprite batch has been flushed, before `renderer.end()`.
252
+ * Receives the bridge as 3rd arg so the hook can call
253
+ * `bridge.setPostFxBinding(runtime, chain)` to register the postfx runtime
254
+ * and chain for the current frame. */
255
+ onRenderPostFx?: PostFxRenderHook;
256
+ /**
257
+ * Promote the underlying Skia surface from a TextureView (default) to a
258
+ * SurfaceView on Android. With `opaque: true`, SurfaceView paints in a
259
+ * separate compositing layer below the regular RN view tree, which lets
260
+ * full-screen RN overlays (HUDs, menus) render on top without needing
261
+ * elevation/zIndex tricks.
262
+ *
263
+ * Without this, RN-Skia's TextureView can clip overlapping full-screen
264
+ * RN siblings on certain Android devices/Fabric configurations.
265
+ *
266
+ * Implies the canvas content is opaque — the clearColor's alpha must be
267
+ * fully opaque (0xFF). Defaults to `false` to preserve the current
268
+ * iOS-equivalent behavior.
269
+ */
270
+ opaque?: boolean;
271
+ }
272
+ /** Props for the <GameView> component. */
273
+ interface GameViewProps {
274
+ /** Game configuration. */
275
+ config?: GameConfig;
276
+ /** Called once the game context is ready (loop not yet started). */
277
+ onReady?: (ctx: GameContextValue) => void;
278
+ /** Style applied to the outer View container. */
279
+ style?: ViewStyle;
280
+ /** Optional overlay children (e.g. VirtualJoystick, VirtualButton). */
281
+ children?: React__default.ReactNode;
282
+ /** Explicit safe-area insets. If omitted, resolved from react-native-safe-area-context
283
+ * via `useSafeAreaInsets()` (requires a `<SafeAreaProvider>` ancestor; falls back to
284
+ * zero insets when no provider is mounted). */
285
+ safeArea?: SafeArea;
286
+ }
287
+ /**
288
+ * GameView — root component that sets up the Skia canvas, game loop,
289
+ * and all core game systems. Provides GameContext to descendants.
290
+ *
291
+ * Overlay controls (VirtualJoystick, VirtualButton) should be placed
292
+ * as children; they render on top of the Skia canvas.
293
+ */
294
+ declare function GameView({ config, onReady, style, children, safeArea, }: GameViewProps): React__default.ReactElement;
295
+
296
+ /**
297
+ * useGame — returns the GameContextValue from the nearest <GameView>.
298
+ * Throws if called outside a <GameView>.
299
+ */
300
+ declare function useGame(): GameContextValue;
301
+ /**
302
+ * useEntity — subscribes to an ECS Query and returns the current entity list.
303
+ * Re-renders when entities are added to or removed from the query.
304
+ *
305
+ * @param query An active Query obtained from world.query(...)
306
+ */
307
+ declare function useEntity(query: Query): readonly number[];
308
+ /**
309
+ * useGameLoop — registers a per-frame callback on the game loop's onUpdate signal.
310
+ * The callback is called each frame with delta time in seconds.
311
+ * Automatically unregisters on unmount.
312
+ *
313
+ * @param callback Function called each frame with dt in seconds.
314
+ */
315
+ declare function useGameLoop(callback: (dt: number) => void): void;
316
+
317
+ /** Props for the <VirtualJoystick> component. */
318
+ interface VirtualJoystickProps {
319
+ /** Joystick configuration (dead zone, max radius). */
320
+ config?: VirtualJoystickConfig;
321
+ /** Called on each state change. */
322
+ onStateChange?: (state: VirtualJoystickState) => void;
323
+ /** Style applied to the outer container. */
324
+ style?: ViewStyle;
325
+ /** Custom node rendered in place of the default base circle View. */
326
+ base?: React__default.ReactNode;
327
+ /** Custom node rendered in place of the default knob View. */
328
+ thumb?: React__default.ReactNode;
329
+ }
330
+ /**
331
+ * VirtualJoystick — an on-screen joystick overlay component.
332
+ *
333
+ * Renders a base circle and a knob that follows the user's touch.
334
+ * Claims the React Native touch responder so children of a parent that
335
+ * also claims the responder (e.g. <GameView>) still receive move/end events.
336
+ */
337
+ declare function VirtualJoystick({ config, onStateChange, style, base, thumb, }: VirtualJoystickProps): React__default.ReactElement;
338
+
339
+ /** Props for the <VirtualButton> component. */
340
+ interface VirtualButtonProps {
341
+ /** Called on each state change. */
342
+ onStateChange?: (state: VirtualButtonState) => void;
343
+ /** Style applied to the button. */
344
+ style?: ViewStyle;
345
+ /** Button label / overlay content. */
346
+ children?: React__default.ReactNode;
347
+ }
348
+ /**
349
+ * VirtualButton — an on-screen button overlay component.
350
+ *
351
+ * Claims the React Native touch responder so press/release fire reliably
352
+ * even when an ancestor (e.g. <GameView>) also claims the responder.
353
+ */
354
+ declare function VirtualButton({ onStateChange, style, children, }: VirtualButtonProps): React__default.ReactElement;
355
+
356
+ /** Props for the <LoadingScreen> component. */
357
+ interface LoadingScreenProps {
358
+ /** Progress in [0, 1]. Values outside this range are clamped. */
359
+ progress: number;
360
+ /** Style applied to the outer container (covers parent by default). */
361
+ style?: ViewStyle;
362
+ /** Filled portion color. */
363
+ barColor?: string;
364
+ /** Track color. */
365
+ trackColor?: string;
366
+ /** Background color behind the track. */
367
+ backgroundColor?: string;
368
+ }
369
+ /**
370
+ * LoadingScreen — full-screen asset-load overlay.
371
+ *
372
+ * Renders before `<GameView>` mounts its Skia canvas (or alongside it
373
+ * while `AssetManager.load()` resolves). Pure RN Views so it works
374
+ * without a live Skia context. Consumers drive `progress` from the
375
+ * AssetManager progress callback.
376
+ */
377
+ declare function LoadingScreen({ progress, style, barColor, trackColor, backgroundColor, }: LoadingScreenProps): React__default.ReactElement;
378
+
379
+ export { type CompiledPassLike, type GameConfig, GameContext, type GameContextValue, GameView, type GameViewProps, LoadingScreen, type LoadingScreenProps, type PostFxChainLike, type PostFxPassDescriptor, type PostFxRenderHook, type PostFxRuntimeLike, type RenderHook, type RenderShapesOpts, type SafeArea, SafeAreaContext, type ShapeRect, type SkOffscreenCanvasLike, type SkiaFrameRenderer, type SkiaModuleLike, VirtualButton, type VirtualButtonProps, VirtualJoystick, type VirtualJoystickProps, createSkiaFrameRenderer, renderShapesToImage, useEntity, useGame, useGameLoop, useSafeArea };