react-three-game 0.0.58 → 0.0.60

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.
@@ -13,7 +13,7 @@ import { forwardRef, useCallback, useContext, useEffect, useImperativeHandle, us
13
13
  import { BoxHelper, Euler, Matrix4, Quaternion, SRGBColorSpace, TextureLoader, Vector3, } from "three";
14
14
  import { getComponent, registerComponent, getNonComposableKeys } from "./components/ComponentRegistry";
15
15
  import components from "./components";
16
- import { loadModel } from "../dragdrop/modelLoader";
16
+ import { loadModel } from "../dragdrop";
17
17
  import { GameInstance, GameInstanceProvider, useInstanceCheck } from "./InstanceProvider";
18
18
  import { focusCameraOnObject, updateNode } from "./utils";
19
19
  import { EditorContext } from "./EditorContext";
@@ -40,15 +40,9 @@ export const PrefabRoot = forwardRef(({ editMode, data, onPrefabChange, selected
40
40
  const injectModel = useCallback((filename, model) => {
41
41
  setModels(m => (Object.assign(Object.assign({}, m), { [filename]: model })));
42
42
  }, []);
43
- const injectTexture = useCallback((filename, file) => {
43
+ const injectTexture = useCallback((filename, texture) => {
44
44
  loading.current.add(filename);
45
- const url = URL.createObjectURL(file);
46
- const loader = new TextureLoader();
47
- loader.load(url, tex => {
48
- tex.colorSpace = SRGBColorSpace;
49
- setTextures(t => (Object.assign(Object.assign({}, t), { [filename]: tex })));
50
- URL.revokeObjectURL(url);
51
- }, undefined, () => URL.revokeObjectURL(url));
45
+ setTextures(t => (Object.assign(Object.assign({}, t), { [filename]: texture })));
52
46
  }, []);
53
47
  useImperativeHandle(ref, () => ({
54
48
  root: rootRef.current,
@@ -120,8 +114,10 @@ export const PrefabRoot = forwardRef(({ editMode, data, onPrefabChange, selected
120
114
  ? `${basePath}${file}`
121
115
  : `${basePath}/${file}`;
122
116
  const res = yield loadModel(path);
123
- res.success && res.model &&
124
- setModels(m => (Object.assign(Object.assign({}, m), { [file]: res.model })));
117
+ const model = res.model;
118
+ if (res.success && model) {
119
+ setModels(m => (Object.assign(Object.assign({}, m), { [file]: model })));
120
+ }
125
121
  }));
126
122
  const loader = new TextureLoader();
127
123
  texturesToLoad.forEach(file => {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "react-three-game",
3
- "version": "0.0.58",
4
- "description": "Batteries included React Three Fiber game engine",
3
+ "version": "0.0.60",
4
+ "description": "high performance 3D game engine for React",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -124,6 +124,8 @@ Scenes are defined as JSON prefabs with a root node containing children:
124
124
  | SpotLight | `SpotLight` | `color`, `intensity`, `angle`, `penumbra`, `distance?`, `castShadow?` |
125
125
  | DirectionalLight | `DirectionalLight` | `color`, `intensity`, `castShadow?`, `targetOffset?: [x,y,z]` |
126
126
  | AmbientLight | `AmbientLight` | `color`, `intensity` |
127
+ | Environment | `Environment` | `intensity`, `resolution` |
128
+ | Camera | `Camera` | `fov`, `near`, `far`, `zoom` |
127
129
  | Text | `Text` | `text`, `font`, `size`, `depth`, `width`, `align`, `color` |
128
130
 
129
131
  ### Text Component
@@ -167,20 +169,23 @@ Use radians: `1.57` = 90°, `3.14` = 180°, `-1.57` = -90°
167
169
 
168
170
  ### Usage Modes
169
171
 
170
- **GameCanvas + PrefabRoot**: Pure renderer for embedding prefab data in standard R3F applications. Minimal wrapper - just renders the prefab as Three.js objects. Requires manual `<Physics>` setup. Physics always active. Use this to integrate prefabs into larger R3F scenes.
172
+ **PrefabRoot**: Pure renderer for embedding prefab data in standard R3F applications. Render it inside a regular `@react-three/fiber` `Canvas`. `GameCanvas` provides the WebGPU canvas setup. Add a `Physics` wrapper to enable physics. Use this to integrate prefabs into larger R3F scenes.
171
173
 
172
174
  ```jsx
175
+ import { Canvas } from '@react-three/fiber';
173
176
  import { Physics } from '@react-three/rapier';
174
- import { GameCanvas, PrefabRoot } from 'react-three-game';
177
+ import { PrefabRoot } from 'react-three-game';
175
178
 
176
- <GameCanvas>
179
+ <Canvas>
177
180
  <Physics>
178
181
  <PrefabRoot data={prefabData} />
179
182
  <CustomComponent />
180
183
  </Physics>
181
- </GameCanvas>
184
+ </Canvas>
182
185
  ```
183
186
 
187
+ `GameCanvas` provides the library's WebGPU canvas setup.
188
+
184
189
  **PrefabEditor**: Managed scene with editor UI and play/pause controls for physics. Full authoring tool for level design and prototyping. Includes canvas, physics, transform gizmos, and inspector. Physics only runs in play mode. Can pass R3F components as children. Editor actions live under `Menu > File`, and exports under `Menu > Export`.
185
190
 
186
191
  ```jsx
@@ -231,6 +236,36 @@ function DynamicLight() {
231
236
 
232
237
  **Use cases**: Player controllers, AI behaviors, procedural animation, real-time effects.
233
238
 
239
+ ## World Scene Pattern
240
+
241
+ The current world demo combines prefab-authored level geometry with runtime React behavior:
242
+
243
+ - Static level layout, props, and collision live in prefab JSON.
244
+ - `Environment` can wrap sky geometry or lighting content for a full scene backdrop.
245
+ - `Camera` can live in the prefab so view-only scenes and editor scenes share the same authored viewpoint.
246
+ - Runtime logic can use `useFrame` plus `updateNodeById` to animate prefab entities without abandoning the JSON scene model.
247
+
248
+ ```json
249
+ {
250
+ "id": "environment",
251
+ "components": {
252
+ "environment": {
253
+ "type": "Environment",
254
+ "properties": { "intensity": 1, "resolution": 256 }
255
+ }
256
+ },
257
+ "children": [
258
+ {
259
+ "id": "sky",
260
+ "components": {
261
+ "geometry": { "type": "Geometry", "properties": { "geometryType": "sphere", "args": [100, 32, 16] } },
262
+ "material": { "type": "Material", "properties": { "texture": "/textures/skybox/skybox1.jpg", "side": "BackSide", "materialType": "basic" } }
263
+ }
264
+ }
265
+ ]
266
+ }
267
+ ```
268
+
234
269
  ## Quick Reference Examples
235
270
 
236
271
  ```json
@@ -379,6 +414,26 @@ const MyComponent: Component = {
379
414
  registerComponent(MyComponent);
380
415
  ```
381
416
 
417
+ Use the component in prefab JSON by adding a component entry whose `type` matches the registered component name:
418
+
419
+ ```json
420
+ {
421
+ "components": {
422
+ "mycomponent": {
423
+ "type": "MyComponent",
424
+ "properties": {
425
+ "speed": 1
426
+ }
427
+ }
428
+ }
429
+ }
430
+ ```
431
+
432
+ Rules:
433
+ - Call `registerComponent(MyComponent)` before rendering `<PrefabEditor>` or `<PrefabRoot>` with prefab data that uses it.
434
+ - `type` must match the registered component name exactly (`name: 'MyComponent'` -> `"type": "MyComponent"`).
435
+ - Use `View` to render visible content, wrap `children`, or add runtime behavior with hooks like `useFrame`.
436
+
382
437
  **Field types**: `vector3`, `number`, `string`, `color`, `boolean`, `select`, `custom`
383
438
 
384
439
  ## Game Events
@@ -48,6 +48,7 @@ Complete reference for `Physics` component properties:
48
48
  | `lockRotations` | `boolean` | `false` | Freeze rotation |
49
49
  | `enabledTranslations` | `[bool, bool, bool]` | `[true, true, true]` | Lock per axis (X, Y, Z) |
50
50
  | `enabledRotations` | `[bool, bool, bool]` | `[true, true, true]` | Lock rotation per axis |
51
+ | `colliders` | `'hull'` \| `'trimesh'` \| `'cuboid'` \| `'ball'` | auto | Collider shape override (`fixed` defaults to `trimesh`, others to `hull`) |
51
52
  | `ccd` | `boolean` | `false` | Continuous collision detection (fast objects) |
52
53
  | `sensor` | `boolean` | `false` | Trigger only, no collision response |
53
54
  | `activeCollisionTypes` | `'all'` | - | Enable kinematic/fixed collision detection (default: dynamic only) |
@@ -284,21 +285,21 @@ Objects will **slide off** the tilted surface.
284
285
 
285
286
  ## Instanced Physics
286
287
 
287
- When using `"instanced": true` on models, physics behaves differently than standard objects. **All instances of the same model share a single `InstancedRigidBodies` component** for optimal GPU performance.
288
+ When using `"instanced": true` on models, physics behaves differently than standard objects. Physics instancing is designed for batched `fixed` and `dynamic` bodies, where instances of the same model share an `InstancedRigidBodies` path for better performance.
288
289
 
289
290
  ### Standard vs Instanced Physics
290
291
 
291
292
  | Aspect | Standard Physics | Instanced Physics |
292
293
  |--------|------------------|-------------------|
293
- | RigidBody Component | Individual `<RigidBody>` per object | Single `<InstancedRigidBodies>` for all instances |
294
+ | RigidBody Component | Individual `<RigidBody>` per object | Single `<InstancedRigidBodies>` group per model + supported physics type |
294
295
  | Ref Access | `rigidBodyRefs.get(nodeId)` returns single RigidBody | Not accessible via `rigidBodyRefs` |
295
296
  | Force Application | Direct per-object | Must access via InstancedRigidBodies ref |
296
- | Collider Type | `hull` (dynamic) or `trimesh` (fixed) | Same, auto-selected |
297
+ | Collider Type | `hull` (dynamic) or `trimesh` (fixed) | Auto-selected by instanced physics path |
297
298
  | Performance | One draw call per object | One draw call for all instances |
298
299
 
299
300
  ### Defining Instanced Objects
300
301
 
301
- Set `"instanced": true` in the model component. **All instances of the same model+physics type are automatically batched**:
302
+ Set `"instanced": true` in the model component. **Instances with the same model path and supported physics type are automatically batched**:
302
303
 
303
304
  ```json
304
305
  {
@@ -326,7 +327,7 @@ Add multiple instances - they'll be automatically batched:
326
327
 
327
328
  ### Force Application on Instanced Objects
328
329
 
329
- **Instanced physics bodies are not individually accessible.** For objects requiring force/impulse control, use non-instanced physics (`"instanced": false` or omit the property).
330
+ **Instanced physics bodies are not individually accessible.** For objects requiring force/impulse control, kinematic motion, or per-body refs, use non-instanced physics (`"instanced": false` or omit the property).
330
331
 
331
332
  ### When to Use Instanced Physics
332
333
 
@@ -345,6 +346,7 @@ Add multiple instances - they'll be automatically batched:
345
346
  ### Performance Notes
346
347
 
347
348
  - **Batching**: All instances with the same `filename` and `physics.type` are rendered in a single draw call
349
+ - **Supported body types**: The instanced physics path is intended for `fixed` and `dynamic` bodies; use standard non-instanced physics for kinematic bodies
348
350
  - **Scale handling**: Visual scale is applied per-instance, but collider scale may differ
349
351
  - **Transform updates**: Use `updateNodeById` to move instances (triggers re-sync)
350
352
  - **Memory**: One set of GPU buffers shared across all instances
package/src/index.ts CHANGED
@@ -50,7 +50,7 @@ export { entityEvents, useEntityEvent } from './tools/prefabeditor/GameEvents';
50
50
  export type { EntityEventType, EntityEventPayload } from './tools/prefabeditor/GameEvents';
51
51
 
52
52
  // Asset Tools
53
- export { DragDropLoader } from './tools/dragdrop/DragDropLoader';
53
+ export * from './tools/dragdrop';
54
54
  export {
55
55
  TextureListViewer,
56
56
  ModelListViewer,
@@ -2,7 +2,7 @@ import { Canvas } from "@react-three/fiber";
2
2
  import { OrbitControls, Stage, View, PerspectiveCamera } from "@react-three/drei";
3
3
  import { Component as ReactComponent, Suspense, useEffect, useState, useRef } from "react";
4
4
  import { TextureLoader } from "three";
5
- import { loadModel } from "../dragdrop/modelLoader";
5
+ import { loadModel } from "../dragdrop";
6
6
 
7
7
  class ErrorBoundary extends ReactComponent<{ onError?: () => void; children: React.ReactNode }, { hasError: boolean }> {
8
8
  constructor(props: any) {
@@ -1,73 +1,159 @@
1
- // DragDropLoader.tsx
2
- import { useEffect, ChangeEvent } from "react";
3
- import { parseModelFromFile } from "./modelLoader";
1
+ import { ChangeEvent, useRef } from "react";
2
+ import type { DragEvent, HTMLAttributes, MouseEvent, ReactNode } from "react";
3
+ import type { LoadedModel, LoadedTexture } from "./modelLoader";
4
+ import { canParseModelFile, canParseTextureFile, parseModelFromFile, parseTextureFromFile } from "./modelLoader";
4
5
 
5
- interface DragDropLoaderProps {
6
- onModelLoaded: (model: any, filename: string) => void;
6
+ export interface AssetLoadOptions {
7
+ onModelLoaded?: (model: LoadedModel, filename: string, file: File) => void | Promise<void>;
8
+ onTextureLoaded?: (texture: LoadedTexture, filename: string, file: File) => void | Promise<void>;
9
+ onUnhandledFile?: (file: File) => void | Promise<void>;
10
+ onFilesLoaded?: (files: File[]) => void | Promise<void>;
11
+ onLoadError?: (error: unknown, filename: string, file: File) => void | Promise<void>;
7
12
  }
8
13
 
9
- function handleFiles(files: File[], onModelLoaded: (model: any, filename: string) => void) {
10
- files.forEach(async (file) => {
11
- const result = await parseModelFromFile(file);
12
- if (result.success && result.model) {
13
- onModelLoaded(result.model, file.name);
14
- } else {
15
- console.error("Model parse error:", result.error);
16
- }
17
- });
14
+ type DivProps = Omit<HTMLAttributes<HTMLDivElement>, "children" | "onDrop" | "onDragOver">;
15
+
16
+ export interface DragDropLoaderProps extends AssetLoadOptions, DivProps {
17
+ children?: ReactNode;
18
18
  }
19
19
 
20
- export function DragDropLoader({ onModelLoaded }: DragDropLoaderProps) {
21
- useEffect(() => {
22
- function handleDrop(e: DragEvent) {
23
- e.preventDefault();
24
- e.stopPropagation();
25
- const files = e.dataTransfer?.files ? Array.from(e.dataTransfer.files) : [];
26
- handleFiles(files, onModelLoaded);
27
- }
28
- function handleDragOver(e: DragEvent) {
29
- e.preventDefault();
30
- e.stopPropagation();
31
- }
32
- window.addEventListener("drop", handleDrop);
33
- window.addEventListener("dragover", handleDragOver);
34
- return () => {
35
- window.removeEventListener("drop", handleDrop);
36
- window.removeEventListener("dragover", handleDragOver);
37
- };
38
- }, [onModelLoaded]);
39
- return null;
20
+ export interface FilePickerProps extends AssetLoadOptions, DivProps {
21
+ accept?: string;
22
+ children?: ReactNode;
23
+ multiple?: boolean;
24
+ }
25
+
26
+ const DEFAULT_ACCEPT = ".glb,.gltf,.fbx,.png,.jpg,.jpeg,.webp,.gif,.bmp,.svg";
27
+
28
+ function getFiles(fileList?: FileList | null) {
29
+ return fileList ? Array.from(fileList) : [];
30
+ }
31
+
32
+ export async function loadFiles(
33
+ files: File[],
34
+ { onModelLoaded, onTextureLoaded, onUnhandledFile, onFilesLoaded, onLoadError }: AssetLoadOptions,
35
+ ) {
36
+ await Promise.all(
37
+ files.map(async (file) => {
38
+ const shouldParseModel = canParseModelFile(file);
39
+ const shouldParseTexture = canParseTextureFile(file);
40
+
41
+ if (shouldParseModel) {
42
+ const result = await parseModelFromFile(file);
43
+
44
+ if (result.success && result.model) {
45
+ await onModelLoaded?.(result.model, file.name, file);
46
+ return;
47
+ }
48
+
49
+ if (onLoadError) {
50
+ await onLoadError(result.error, file.name, file);
51
+ return;
52
+ }
53
+
54
+ console.error("Model parse error:", result.error);
55
+ return;
56
+ }
57
+
58
+ if (shouldParseTexture) {
59
+ const result = await parseTextureFromFile(file);
60
+
61
+ if (result.success && result.texture) {
62
+ await onTextureLoaded?.(result.texture, file.name, file);
63
+ return;
64
+ }
65
+
66
+ if (onLoadError) {
67
+ await onLoadError(result.error, file.name, file);
68
+ return;
69
+ }
70
+
71
+ console.error("Texture parse error:", result.error);
72
+ return;
73
+ }
74
+
75
+ if (onUnhandledFile) {
76
+ await onUnhandledFile(file);
77
+ }
78
+ }),
79
+ );
80
+
81
+ await onFilesLoaded?.(files);
82
+ }
83
+
84
+ function reportFileLoadError(error: unknown) {
85
+ console.error("File load error:", error);
40
86
  }
41
87
 
42
- // FilePicker component
43
- interface FilePickerProps {
44
- onModelLoaded: (model: any, filename: string) => void;
88
+ function createLoadHandlers(options: AssetLoadOptions) {
89
+ return {
90
+ onFilesLoaded: options.onFilesLoaded,
91
+ onModelLoaded: options.onModelLoaded,
92
+ onTextureLoaded: options.onTextureLoaded,
93
+ onUnhandledFile: options.onUnhandledFile,
94
+ onLoadError: options.onLoadError,
95
+ } satisfies AssetLoadOptions;
45
96
  }
46
97
 
47
- export function FilePicker({ onModelLoaded }: FilePickerProps) {
48
- function onChange(e: ChangeEvent<HTMLInputElement>) {
49
- const files = e.target.files ? Array.from(e.target.files) : [];
50
- handleFiles(files, onModelLoaded);
98
+ export function DragDropLoader({
99
+ children,
100
+ ...divProps
101
+ }: DragDropLoaderProps) {
102
+ const loadOptions = createLoadHandlers(divProps);
103
+
104
+ function handleDrop(event: DragEvent<HTMLDivElement>) {
105
+ event.preventDefault();
106
+ event.stopPropagation();
107
+
108
+ void loadFiles(getFiles(event.dataTransfer?.files), loadOptions).catch(reportFileLoadError);
51
109
  }
52
- // Ref for the hidden input
53
- const inputId = "file-picker-input";
110
+
111
+ function handleDragOver(event: DragEvent<HTMLDivElement>) {
112
+ event.preventDefault();
113
+ event.stopPropagation();
114
+ }
115
+
116
+ return (
117
+ <div {...divProps} onDrop={handleDrop} onDragOver={handleDragOver}>
118
+ {children}
119
+ </div>
120
+ );
121
+ }
122
+
123
+ export function FilePicker({
124
+ accept = DEFAULT_ACCEPT,
125
+ children,
126
+ multiple = true,
127
+ ...divProps
128
+ }: FilePickerProps) {
129
+ const inputRef = useRef<HTMLInputElement>(null);
130
+ const { onClick, ...wrapperProps } = divProps;
131
+ const loadOptions = createLoadHandlers(divProps);
132
+
133
+ function onChange(event: ChangeEvent<HTMLInputElement>) {
134
+ void loadFiles(getFiles(event.target.files), loadOptions).catch(reportFileLoadError);
135
+ event.target.value = "";
136
+ }
137
+
138
+ function handleClick(event: MouseEvent<HTMLDivElement>) {
139
+ onClick?.(event);
140
+
141
+ if (!event.defaultPrevented) {
142
+ inputRef.current?.click();
143
+ }
144
+ }
145
+
54
146
  return (
55
- <>
147
+ <div {...wrapperProps} onClick={handleClick}>
56
148
  <input
57
- id={inputId}
149
+ ref={inputRef}
58
150
  type="file"
59
- accept=".glb,.gltf,.fbx"
60
- multiple
151
+ accept={accept}
152
+ multiple={multiple}
61
153
  onChange={onChange}
62
- className="hidden"
154
+ hidden
63
155
  />
64
- <button
65
- className="px-3 py-1 bg-blue-500/20 hover:bg-blue-500/30 border border-blue-400/40 hover:border-blue-400/60 text-blue-200 hover:text-blue-100 text-xs font-medium transition-all"
66
- type="button"
67
- onClick={() => document.getElementById(inputId)?.click()}
68
- >
69
- Select Files
70
- </button>
71
- </>
156
+ {children ?? "Select Files"}
157
+ </div>
72
158
  );
73
159
  }
@@ -0,0 +1,4 @@
1
+ export { DragDropLoader, FilePicker, loadFiles } from "./DragDropLoader";
2
+ export type { AssetLoadOptions, DragDropLoaderProps, FilePickerProps } from "./DragDropLoader";
3
+ export { loadModel, loadTexture, parseModelFromFile, parseTextureFromFile } from "./modelLoader";
4
+ export type { LoadedModel, LoadedTexture, ModelLoadResult, ProgressCallback, TextureLoadResult } from "./modelLoader";