Sure! Let's develop a comprehensive React Three Fiber (R3F) application that fulfills your requirements. We'll create a system where each 3D object (defaulting to a cube) can be selected, manipulated, and have its shape and material properties adjusted via an HTML interface. We'll use Zustand for state management and ensure that each shape uses BufferGeometry for better performance and flexibility.
Overview of Features
- Selectable Objects: Click on any object to select it. The selected object can be manipulated using
TransformControls.
- Dynamic HTML Overlay: Each selected object displays an HTML panel allowing you to change its shape and material properties.
- Multiple Shapes: Start with a default cube, but you can add more shapes (e.g., sphere, cone, etc.) dynamically.
- Material Customization: Adjust material properties like color, metalness, and roughness.
- Optimized State Management: Use Zustand to manage the global state, including the selected object and the scene.
Project Structure
- Context (Store): Manages the global state using Zustand.
- App Component: Sets up the Canvas and overall scene.
- Shapes Component: Renders all the shapes in the scene.
- Shape Component: Represents individual shapes with their properties and controls.
- HTML Overlay: Interface for editing the selected shape's properties.
Let's implement each part step by step.
1. Setting Up Zustand Store
We'll use Zustand to manage the global state, including the list of shapes and the currently selected shape.
// src/store.js
import { create } from "zustand";
// Define available shapes
export const availableShapes = ["Box", "Sphere", "Cone", "Cylinder", "Torus"];
const useStore = create((set) => ({
shapes: [
{
id: 1,
type: "Box",
position: [0, 0, 0],
rotation: [0, 0, 0],
scale: [1, 1, 1],
material: {
color: "#ff9051",
metalness: 0.5,
roughness: 0.5,
},
},
],
selectedShapeId: null,
setSelectedShapeId: (id) => set({ selectedShapeId: id }),
addShape: (shape) =>
set((state) => ({ shapes: [...state.shapes, { id: Date.now(), ...shape }] })),
updateShape: (id, newProps) =>
set((state) => ({
shapes: state.shapes.map((shape) =>
shape.id === id ? { ...shape, ...newProps } : shape
),
})),
removeShape: (id) =>
set((state) => ({
shapes: state.shapes.filter((shape) => shape.id !== id),
selectedShapeId: state.selectedShapeId === id ? null : state.selectedShapeId,
})),
}));
export default useStore;
Explanation:
- shapes: An array of shape objects, each with unique
id, type, position, rotation, scale, and material properties.
- selectedShapeId: The
id of the currently selected shape.
- setSelectedShapeId: Function to set the selected shape.
- addShape: Function to add a new shape to the scene.
- updateShape: Function to update properties of an existing shape.
- removeShape: Function to remove a shape from the scene.
2. Creating the App Component
The App component sets up the 3D Canvas, lighting, controls, and renders the shapes.
// src/App.js
import React, { Suspense } from "react";
import { Canvas } from "@react-three/fiber";
import { OrbitControls, GizmoHelper, GizmoViewport } from "@react-three/drei";
import Shapes from "./Shapes";
import ShapeEditor from "./ShapeEditor";
import useStore from "./store";
function App() {
const selectedShapeId = useStore((state) => state.selectedShapeId);
return (
<>
<Canvas
style={{
position: "absolute",
width: "100%",
height: "100%",
}}
camera={{ position: [5, 5, 5], fov: 60 }}
>
<ambientLight intensity={0.5} />
<directionalLight position={[10, 10, 5]} intensity={1} />
<Suspense fallback={null}>
<Shapes />
</Suspense>
<OrbitControls enabled={!selectedShapeId} />
<GizmoHelper alignment="bottom-right" margin={[80, 80]}>
<GizmoViewport axisColors={["red", "green", "blue"]} labelColor="black" />
</GizmoHelper>
</Canvas>
{selectedShapeId && <ShapeEditor />}
</>
);
}
export default App;
Explanation:
- Canvas: The primary 3D rendering surface.
- Lighting: Ambient and directional lights to illuminate the scene.
- OrbitControls: Allows the user to orbit around the scene when no object is selected.
- GizmoHelper & GizmoViewport: Adds a viewport gizmo for orientation.
- Shapes: Renders all the shapes in the scene.
- ShapeEditor: Displays the HTML overlay for editing the selected shape's properties when a shape is selected.
3. Rendering Shapes
The Shapes component maps through all shapes in the store and renders each using the Shape component.
// src/Shapes.js
import React from "react";
import { TransformControls } from "@react-three/drei";
import useStore, { availableShapes } from "./store";
import Shape from "./Shape";
const Shapes = () => {
const shapes = useStore((state) => state.shapes);
const selectedShapeId = useStore((state) => state.selectedShapeId);
const setSelectedShapeId = useStore((state) => state.setSelectedShapeId);
return (
<>
{shapes.map((shape) => (
<Shape
key={shape.id}
shape={shape}
isSelected={shape.id === selectedShapeId}
onSelect={() => setSelectedShapeId(shape.id)}
/>
))}
</>
);
};
export default Shapes;
Explanation:
- Shapes Mapping: Iterates over all shapes and renders each one.
- Selection Handling: Passes
isSelected prop to indicate if the shape is currently selected and an onSelect handler to select the shape when clicked.
4. Individual Shape Component
The Shape component represents each individual shape in the scene. It handles selection, transformation, and rendering based on its type and material.
// src/Shape.js
import React, { useRef } from "react";
import { Html, TransformControls } from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import useStore from "./store";
import * as THREE from "three";
const Shape = ({ shape, isSelected, onSelect }) => {
const meshRef = useRef();
const transformRef = useRef();
const setSelectedShapeId = useStore((state) => state.setSelectedShapeId);
// Handle pointer down event
const handlePointerDown = (e) => {
e.stopPropagation();
onSelect();
};
// Constrain transformation updates to the store
useFrame(() => {
if (isSelected && transformRef.current) {
const { position, rotation, scale } = transformRef.current.object;
useStore.getState().updateShape(shape.id, {
position: [position.x, position.y, position.z],
rotation: [rotation.x, rotation.y, rotation.z],
scale: [scale.x, scale.y, scale.z],
});
}
});
// Determine geometry based on shape type
const getGeometry = (type) => {
switch (type) {
case "Box":
return <boxBufferGeometry args={[1, 1, 1]} />;
case "Sphere":
return <sphereBufferGeometry args={[0.75, 32, 32]} />;
case "Cone":
return <coneBufferGeometry args={[0.75, 1.5, 32]} />;
case "Cylinder":
return <cylinderBufferGeometry args={[0.75, 0.75, 1.5, 32]} />;
case "Torus":
return <torusBufferGeometry args={[0.5, 0.2, 16, 100]} />;
default:
return <boxBufferGeometry args={[1, 1, 1]} />;
}
};
return (
<group>
<TransformControls
ref={transformRef}
object={meshRef.current}
enabled={isSelected}
onDragStart={() => useStore.getState().setSelectedShapeId(shape.id)}
onDragEnd={() => {}}
>
<mesh ref={meshRef} onPointerDown={handlePointerDown} castShadow receiveShadow>
{getGeometry(shape.type)}
<meshStandardMaterial
color={shape.material.color}
metalness={shape.material.metalness}
roughness={shape.material.roughness}
/>
</mesh>
</TransformControls>
{isSelected && (
<Html position={[0, 1.5, 0]} center distanceFactor={10}>
<div
style={{
background: "white",
padding: "10px",
borderRadius: "8px",
maxWidth: "200px",
}}
>
<strong>Shape ID: {shape.id}</strong>
<br />
<em>Click elsewhere to deselect.</em>
</div>
</Html>
)}
</group>
);
};
export default Shape;
Explanation:
- Geometry Selection: Chooses the appropriate geometry based on the
type of the shape.
- TransformControls: Allows manipulation (translate, rotate, scale) of the selected shape.
- Selection Handling: When a shape is clicked, it becomes the selected shape.
- Html Overlay: Displays basic information when the shape is selected. This can be expanded to include more controls.
5. Creating the Shape Editor (HTML Overlay)
The ShapeEditor component provides a user interface to edit the selected shape's properties, including changing its type and material.
// src/ShapeEditor.js
import React from "react";
import useStore, { availableShapes } from "./store";
const ShapeEditor = () => {
const selectedShape = useStore((state) =>
state.shapes.find((shape) => shape.id === state.selectedShapeId)
);
const updateShape = useStore((state) => state.updateShape);
const removeShape = useStore((state) => state.removeShape);
const setSelectedShapeId = useStore((state) => state.setSelectedShapeId);
if (!selectedShape) return null;
const handleChange = (e) => {
const { name, value } = e.target;
if (["metalness", "roughness"].includes(name)) {
updateShape(selectedShape.id, {
material: {
...selectedShape.material,
[name]: parseFloat(value),
},
});
} else {
updateShape(selectedShape.id, {
[name]: value,
});
}
};
const handleColorChange = (e) => {
const { value } = e.target;
updateShape(selectedShape.id, {
material: {
...selectedShape.material,
color: value,
},
});
};
const handleDelete = () => {
removeShape(selectedShape.id);
};
return (
<div
style={{
position: "absolute",
top: 20,
right: 20,
background: "rgba(255,255,255,0.9)",
padding: "20px",
borderRadius: "8px",
maxWidth: "300px",
boxShadow: "0 2px 10px rgba(0,0,0,0.1)",
}}
>
<h3>Edit Shape</h3>
<div style={{ marginBottom: "10px" }}>
<label>Type:</label>
<select name="type" value={selectedShape.type} onChange={handleChange}>
{availableShapes.map((shape) => (
<option key={shape} value={shape}>
{shape}
</option>
))}
</select>
</div>
<div style={{ marginBottom: "10px" }}>
<label>Color:</label>
<input
type="color"
name="color"
value={selectedShape.material.color}
onChange={handleColorChange}
/>
</div>
<div style={{ marginBottom: "10px" }}>
<label>Metalness:</label>
<input
type="range"
name="metalness"
min="0"
max="1"
step="0.01"
value={selectedShape.material.metalness}
onChange={handleChange}
/>
<span>{selectedShape.material.metalness}</span>
</div>
<div style={{ marginBottom: "10px" }}>
<label>Roughness:</label>
<input
type="range"
name="roughness"
min="0"
max="1"
step="0.01"
value={selectedShape.material.roughness}
onChange={handleChange}
/>
<span>{selectedShape.material.roughness}</span>
</div>
<button onClick={handleDelete} style={{ background: "red", color: "white", padding: "5px 10px", border: "none", borderRadius: "4px", cursor: "pointer" }}>
Delete Shape
</button>
</div>
);
};
export default ShapeEditor;
Explanation:
- Shape Type Selector: Allows changing the shape's type (e.g., Box, Sphere).
- Color Picker: Changes the material's color.
- Metalness & Roughness Sliders: Adjusts the material's metalness and roughness properties.
- Delete Button: Removes the shape from the scene.
- Styling: Positioned absolutely on the screen for easy access.
6. Adding New Shapes
Let's enhance the application by allowing users to add new shapes dynamically.
Update the App Component to Include an Add Shape Button
// src/App.js (updated)
import React, { Suspense } from "react";
import { Canvas } from "@react-three/fiber";
import { OrbitControls, GizmoHelper, GizmoViewport } from "@react-three/drei";
import Shapes from "./Shapes";
import ShapeEditor from "./ShapeEditor";
import useStore, { availableShapes } from "./store";
function App() {
const selectedShapeId = useStore((state) => state.selectedShapeId);
const addShape = useStore((state) => state.addShape);
const handleAddShape = () => {
const randomType = availableShapes[Math.floor(Math.random() * availableShapes.length)];
addShape({
type: randomType,
position: [Math.random() * 4 - 2, Math.random() * 4 - 2, Math.random() * 4 - 2],
rotation: [0, 0, 0],
scale: [1, 1, 1],
material: {
color: "#ffffff",
metalness: 0.5,
roughness: 0.5,
},
});
};
return (
<>
<Canvas
style={{
position: "absolute",
width: "100%",
height: "100%",
}}
camera={{ position: [5, 5, 5], fov: 60 }}
>
<ambientLight intensity={0.5} />
<directionalLight position={[10, 10, 5]} intensity={1} />
<Suspense fallback={null}>
<Shapes />
</Suspense>
<OrbitControls enabled={!selectedShapeId} />
<GizmoHelper alignment="bottom-right" margin={[80, 80]}>
<GizmoViewport axisColors={["red", "green", "blue"]} labelColor="black" />
</GizmoHelper>
</Canvas>
{selectedShapeId && <ShapeEditor />}
<button
onClick={handleAddShape}
style={{
position: "absolute",
top: 20,
left: 20,
padding: "10px 20px",
background: "#28a745",
color: "white",
border: "none",
borderRadius: "8px",
cursor: "pointer",
}}
>
Add Shape
</button>
</>
);
}
export default App;
Explanation:
- Add Shape Button: Positioned at the top-left corner, clicking it adds a new shape with random type and position.
- handleAddShape: Selects a random shape type from the available shapes and adds it to the store with default material properties.
7. Final Touches and Enhancements
Handling Deselection
To allow users to deselect a shape by clicking on the background, update the Shapes component to handle background clicks.
// src/Shapes.js (updated)
import React from "react";
import { TransformControls } from "@react-three/drei";
import useStore, { availableShapes } from "./store";
import Shape from "./Shape";
const Shapes = () => {
const shapes = useStore((state) => state.shapes);
const selectedShapeId = useStore((state) => state.selectedShapeId);
const setSelectedShapeId = useStore((state) => state.setSelectedShapeId);
const handleBackgroundClick = (e) => {
// Deselect when clicking on the background
setSelectedShapeId(null);
};
return (
<group onPointerDown={handleBackgroundClick}>
{shapes.map((shape) => (
<Shape
key={shape.id}
shape={shape}
isSelected={shape.id === selectedShapeId}
onSelect={() => setSelectedShapeId(shape.id)}
/>
))}
</group>
);
};
export default Shapes;
Explanation:
- handleBackgroundClick: When the user clicks on the background (i.e., not on any shape), it deselects the currently selected shape by setting
selectedShapeId to null.
Improving Material Controls
You can further enhance the ShapeEditor by adding more material properties or even texture controls. Here's an example of adding an emissive color picker.
// src/ShapeEditor.js (updated)
import React from "react";
import useStore, { availableShapes } from "./store";
const ShapeEditor = () => {
const selectedShape = useStore((state) =>
state.shapes.find((shape) => shape.id === state.selectedShapeId)
);
const updateShape = useStore((state) => state.updateShape);
const removeShape = useStore((state) => state.removeShape);
const setSelectedShapeId = useStore((state) => state.setSelectedShapeId);
if (!selectedShape) return null;
const handleChange = (e) => {
const { name, value } = e.target;
if (["metalness", "roughness"].includes(name)) {
updateShape(selectedShape.id, {
material: {
...selectedShape.material,
[name]: parseFloat(value),
},
});
} else {
updateShape(selectedShape.id, {
[name]: value,
});
}
};
const handleColorChange = (e) => {
const { value } = e.target;
updateShape(selectedShape.id, {
material: {
...selectedShape.material,
color: value,
},
});
};
const handleDelete = () => {
removeShape(selectedShape.id);
};
return (
<div
style={{
position: "absolute",
top: 20,
right: 20,
background: "rgba(255,255,255,0.95)",
padding: "20px",
borderRadius: "8px",
maxWidth: "300px",
boxShadow: "0 2px 10px rgba(0,0,0,0.2)",
}}
>
<h3>Edit Shape</h3>
<div style={{ marginBottom: "10px" }}>
<label>Type:</label>
<select name="type" value={selectedShape.type} onChange={handleChange}>
{availableShapes.map((shape) => (
<option key={shape} value={shape}>
{shape}
</option>
))}
</select>
</div>
<div style={{ marginBottom: "10px" }}>
<label>Color:</label>
<input
type="color"
name="color"
value={selectedShape.material.color}
onChange={handleColorChange}
/>
</div>
<div style={{ marginBottom: "10px" }}>
<label>Metalness:</label>
<input
type="range"
name="metalness"
min="0"
max="1"
step="0.01"
value={selectedShape.material.metalness}
onChange={handleChange}
/>
<span>{selectedShape.material.metalness}</span>
</div>
<div style={{ marginBottom: "10px" }}>
<label>Roughness:</label>
<input
type="range"
name="roughness"
min="0"
max="1"
step="0.01"
value={selectedShape.material.roughness}
onChange={handleChange}
/>
<span>{selectedShape.material.roughness}</span>
</div>
<button
onClick={handleDelete}
style={{
background: "red",
color: "white",
padding: "8px 12px",
border: "none",
borderRadius: "4px",
cursor: "pointer",
}}
>
Delete Shape
</button>
</div>
);
};
export default ShapeEditor;
8. Final Implementation and Usage
After implementing all the components above, ensure your project structure resembles the following:
src/
├── App.js
├── Shape.js
├── ShapeEditor.js
├── Shapes.js
├── store.js
└── index.js
index.js Setup
Ensure your index.js properly renders the App component.
// src/index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "./styles.css"; // Optional: Add some basic styling
ReactDOM.render(<App />, document.getElementById("root"));
Example styles.css (Optional)
/* src/styles.css */
body {
margin: 0;
overflow: hidden;
font-family: Arial, sans-serif;
}
Installing Dependencies
Make sure you have the necessary dependencies installed. If not, install them using the following command:
npm install react react-dom @react-three/fiber @react-three/drei zustand three
Running the Application
Start your development server:
npm start
Usage
- Adding a Shape: Click the "Add Shape" button to add a new shape with random type and position.
- Selecting a Shape: Click on any shape in the scene to select it. The selected shape will display an HTML overlay with its ID.
- Editing Shape Properties: When a shape is selected, the Shape Editor UI appears on the top-right corner. Use it to change the shape's type, color, metalness, and roughness.
- Manipulating Shapes: Click and drag the selected shape to move, rotate, or scale it using the
TransformControls.
- Deselecting a Shape: Click on the background or press the "Escape" key to deselect the currently selected shape.
- Deleting a Shape: Use the "Delete Shape" button in the Shape Editor to remove the shape from the scene.
Further Enhancements
To make the application even more robust and feature-rich, consider implementing the following:
- Texture Support: Allow users to upload and apply textures to materials.
- Saving and Loading Scenes: Implement functionality to export the scene to formats like GLB or JSON and load them back.
- Grouping Objects: Allow grouping multiple objects together for collective transformations.
- Advanced Material Properties: Enable editing more material properties such as emissive, opacity, etc.
- UI Improvements: Use a UI library like
react-bootstrap or Material-UI for a more polished interface.
- Performance Optimizations: Implement techniques like frustum culling, memoization, and others to optimize rendering performance for complex scenes.
Conclusion
You've now built a dynamic and interactive 3D scene editor using React Three Fiber and Zustand. This setup allows for creating, selecting, manipulating, and editing multiple 3D objects with customizable shapes and materials. By leveraging Zustand's state management and React Three Fiber's declarative 3D rendering, you have a solid foundation for building complex 3D applications.
Feel free to expand upon this foundation to suit your specific project needs!