Back to campField Journalby Zin
All entries

threejs · react-three-fiber · webgl

Three.js & React Three Fiber: Zero to Hero

A complete beginner-to-confident guide to 3D on the web: scenes, cameras, lights, shadows, textures, models and performance in plain Three.js, then the same ideas in React Three Fiber, ending with a small night campsite you can build and click.

28 min read0 likes

Three.js & React Three Fiber: Zero to Hero

Web ပေါ်က 3D ကို အစကနေ ယုံကြည်မှုရှိရှိ ရေးနိုင်တဲ့အထိ လေ့လာမယ့် guide ပါ။ Scene၊ camera၊ light၊ shadow၊ texture၊ model နဲ့ performance တွေကို Three.js သက်သက်နဲ့ အရင်ရေးပြီး၊ အဲဒီ idea တွေကိုပဲ React Three Fiber နဲ့ ပြန်ရေးပါမယ်။ နောက်ဆုံးမှာ click လုပ်လို့ရတဲ့ ညဘက် campsite အသေးလေး တစ်ခု တည်ဆောက်ပါမယ်။

ဖတ်ချိန် 27 မိနစ်0 likes

Every developer has seen one: a product page where you drag a sneaker around, a portfolio that opens on a floating island, a landing page whose logo is made of glass. It looks like magic, and it feels like it needs a games degree. It doesn't. It needs about a dozen ideas, and once you hold them, 3D on the web becomes just another thing you can build.

This guide teaches those ideas twice. First in plain Three.js, so you see every moving part with nothing hidden. Then in React Three Fiber (R3F), which lets you write the same scenes as React components. We finish with a small project: a campsite at night with a flickering fire, a forest of 600 trees drawn in one go, and a tent you can click to switch on a lantern.

What 3D on the web really is

Your screen is a grid of pixels. To draw a 3D scene, something has to work out, about 60 times a second, what colour every pixel should be, given some shapes, some lights and a viewpoint. That work runs on the GPU, the graphics card, because it is millions of small sums done in parallel. Browsers let JavaScript talk to the GPU through WebGL (in every browser for years) and its newer successor WebGPU.

Raw WebGL is very low level: drawing one lit cube takes a couple of hundred lines of buffers and shader code. Three.js wraps all of that in friendly objects like Scene, Camera, Mesh and Light. React Three Fiber sits one level higher: it is a React renderer that turns JSX like <mesh> into those same Three.js objects. Here is the stack:

text
Your code   |   vReact Three Fiber    <mesh>, <boxGeometry />, useFrame()     (optional)   |   vthree.js             Scene, Camera, Mesh, Material, Light   |   vWebGL 2 / WebGPU     the browser's door to the graphics card   |   vGPU                  millions of pixels, about 60 times a second

Line by line

  1. Optional. It does not replace Three.js; it builds Three.js objects from JSX and keeps them in sync with React state.
  2. Where the real 3D concepts live. Everything you learn here still applies when you switch to R3F.
  3. You will almost never touch this layer directly. Three.js speaks it for you, and can speak WebGPU too.

So the order of learning matters. If you learn R3F first, every bug sends you to Three.js documentation you can't read yet. If you learn Three.js first, R3F takes an afternoon.

Before you start

  • JavaScript you are comfortable with: modules, arrow functions, classes, async/await.
  • React basics for part two: components, props, useState, useRef, useEffect.
  • Node.js 20 or newer and a code editor.
  • A browser with WebGL 2, which means any current browser on a computer or phone.
  • No maths degree. You need to know that a position is three numbers (x, y, z) and that angles are in radians (Math.PI is half a turn). That's it.

Part one: Three.js by hand

Start a plain Vite project and add Three.js. Vite gives you a dev server that reloads on save and understands import from npm packages, which is all we need.

sh
npm create vite@latest three-camp -- --template vanillacd three-campnpm install threenpm run dev

Line by line

  1. Makes a tiny project with an index.html and src/main.js. 'vanilla' means no framework.
  2. One package. Extras like OrbitControls and GLTFLoader ship inside it, under three/addons/.
  3. Opens http://localhost:5173. Paste each example below into src/main.js and the page reloads.

Delete everything Vite put in src/main.js and src/style.css. Add one rule to the CSS, canvas { display: block }, and set margin: 0 on the body, so the canvas fills the window without scroll bars.

Your first scene: scene, camera, renderer

Every Three.js program has the same three objects. The scene is the world, a container you put things in. The camera is the eye you look through. The renderer takes the scene and the camera and paints a picture into a <canvas>. Add a mesh to the scene, call the renderer in a loop, and you have an animation.

js
// vanilla/01-hello-cube.jsimport * as THREE from 'three'; // 1. Scene: the world that holds everythingconst scene = new THREE.Scene();scene.background = new THREE.Color('#0d131f'); // 2. Camera: the eye we look throughconst camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 100);camera.position.set(0, 1.2, 4);camera.lookAt(0, 0, 0); // 3. Renderer: draws the scene, as the camera sees it, into a <canvas>const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setPixelRatio(Math.min(devicePixelRatio, 2));renderer.setSize(innerWidth, innerHeight);document.body.appendChild(renderer.domElement); // 4. A mesh = geometry (the shape) + material (the surface)const geometry = new THREE.BoxGeometry(1, 1, 1);const material = new THREE.MeshNormalMaterial();const cube = new THREE.Mesh(geometry, material);scene.add(cube); // 5. The loop: update, then draw, once per frameconst timer = new THREE.Timer();timer.connect(document); renderer.setAnimationLoop((timestamp) => {  timer.update(timestamp);  const delta = timer.getDelta();  cube.rotation.x += 0.6 * delta;  cube.rotation.y += 0.9 * delta;  renderer.render(scene, camera);}); // 6. Keep the picture correct when the window changes sizeaddEventListener('resize', () => {  camera.aspect = innerWidth / innerHeight;  camera.updateProjectionMatrix();  renderer.setSize(innerWidth, innerHeight);});

Line by line

  1. The scene is a tree of objects. Anything not added to it, directly or through a parent, is not drawn.
  2. A plain colour behind everything. Three.js accepts CSS colour strings wherever it takes a colour.
  3. Four numbers: field of view in degrees (50 is a natural lens), aspect ratio (width ÷ height), and the near and far limits. Nothing closer than 0.1 or farther than 100 units is drawn.
  4. x is right, y is up, z points out of the screen towards you. The camera sits 4 units back and a little above the middle.
  5. Turns the camera to face a point, here the centre of the world, where the cube is.
  6. antialias smooths the jagged edges. The renderer creates its own <canvas>, available as renderer.domElement.
  7. Sharp on retina screens, but capped at 2: a 3× phone would otherwise paint 9 times the pixels of a normal screen for little visible gain.
  8. The canvas size in CSS pixels. Here the whole window.
  9. Puts the canvas on the page. Until then it exists only in memory.
  10. The shape: a box 1 × 1 × 1. Units mean whatever you decide; most people treat 1 unit as 1 metre.
  11. The surface. This debug material colours each face by the direction it points, so you can see the shape without any lights.
  12. A mesh pairs one geometry with one material. Many meshes can share the same geometry and material.
  13. Now the cube is part of the world, at position (0, 0, 0) by default.
  14. Measures the time between frames. Timer replaced the older Clock, which has been deprecated since r183.
  15. Pauses the timer while the tab is hidden, so you don't get one huge jump when the reader comes back.
  16. Calls the function before every screen refresh, usually 60 times a second (120 on fast screens). It is requestAnimationFrame, plus support for VR headsets.
  17. Call this once per frame, first. Every read after it in the same frame gives the same values.
  18. Seconds since the last frame, about 0.016 at 60 fps.
  19. Speed × delta, never a fixed amount per frame. Now the cube turns at the same speed on a 60 Hz laptop and a 120 Hz phone.
  20. Draws one picture of the scene from the camera. Without this call, nothing changes on screen.
  21. If the window changes size and you skip this, the picture stretches and goes blurry.
  22. Cameras cache their maths. After changing aspect, fov, near or far, tell the camera to recompute.

Run it and you get a slowly tumbling, rainbow-faced cube. That file is the skeleton of every Three.js project you will ever write: make a scene, a camera and a renderer, add meshes, update and render in a loop, handle resize. Everything from here on adds detail to one of those steps.

The loop and delta time

Three.js does not redraw by itself. Nothing on screen moves unless you change something and call renderer.render() again. The animation loop is where you do both, once per frame, in that order:

  1. Update: read input, move objects, advance animations, using delta so speed doesn't depend on the frame rate.
  2. Render: call renderer.render(scene, camera) once.

Keep the work inside the loop small. At 60 frames a second you have about 16 milliseconds per frame for everything, including the browser's own work. Creating new objects every frame (a new THREE.Vector3() here, a new array there) feeds the garbage collector, and it repays you with stutters. Create helpers once, outside the loop, and reuse them.

Meshes: geometry plus material

A geometry is the shape: a list of points (vertices) joined into triangles. Three.js ships the common ones: BoxGeometry, SphereGeometry, PlaneGeometry, CylinderGeometry, ConeGeometry, TorusGeometry, CircleGeometry and more. Their constructor arguments set the size and how many segments to use: more segments mean a rounder sphere and more triangles to draw.

A material decides how the surface reacts to light. You will use four most of the time:

  • MeshBasicMaterial: a flat colour that ignores light. Good for UI, skies and things that glow.
  • MeshStandardMaterial: physically based (PBR). Set color, roughness (0 is a mirror, 1 is chalk) and metalness (0 or 1, rarely between). Your default choice.
  • MeshPhysicalMaterial: Standard plus extras: clear coat, glass-like transmission, sheen for fabric. Slower, so use it for the hero object only.
  • MeshNormalMaterial: the debug material from the first example. No lights needed.

Light and shadow

Lights come in two kinds. Some light everything evenly and are cheap: AmbientLight (the same from every side) and HemisphereLight (a sky colour from above, a ground colour from below, which looks far more natural). Others come from somewhere and can cast shadows: DirectionalLight (sun-like parallel rays), PointLight (a bulb) and SpotLight (a cone). A good start for almost any scene is one hemisphere light for fill and one directional light as the sun.

This example puts the same sphere in three different materials, lights them, and adds shadows:

js
// vanilla/02-materials-lights.jsimport * as THREE from 'three';import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js'; const scene = new THREE.Scene();scene.background = new THREE.Color('#141a26'); const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.1, 100);camera.position.set(0, 2.2, 7.5);camera.lookAt(0, 0.6, 0); const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setPixelRatio(Math.min(devicePixelRatio, 2));renderer.setSize(innerWidth, innerHeight);renderer.toneMapping = THREE.ACESFilmicToneMapping;renderer.shadowMap.enabled = true;document.body.appendChild(renderer.domElement); // Soft light from all around: blue sky above, brown earth belowconst hemi = new THREE.HemisphereLight('#9db8ff', '#3a2a1a', 0.6);scene.add(hemi); // One warm "sun" that casts shadowsconst sun = new THREE.DirectionalLight('#ffd7a0', 2.4);sun.position.set(4, 6, 3);sun.castShadow = true;sun.shadow.mapSize.set(2048, 2048);sun.shadow.camera.left = -5;sun.shadow.camera.right = 5;sun.shadow.camera.top = 5;sun.shadow.camera.bottom = -5;scene.add(sun); const ground = new THREE.Mesh(  new THREE.PlaneGeometry(20, 20),  new THREE.MeshStandardMaterial({ color: '#2b3245', roughness: 0.95 }),);ground.rotation.x = -Math.PI / 2;ground.receiveShadow = true;scene.add(ground); // The same sphere with three different materialsconst sphere = new THREE.SphereGeometry(0.8, 64, 32);const materials = [  new THREE.MeshBasicMaterial({ color: '#e8a848' }),  new THREE.MeshStandardMaterial({ color: '#e8a848', roughness: 0.45, metalness: 0 }),  new THREE.MeshPhysicalMaterial({ color: '#e8a848', roughness: 0.2, metalness: 1, clearcoat: 1, clearcoatRoughness: 0.1 }),];materials.forEach((material, i) => {  const ball = new THREE.Mesh(sphere, material);  ball.position.set((i - 1) * 2.1, 0.8, 0);  ball.castShadow = true;  scene.add(ball);}); // Metal reflects its surroundings, so give it something to reflectconst pmrem = new THREE.PMREMGenerator(renderer);scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;scene.environmentIntensity = 0.35; renderer.setAnimationLoop(() => renderer.render(scene, camera));

Line by line

  1. A small built-in scene of a lit room. We use it below as something for the metal ball to reflect.
  2. Turns very bright values into ones a screen can show, the way a camera does, instead of clipping them to flat white. ACES Filmic gives a film-like curve.
  3. Shadow switch 1 of 4: the renderer must allow shadows. They are off by default because they cost a lot.
  4. Cheap, soft fill light: blue from above, brown from below, at 0.6 strength. It casts no shadows.
  5. A warm sun. Its rays are parallel, like real sunlight, and they point from its position towards (0, 0, 0).
  6. Shadow switch 2 of 4: the light must cast them.
  7. The resolution of the shadow picture. 2048 is crisp; 512 is blurry but cheaper. Powers of two only.
  8. A directional light renders its shadows through a box-shaped camera. Make the box just big enough to cover the objects; a huge box spreads the same pixels thin and gives blocky shadows.
  9. A flat 20 × 20 rectangle for the ground.
  10. Planes are created standing up, facing you. Rotating -90° around x lays the plane flat on the ground.
  11. Shadow switch 3 of 4: the ground receives shadows.
  12. Left ball: ignores light completely, so it looks like a flat paper disc.
  13. Middle ball: Standard, not metal, half rough. It has proper shading and a soft highlight.
  14. Right ball: full metal with a clear coat on top, like polished brass under lacquer.
  15. Shadow switch 4 of 4: each object that should throw a shadow says so.
  16. Metal shows almost nothing but reflections. With nothing to reflect it looks black, so we give the scene an environment map, built from RoomEnvironment.
  17. How strongly the environment lights the scene. Keep it low here so the sun still leads.
Fig. 01The same sphere three times. Left: MeshBasicMaterial ignores light. Middle: MeshStandardMaterial, roughness 0.45. Right: MeshPhysicalMaterial, metal with a clear coat, reflecting the environment map.

Textures and colour

A texture is an image wrapped onto a geometry. Every built-in geometry already has UV coordinates, which say which part of the image goes where. A PBR material can take several maps at once: a colour map (map), a normalMap for fake small bumps, a roughnessMap, and others. Free, good-quality sets are on ambientCG and Poly Haven.

js
// src/snippets/textures.jsimport * as THREE from 'three'; const loader = new THREE.TextureLoader(); // Colour images are sRGB; tell three, or they look washed outconst color = loader.load('/textures/bark_color.jpg');color.colorSpace = THREE.SRGBColorSpace; // Data maps (normal, roughness) are NOT colours: leave them linearconst normal = loader.load('/textures/bark_normal.jpg');const roughness = loader.load('/textures/bark_roughness.jpg'); // Repeat the image 4 × 4 times across the surfacefor (const map of [color, normal, roughness]) {  map.wrapS = map.wrapT = THREE.RepeatWrapping;  map.repeat.set(4, 4);} export const bark = new THREE.MeshStandardMaterial({  map: color,  normalMap: normal,  roughnessMap: roughness,});

Line by line

  1. Loads images into textures. load() returns the texture at once; the image fills in when it arrives.
  2. The most common texture bug. Photos and colour images are stored in sRGB. Without this line, colours look pale and washed out.
  3. Normal and roughness maps hold numbers, not colours. Leave them in the default linear space.
  4. By default an image is stretched once over the surface. RepeatWrapping lets it tile.
  5. Four copies across and four down. Good for ground, walls and bark.
  6. Plug each texture into its slot. Roughness from the map is multiplied by the roughness number (default 1).

Keep textures small. A 4096 × 4096 image takes at least 64 MB of GPU memory once decoded, whatever its file size on disk. For most web scenes 1024 or 2048 is plenty, and the KTX2 format keeps textures compressed even on the GPU.

Moving around and picking things

Two things make a scene feel alive: moving the camera, and clicking objects. For the camera, Three.js ships OrbitControls (drag to orbit, scroll to zoom, right-drag to pan). For clicking, you use a raycaster: it shoots an invisible ray from the camera through the mouse and tells you what it hits, nearest first.

js
// vanilla/03-interaction.jsimport * as THREE from 'three';import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; const scene = new THREE.Scene();scene.background = new THREE.Color('#0d131f');const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 100);camera.position.set(6, 6, 8); const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setPixelRatio(Math.min(devicePixelRatio, 2));renderer.setSize(innerWidth, innerHeight);document.body.appendChild(renderer.domElement); scene.add(new THREE.HemisphereLight('#c8d8ff', '#202030', 2)); // Drag to orbit, scroll to zoom, right-drag to panconst controls = new OrbitControls(camera, renderer.domElement);controls.enableDamping = true;controls.target.set(0, 0, 0); // A 5 × 5 grid of boxes; each gets its own material so it can light up aloneconst boxes = [];for (let x = -2; x <= 2; x++) {  for (let z = -2; z <= 2; z++) {    const box = new THREE.Mesh(      new THREE.BoxGeometry(0.8, 0.8, 0.8),      new THREE.MeshStandardMaterial({ color: '#3d4b6b' }),    );    box.position.set(x * 1.1, 0, z * 1.1);    scene.add(box);    boxes.push(box);  }} // Raycasting: shoot a ray from the camera through the mouseconst raycaster = new THREE.Raycaster();const pointer = new THREE.Vector2();let hovered = null; addEventListener('pointermove', (event) => {  pointer.x = (event.clientX / innerWidth) * 2 - 1;  pointer.y = -(event.clientY / innerHeight) * 2 + 1;}); addEventListener('click', () => {  if (hovered) hovered.position.y = hovered.position.y > 0 ? 0 : 0.6;}); renderer.setAnimationLoop(() => {  raycaster.setFromCamera(pointer, camera);  const [hit] = raycaster.intersectObjects(boxes, false);  const next = hit ? hit.object : null;  if (next !== hovered) {    hovered?.material.emissive.set('#000000');    next?.material.emissive.set('#e8a848');    document.body.style.cursor = next ? 'pointer' : 'auto';    hovered = next;  }  controls.update();  renderer.render(scene, camera);});

Line by line

  1. Addons live under three/addons/. They are part of the three package, so there's nothing extra to install.
  2. Needs the camera to move and the element to listen on, the canvas.
  3. Adds a little inertia so the camera glides to a stop. It only works if you call controls.update() every frame.
  4. Each box gets its own material. If they all shared one, lighting one up would light up all 25.
  5. Create the raycaster and the pointer vector once and reuse them every frame.
  6. The raycaster wants the mouse in "normalised device coordinates": -1 at the left edge, +1 at the right…
  7. …and +1 at the top, -1 at the bottom. That is why y is flipped.
  8. Clicking the hovered box lifts it 0.6 units, or puts it back.
  9. Aim the ray from the camera through the pointer, every frame, because the camera may have moved.
  10. Test only the boxes, not the whole scene; it is faster and avoids hitting the floor. The result is sorted by distance; we take the nearest.
  11. Emissive colour is light the surface gives off by itself. A cheap and clear hover effect.
  12. Show a hand cursor over clickable things. A small detail that tells people they can click.
  13. Required every frame when damping is on.
Fig. 02The raycaster at work: the cube under the mouse glows amber, and a click lifted it out of the grid.

Loading real models (glTF)

Boxes and spheres take you a long way, but sooner or later you want a real model: a character, a product, a building. Use glTF, the "JPEG of 3D". A .glb file is one binary file holding meshes, materials, textures and animations. Blender exports it directly, and Sketchfab and Poly Pizza offer thousands of free models in it.

js
// vanilla/04-gltf.jsimport * as THREE from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { DRACOLoader, DRACO_GLTF_CONFIG } from 'three/addons/loaders/DRACOLoader.js'; /** Loads a .glb, turns on shadows and starts its first animation. */export async function loadModel(scene, url) {  const draco = new DRACOLoader();  draco.setDecoderPath(DRACO_GLTF_CONFIG);   const loader = new GLTFLoader();  loader.setDRACOLoader(draco);   const gltf = await loader.loadAsync(url, (event) => {    if (event.total) console.log(`loading ${Math.round((event.loaded / event.total) * 100)}%`);  });   gltf.scene.traverse((child) => {    if (child.isMesh) {      child.castShadow = true;      child.receiveShadow = true;    }  });  scene.add(gltf.scene);   const mixer = new THREE.AnimationMixer(gltf.scene);  if (gltf.animations.length) mixer.clipAction(gltf.animations[0]).play();  return mixer; // call mixer.update(delta) every frame}

Line by line

  1. Draco is mesh compression, often 5–10× smaller files. Recent releases ship the decoder inside three, so no CDN path is needed.
  2. Points the Draco loader at the decoder files bundled with three.
  3. Now the GLTFLoader can read both compressed and normal files.
  4. A promise-based load. The second argument reports progress, which you can show as a loading bar.
  5. A model is a tree of objects. traverse visits every node, so you can change all the meshes at once, here to turn on shadows.
  6. gltf.scene is a Group holding the whole model. Add it like any other object, and move or scale it as one.
  7. Plays the animations stored in the file. One mixer per animated model.
  8. Turns a clip ("Walk", "Run"…) into an action you can play, pause, fade or blend.
  9. The mixer only moves forward when you tell it how much time has passed, inside your loop.

Models from the internet are often far too heavy for the web. Before using one, open it at gltf.report to see its size, triangle count and texture sizes. Then shrink it with one command:

sh
npx @gltf-transform/cli optimize fox.glb fox-small.glb --compress draco --texture-compress webp

Line by line

  1. Merges meshes, removes unused data, resizes huge textures, compresses the geometry with Draco and the textures to WebP. A 20 MB download often becomes 2 MB.

Many objects, one draw call

Here is the most important performance idea in 3D. Every separate mesh costs a draw call: the CPU tells the GPU "draw this, with this material, here". The GPU can draw millions of triangles, but a few thousand draw calls a frame will choke the CPU, especially on phones. So when you need many copies of the same thing, such as trees, grass, coins or particles, use an InstancedMesh: one geometry, one material, and a list of positions. Two thousand trees, one draw call.

js
// vanilla/05-forest.jsimport * as THREE from 'three'; const scene = new THREE.Scene();scene.background = new THREE.Color('#0b1220');scene.fog = new THREE.Fog('#0b1220', 14, 40); const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 100);camera.position.set(0, 9, 17);camera.lookAt(0, 0, 0); const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setPixelRatio(Math.min(devicePixelRatio, 2));renderer.setSize(innerWidth, innerHeight);document.body.appendChild(renderer.domElement); scene.add(new THREE.HemisphereLight('#6d86c9', '#120c08', 0.9));const fire = new THREE.PointLight('#ff9a3c', 60, 18, 2);fire.position.set(0, 0.6, 0);scene.add(fire); const ground = new THREE.Mesh(  new THREE.CircleGeometry(30, 64),  new THREE.MeshStandardMaterial({ color: '#1c2418' }),);ground.rotation.x = -Math.PI / 2;scene.add(ground); // 2,000 trees, ONE draw call: one geometry + one material, many matricesconst COUNT = 2000;const tree = new THREE.ConeGeometry(0.5, 1.6, 7);tree.translate(0, 0.8, 0); // move the pivot to the base so trees stand on the groundconst forest = new THREE.InstancedMesh(tree, new THREE.MeshStandardMaterial({ roughness: 0.9 }), COUNT); const dummy = new THREE.Object3D();const color = new THREE.Color();for (let i = 0; i < COUNT; i++) {  const angle = Math.random() * Math.PI * 2;  const radius = 5 + Math.sqrt(Math.random()) * 22; // keep a clearing in the middle  dummy.position.set(Math.cos(angle) * radius, 0, Math.sin(angle) * radius);  dummy.scale.setScalar(0.6 + Math.random() * 1.4);  dummy.rotation.y = Math.random() * Math.PI;  dummy.updateMatrix();  forest.setMatrixAt(i, dummy.matrix);  forest.setColorAt(i, color.setHSL(0.28 + Math.random() * 0.08, 0.5, 0.12 + Math.random() * 0.08));}forest.instanceMatrix.needsUpdate = true;forest.instanceColor.needsUpdate = true;scene.add(forest); const timer = new THREE.Timer();timer.connect(document);renderer.setAnimationLoop((timestamp) => {  timer.update(timestamp);  const t = timer.getElapsed();  fire.intensity = 60 + Math.sin(t * 12) * 6 + Math.sin(t * 7.3) * 4; // flicker  renderer.render(scene, camera);}); setTimeout(() => console.log('draw calls:', renderer.info.render.calls), 1000); // 2: the ground and the whole forest

Line by line

  1. Fog fades distant things into the background colour. It hides the edge of the world and adds depth almost for free.
  2. The campfire: an orange bulb with strength 60, a range of 18 units and decay 2 (real-world falloff).
  3. Try 20000. It still runs smoothly, because the number of draw calls doesn't change.
  4. Cones are built around their middle. Moving the geometry up by half its height puts the pivot at the base, so scaling a tree keeps it standing on the ground.
  5. One geometry, one material, room for COUNT copies.
  6. A helper we never add to the scene. We set its position, scale and rotation, then copy its matrix into each slot.
  7. Without the square root, trees would bunch up near the middle. The 5 + leaves a clearing for the fire.
  8. Bakes position, rotation and scale into one 4 × 4 matrix.
  9. Stores that matrix in slot i. The InstancedMesh holds all 2,000 of them in one buffer for the GPU.
  10. Each copy can have its own colour too. A little variation makes a forest look natural.
  11. Tells three to upload the changed buffers to the GPU. Forget it and nothing shows.
  12. Two sine waves at odd speeds make a flicker that never repeats exactly.
  13. renderer.info counts the work of the last frame. This scene logs 2: the ground and the whole forest.
Fig. 03Two thousand trees in one InstancedMesh, lit by one flickering point light. renderer.info reports 2 draw calls for the whole frame.

One last habit before we switch to React. Removing a mesh from the scene does not free its memory on the GPU. In a long-lived app, such as a configurator that swaps models, dispose of what you remove:

js
// src/snippets/dispose.js// Removing a mesh from the scene does not free GPU memory: dispose it tooexport function removeMesh(scene, mesh) {  scene.remove(mesh);  mesh.geometry.dispose();  const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];  for (const material of materials) {    for (const value of Object.values(material)) {      if (value?.isTexture) value.dispose();    }    material.dispose();  }}

Line by line

  1. Stops drawing it. The geometry and textures are still in GPU memory.
  2. Frees the vertex buffers.
  3. Materials hold textures in many slots (map, normalMap, …). This finds them all.
  4. Frees the compiled shader program. Watch renderer.info.memory to check that the numbers go down.

Part two: React Three Fiber

Vanilla Three.js works well, but look at what grows as a scene gets bigger: lists of objects you have to keep in sync with your data, event listeners you must remember to remove, cleanup code, and state scattered across variables. React already solves those problems for the DOM. React Three Fiber is a React renderer, like react-dom, except that it renders to a Three.js scene instead of the page.

  • Same objects, same speed. R3F creates normal Three.js objects. There's no wrapper layer in the render loop, so a scene runs as fast as the vanilla version.
  • Components. A tree, a tent, a campfire, each a component with props. Reuse and compose them like any React UI.
  • Automatic cleanup. When a component unmounts, R3F removes its objects and disposes of their geometries and materials.
  • Pointer events built in. onClick and onPointerOver on meshes, powered by a raycaster you never write yourself.
  • An ecosystem. drei (helpers), rapier (physics), postprocessing (effects), xr (VR and AR), all made to fit together.
sh
npm create vite@latest r3f-camp -- --template react-tscd r3f-campnpm install three @react-three/fiber @react-three/drei zustandnpm install -D @types/threenpm run dev

Line by line

  1. React with TypeScript. Types matter more in 3D than usual: they tell you which props a mesh or a light accepts.
  2. The renderer. drei is a big box of ready-made helpers. zustand is a tiny state library we use for the mini project.
  3. Three.js is written in JavaScript; its types come from this separate package.

JSX is Three.js

Here is the first cube again, as R3F. Compare it with the vanilla file. It is the same scene, with the plumbing gone:

tsx
// src/snippets/HelloCube.tsximport { Canvas } from '@react-three/fiber'; // The same cube as 01-hello-cube.js, written as JSXexport function HelloCube() {  return (    <Canvas camera={{ position: [0, 1.2, 4], fov: 50 }}>      <color attach="background" args={['#0d131f']} />      <mesh rotation={[0.4, 0.6, 0]} position-y={0}>        <boxGeometry args={[1, 1, 1]} />        <meshNormalMaterial />      </mesh>    </Canvas>  );}

Line by line

  1. Canvas creates the scene, the renderer, a default camera and the render loop, and resizes everything with its parent element. Give the parent a height.
  2. Settings for the default PerspectiveCamera. This is the same position and field of view as the vanilla example.
  3. attach puts the object on a property of its parent, here scene.background, instead of adding it as a child.
  4. new THREE.Mesh(). rotation and position take arrays. position-y is a "dash" prop that sets mesh.position.y alone.
  5. args are the constructor arguments: new THREE.BoxGeometry(1, 1, 1). Children named …Geometry and …Material attach to their mesh by themselves.
  6. new THREE.MeshNormalMaterial(). Any property you can set on the object, you can set as a prop.

The rules are short enough to memorise:

  • Every Three.js class is an element with a lower-case first letter: THREE.PointLight → <pointLight>, THREE.InstancedMesh → <instancedMesh>.
  • args are constructor arguments. Changing them rebuilds the object, so keep them stable.
  • Other props set properties. position={[1, 2, 3]} calls position.set(1, 2, 3); color="orange" calls color.set('orange').
  • Dashes reach inside: position-x={2}, shadow-mapSize={[1024, 1024]}, rotation-y={Math.PI}.
  • attach decides where a child goes; geometries and materials attach automatically.
  • <primitive object={thing} /> drops an existing Three.js object, such as a loaded model, into the tree.

useFrame, refs and events

Animation in R3F happens in useFrame, a hook that runs your function every frame, inside the render loop, just before drawing. The one rule that matters most in all of R3F: inside useFrame, change the Three.js object directly through a ref. Never call setState there. setState 60 times a second re-renders your component 60 times a second, and that is the number one cause of slow R3F apps.

tsx
// src/components/SpinningBox.tsximport { useRef, useState } from 'react';import { useFrame, type ThreeElements } from '@react-three/fiber';import { useCursor } from '@react-three/drei';import type { Mesh } from 'three'; export function SpinningBox(props: ThreeElements['mesh']) {  const ref = useRef<Mesh>(null!);  const [hovered, setHovered] = useState(false);  const [active, setActive] = useState(false);  useCursor(hovered);   // Runs every frame, outside React: mutate the object, never setState here  useFrame((_state, delta) => {    ref.current.rotation.x += 0.6 * delta;    ref.current.rotation.y += 0.9 * delta;  });   return (    <mesh      {...props}      ref={ref}      scale={active ? 1.4 : 1}      onClick={(event) => {        event.stopPropagation();        setActive(!active);      }}      onPointerOver={(event) => {        event.stopPropagation();        setHovered(true);      }}      onPointerOut={() => setHovered(false)}    >      <boxGeometry args={[1, 1, 1]} />      <meshStandardMaterial color={hovered ? '#e8a848' : '#5b7bd5'} />    </mesh>  );}

Line by line

  1. R3F's types: ThreeElements['mesh'] is every prop a <mesh> accepts, so <SpinningBox position={[1, 0, 0]} /> is fully typed.
  2. The ref gives you the real THREE.Mesh after mount. The null! says "this is set before I use it", which is true inside useFrame.
  3. React state is fine for things that change on a click or hover, a few times, not every frame.
  4. A drei hook: sets the page cursor to a pointer while hovered is true, and restores it afterwards.
  5. Runs every frame. state holds the camera, scene, pointer, clock and size; delta is seconds since the last frame, as in part one.
  6. Direct change, no re-render. This is the same line as in the vanilla cube.
  7. A prop driven by state. When active changes, React re-renders once and R3F updates the scale.
  8. Pointer events on a mesh, raycast for you. The event has the hit point, distance, face and the object itself.
  9. R3F events pass through to objects behind, like light through glass. stopPropagation makes this mesh block them.
  10. Fires when the pointer moves onto the mesh. Its partner onPointerOut fires when it leaves.
  11. Changing a material colour through props is cheap. R3F updates the existing material; it doesn't create a new one.

drei: the helper toolbox

@react-three/drei is a large collection of ready-made pieces for R3F. Before writing something yourself, check whether drei has it. The ones you will use in nearly every project:

  • <OrbitControls />: the controls from part one, with damping set up and the loop handled for you.
  • <Environment preset="sunset" />: realistic lighting and reflections from an HDR image in one line. It replaces the PMREM code from part one.
  • <ContactShadows />: a soft shadow under an object without setting up shadow maps. Perfect for product viewers.
  • useGLTF / useAnimations: load models and play their animations, with caching and Draco built in.
  • <Instances> / <Instance>: instancing as components, so each copy can have its own props and events.
  • <Text> and <Text3D>: crisp text inside the scene.
  • <Float>, <Sparkles>, <Stars>, <Cloud>: instant atmosphere.
  • <Html>: pins normal DOM elements, such as a label or a button, to a point in 3D.
  • <Loader /> and useProgress: a loading screen that follows every asset loading behind Suspense.
  • <PerformanceMonitor>, <AdaptiveDpr>, <Bvh>: keep the frame rate up on weaker devices.

Loading models with Suspense

In R3F, loading is handled by React Suspense. useGLTF suspends the component until the file is ready. A <Suspense> boundary above it shows a fallback in the meantime, and drei's <Loader /> shows overall progress. No callbacks, no loading flags.

tsx
// src/components/Model.tsximport { useEffect } from 'react';import { useGLTF, useAnimations } from '@react-three/drei'; // Put the file in public/models/ and it is served from /models/const URL = '/models/fox.glb'; export function Model(props: { scale?: number }) {  const { scene, animations } = useGLTF(URL); // suspends until loaded  const { actions, names } = useAnimations(animations, scene);   useEffect(() => {    const action = actions[names[0]];    action?.reset().fadeIn(0.4).play();    return () => {      action?.fadeOut(0.4);    };  }, [actions, names]);   return <primitive object={scene} {...props} />;} useGLTF.preload(URL); // start downloading before the component renders

Line by line

  1. Files in Vite's public/ folder are served from the site root, so public/models/fox.glb becomes /models/fox.glb.
  2. Loads, caches and returns the parsed glTF. Two components asking for the same URL share one download.
  3. Creates the AnimationMixer and updates it every frame for you. actions holds one action per clip, keyed by name.
  4. Fade the first clip in over 0.4 seconds. To switch animations, fade one out and another in for a smooth blend.
  5. Cleanup: fade out when the component unmounts or the clip changes.
  6. The loaded model is already a Three.js object, so primitive puts it into the tree as it is.
  7. Starts the download when this file is imported, before the component even renders.

To get typed, editable JSX for a model, run gltfjsx. It reads a .glb and writes a React component with one element per mesh, so you can change a material or hide a part with props. With --transform it also compresses the model:

sh
npx gltfjsx public/models/fox.glb --transform --types

Line by line

  1. Writes an optimised copy (Draco, resized WebP textures, merged meshes) next to the generated component.

State outside the loop

Scenes often share state with the rest of the page: the selected colour of a product, whether music is on, which room you are in. Prop drilling through a 3D tree gets messy fast. zustand (by the same pmndrs collective as R3F) gives you a tiny global store. Components subscribe to just the values they need, and a useFrame can read the store without causing re-renders.

ts
// src/store.tsimport { create } from 'zustand'; type CampState = {  lantern: boolean;  toggleLantern: () => void;}; // State that lives outside React's tree: any component can read or change itexport const useCamp = create<CampState>((set) => ({  lantern: true,  toggleLantern: () => set((state) => ({ lantern: !state.lantern })),}));

Line by line

  1. The shape of the store: one value and one action.
  2. Makes a hook. Any component, inside or outside the Canvas, can call useCamp().
  3. Actions update the store by returning the changed part. Every component that reads lantern re-renders; nothing else does.

Mini project: a campsite at night

Time to put it all together. We build a small night scene: a ring of 600 instanced trees around a clearing, a campfire whose light flickers, embers drifting up, a tent you can click to switch its lantern on and off, and an ordinary HTML button that does the same thing through the shared store. Each part is a small component.

Fig. 04The finished campsite, rendered from the code below. Drag to orbit; click the tent or the button to switch the lantern.

The forest

tsx
// src/components/Forest.tsximport { useMemo } from 'react';import { Instances, Instance } from '@react-three/drei'; // A small seeded random, so the forest looks the same on every visitfunction random(seed: number) {  return () => ((seed = (seed * 16807) % 2147483647) - 1) / 2147483646;} export function Forest({ count = 600 }: { count?: number }) {  const trees = useMemo(() => {    const rand = random(42);    return Array.from({ length: count }, () => {      const angle = rand() * Math.PI * 2;      const radius = 7 + Math.sqrt(rand()) * 16;      return {        position: [Math.cos(angle) * radius, 0, Math.sin(angle) * radius] as const,        scale: 0.7 + rand() * 1.3,        color: `hsl(${105 + rand() * 30}, 35%, ${14 + rand() * 10}%)`,      };    });  }, [count]);   return (    <Instances limit={count} castShadow receiveShadow>      <coneGeometry args={[0.5, 1.6, 7]} onUpdate={(geometry) => geometry.translate(0, 0.8, 0)} />      <meshStandardMaterial roughness={0.9} />      {trees.map((tree, i) => (        <Instance key={i} position={tree.position} scale={tree.scale} color={tree.color} />      ))}    </Instances>  );}

Line by line

  1. A seeded random number generator. Math.random would give a new forest on every reload, and different trees on the server and the client.
  2. Compute the 600 positions once. Without useMemo, every re-render would scatter a new forest.
  3. Trees from 7 to 23 units out: a clearing for the camp, spread evenly across the ring.
  4. Tells TypeScript the position is exactly three numbers, the shape the Instance prop wants.
  5. drei's instancing: one InstancedMesh under the hood, with room for count copies.
  6. Runs once the geometry exists. It is the same pivot-to-base trick as part one, done in JSX.
  7. Each Instance is a light component with its own position, scale and colour. It could have onClick too, and R3F would tell you which tree was hit.

The campfire

tsx
// src/components/Campfire.tsximport { useRef } from 'react';import { useFrame } from '@react-three/fiber';import { Sparkles } from '@react-three/drei';import type { Group, PointLight } from 'three'; export function Campfire() {  const light = useRef<PointLight>(null!);  const flames = useRef<Group>(null!);   useFrame((state) => {    const t = state.clock.elapsedTime;    light.current.intensity = 30 + Math.sin(t * 12) * 3 + Math.sin(t * 7.3) * 2;    flames.current.scale.y = 1 + Math.sin(t * 9) * 0.08;  });   return (    <group>      {/* logs */}      {[0, 1, 2].map((i) => (        <mesh key={i} rotation={[Math.PI / 2, 0, (i * Math.PI) / 3]} position-y={0.08} castShadow>          <cylinderGeometry args={[0.07, 0.07, 0.9, 8]} />          <meshStandardMaterial color="#4a2e1c" roughness={1} />        </mesh>      ))}      {/* flames: emissive, so they glow without needing light */}      <group ref={flames}>        <mesh position-y={0.35}>          <coneGeometry args={[0.22, 0.6, 8]} />          <meshStandardMaterial color="#ff7a1a" emissive="#ff5a00" emissiveIntensity={3} toneMapped={false} />        </mesh>        <mesh position-y={0.3} scale={0.6}>          <coneGeometry args={[0.22, 0.6, 8]} />          <meshStandardMaterial color="#ffd27a" emissive="#ffc04a" emissiveIntensity={4} toneMapped={false} />        </mesh>      </group>      <pointLight ref={light} position-y={0.6} color="#ff9a3c" intensity={30} distance={14} decay={2} castShadow shadow-mapSize={[1024, 1024]} />      <Sparkles count={40} scale={[1, 2.4, 1]} position-y={1.3} size={3} speed={0.6} color="#ffb060" />    </group>  );}

Line by line

  1. Refs to the light and the flame group, so useFrame can change them directly.
  2. Seconds since the Canvas started. Good for effects that depend on time, not on how far the last frame moved.
  3. The same two-sine flicker as the vanilla forest, without a single re-render.
  4. The flames stretch a little in time with the light, so the glow and the shape agree.
  5. Three logs, each a cylinder lying flat and turned 60° from the last. Plain React lists work in 3D.
  6. Emissive flames glow without needing light. toneMapped={false} lets them go brighter than white-capped colours, so they really burn.
  7. The firelight. castShadow plus shadow-mapSize (a dash prop) gives the tent and logs real shadows.
  8. drei: 40 glowing points drifting up in a 1 × 2.4 × 1 box. Embers in one line.

The tent and the lantern

tsx
// src/components/Tent.tsximport { useState } from 'react';import { useCursor } from '@react-three/drei';import { useCamp } from '../store'; export function Tent(props: { position: [number, number, number] }) {  const lantern = useCamp((state) => state.lantern);  const toggleLantern = useCamp((state) => state.toggleLantern);  const [hovered, setHovered] = useState(false);  useCursor(hovered);   return (    <group {...props} rotation-y={Math.PI / 4}>      <mesh        position-y={0.75}        castShadow        receiveShadow        onClick={(event) => {          event.stopPropagation();          toggleLantern();        }}        onPointerOver={() => setHovered(true)}        onPointerOut={() => setHovered(false)}      >        {/* a cone with 4 sides is a pyramid: our tent */}        <coneGeometry args={[1.2, 1.5, 4]} />        <meshStandardMaterial color={hovered ? '#d9a35f' : '#b5773d'} roughness={0.8} flatShading />      </mesh>      {/* the lantern, outside the door */}      <group position={[0.75, 0.12, 0.75]}>        <mesh>          <sphereGeometry args={[0.08, 16, 16]} />          <meshStandardMaterial color="#ffe2a8" emissive="#ffc46a" emissiveIntensity={lantern ? 4 : 0} toneMapped={false} />        </mesh>        {lantern && <pointLight color="#ffcf8a" intensity={6} distance={5} />}      </group>    </group>  );}

Line by line

  1. Subscribe to one value. When the lantern changes, only components that read it re-render.
  2. Turn the tent 45° so a flat side, not a corner, faces the fire.
  3. Clicking the tent toggles the lantern in the shared store. The button outside the Canvas will update too.
  4. A cone with only 4 sides is a pyramid. Low-poly shapes like this are cheap and have a style of their own.
  5. Shades each face as one flat colour, which gives the crisp, folded-canvas look.
  6. The lantern sits outside the door. A light inside a closed mesh lights only the inside faces, which you never see.
  7. The bulb glows only while the lantern is on.
  8. Conditional rendering works on lights too. Adding or removing a light makes three recompile the lit materials once. That is fine for a click, but don't do it every frame.

Putting the scene together

tsx
// src/App.tsximport { Suspense, useState } from 'react';import { Canvas } from '@react-three/fiber';import { OrbitControls, Stars, PerformanceMonitor, Loader } from '@react-three/drei';import { Forest } from './components/Forest';import { Campfire } from './components/Campfire';import { Tent } from './components/Tent';import { useCamp } from './store'; // Plain React DOM, outside the Canvas; the store connects it to the 3D tentfunction Hud() {  const lantern = useCamp((state) => state.lantern);  const toggleLantern = useCamp((state) => state.toggleLantern);  return (    <button className="hud" onClick={toggleLantern} aria-pressed={lantern}>      {lantern ? 'Lantern on' : 'Lantern off'}    </button>  );} export default function App() {  const [dpr, setDpr] = useState(1.5);   return (    <>      <Canvas        shadows="percentage"        dpr={dpr}        camera={{ position: [4.5, 3, 5.5], fov: 50 }}        gl={{ antialias: true }}      >        <PerformanceMonitor onIncline={() => setDpr(2)} onDecline={() => setDpr(1)} />        <color attach="background" args={['#0b1220']} />        <fog attach="fog" args={['#0b1220', 12, 30]} />         <hemisphereLight args={['#6d86c9', '#120c08', 0.5]} />        <Stars radius={60} depth={30} count={2500} factor={3} fade speed={0.5} />         <Suspense fallback={null}>          <mesh rotation-x={-Math.PI / 2} receiveShadow>            <circleGeometry args={[30, 64]} />            <meshStandardMaterial color="#1c2418" roughness={1} />          </mesh>          <Campfire />          <Tent position={[-2.2, 0, -1.2]} />          <Forest count={600} />        </Suspense>         <OrbitControls          makeDefault          target={[0, 0.6, 0]}          enableDamping          minDistance={3}          maxDistance={14}          maxPolarAngle={Math.PI / 2.15}        />      </Canvas>      <Hud />      <Loader />    </>  );}

Line by line

  1. A normal React DOM component that lives outside the Canvas. The zustand store connects it to the 3D scene.
  2. It is a toggle button, so screen readers announce "pressed" or "not pressed". 3D scenes still need accessible controls.
  3. The device pixel ratio we render at. PerformanceMonitor lowers or raises it below.
  4. Turns on shadow maps with PCF filtering. Plain shadows (true) asks for PCFSoftShadowMap, which current three no longer has, so it logs a warning.
  5. Start inside the clearing, a little above head height, looking towards the fire.
  6. drei watches the frame rate. On a struggling device it calls onDecline, and we drop to 1× pixels: often the single biggest speed-up on phones.
  7. The same fog as part one, attached to scene.fog. Its colour matches the background, so the forest fades into the night.
  8. Moonlight fill: blue from above, almost black below.
  9. drei: 2,500 stars on a large sphere, one draw call.
  10. Anything that loads (models, textures, fonts) suspends here. Nothing here loads today, but adding a useGLTF later won't need any changes.
  11. The forest floor, laid flat with rotation-x, receiving shadows.
  12. makeDefault registers these controls so other drei helpers can find them. The target is the fire.
  13. Stops the camera going below the ground. Small limits like this make a scene feel finished.
  14. Rendered next to the Canvas, over it. Normal DOM, normal CSS, normal accessibility.
  15. drei's loading overlay. It appears only while something inside Suspense is loading.

Run npm run dev, and the camp appears. Drag to walk around the fire, scroll to step closer, click the tent. On a phone the same code works with touch: one finger to orbit, two to zoom.

Performance in React Three Fiber

Most slow 3D sites are slow for the same handful of reasons. In rough order of how much they help:

  1. Fewer draw calls. Instance repeated objects, merge static meshes, and share geometries and materials.
  2. Lower pixel ratio on weak devices. dpr={[1, 2]} caps it, and PerformanceMonitor adjusts it live.
  3. Smaller assets. Compress models with Draco or Meshopt and textures with KTX2 or WebP. Ship 1K textures, not 4K.
  4. No React work per frame. Mutate through refs in useFrame; keep setState for user actions.
  5. Draw only when needed. For scenes that are still most of the time, render on demand (below).
  6. Fewer lights casting shadows. Each shadow-casting light renders the scene again. Bake shadows into textures when things don't move.
  7. Lazy-load the scene. The 3D bundle is heavy. Load it after the main content, not before.

A product viewer is the classic case for on-demand rendering. Nothing moves until the user drags or changes something, so drawing 60 frames a second of the same picture just drains the battery:

tsx
// src/snippets/OnDemand.tsximport { Canvas, useThree } from '@react-three/fiber';import { OrbitControls } from '@react-three/drei'; function Swatch({ color }: { color: string }) {  const invalidate = useThree((state) => state.invalidate);  return (    <mesh onClick={() => invalidate()}>      <sphereGeometry args={[1, 64, 32]} />      <meshStandardMaterial color={color} />    </mesh>  );} // Draws only when something changes: props, controls, or invalidate()export function ProductViewer({ color }: { color: string }) {  return (    <Canvas frameloop="demand" dpr={[1, 2]}>      <ambientLight intensity={0.6} />      <directionalLight position={[3, 4, 2]} />      <Swatch color={color} />      <OrbitControls />    </Canvas>  );}

Line by line

  1. useThree reads from the Canvas store. invalidate() asks for one new frame.
  2. Call invalidate after you change something yourself, outside React props, such as a manual change through a ref.
  3. Render only when props change, controls move, or invalidate() is called. A still scene uses no GPU time at all.
  4. Use the device pixel ratio, but never above 2.
  5. drei controls call invalidate for you while dragging and damping.

Using it in Next.js

R3F works in Next.js with one rule: the Canvas and everything inside it are client-side, because WebGL exists only in the browser. Put the scene in a file marked 'use client'; a Server Component page can then render it like any other component.

tsx
// app/camp/scene.tsx'use client'; import { Canvas } from '@react-three/fiber';import { OrbitControls } from '@react-three/drei';import { Campfire } from '@/components/Campfire'; export default function Scene() {  return (    <Canvas shadows="percentage" camera={{ position: [4, 3, 5] }}>      <Campfire />      <OrbitControls makeDefault />    </Canvas>  );}

Line by line

  1. Everything this file imports goes to the browser bundle. Hooks like useFrame only work in client components.
  2. A normal component. The page around it can stay a Server Component and render the text, SEO and links on the server.
tsx
// app/camp/lazy-scene.tsx'use client'; import dynamic from 'next/dynamic'; const Scene = dynamic(() => import('./scene'), {  ssr: false,  loading: () => <p className="scene-placeholder">Lighting the fire…</p>,}); export default function LazyScene() {  return <Scene />;}

Line by line

  1. Splits Three.js and the scene into their own chunk, so they load after the page's own code.
  2. Skips server rendering for the scene. This option is only allowed inside a client component, which is why this file has its own use client.
  3. Shown while the chunk downloads. Give its container the same height as the canvas, so the page doesn't jump.

Common mistakes and quick fixes

  • Black screen, no errors. A Standard material with no lights, a camera inside the object, or an object outside the camera's near/far range. Swap in MeshNormalMaterial to test.
  • Nothing at all in R3F. The Canvas fills its parent, and the parent has 0 height. Give it one: height: 100dvh or a fixed size.
  • Washed-out colours. A colour texture without colorSpace = SRGBColorSpace. (R3F and useTexture usually set this for you.)
  • Stretched, blurry picture (vanilla). No resize handler, or updateProjectionMatrix() not called after changing the aspect.
  • Choppy animation. Fixed steps per frame instead of delta, or setState inside useFrame.
  • Slow on phones. Too many draw calls, a pixel ratio of 3, 4K textures, or several shadow-casting lights.
  • Memory keeps growing. Objects removed in vanilla Three.js without dispose(). R3F does this for you when a component unmounts.
  • The model is tiny, huge or missing. Models come in any scale. Use <Center> and <Bounds> from drei, or measure with new THREE.Box3().setFromObject(model).

Where to go next

You now know the core. Each of these opens a new area, and every one builds on what you just learned:

  • Shaders. Write your own materials in GLSL with ShaderMaterial, or in TSL, Three.js's node-based shading language, which compiles to both WebGL and WebGPU.
  • WebGPU. WebGPURenderer from three/webgpu uses WebGPU where the browser has it and falls back to WebGL 2 on its own. In R3F, pass it through the gl prop (example below).
  • Post-processing. Bloom, depth of field and colour grading with @react-three/postprocessing. Bloom on our emissive flames is a two-line upgrade.
  • Physics. @react-three/rapier gives you gravity, collisions and joints with components like <RigidBody>.
  • Scroll scenes. drei's <ScrollControls>, or GSAP ScrollTrigger driving the camera.
  • VR and AR. @react-three/xr turns the same scene into an immersive one.
tsx
// src/snippets/WebGPU.tsximport { Canvas } from '@react-three/fiber';import { WebGPURenderer } from 'three/webgpu'; // WebGPU where the browser has it; three falls back to WebGL 2 by itselfexport function WebGPUCanvas({ children }: { children: React.ReactNode }) {  return (    <Canvas      gl={async (props) => {        const renderer = new WebGPURenderer({ canvas: props.canvas as HTMLCanvasElement, antialias: true });        await renderer.init();        return renderer;      }}    >      {children}    </Canvas>  );}

Line by line

  1. The WebGPU build of three. It falls back to WebGL 2 by itself in browsers without WebGPU.
  2. R3F 9 accepts a function that returns a renderer, or a promise of one, so async setup is fine.
  3. R3F has made the <canvas> already; pass it to the new renderer.
  4. WebGPU needs an async start (asking the browser for a GPU device) before the first frame.

For reference and practice: the official documentation and manual at threejs.org, with hundreds of runnable examples; the R3F docs at r3f.docs.pmnd.rs; and the drei storybook, where you can try every helper live. When you get stuck, the three.js forum and the pmndrs Discord are friendly and fast.

Start small. Rebuild the campsite from memory, then change one thing: a moon, a river, a second tent, a model of your own. 3D gets easier the same way everything in programming does, one small working scene at a time. See you by the fire. 🔥

Developer တိုင်း တစ်ခါလောက်တော့ မြင်ဖူးကြမှာပါ — ဖိနပ်ကို mouse နဲ့ ဆွဲလှည့်ကြည့်လို့ရတဲ့ product page၊ လေထဲမှာ ပေါ်နေတဲ့ ကျွန်းလေးနဲ့ စတဲ့ portfolio၊ logo ကို မှန်နဲ့လုပ်ထားသလို ဖြစ်နေတဲ့ landing page။ မှော်ပညာလိုပဲ ကြည့်ရပြီး game ဘွဲ့ရမှ လုပ်နိုင်မယ် ထင်ရပါတယ်။ တကယ်တော့ မလိုပါဘူး။ Idea တစ်ဒါဇင်လောက်ပဲ လိုပါတယ်။ အဲဒါတွေကို နားလည်သွားရင် web ပေါ်က 3D ဟာ ကိုယ်တည်ဆောက်နိုင်တဲ့ အရာတွေထဲက တစ်ခု ဖြစ်သွားပါပြီ။

ဒီ guide က အဲဒီ idea တွေကို နှစ်ခါ သင်ပေးပါမယ်။ ပထမ Three.js သက်သက်နဲ့ — ဘာမှ ဖုံးကွယ်မထားဘဲ အစိတ်အပိုင်း တိုင်းကို မြင်ရအောင်ပါ။ ပြီးရင် React Three Fiber (R3F) နဲ့ — scene တွေကို React component တွေအဖြစ် ရေးလို့ရပါတယ်။ နောက်ဆုံးမှာ project အသေးလေး တစ်ခု လုပ်ပါမယ် — ညဘက် campsite တစ်ခု၊ တဖျပ်ဖျပ် လင်းနေတဲ့ မီးပုံ၊ တစ်ခါတည်း ဆွဲတဲ့ သစ်ပင် ၆၀၀ ပါတဲ့ တောအုပ်နဲ့ click လုပ်ရင် မီးအိမ် ဖွင့်ပေးတဲ့ တဲလေး။

Web ပေါ်က 3D ဆိုတာ တကယ်တော့ ဘာလဲ

ကိုယ့် screen က pixel တွေနဲ့ ဖွဲ့ထားတဲ့ grid တစ်ခုပါ။ 3D scene တစ်ခုကို ဆွဲဖို့ဆိုရင် shape တွေ၊ light တွေနဲ့ ကြည့်တဲ့နေရာ တစ်ခုကို ပေးပြီး pixel တိုင်း ဘာအရောင် ဖြစ်ရမလဲဆိုတာကို တစ်စက္ကန့်ကို ၆၀ ခါလောက် တွက်ပေးရပါတယ်။ အဲဒီအလုပ်က သေးငယ်တဲ့ တွက်ချက်မှု သန်းပေါင်းများစွာကို တပြိုင်နက် လုပ်ရတာမို့ GPU (graphics card) ပေါ်မှာ run ပါတယ်။ Browser တွေက JavaScript ကို GPU နဲ့ စကားပြောခွင့်ပေးတာက WebGL (browser တိုင်းမှာ နှစ်ပေါင်းများစွာ ရှိပြီးသား) နဲ့ သူ့နောက်ဆက်ခံ WebGPU ကတစ်ဆင့်ပါ။

WebGL သက်သက်က အရမ်း low level ဆန်ပါတယ် — light ထိနေတဲ့ cube တစ်လုံး ဆွဲဖို့တင် buffer နဲ့ shader code စာကြောင်း ရာချီ ရေးရပါတယ်။ Three.js က အဲဒါတွေ အားလုံးကို Scene၊ Camera၊ Mesh၊ Light လို နားလည်ရလွယ်တဲ့ object တွေထဲ ထုပ်ပေးထားပါတယ်။ React Three Fiber က အဲဒီ့ အပေါ်တစ်ထပ်မှာ ရှိပါတယ် — <mesh> လို JSX ကို Three.js object တွေအဖြစ် ပြောင်းပေးတဲ့ React renderer တစ်ခုပါ။ Stack တစ်ခုလုံးက ဒီလိုပါ —

text
Your code   |   vReact Three Fiber    <mesh>, <boxGeometry />, useFrame()     (optional)   |   vthree.js             Scene, Camera, Mesh, Material, Light   |   vWebGL 2 / WebGPU     the browser's door to the graphics card   |   vGPU                  millions of pixels, about 60 times a second

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. မဖြစ်မနေ မလိုပါဘူး။ Three.js ကို အစားမထိုးပါဘူး — JSX ကနေ Three.js object တွေ ဆောက်ပေးပြီး React state နဲ့ အမြဲ ကိုက်ညီနေအောင် လုပ်ပေးတာပါ။
  2. တကယ့် 3D concept တွေက ဒီမှာ ရှိပါတယ်။ ဒီမှာ သင်ယူတာ အားလုံးက R3F ကို ပြောင်းသုံးတဲ့အခါမှာလည်း အသုံးဝင်နေမှာပါ။
  3. ဒီအလွှာကို တိုက်ရိုက် ကိုင်ဖို့ မရှိသလောက်ပါ။ Three.js က ကိုယ့်ကိုယ်စား ပြောပေးပြီး WebGPU လည်း ပြောတတ်ပါတယ်။

ဒါကြောင့် ဘာကို အရင်လေ့လာမလဲဆိုတာ အရေးကြီးပါတယ်။ R3F ကို အရင်သင်ရင် bug တစ်ခုတွေ့တိုင်း ကိုယ်မဖတ်တတ်သေးတဲ့ Three.js documentation ဆီ ရောက်သွားပါလိမ့်မယ်။ Three.js ကို အရင်သင်ထားရင်တော့ R3F ကို နေ့တစ်ဝက်နဲ့ တတ်သွားပါတယ်။

မစခင် ပြင်ဆင်ရမယ့်အရာများ

  • အဆင်ပြေပြေ ရေးတတ်တဲ့ JavaScript — module၊ arrow function၊ class နဲ့ async/await။
  • ဒုတိယပိုင်းအတွက် React အခြေခံ — component၊ props၊ useState၊ useRef၊ useEffect။
  • Node.js 20 နဲ့အထက် နဲ့ code editor တစ်ခု။
  • WebGL 2 ပါတဲ့ browser — ကွန်ပျူတာ ဒါမှမဟုတ် ဖုန်းပေါ်က လက်ရှိ browser မှန်သမျှ ရပါတယ်။
  • သင်္ချာဘွဲ့ မလိုပါ။ နေရာ (position) တစ်ခုဟာ ဂဏန်းသုံးလုံး (x, y, z) ဖြစ်တယ်ဆိုတာနဲ့ ထောင့်တွေကို radian နဲ့ တိုင်းတယ် (Math.PI က တစ်ပတ်ရဲ့ တစ်ဝက်) ဆိုတာ သိရင် လုံလောက်ပါပြီ။

ပထမပိုင်း — Three.js ကို လက်နဲ့ ရေးကြည့်ခြင်း

ရိုးရိုး Vite project တစ်ခု စပြီး Three.js ထည့်ပါ။ Vite က save လုပ်တိုင်း reload လုပ်ပေးတဲ့ dev server ပေးပြီး npm package တွေကနေ import လုပ်တာကိုလည်း နားလည်ပါတယ် — ကျွန်တော်တို့ လိုတာ ဒါပါပဲ။

sh
npm create vite@latest three-camp -- --template vanillacd three-campnpm install threenpm run dev

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. index.html နဲ့ src/main.js ပါတဲ့ project အသေးလေး လုပ်ပေးပါတယ်။ vanilla ဆိုတာ framework မပါဘူးလို့ ဆိုလိုတာပါ။
  2. Package တစ်ခုတည်းပါ။ OrbitControls နဲ့ GLTFLoader လို အပိုတွေက အဲဒီ package ထဲမှာပဲ three/addons/ အောက်မှာ ပါပြီးသားပါ။
  3. http://localhost:5173 ကို ဖွင့်ပေးပါတယ်။ အောက်က ဥပမာတစ်ခုချင်းကို src/main.js ထဲ ကူးထည့်လိုက်ရင် page က reload ဖြစ်ပါမယ်။

Vite က src/main.js နဲ့ src/style.css ထဲ ထည့်ထားတာတွေ အကုန်ဖျက်ပါ။ CSS ထဲမှာ canvas { display: block } ဆိုတဲ့ rule တစ်ခုထည့်ပြီး body မှာ margin: 0 ထားပါ — ဒါဆိုရင် canvas က scroll bar မပါဘဲ window တစ်ခုလုံး ပြည့်နေပါမယ်။

ပထမဆုံး scene — scene၊ camera၊ renderer

Three.js program တိုင်းမှာ object သုံးခုတည်း ပါပါတယ်။ Scene က ကမ္ဘာပါ — အရာတွေ ထည့်ထားတဲ့ container တစ်ခုပါ။ Camera က ကြည့်တဲ့ မျက်လုံးပါ။ Renderer က scene နဲ့ camera ကို ယူပြီး <canvas> ထဲကို ပုံဆွဲပေးပါတယ်။ Scene ထဲကို mesh တစ်ခုထည့်၊ renderer ကို loop ထဲမှာ ခေါ်လိုက်ရင် animation တစ်ခု ရပါပြီ။

js
// vanilla/01-hello-cube.jsimport * as THREE from 'three'; // 1. Scene: the world that holds everythingconst scene = new THREE.Scene();scene.background = new THREE.Color('#0d131f'); // 2. Camera: the eye we look throughconst camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 100);camera.position.set(0, 1.2, 4);camera.lookAt(0, 0, 0); // 3. Renderer: draws the scene, as the camera sees it, into a <canvas>const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setPixelRatio(Math.min(devicePixelRatio, 2));renderer.setSize(innerWidth, innerHeight);document.body.appendChild(renderer.domElement); // 4. A mesh = geometry (the shape) + material (the surface)const geometry = new THREE.BoxGeometry(1, 1, 1);const material = new THREE.MeshNormalMaterial();const cube = new THREE.Mesh(geometry, material);scene.add(cube); // 5. The loop: update, then draw, once per frameconst timer = new THREE.Timer();timer.connect(document); renderer.setAnimationLoop((timestamp) => {  timer.update(timestamp);  const delta = timer.getDelta();  cube.rotation.x += 0.6 * delta;  cube.rotation.y += 0.9 * delta;  renderer.render(scene, camera);}); // 6. Keep the picture correct when the window changes sizeaddEventListener('resize', () => {  camera.aspect = innerWidth / innerHeight;  camera.updateProjectionMatrix();  renderer.setSize(innerWidth, innerHeight);});

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Scene က object တွေရဲ့ tree တစ်ခုပါ။ တိုက်ရိုက်ဖြစ်ဖြစ်၊ parent ကတစ်ဆင့်ဖြစ်ဖြစ် scene ထဲ မထည့်ထားတာမှန်သမျှ မဆွဲပါဘူး။
  2. အရာအားလုံးရဲ့ နောက်ခံ အရောင်ပါ။ Three.js က အရောင်ယူတဲ့ နေရာတိုင်းမှာ CSS color string ကို လက်ခံပါတယ်။
  3. ဂဏန်းလေးလုံး — degree နဲ့ field of view (50 က သဘာဝကျတဲ့ lens)၊ aspect ratio (width ÷ height) နဲ့ near/far ကန့်သတ်ချက်။ 0.1 ထက်နီးတာ၊ 100 unit ထက်ဝေးတာ မဆွဲပါဘူး။
  4. x က ညာဘက်၊ y က အပေါ်၊ z က screen ထဲကနေ ကိုယ့်ဘက်ကို ထွက်လာတဲ့ ဘက်ပါ။ Camera က unit 4 နောက်ဆုတ်ပြီး အလယ်ထက် နည်းနည်းမြင့်တဲ့နေရာမှာ ရှိပါတယ်။
  5. Camera ကို point တစ်ခုဆီ လှည့်ပေးတာပါ — ဒီမှာတော့ cube ရှိတဲ့ ကမ္ဘာ့အလယ်ကိုပါ။
  6. antialias က အစွန်းတွေ ချွန်တက်နေတာကို ချောမွေ့စေပါတယ်။ Renderer က ကိုယ်ပိုင် <canvas> ကို ဆောက်ပြီး renderer.domElement အနေနဲ့ ရယူလို့ရပါတယ်။
  7. Retina screen တွေမှာ ကြည်လင်အောင်လုပ်ပေးပေမဲ့ 2 မှာ ကန့်သတ်ထားပါတယ် — မဟုတ်ရင် 3× ဖုန်းက ရိုးရိုး screen ထက် pixel ၉ ဆ ဆွဲရပြီး မျက်စိနဲ့ မြင်ရတဲ့ ကွာခြားချက်က နည်းနည်းလေးပါ။
  8. CSS pixel နဲ့ canvas အရွယ်အစားပါ။ ဒီမှာတော့ window တစ်ခုလုံးပါ။
  9. Canvas ကို page ပေါ် တင်လိုက်တာပါ။ အဲဒီအချိန်အထိ memory ထဲမှာပဲ ရှိနေပါတယ်။
  10. ပုံသဏ္ဌာန် (shape) — 1 × 1 × 1 box ပါ။ Unit က ကိုယ်သတ်မှတ်သလို အဓိပ္ပာယ်ရပါတယ်၊ လူအများစုက 1 unit ကို 1 meter လို့ သဘောထားပါတယ်။
  11. မျက်နှာပြင် (surface) ပါ။ ဒီ debug material က face တစ်ခုချင်းကို သူမျက်နှာမူတဲ့ ဦးတည်ရာနဲ့ အရောင်ခြယ်ပေးတာမို့ light မပါဘဲ shape ကို မြင်ရပါတယ်။
  12. Mesh တစ်ခုက geometry တစ်ခုနဲ့ material တစ်ခုကို တွဲပေးပါတယ်။ Mesh အများကြီးက geometry နဲ့ material တစ်ခုတည်းကို မျှသုံးလို့ရပါတယ်။
  13. အခု cube က ကမ္ဘာရဲ့ အစိတ်အပိုင်း ဖြစ်သွားပါပြီ — default အနေနဲ့ (0, 0, 0) နေရာမှာပါ။
  14. Frame တစ်ခုနဲ့ တစ်ခုကြား အချိန်ကို တိုင်းပါတယ်။ Timer က r183 ကတည်းက deprecated ဖြစ်သွားတဲ့ Clock အဟောင်းကို အစားထိုးတာပါ။
  15. Tab ကို ဖျောက်ထားတဲ့အချိန်မှာ timer ကို ခဏရပ်ပေးတာမို့ ပြန်လာတဲ့အခါ အချိန် တစ်ခါတည်း အကြီးကြီး ခုန်မသွားပါဘူး။
  16. Screen refresh တိုင်းမတိုင်ခင် function ကို ခေါ်ပေးပါတယ် — များသောအားဖြင့် တစ်စက္ကန့် ၆၀ ခါ (မြန်တဲ့ screen တွေမှာ ၁၂၀)။ requestAnimationFrame အပြင် VR headset support ပါ ပါတာပါ။
  17. Frame တိုင်းမှာ ဒါကို အရင်ဆုံး တစ်ခါ ခေါ်ပါ။ အဲဒီ frame ထဲမှာ နောက်ကဖတ်တာ အားလုံးက တန်ဖိုး တူတူပဲ ရပါမယ်။
  18. နောက်ဆုံး frame ကနေ ကြာခဲ့တဲ့ စက္ကန့်ပါ — 60 fps မှာ 0.016 လောက်ပါ။
  19. Frame တိုင်း ပမာဏ အသေ မပေါင်းပါနဲ့ — အမြန်နှုန်း × delta ကို သုံးပါ။ ဒါဆိုရင် 60 Hz laptop မှာရော 120 Hz ဖုန်းမှာပါ cube က အမြန်နှုန်း တူတူ လည်ပါမယ်။
  20. Scene ကို camera ကနေ ပုံတစ်ပုံ ဆွဲပါတယ်။ ဒါကို မခေါ်ရင် screen ပေါ်မှာ ဘာမှ မပြောင်းပါဘူး။
  21. Window အရွယ်အစား ပြောင်းသွားပြီး ဒါကို မလုပ်ထားရင် ပုံက ဆွဲဆန့်သွားပြီး ဝါးသွားပါတယ်။
  22. Camera တွေက သူ့သင်္ချာကို cache လုပ်ထားပါတယ်။ aspect၊ fov၊ near ဒါမှမဟုတ် far ကို ပြောင်းပြီးရင် ပြန်တွက်ခိုင်းရပါတယ်။

Run ကြည့်လိုက်ရင် face တွေမှာ သက်တံ့ရောင်တွေပါတဲ့ cube တစ်လုံး ဖြည်းဖြည်းချင်း လှိမ့်လည်နေတာ မြင်ရပါမယ်။ အဲဒီ file က ကိုယ်ရေးမယ့် Three.js project တိုင်းရဲ့ အရိုးစုပါ — scene၊ camera၊ renderer ဆောက်၊ mesh တွေထည့်၊ loop ထဲမှာ update လုပ်ပြီး render လုပ်၊ resize ကို ကိုင်တွယ်။ ဒီကနေ ရှေ့ဆက်တာ အားလုံးက အဲဒီအဆင့်တွေထဲက တစ်ခုခုကို အသေးစိတ် ထပ်ဖြည့်တာပါ။

Loop နဲ့ delta time

Three.js က သူ့ဘာသာ ပြန်မဆွဲပါဘူး။ တစ်ခုခုကို ပြောင်းပြီး renderer.render() ကို ထပ်မခေါ်မချင်း screen ပေါ်မှာ ဘာမှ မလှုပ်ပါဘူး။ Animation loop က ဒီနှစ်ခုကို frame တိုင်း၊ ဒီအစဉ်အတိုင်း လုပ်တဲ့နေရာပါ —

  1. Update — input ဖတ်၊ object တွေရွှေ့၊ animation တွေကို ရှေ့ဆက်ပါ။ Frame rate ပေါ် အမြန်နှုန်း မမူတည်အောင် delta ကို သုံးပါ။
  2. Render — renderer.render(scene, camera) ကို တစ်ခါ ခေါ်ပါ။

Loop ထဲက အလုပ်ကို နည်းနည်းပဲ ထားပါ။ တစ်စက္ကန့် frame ၆၀ ဆိုရင် browser ရဲ့ ကိုယ်ပိုင်အလုပ်ပါ အပါအဝင် frame တစ်ခုကို 16 millisecond လောက်ပဲ ရပါတယ်။ Frame တိုင်း object အသစ်တွေ ဆောက်နေရင် (ဒီမှာ new THREE.Vector3()၊ ဟိုမှာ array အသစ်) garbage collector ကို အစာကျွေးနေသလိုဖြစ်ပြီး ပြန်ရလာတာက တုန့်တုန့်နဲ့ ထစ်တာပါ။ Helper တွေကို loop အပြင်မှာ တစ်ခါပဲ ဆောက်ပြီး ပြန်သုံးပါ။

Mesh — geometry နဲ့ material

Geometry က shape ပါ — triangle တွေအဖြစ် ဆက်ထားတဲ့ point (vertex) တွေရဲ့ list တစ်ခုပါ။ Three.js မှာ အသုံးများတာတွေ ပါပြီးသားပါ — BoxGeometry၊ SphereGeometry၊ PlaneGeometry၊ CylinderGeometry၊ ConeGeometry၊ TorusGeometry၊ CircleGeometry စသဖြင့်။ Constructor argument တွေက အရွယ်အစားနဲ့ segment ဘယ်နှခု သုံးမလဲ သတ်မှတ်ပါတယ် — segment များလေ sphere ပိုဝိုင်းလေ၊ ဆွဲရမယ့် triangle ပိုများလေပါ။

Material က မျက်နှာပြင်က light ကို ဘယ်လိုတုံ့ပြန်မလဲ ဆုံးဖြတ်ပါတယ်။ အများအားဖြင့် လေးမျိုး သုံးဖြစ်ပါမယ် —

  • MeshBasicMaterial — light ကို လျစ်လျူရှုတဲ့ အရောင်ပြား။ UI၊ ကောင်းကင်နဲ့ အလင်းထုတ်နေတဲ့ အရာတွေအတွက် ကောင်းပါတယ်။
  • MeshStandardMaterial — physically based (PBR)။ color၊ roughness (0 က မှန်၊ 1 က မြေဖြူ) နဲ့ metalness (0 ဒါမှမဟုတ် 1၊ ကြားက တန်ဖိုး ရှားပါတယ်) ကို သတ်မှတ်ပါ။ Default ရွေးချယ်မှုပါ။
  • MeshPhysicalMaterial — Standard အပြင် clear coat၊ မှန်လို ဖောက်ထွင်းမြင်ရတဲ့ transmission၊ အထည်အတွက် sheen စတာတွေ ပါပါတယ်။ ပိုနှေးတာမို့ အဓိက object တစ်ခုတည်းအတွက်ပဲ သုံးပါ။
  • MeshNormalMaterial — ပထမ ဥပမာထဲက debug material ပါ။ Light မလိုပါဘူး။

Light နဲ့ shadow

Light တွေ နှစ်မျိုး ရှိပါတယ်။ တချို့က အရာအားလုံးကို ညီညီညာညာ လင်းစေပြီး ဈေးပေါပါတယ် — AmbientLight (ဘက်တိုင်းကနေ အတူတူ) နဲ့ HemisphereLight (အပေါ်က ကောင်းကင်အရောင်၊ အောက်က မြေအရောင် — ပိုသဘာဝကျပါတယ်)။ တချို့က တစ်နေရာရာကနေ လာပြီး shadow ချနိုင်ပါတယ် — DirectionalLight (နေရောင်လို အပြိုင်ရောင်ခြည်)၊ PointLight (မီးသီး) နဲ့ SpotLight (ပုံးပုံ)။ Scene တော်တော်များများအတွက် ကောင်းတဲ့ အစက fill အတွက် hemisphere light တစ်ခုနဲ့ နေအဖြစ် directional light တစ်ခုပါ။

ဒီဥပမာက sphere တစ်ခုတည်းကို material သုံးမျိုးနဲ့ ထားပြီး light ထိုးကာ shadow ထည့်ထားပါတယ် —

js
// vanilla/02-materials-lights.jsimport * as THREE from 'three';import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js'; const scene = new THREE.Scene();scene.background = new THREE.Color('#141a26'); const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.1, 100);camera.position.set(0, 2.2, 7.5);camera.lookAt(0, 0.6, 0); const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setPixelRatio(Math.min(devicePixelRatio, 2));renderer.setSize(innerWidth, innerHeight);renderer.toneMapping = THREE.ACESFilmicToneMapping;renderer.shadowMap.enabled = true;document.body.appendChild(renderer.domElement); // Soft light from all around: blue sky above, brown earth belowconst hemi = new THREE.HemisphereLight('#9db8ff', '#3a2a1a', 0.6);scene.add(hemi); // One warm "sun" that casts shadowsconst sun = new THREE.DirectionalLight('#ffd7a0', 2.4);sun.position.set(4, 6, 3);sun.castShadow = true;sun.shadow.mapSize.set(2048, 2048);sun.shadow.camera.left = -5;sun.shadow.camera.right = 5;sun.shadow.camera.top = 5;sun.shadow.camera.bottom = -5;scene.add(sun); const ground = new THREE.Mesh(  new THREE.PlaneGeometry(20, 20),  new THREE.MeshStandardMaterial({ color: '#2b3245', roughness: 0.95 }),);ground.rotation.x = -Math.PI / 2;ground.receiveShadow = true;scene.add(ground); // The same sphere with three different materialsconst sphere = new THREE.SphereGeometry(0.8, 64, 32);const materials = [  new THREE.MeshBasicMaterial({ color: '#e8a848' }),  new THREE.MeshStandardMaterial({ color: '#e8a848', roughness: 0.45, metalness: 0 }),  new THREE.MeshPhysicalMaterial({ color: '#e8a848', roughness: 0.2, metalness: 1, clearcoat: 1, clearcoatRoughness: 0.1 }),];materials.forEach((material, i) => {  const ball = new THREE.Mesh(sphere, material);  ball.position.set((i - 1) * 2.1, 0.8, 0);  ball.castShadow = true;  scene.add(ball);}); // Metal reflects its surroundings, so give it something to reflectconst pmrem = new THREE.PMREMGenerator(renderer);scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;scene.environmentIntensity = 0.35; renderer.setAnimationLoop(() => renderer.render(scene, camera));

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Light ထိုးထားတဲ့ အခန်းတစ်ခုရဲ့ built-in scene အသေးလေးပါ။ အောက်မှာ metal ဘောလုံး ရောင်ပြန်ဟပ်ဖို့ အရာအဖြစ် သုံးပါမယ်။
  2. အရမ်းလင်းတဲ့ တန်ဖိုးတွေကို အဖြူပြားအဖြစ် ဖြတ်ပစ်မယ့်အစား camera တစ်လုံးလိုပဲ screen ပြနိုင်တဲ့ တန်ဖိုးတွေအဖြစ် ပြောင်းပေးပါတယ်။ ACES Filmic က ရုပ်ရှင်ဆန်တဲ့ curve ပေးပါတယ်။
  3. Shadow switch 1/4 — renderer က shadow ကို ခွင့်ပြုရပါမယ်။ ကုန်ကျစရိတ် များလို့ default မှာ ပိတ်ထားပါတယ်။
  4. ဈေးပေါပြီး နူးညံ့တဲ့ fill light — အပေါ်က အပြာ၊ အောက်က အညို၊ ပြင်းအား 0.6။ Shadow မချပါဘူး။
  5. နွေးထွေးတဲ့ နေ။ ရောင်ခြည်တွေက တကယ့်နေရောင်လို အပြိုင်ဖြစ်ပြီး သူ့ position ကနေ (0, 0, 0) ဘက်ကို ညွှန်ပါတယ်။
  6. Shadow switch 2/4 — light က shadow ချရပါမယ်။
  7. Shadow ပုံရဲ့ resolution ပါ။ 2048 က ကြည်လင်ပြီး 512 က ဝါးပေမဲ့ ဈေးပေါပါတယ်။ Power of two တွေပဲ သုံးပါ။
  8. Directional light က shadow တွေကို box ပုံ camera တစ်ခုကနေ render လုပ်ပါတယ်။ Box ကို object တွေ ဖုံးမိရုံလောက်ပဲ ထားပါ — box အကြီးကြီးဆိုရင် pixel တူတူကို ပါးပါးလေး ဖြန့်ရတာမို့ shadow တွေ တုံးတုံးဖြစ်သွားပါတယ်။
  9. မြေပြင်အတွက် 20 × 20 စတုဂံ အပြားပါ။
  10. Plane တွေက ကိုယ့်ကို မျက်နှာမူပြီး မတ်တပ်ရပ်လျက် ဆောက်ပါတယ်။ x ဝင်ရိုးမှာ -90° လှည့်လိုက်ရင် မြေပြင်ပေါ် ပြားပြားလေး ချထားသလို ဖြစ်သွားပါတယ်။
  11. Shadow switch 3/4 — မြေပြင်က shadow ကို လက်ခံပါတယ်။
  12. ဘယ်ဘက်ဘောလုံး — light ကို လုံးဝ လျစ်လျူရှုတာမို့ စက္ကူဝိုင်းပြားလေးလို ပြားပြားလေး မြင်ရပါတယ်။
  13. အလယ်ဘောလုံး — Standard၊ metal မဟုတ်၊ တစ်ဝက်ကြမ်းပါတယ်။ အရိပ်အလင်း မှန်မှန်ကန်ကန်နဲ့ နူးညံ့တဲ့ highlight ရှိပါတယ်။
  14. ညာဘက်ဘောလုံး — အပေါ်မှာ clear coat ပါတဲ့ metal အပြည့်ပါ၊ lacquer သုတ်ထားတဲ့ ကြေးဝါလိုပါ။
  15. Shadow switch 4/4 — shadow ချရမယ့် object တိုင်းက ကိုယ်တိုင် ပြောရပါတယ်။
  16. Metal က ရောင်ပြန်ဟပ်မှုကလွဲရင် ဘာမှ မပြသလောက်ပါ။ ရောင်ပြန်ဟပ်စရာ မရှိရင် မည်းနေတာမို့ RoomEnvironment ကနေ ဆောက်ထားတဲ့ environment map ကို scene ကို ပေးလိုက်ပါတယ်။
  17. Environment က scene ကို ဘယ်လောက် ပြင်းပြင်း လင်းစေမလဲပါ။ နေက ဦးဆောင်နေဆဲ ဖြစ်အောင် ဒီမှာ နိမ့်နိမ့်ပဲ ထားပါ။
Fig. 01Sphere တစ်ခုတည်း သုံးခါ။ ဘယ် — MeshBasicMaterial က light ကို လျစ်လျူရှုပါတယ်။ အလယ် — MeshStandardMaterial၊ roughness 0.45။ ညာ — clear coat ပါတဲ့ metal ဖြစ်တဲ့ MeshPhysicalMaterial၊ environment map ကို ရောင်ပြန်ဟပ်နေပါတယ်။

Texture နဲ့ အရောင်

Texture ဆိုတာ geometry ပေါ်ကို ပတ်ထားတဲ့ ပုံတစ်ပုံပါ။ Built-in geometry တိုင်းမှာ UV coordinate တွေ ပါပြီးသားဖြစ်ပြီး ပုံရဲ့ ဘယ်အပိုင်းက ဘယ်နေရာ သွားမလဲ ပြောပါတယ်။ PBR material တစ်ခုက map အများကြီးကို တပြိုင်နက် ယူနိုင်ပါတယ် — အရောင် map (map)၊ အဖုအထစ် သေးသေးလေးတွေ အတုလုပ်ဖို့ normalMap၊ roughnessMap စသဖြင့်ပါ။ အခမဲ့ အရည်အသွေးကောင်းတဲ့ set တွေကို ambientCG နဲ့ Poly Haven မှာ ရနိုင်ပါတယ်။

js
// src/snippets/textures.jsimport * as THREE from 'three'; const loader = new THREE.TextureLoader(); // Colour images are sRGB; tell three, or they look washed outconst color = loader.load('/textures/bark_color.jpg');color.colorSpace = THREE.SRGBColorSpace; // Data maps (normal, roughness) are NOT colours: leave them linearconst normal = loader.load('/textures/bark_normal.jpg');const roughness = loader.load('/textures/bark_roughness.jpg'); // Repeat the image 4 × 4 times across the surfacefor (const map of [color, normal, roughness]) {  map.wrapS = map.wrapT = THREE.RepeatWrapping;  map.repeat.set(4, 4);} export const bark = new THREE.MeshStandardMaterial({  map: color,  normalMap: normal,  roughnessMap: roughness,});

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. ပုံတွေကို texture အဖြစ် load လုပ်ပါတယ်။ load() က texture ကို ချက်ချင်း ပြန်ပေးပြီး ပုံရောက်လာတဲ့အခါ ဖြည့်ပေးပါတယ်။
  2. အဖြစ်အများဆုံး texture bug ပါ။ ဓာတ်ပုံနဲ့ အရောင်ပုံတွေကို sRGB နဲ့ သိမ်းထားပါတယ်။ ဒီစာကြောင်း မပါရင် အရောင်တွေ ဖျော့ပြီး မှိန်နေပါမယ်။
  3. Normal နဲ့ roughness map တွေက အရောင် မဟုတ်ဘဲ ဂဏန်းတွေ သိမ်းထားတာပါ။ Default linear space မှာပဲ ထားပါ။
  4. Default မှာ ပုံကို မျက်နှာပြင်ပေါ် တစ်ခါတည်း ဆွဲဆန့်ပါတယ်။ RepeatWrapping က ကြွေပြားလို ထပ်ခါထပ်ခါ ခင်းခွင့်ပေးပါတယ်။
  5. အလျားလိုက် လေးခု၊ ဒေါင်လိုက် လေးခု။ မြေပြင်၊ နံရံနဲ့ သစ်ခေါက်အတွက် ကောင်းပါတယ်။
  6. Texture တစ်ခုချင်းကို သူ့ slot ထဲ ထည့်ပါ။ Map ထဲက roughness ကို roughness ဂဏန်း (default 1) နဲ့ မြှောက်ပါတယ်။

Texture တွေကို သေးသေးလေးပဲ ထားပါ။ 4096 × 4096 ပုံတစ်ပုံက disk ပေါ်မှာ file size ဘယ်လောက်ပဲဖြစ်ဖြစ် decode လုပ်ပြီးတာနဲ့ GPU memory အနည်းဆုံး 64 MB ယူပါတယ်။ Web scene အများစုအတွက် 1024 ဒါမှမဟုတ် 2048 လုံလောက်ပါတယ်။ KTX2 format က GPU ပေါ်မှာတောင် texture တွေကို compress လုပ်ထားပေးပါတယ်။

လှည့်ပတ်ကြည့်ခြင်းနဲ့ အရာတွေကို ရွေးခြင်း

Scene တစ်ခုကို အသက်ဝင်စေတာ နှစ်ခုရှိပါတယ် — camera ကို ရွှေ့တာနဲ့ object တွေကို click လုပ်တာပါ။ Camera အတွက် Three.js မှာ OrbitControls ပါပါတယ် (ဆွဲရင် ပတ်လည်၊ scroll ရင် zoom၊ right-drag ရင် pan)။ Click အတွက်တော့ raycaster ကို သုံးပါတယ် — camera ကနေ mouse ကိုဖြတ်ပြီး မမြင်ရတဲ့ ရောင်ခြည်တစ်ခု ပစ်လိုက်ပြီး ဘာကို ထိလဲ အနီးဆုံးကနေ စပြီး ပြောပြပါတယ်။

js
// vanilla/03-interaction.jsimport * as THREE from 'three';import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; const scene = new THREE.Scene();scene.background = new THREE.Color('#0d131f');const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 100);camera.position.set(6, 6, 8); const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setPixelRatio(Math.min(devicePixelRatio, 2));renderer.setSize(innerWidth, innerHeight);document.body.appendChild(renderer.domElement); scene.add(new THREE.HemisphereLight('#c8d8ff', '#202030', 2)); // Drag to orbit, scroll to zoom, right-drag to panconst controls = new OrbitControls(camera, renderer.domElement);controls.enableDamping = true;controls.target.set(0, 0, 0); // A 5 × 5 grid of boxes; each gets its own material so it can light up aloneconst boxes = [];for (let x = -2; x <= 2; x++) {  for (let z = -2; z <= 2; z++) {    const box = new THREE.Mesh(      new THREE.BoxGeometry(0.8, 0.8, 0.8),      new THREE.MeshStandardMaterial({ color: '#3d4b6b' }),    );    box.position.set(x * 1.1, 0, z * 1.1);    scene.add(box);    boxes.push(box);  }} // Raycasting: shoot a ray from the camera through the mouseconst raycaster = new THREE.Raycaster();const pointer = new THREE.Vector2();let hovered = null; addEventListener('pointermove', (event) => {  pointer.x = (event.clientX / innerWidth) * 2 - 1;  pointer.y = -(event.clientY / innerHeight) * 2 + 1;}); addEventListener('click', () => {  if (hovered) hovered.position.y = hovered.position.y > 0 ? 0 : 0.6;}); renderer.setAnimationLoop(() => {  raycaster.setFromCamera(pointer, camera);  const [hit] = raycaster.intersectObjects(boxes, false);  const next = hit ? hit.object : null;  if (next !== hovered) {    hovered?.material.emissive.set('#000000');    next?.material.emissive.set('#e8a848');    document.body.style.cursor = next ? 'pointer' : 'auto';    hovered = next;  }  controls.update();  renderer.render(scene, camera);});

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Addon တွေက three/addons/ အောက်မှာ ရှိပါတယ်။ three package ရဲ့ အစိတ်အပိုင်းမို့ ထပ် install စရာ မလိုပါဘူး။
  2. ရွှေ့ရမယ့် camera နဲ့ နားထောင်ရမယ့် element (canvas) ကို လိုပါတယ်။
  3. Camera က ဖြည်းဖြည်းချင်း လျှောရပ်သွားအောင် inertia နည်းနည်း ထည့်ပေးပါတယ်။ Frame တိုင်း controls.update() ကို ခေါ်မှ အလုပ်လုပ်ပါတယ်။
  4. Box တစ်ခုချင်းစီက ကိုယ်ပိုင် material ရပါတယ်။ တစ်ခုတည်းကို မျှသုံးထားရင် တစ်ခု လင်းတာနဲ့ ၂၅ ခုလုံး လင်းသွားပါမယ်။
  5. Raycaster နဲ့ pointer vector ကို တစ်ခါပဲ ဆောက်ပြီး frame တိုင်း ပြန်သုံးပါ။
  6. Raycaster က mouse ကို "normalised device coordinates" နဲ့ လိုချင်ပါတယ် — ဘယ်ဘက်အစွန်းမှာ -1၊ ညာဘက်မှာ +1…
  7. …အပေါ်မှာ +1၊ အောက်မှာ -1 ပါ။ ဒါကြောင့် y ကို ပြောင်းပြန်လှန်ထားတာပါ။
  8. Hover ဖြစ်နေတဲ့ box ကို click လုပ်ရင် 0.6 unit မြှင့်တင်ပါတယ်၊ ဒါမှမဟုတ် နေရာဟောင်း ပြန်ချပါတယ်။
  9. Camera ရွှေ့ထားနိုင်တာမို့ frame တိုင်း ray ကို camera ကနေ pointer ကိုဖြတ်ပြီး ချိန်ပါ။
  10. Scene တစ်ခုလုံးမဟုတ်ဘဲ box တွေကိုပဲ စစ်ပါ — ပိုမြန်ပြီး ကြမ်းပြင်ကို မထိမိအောင်ပါ။ Result ကို အကွာအဝေးအလိုက် စီထားပြီး အနီးဆုံးကို ယူပါတယ်။
  11. Emissive color ဆိုတာ မျက်နှာပြင်က ကိုယ်တိုင်ထုတ်တဲ့ အလင်းပါ။ ဈေးပေါပြီး ရှင်းလင်းတဲ့ hover effect ပါ။
  12. Click လုပ်လို့ရတဲ့ အရာပေါ်မှာ လက်ပုံ cursor ပြပါ။ Click လုပ်လို့ရတယ်ဆိုတာ ပြောပြတဲ့ အသေးစိတ်လေးပါ။
  13. Damping ဖွင့်ထားရင် frame တိုင်း မဖြစ်မနေ ခေါ်ရပါမယ်။
Fig. 02Raycaster အလုပ်လုပ်နေပုံ — mouse အောက်က cube က ပယင်းရောင် လင်းနေပြီး click တစ်ချက်နဲ့ grid ထဲကနေ မြင့်တက်လာပါတယ်။

တကယ့် model တွေ load လုပ်ခြင်း (glTF)

Box နဲ့ sphere တွေနဲ့ အတော်ဝေးဝေး ရောက်နိုင်ပေမဲ့ တစ်နေ့နေ့မှာ တကယ့် model တစ်ခု လိုလာပါလိမ့်မယ် — character၊ product ဒါမှမဟုတ် အဆောက်အအုံ။ "3D ရဲ့ JPEG" လို့ ခေါ်တဲ့ glTF ကို သုံးပါ။ .glb file တစ်ခုက mesh၊ material၊ texture နဲ့ animation တွေကို binary file တစ်ခုတည်းထဲမှာ ထည့်ထားပါတယ်။ Blender က တိုက်ရိုက် export လုပ်ပေးနိုင်ပြီး Sketchfab နဲ့ Poly Pizza မှာ အခမဲ့ model ထောင်ပေါင်းများစွာ ရှိပါတယ်။

js
// vanilla/04-gltf.jsimport * as THREE from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { DRACOLoader, DRACO_GLTF_CONFIG } from 'three/addons/loaders/DRACOLoader.js'; /** Loads a .glb, turns on shadows and starts its first animation. */export async function loadModel(scene, url) {  const draco = new DRACOLoader();  draco.setDecoderPath(DRACO_GLTF_CONFIG);   const loader = new GLTFLoader();  loader.setDRACOLoader(draco);   const gltf = await loader.loadAsync(url, (event) => {    if (event.total) console.log(`loading ${Math.round((event.loaded / event.total) * 100)}%`);  });   gltf.scene.traverse((child) => {    if (child.isMesh) {      child.castShadow = true;      child.receiveShadow = true;    }  });  scene.add(gltf.scene);   const mixer = new THREE.AnimationMixer(gltf.scene);  if (gltf.animations.length) mixer.clipAction(gltf.animations[0]).play();  return mixer; // call mixer.update(delta) every frame}

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Draco က mesh compression ပါ — file တွေ ၅ ဆကနေ ၁၀ ဆအထိ သေးသွားတတ်ပါတယ်။ နောက်ဆုံး release တွေမှာ decoder ကို three ထဲမှာ ထည့်ပေးထားတာမို့ CDN path မလိုတော့ပါဘူး။
  2. Draco loader ကို three နဲ့အတူ ပါလာတဲ့ decoder file တွေဆီ ညွှန်ပေးပါတယ်။
  3. အခု GLTFLoader က compress လုပ်ထားတဲ့ file ရော ရိုးရိုး file ပါ ဖတ်နိုင်ပါပြီ။
  4. Promise အခြေခံ load ပါ။ ဒုတိယ argument က progress ကို report လုပ်ပေးတာမို့ loading bar အဖြစ် ပြလို့ရပါတယ်။
  5. Model တစ်ခုက object တွေရဲ့ tree ပါ။ traverse က node တိုင်းကို လှည့်လည်သွားတာမို့ mesh အားလုံးကို တစ်ခါတည်း ပြောင်းလို့ရပါတယ် — ဒီမှာ shadow ဖွင့်ဖို့ပါ။
  6. gltf.scene က model တစ်ခုလုံးကို ကိုင်ထားတဲ့ Group ပါ။ တခြား object တွေလိုပဲ ထည့်ပြီး တစ်ခုတည်းအနေနဲ့ ရွှေ့တာ၊ scale လုပ်တာ လုပ်ပါ။
  7. File ထဲမှာ သိမ်းထားတဲ့ animation တွေကို ဖွင့်ပေးပါတယ်။ Animated model တစ်ခုကို mixer တစ်ခုပါ။
  8. Clip ("Walk"၊ "Run"…) တစ်ခုကို play၊ pause၊ fade၊ blend လုပ်လို့ရတဲ့ action အဖြစ် ပြောင်းပေးပါတယ်။
  9. Mixer က အချိန် ဘယ်လောက်ကြာသွားပြီလဲ loop ထဲကနေ ပြောပြမှ ရှေ့ဆက်ပါတယ်။

Internet ပေါ်က model တွေက web အတွက် အရမ်းလေးနေတတ်ပါတယ်။ မသုံးခင် gltf.report မှာ ဖွင့်ပြီး size၊ triangle အရေအတွက်နဲ့ texture အရွယ်အစားတွေကို ကြည့်ပါ။ ပြီးရင် command တစ်ကြောင်းတည်းနဲ့ ချုံ့ပါ —

sh
npx @gltf-transform/cli optimize fox.glb fox-small.glb --compress draco --texture-compress webp

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Mesh တွေ ပေါင်း၊ မသုံးတဲ့ data တွေ ဖယ်၊ texture အကြီးကြီးတွေ resize လုပ်ပြီး geometry ကို Draco နဲ့၊ texture တွေကို WebP နဲ့ compress လုပ်ပေးပါတယ်။ 20 MB download က 2 MB ဖြစ်သွားတတ်ပါတယ်။

Object အများကြီး၊ draw call တစ်ခုတည်း

3D မှာ အရေးအကြီးဆုံး performance idea က ဒါပါ။ သီးခြား mesh တိုင်းက draw call တစ်ခု ကုန်ပါတယ် — CPU က GPU ကို "ဒါကို ဒီ material နဲ့ ဒီနေရာမှာ ဆွဲ" လို့ ပြောတာပါ။ GPU က triangle သန်းပေါင်းများစွာ ဆွဲနိုင်ပေမဲ့ frame တစ်ခုမှာ draw call ထောင်ချီရှိရင် CPU က အသက်ရှူကျပ်သွားပါတယ်၊ အထူးသဖြင့် ဖုန်းတွေမှာပါ။ ဒါကြောင့် သစ်ပင်၊ မြက်၊ အကြွေစေ့၊ particle လို အရာတစ်ခုတည်းကို အများကြီး လိုတဲ့အခါ InstancedMesh ကို သုံးပါ — geometry တစ်ခု၊ material တစ်ခုနဲ့ position list တစ်ခု။ သစ်ပင် နှစ်ထောင်၊ draw call တစ်ခု။

js
// vanilla/05-forest.jsimport * as THREE from 'three'; const scene = new THREE.Scene();scene.background = new THREE.Color('#0b1220');scene.fog = new THREE.Fog('#0b1220', 14, 40); const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 100);camera.position.set(0, 9, 17);camera.lookAt(0, 0, 0); const renderer = new THREE.WebGLRenderer({ antialias: true });renderer.setPixelRatio(Math.min(devicePixelRatio, 2));renderer.setSize(innerWidth, innerHeight);document.body.appendChild(renderer.domElement); scene.add(new THREE.HemisphereLight('#6d86c9', '#120c08', 0.9));const fire = new THREE.PointLight('#ff9a3c', 60, 18, 2);fire.position.set(0, 0.6, 0);scene.add(fire); const ground = new THREE.Mesh(  new THREE.CircleGeometry(30, 64),  new THREE.MeshStandardMaterial({ color: '#1c2418' }),);ground.rotation.x = -Math.PI / 2;scene.add(ground); // 2,000 trees, ONE draw call: one geometry + one material, many matricesconst COUNT = 2000;const tree = new THREE.ConeGeometry(0.5, 1.6, 7);tree.translate(0, 0.8, 0); // move the pivot to the base so trees stand on the groundconst forest = new THREE.InstancedMesh(tree, new THREE.MeshStandardMaterial({ roughness: 0.9 }), COUNT); const dummy = new THREE.Object3D();const color = new THREE.Color();for (let i = 0; i < COUNT; i++) {  const angle = Math.random() * Math.PI * 2;  const radius = 5 + Math.sqrt(Math.random()) * 22; // keep a clearing in the middle  dummy.position.set(Math.cos(angle) * radius, 0, Math.sin(angle) * radius);  dummy.scale.setScalar(0.6 + Math.random() * 1.4);  dummy.rotation.y = Math.random() * Math.PI;  dummy.updateMatrix();  forest.setMatrixAt(i, dummy.matrix);  forest.setColorAt(i, color.setHSL(0.28 + Math.random() * 0.08, 0.5, 0.12 + Math.random() * 0.08));}forest.instanceMatrix.needsUpdate = true;forest.instanceColor.needsUpdate = true;scene.add(forest); const timer = new THREE.Timer();timer.connect(document);renderer.setAnimationLoop((timestamp) => {  timer.update(timestamp);  const t = timer.getElapsed();  fire.intensity = 60 + Math.sin(t * 12) * 6 + Math.sin(t * 7.3) * 4; // flicker  renderer.render(scene, camera);}); setTimeout(() => console.log('draw calls:', renderer.info.render.calls), 1000); // 2: the ground and the whole forest

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Fog က အဝေးက အရာတွေကို နောက်ခံအရောင်ထဲ မှိန်ပျောက်သွားစေပါတယ်။ ကမ္ဘာရဲ့ အစွန်းကို ဖုံးပေးပြီး အနက်အရှိုင်းကို အလကားနီးပါး ထည့်ပေးပါတယ်။
  2. မီးပုံပါ — ပြင်းအား 60၊ အကွာအဝေး 18 unit နဲ့ decay 2 (တကယ့်ကမ္ဘာလို လျော့ကျပုံ) ရှိတဲ့ လိမ္မော်ရောင် မီးသီး။
  3. 20000 ကို စမ်းကြည့်ပါ။ Draw call အရေအတွက် မပြောင်းတာမို့ ချောချောမွေ့မွေ့ပဲ run နေပါဦးမယ်။
  4. Cone တွေကို သူ့အလယ်ကို ဗဟိုပြုပြီး ဆောက်ပါတယ်။ Geometry ကို အမြင့်တစ်ဝက် အပေါ်တင်လိုက်ရင် pivot က အခြေမှာ ရောက်သွားတာမို့ သစ်ပင်ကို scale လုပ်ရင်လည်း မြေပြင်ပေါ်မှာ မတ်တပ်ရပ်နေဆဲပါ။
  5. Geometry တစ်ခု၊ material တစ်ခုနဲ့ COUNT ခုစာ နေရာ။
  6. Scene ထဲ ဘယ်တော့မှ မထည့်တဲ့ helper ပါ။ သူ့ position၊ scale၊ rotation ကို သတ်မှတ်ပြီး သူ့ matrix ကို slot တစ်ခုချင်းထဲ ကူးထည့်ပါတယ်။
  7. Square root မပါရင် သစ်ပင်တွေ အလယ်နားမှာ စုပြုံနေပါမယ်။ 5 + က မီးပုံအတွက် ကွင်းပြင်တစ်ခု ချန်ထားပေးပါတယ်။
  8. Position၊ rotation နဲ့ scale ကို 4 × 4 matrix တစ်ခုထဲ ပေါင်းထည့်ပါတယ်။
  9. အဲဒီ matrix ကို slot i ထဲ သိမ်းပါတယ်။ InstancedMesh က ၂၀၀၀ လုံးကို GPU အတွက် buffer တစ်ခုတည်းထဲမှာ ကိုင်ထားပါတယ်။
  10. တစ်ခုချင်းစီ ကိုယ်ပိုင်အရောင်လည်း ရှိနိုင်ပါတယ်။ ကွဲပြားမှု နည်းနည်းက တောအုပ်ကို သဘာဝကျစေပါတယ်။
  11. ပြောင်းထားတဲ့ buffer တွေကို GPU ဆီ upload လုပ်ဖို့ three ကို ပြောတာပါ။ မေ့သွားရင် ဘာမှ ပေါ်မလာပါဘူး။
  12. အမြန်နှုန်း မတူတဲ့ sine wave နှစ်ခုက ဘယ်တော့မှ အတိအကျ ထပ်မကျတဲ့ မီးတဖျပ်ဖျပ်ကို ဖန်တီးပေးပါတယ်။
  13. renderer.info က နောက်ဆုံး frame ရဲ့ အလုပ်ကို ရေတွက်ပါတယ်။ ဒီ scene က 2 လို့ log ထုတ်ပါတယ် — မြေပြင်နဲ့ တောအုပ်တစ်ခုလုံးပါ။
Fig. 03InstancedMesh တစ်ခုတည်းထဲက သစ်ပင် နှစ်ထောင်ကို တဖျပ်ဖျပ်လင်းနေတဲ့ point light တစ်ခုက လင်းစေနေပါတယ်။ renderer.info က frame တစ်ခုလုံးအတွက် draw call 2 ခုလို့ ပြပါတယ်။

React ကို မပြောင်းခင် နောက်ဆုံး အလေ့အထ တစ်ခုပါ။ Mesh တစ်ခုကို scene ထဲကနေ ဖယ်လိုက်တာနဲ့ GPU ပေါ်က သူ့ memory ကို လွှတ်မပေးပါဘူး။ Model တွေ လဲလှယ်နေတဲ့ configurator လို အကြာကြီး run နေတဲ့ app မှာ ဖယ်လိုက်တာတွေကို dispose လုပ်ပါ —

js
// src/snippets/dispose.js// Removing a mesh from the scene does not free GPU memory: dispose it tooexport function removeMesh(scene, mesh) {  scene.remove(mesh);  mesh.geometry.dispose();  const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];  for (const material of materials) {    for (const value of Object.values(material)) {      if (value?.isTexture) value.dispose();    }    material.dispose();  }}

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. ဆွဲတာ ရပ်သွားပါတယ်။ Geometry နဲ့ texture တွေက GPU memory ထဲမှာ ရှိနေဆဲပါ။
  2. Vertex buffer တွေကို လွှတ်ပေးပါတယ်။
  3. Material တွေက texture တွေကို slot အများကြီး (map၊ normalMap …) ထဲမှာ ကိုင်ထားပါတယ်။ ဒါက အားလုံးကို ရှာပေးပါတယ်။
  4. Compile လုပ်ထားတဲ့ shader program ကို လွှတ်ပေးပါတယ်။ ဂဏန်းတွေ လျော့သွားလား renderer.info.memory မှာ စစ်ကြည့်ပါ။

ဒုတိယပိုင်း — React Three Fiber

Vanilla Three.js က ကောင်းကောင်း အလုပ်လုပ်ပေမဲ့ scene ကြီးလာတာနဲ့အမျှ ဘာတွေ တိုးလာလဲ ကြည့်ပါ — ကိုယ့် data နဲ့ ကိုက်ညီနေအောင် ထိန်းရမယ့် object list တွေ၊ ဖယ်ဖို့ မမေ့ရမယ့် event listener တွေ၊ cleanup code တွေနဲ့ variable တွေမှာ ပြန့်ကျဲနေတဲ့ state တွေ။ React က DOM အတွက် ဒီပြဿနာတွေကို ဖြေရှင်းပြီးသားပါ။ React Three Fiber က react-dom လိုပဲ React renderer တစ်ခုပါ — page အစား Three.js scene ထဲကို render လုပ်တာပဲ ကွာပါတယ်။

  • Object တူတူ၊ အမြန်နှုန်း တူတူ။ R3F က ရိုးရိုး Three.js object တွေကိုပဲ ဆောက်ပါတယ်။ Render loop ထဲမှာ wrapper အလွှာ မရှိတာမို့ scene က vanilla version လောက် မြန်ပါတယ်။
  • Component တွေ။ သစ်ပင်၊ တဲ၊ မီးပုံ — တစ်ခုချင်းက props ပါတဲ့ component ပါ။ React UI တွေလိုပဲ ပြန်သုံးပြီး ပေါင်းစပ်ပါ။
  • အလိုအလျောက် cleanup။ Component unmount ဖြစ်တဲ့အခါ R3F က သူ့ object တွေကို ဖယ်ပြီး geometry နဲ့ material တွေကို dispose လုပ်ပေးပါတယ်။
  • Pointer event တွေ ပါပြီးသား။ Mesh တွေပေါ်မှာ onClick၊ onPointerOver — ကိုယ်တိုင် ဘယ်တော့မှ မရေးရတဲ့ raycaster က နောက်ကွယ်ကနေ အလုပ်လုပ်ပေးပါတယ်။
  • Ecosystem တစ်ခု။ drei (helper တွေ)၊ rapier (physics)၊ postprocessing (effect တွေ)၊ xr (VR နဲ့ AR) — အားလုံး တစ်ခုနဲ့တစ်ခု ကိုက်ညီအောင် လုပ်ထားပါတယ်။
sh
npm create vite@latest r3f-camp -- --template react-tscd r3f-campnpm install three @react-three/fiber @react-three/drei zustandnpm install -D @types/threenpm run dev

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. TypeScript ပါတဲ့ React ပါ။ 3D မှာ type တွေက ပုံမှန်ထက် ပိုအရေးကြီးပါတယ် — mesh ဒါမှမဟုတ် light တစ်ခုက ဘယ် props တွေ လက်ခံလဲ ပြောပြပေးလို့ပါ။
  2. Renderer ပါ။ drei က အဆင်သင့်လုပ်ထားတဲ့ helper သေတ္တာကြီး တစ်ခုပါ။ zustand က mini project အတွက် သုံးမယ့် state library အသေးလေးပါ။
  3. Three.js ကို JavaScript နဲ့ ရေးထားတာမို့ သူ့ type တွေက ဒီ package သီးသန့်ကနေ လာပါတယ်။

JSX ဆိုတာ Three.js ပါပဲ

ပထမ cube ကို R3F နဲ့ ပြန်ရေးထားတာပါ။ Vanilla file နဲ့ နှိုင်းယှဉ်ကြည့်ပါ — scene က အတူတူပဲ၊ ပိုက်ဆက်တဲ့ အလုပ်တွေပဲ ပျောက်သွားတာပါ —

tsx
// src/snippets/HelloCube.tsximport { Canvas } from '@react-three/fiber'; // The same cube as 01-hello-cube.js, written as JSXexport function HelloCube() {  return (    <Canvas camera={{ position: [0, 1.2, 4], fov: 50 }}>      <color attach="background" args={['#0d131f']} />      <mesh rotation={[0.4, 0.6, 0]} position-y={0}>        <boxGeometry args={[1, 1, 1]} />        <meshNormalMaterial />      </mesh>    </Canvas>  );}

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Canvas က scene၊ renderer၊ default camera နဲ့ render loop ကို ဆောက်ပေးပြီး parent element နဲ့အတူ အရွယ်အစား လိုက်ပြောင်းပေးပါတယ်။ Parent ကို height ပေးထားပါ။
  2. Default PerspectiveCamera အတွက် setting တွေပါ။ Vanilla ဥပမာနဲ့ position၊ field of view အတူတူပါပဲ။
  3. attach က object ကို child အဖြစ် ထည့်မယ့်အစား parent ရဲ့ property တစ်ခုပေါ် တင်ပေးပါတယ် — ဒီမှာတော့ scene.background ပါ။
  4. new THREE.Mesh() ပါ။ rotation နဲ့ position က array ယူပါတယ်။ position-y က mesh.position.y တစ်ခုတည်းကို သတ်မှတ်တဲ့ "dash" prop ပါ။
  5. args တွေက constructor argument တွေပါ — new THREE.BoxGeometry(1, 1, 1)။ …Geometry နဲ့ …Material လို့ နာမည်ပေးထားတဲ့ child တွေက သူ့ mesh ပေါ် အလိုအလျောက် attach ဖြစ်ပါတယ်။
  6. new THREE.MeshNormalMaterial() ပါ။ Object ပေါ်မှာ သတ်မှတ်လို့ရတဲ့ property မှန်သမျှကို prop အဖြစ် သတ်မှတ်လို့ရပါတယ်။

စည်းမျဉ်းတွေက အလွတ်ကျက်လို့ရလောက်အောင် တိုပါတယ် —

  • Three.js class တိုင်းက element တစ်ခုပါ — ပထမစာလုံး အသေးနဲ့ပါ — THREE.PointLight → <pointLight>၊ THREE.InstancedMesh → <instancedMesh>။
  • args က constructor argument တွေပါ။ ပြောင်းလိုက်ရင် object ကို ပြန်ဆောက်တာမို့ မပြောင်းလဲအောင် ထားပါ။
  • ကျန်တဲ့ props တွေက property တွေကို သတ်မှတ်ပါတယ်။ position={[1, 2, 3]} က position.set(1, 2, 3) ကို ခေါ်ပြီး color="orange" က color.set('orange') ကို ခေါ်ပါတယ်။
  • Dash တွေက အထဲထိ ရောက်ပါတယ် — position-x={2}၊ shadow-mapSize={[1024, 1024]}၊ rotation-y={Math.PI}။
  • attach က child ဘယ်ကို သွားမလဲ ဆုံးဖြတ်ပါတယ်။ Geometry နဲ့ material တွေက အလိုအလျောက် attach ဖြစ်ပါတယ်။
  • <primitive object={thing} /> က load လုပ်ထားတဲ့ model လို ရှိပြီးသား Three.js object ကို tree ထဲ ထည့်ပေးပါတယ်။

useFrame၊ ref နဲ့ event တွေ

R3F မှာ animation က useFrame ထဲမှာ ဖြစ်ပါတယ် — render loop ထဲမှာ မဆွဲခင် frame တိုင်း ကိုယ့် function ကို run ပေးတဲ့ hook ပါ။ R3F တစ်ခုလုံးမှာ အရေးအကြီးဆုံး စည်းမျဉ်းက — useFrame ထဲမှာ Three.js object ကို ref ကနေ တိုက်ရိုက် ပြောင်းပါ။ အဲဒီမှာ setState ကို ဘယ်တော့မှ မခေါ်ပါနဲ့။ တစ်စက္ကန့် ၆၀ ခါ setState ခေါ်ရင် component ကို တစ်စက္ကန့် ၆၀ ခါ re-render လုပ်ပြီး R3F app တွေ နှေးရတဲ့ နံပါတ်တစ် အကြောင်းရင်း ဖြစ်ပါတယ်။

tsx
// src/components/SpinningBox.tsximport { useRef, useState } from 'react';import { useFrame, type ThreeElements } from '@react-three/fiber';import { useCursor } from '@react-three/drei';import type { Mesh } from 'three'; export function SpinningBox(props: ThreeElements['mesh']) {  const ref = useRef<Mesh>(null!);  const [hovered, setHovered] = useState(false);  const [active, setActive] = useState(false);  useCursor(hovered);   // Runs every frame, outside React: mutate the object, never setState here  useFrame((_state, delta) => {    ref.current.rotation.x += 0.6 * delta;    ref.current.rotation.y += 0.9 * delta;  });   return (    <mesh      {...props}      ref={ref}      scale={active ? 1.4 : 1}      onClick={(event) => {        event.stopPropagation();        setActive(!active);      }}      onPointerOver={(event) => {        event.stopPropagation();        setHovered(true);      }}      onPointerOut={() => setHovered(false)}    >      <boxGeometry args={[1, 1, 1]} />      <meshStandardMaterial color={hovered ? '#e8a848' : '#5b7bd5'} />    </mesh>  );}

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. R3F ရဲ့ type တွေပါ — ThreeElements['mesh'] က <mesh> လက်ခံတဲ့ prop အားလုံးဖြစ်တာမို့ <SpinningBox position={[1, 0, 0]} /> က type အပြည့်ပါပါတယ်။
  2. Mount ဖြစ်ပြီးနောက် ref က တကယ့် THREE.Mesh ကို ပေးပါတယ်။ null! က "မသုံးခင် သတ်မှတ်ပြီးသား ဖြစ်မယ်" လို့ ပြောတာပါ — useFrame ထဲမှာ အဲဒါ မှန်ပါတယ်။
  3. Click ဒါမှမဟုတ် hover လို ခဏခဏ မဟုတ်ဘဲ ပြောင်းတဲ့ အရာတွေအတွက် React state က အဆင်ပြေပါတယ် — frame တိုင်းအတွက် မဟုတ်ပါ။
  4. drei hook ပါ — hovered true ဖြစ်နေသရွေ့ page cursor ကို pointer ပြောင်းပေးပြီး နောက်မှ ပြန်ထားပေးပါတယ်။
  5. Frame တိုင်း run ပါတယ်။ state ထဲမှာ camera၊ scene၊ pointer၊ clock နဲ့ size ပါပြီး delta က ပထမပိုင်းလိုပဲ နောက်ဆုံး frame ကနေ ကြာတဲ့ စက္ကန့်ပါ။
  6. တိုက်ရိုက်ပြောင်းတာမို့ re-render မရှိပါ။ Vanilla cube ထဲက စာကြောင်းနဲ့ အတူတူပါပဲ။
  7. State နဲ့ မောင်းတဲ့ prop ပါ။ active ပြောင်းတဲ့အခါ React က တစ်ခါ re-render လုပ်ပြီး R3F က scale ကို update လုပ်ပါတယ်။
  8. Mesh ပေါ်က pointer event တွေကို raycast ကိုယ့်ကိုယ်စား လုပ်ပေးပါတယ်။ Event ထဲမှာ ထိတဲ့ point၊ အကွာအဝေး၊ face နဲ့ object ကိုယ်တိုင် ပါပါတယ်။
  9. R3F event တွေက မှန်ကိုဖြတ်တဲ့ အလင်းလို နောက်က object တွေဆီ ဖြတ်သွားပါတယ်။ stopPropagation က ဒီ mesh ကို ပိတ်ဆို့ခိုင်းပါတယ်။
  10. Pointer က mesh ပေါ် ရောက်လာတဲ့အခါ ဖြစ်ပါတယ်။ သူ့အဖော် onPointerOut က ထွက်သွားတဲ့အခါ ဖြစ်ပါတယ်။
  11. Material အရောင်ကို props ကနေ ပြောင်းတာ ဈေးပေါပါတယ်။ R3F က ရှိပြီးသား material ကို update လုပ်တာပါ၊ အသစ် မဆောက်ပါဘူး။

drei — helper သေတ္တာ

@react-three/drei က R3F အတွက် အဆင်သင့်လုပ်ထားတဲ့ အစိတ်အပိုင်း အစုအဝေးကြီးပါ။ ကိုယ်တိုင် မရေးခင် drei မှာ ရှိပြီးသားလား အရင်စစ်ပါ။ Project တော်တော်များများမှာ သုံးဖြစ်မယ့်ဟာတွေ —

  • <OrbitControls /> — ပထမပိုင်းက controls ပါ၊ damping ပြင်ထားပြီး loop ကိုပါ ကိုင်တွယ်ပေးပါတယ်။
  • <Environment preset="sunset" /> — HDR ပုံတစ်ပုံကနေ လက်တွေ့ဆန်တဲ့ light နဲ့ ရောင်ပြန်ဟပ်မှုကို တစ်ကြောင်းတည်းနဲ့ ရပါတယ်။ ပထမပိုင်းက PMREM code ကို အစားထိုးပါတယ်။
  • <ContactShadows /> — shadow map မပြင်ဘဲ object အောက်မှာ နူးညံ့တဲ့ အရိပ်ပါ။ Product viewer တွေအတွက် အကောင်းဆုံးပါ။
  • useGLTF / useAnimations — model တွေ load လုပ်ပြီး animation တွေ ဖွင့်ပါ၊ caching နဲ့ Draco ပါပြီးသားပါ။
  • <Instances> / <Instance> — component အဖြစ် instancing ပါ၊ copy တစ်ခုချင်းက ကိုယ်ပိုင် props နဲ့ event တွေ ရှိနိုင်ပါတယ်။
  • <Text> နဲ့ <Text3D> — scene ထဲမှာ ကြည်လင်တဲ့ စာသား။
  • <Float>၊ <Sparkles>၊ <Stars>၊ <Cloud> — ချက်ချင်းရတဲ့ ပတ်ဝန်းကျင် ခံစားမှု။
  • <Html> — label ဒါမှမဟုတ် button လို ရိုးရိုး DOM element တွေကို 3D point တစ်ခုမှာ ချိတ်ထားပေးပါတယ်။
  • <Loader /> နဲ့ useProgress — Suspense နောက်ကွယ်မှာ load ဖြစ်နေတဲ့ asset တိုင်းကို လိုက်ပြတဲ့ loading screen။
  • <PerformanceMonitor>၊ <AdaptiveDpr>၊ <Bvh> — အားနည်းတဲ့ device တွေမှာ frame rate မကျအောင် ထိန်းပေးပါတယ်။

Suspense နဲ့ model load လုပ်ခြင်း

R3F မှာ loading ကို React Suspense က ကိုင်တွယ်ပါတယ်။ useGLTF က file အဆင်သင့် မဖြစ်မချင်း component ကို suspend လုပ်ထားပါတယ်။ အပေါ်က <Suspense> boundary က အဲဒီအတောအတွင်း fallback ပြပြီး drei ရဲ့ <Loader /> က စုစုပေါင်း progress ကို ပြပါတယ်။ Callback မလို၊ loading flag မလိုပါ။

tsx
// src/components/Model.tsximport { useEffect } from 'react';import { useGLTF, useAnimations } from '@react-three/drei'; // Put the file in public/models/ and it is served from /models/const URL = '/models/fox.glb'; export function Model(props: { scale?: number }) {  const { scene, animations } = useGLTF(URL); // suspends until loaded  const { actions, names } = useAnimations(animations, scene);   useEffect(() => {    const action = actions[names[0]];    action?.reset().fadeIn(0.4).play();    return () => {      action?.fadeOut(0.4);    };  }, [actions, names]);   return <primitive object={scene} {...props} />;} useGLTF.preload(URL); // start downloading before the component renders

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Vite ရဲ့ public/ folder ထဲက file တွေကို site root ကနေ serve လုပ်တာမို့ public/models/fox.glb က /models/fox.glb ဖြစ်သွားပါတယ်။
  2. Parse လုပ်ပြီးသား glTF ကို load၊ cache လုပ်ပြီး ပြန်ပေးပါတယ်။ URL တူတူ တောင်းတဲ့ component နှစ်ခုက download တစ်ခုတည်းကို မျှသုံးပါတယ်။
  3. AnimationMixer ကို ဆောက်ပြီး frame တိုင်း update လုပ်ပေးပါတယ်။ actions ထဲမှာ clip တစ်ခုကို action တစ်ခုစီ နာမည်နဲ့ ရှိပါတယ်။
  4. ပထမ clip ကို 0.4 စက္ကန့်အတွင်း fade in လုပ်ပါ။ Animation ပြောင်းဖို့ဆိုရင် တစ်ခုကို fade out၊ နောက်တစ်ခုကို fade in လုပ်ရင် ချောမွေ့စွာ ရောသွားပါတယ်။
  5. Cleanup ပါ — component unmount ဖြစ်တဲ့အခါ ဒါမှမဟုတ် clip ပြောင်းတဲ့အခါ fade out လုပ်ပါ။
  6. Load လုပ်ထားတဲ့ model က Three.js object ဖြစ်ပြီးသားမို့ primitive က tree ထဲကို ဒီအတိုင်း ထည့်ပေးပါတယ်။
  7. ဒီ file ကို import လုပ်တာနဲ့ download စပါတယ် — component render မလုပ်ခင်ကတည်းကပါ။

Model တစ်ခုအတွက် type ပါပြီး ပြင်လို့ရတဲ့ JSX လိုချင်ရင် gltfjsx ကို run ပါ။ .glb ကို ဖတ်ပြီး mesh တစ်ခုကို element တစ်ခုစီနဲ့ React component တစ်ခု ရေးပေးတာမို့ material ပြောင်းတာ၊ အစိတ်အပိုင်း ဖျောက်တာတွေကို props နဲ့ လုပ်လို့ရပါတယ်။ --transform နဲ့ဆိုရင် model ကိုပါ compress လုပ်ပေးပါတယ် —

sh
npx gltfjsx public/models/fox.glb --transform --types

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Generate လုပ်ထားတဲ့ component ဘေးမှာ optimise လုပ်ထားတဲ့ copy (Draco၊ resize လုပ်ထားတဲ့ WebP texture၊ ပေါင်းထားတဲ့ mesh) ကို ရေးပေးပါတယ်။

Loop အပြင်က state

Scene တွေက page ရဲ့ ကျန်တဲ့အပိုင်းနဲ့ state မျှသုံးလေ့ရှိပါတယ် — product ရဲ့ ရွေးထားတဲ့ အရောင်၊ သီချင်း ဖွင့်ထားလား၊ ဘယ်အခန်းထဲ ရောက်နေလဲ။ 3D tree တစ်ခုထဲ prop drilling လုပ်ရင် မြန်မြန် ရှုပ်သွားပါတယ်။ zustand (R3F ကို လုပ်တဲ့ pmndrs အဖွဲ့ကပဲ လုပ်တာ) က global store အသေးလေး တစ်ခု ပေးပါတယ်။ Component တွေက ကိုယ်လိုတဲ့ တန်ဖိုးတွေကိုပဲ subscribe လုပ်ပြီး useFrame ကလည်း re-render မဖြစ်စေဘဲ store ကို ဖတ်နိုင်ပါတယ်။

ts
// src/store.tsimport { create } from 'zustand'; type CampState = {  lantern: boolean;  toggleLantern: () => void;}; // State that lives outside React's tree: any component can read or change itexport const useCamp = create<CampState>((set) => ({  lantern: true,  toggleLantern: () => set((state) => ({ lantern: !state.lantern })),}));

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Store ရဲ့ ပုံသဏ္ဌာန်ပါ — တန်ဖိုး တစ်ခုနဲ့ action တစ်ခု။
  2. Hook တစ်ခု ဆောက်ပေးပါတယ်။ Canvas အတွင်းဖြစ်ဖြစ်၊ အပြင်ဖြစ်ဖြစ် component မှန်သမျှ useCamp() ကို ခေါ်လို့ရပါတယ်။
  3. Action တွေက ပြောင်းတဲ့အပိုင်းကို ပြန်ပေးပြီး store ကို update လုပ်ပါတယ်။ lantern ကို ဖတ်တဲ့ component တွေပဲ re-render ဖြစ်ပြီး ကျန်တာ မဖြစ်ပါဘူး။

Mini project — ညဘက် campsite တစ်ခု

အားလုံးကို ပေါင်းစပ်ဖို့ အချိန်ရောက်ပါပြီ။ ညဘက် scene အသေးလေး တစ်ခု တည်ဆောက်ပါမယ် — ကွင်းပြင်တစ်ခုကို ဝိုင်းထားတဲ့ instanced သစ်ပင် ၆၀၀၊ အလင်းတဖျပ်ဖျပ်ဖြစ်နေတဲ့ မီးပုံ၊ အပေါ်ကို လွင့်တက်နေတဲ့ မီးပွားတွေ၊ click လုပ်ရင် မီးအိမ် ဖွင့်/ပိတ်ပေးတဲ့ တဲလေးနဲ့ shared store ကတစ်ဆင့် အလုပ်တူတူ လုပ်ပေးတဲ့ ရိုးရိုး HTML button တစ်ခု။ အစိတ်အပိုင်း တစ်ခုချင်းက component အသေးလေးတွေပါ။

Fig. 04အောက်က code ကနေ render လုပ်ထားတဲ့ ပြီးဆုံးသွားတဲ့ campsite ပါ။ ဆွဲပြီး ပတ်ကြည့်ပါ၊ မီးအိမ်ကို ဖွင့်/ပိတ်ဖို့ တဲ ဒါမှမဟုတ် button ကို click လုပ်ပါ။

တောအုပ်

tsx
// src/components/Forest.tsximport { useMemo } from 'react';import { Instances, Instance } from '@react-three/drei'; // A small seeded random, so the forest looks the same on every visitfunction random(seed: number) {  return () => ((seed = (seed * 16807) % 2147483647) - 1) / 2147483646;} export function Forest({ count = 600 }: { count?: number }) {  const trees = useMemo(() => {    const rand = random(42);    return Array.from({ length: count }, () => {      const angle = rand() * Math.PI * 2;      const radius = 7 + Math.sqrt(rand()) * 16;      return {        position: [Math.cos(angle) * radius, 0, Math.sin(angle) * radius] as const,        scale: 0.7 + rand() * 1.3,        color: `hsl(${105 + rand() * 30}, 35%, ${14 + rand() * 10}%)`,      };    });  }, [count]);   return (    <Instances limit={count} castShadow receiveShadow>      <coneGeometry args={[0.5, 1.6, 7]} onUpdate={(geometry) => geometry.translate(0, 0.8, 0)} />      <meshStandardMaterial roughness={0.9} />      {trees.map((tree, i) => (        <Instance key={i} position={tree.position} scale={tree.scale} color={tree.color} />      ))}    </Instances>  );}

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Seed ပါတဲ့ random number generator ပါ။ Math.random ဆိုရင် reload တိုင်း တောအုပ်အသစ် ရမှာဖြစ်ပြီး server နဲ့ client မှာ သစ်ပင်တွေ မတူတော့ပါဘူး။
  2. Position ၆၀၀ ကို တစ်ခါပဲ တွက်ပါ။ useMemo မပါရင် re-render တိုင်း တောအုပ်အသစ်တစ်ခု ပြန့်ကျဲသွားပါမယ်။
  3. Unit 7 ကနေ 23 အထိ အကွာမှာ သစ်ပင်တွေ — camp အတွက် ကွင်းပြင်တစ်ခု ချန်ပြီး အဝိုင်းတစ်လျှောက် ညီညီ ဖြန့်ထားပါတယ်။
  4. Position က ဂဏန်း သုံးလုံး အတိအကျ ဖြစ်တယ်လို့ TypeScript ကို ပြောတာပါ — Instance prop လိုချင်တဲ့ ပုံသဏ္ဌာန်ပါ။
  5. drei ရဲ့ instancing ပါ — နောက်ကွယ်မှာ InstancedMesh တစ်ခုတည်းဖြစ်ပြီး count ခုစာ နေရာ ရှိပါတယ်။
  6. Geometry ရှိလာတာနဲ့ တစ်ခါ run ပါတယ်။ ပထမပိုင်းက pivot ကို အခြေကို ရွှေ့တဲ့ နည်းလမ်းကိုပဲ JSX နဲ့ လုပ်တာပါ။
  7. Instance တစ်ခုချင်းက ကိုယ်ပိုင် position၊ scale နဲ့ အရောင်ပါတဲ့ ပေါ့ပါးတဲ့ component ပါ။ onClick လည်း ထည့်လို့ရပြီး ဘယ်သစ်ပင်ကို ထိလဲ R3F က ပြောပြပါမယ်။

မီးပုံ

tsx
// src/components/Campfire.tsximport { useRef } from 'react';import { useFrame } from '@react-three/fiber';import { Sparkles } from '@react-three/drei';import type { Group, PointLight } from 'three'; export function Campfire() {  const light = useRef<PointLight>(null!);  const flames = useRef<Group>(null!);   useFrame((state) => {    const t = state.clock.elapsedTime;    light.current.intensity = 30 + Math.sin(t * 12) * 3 + Math.sin(t * 7.3) * 2;    flames.current.scale.y = 1 + Math.sin(t * 9) * 0.08;  });   return (    <group>      {/* logs */}      {[0, 1, 2].map((i) => (        <mesh key={i} rotation={[Math.PI / 2, 0, (i * Math.PI) / 3]} position-y={0.08} castShadow>          <cylinderGeometry args={[0.07, 0.07, 0.9, 8]} />          <meshStandardMaterial color="#4a2e1c" roughness={1} />        </mesh>      ))}      {/* flames: emissive, so they glow without needing light */}      <group ref={flames}>        <mesh position-y={0.35}>          <coneGeometry args={[0.22, 0.6, 8]} />          <meshStandardMaterial color="#ff7a1a" emissive="#ff5a00" emissiveIntensity={3} toneMapped={false} />        </mesh>        <mesh position-y={0.3} scale={0.6}>          <coneGeometry args={[0.22, 0.6, 8]} />          <meshStandardMaterial color="#ffd27a" emissive="#ffc04a" emissiveIntensity={4} toneMapped={false} />        </mesh>      </group>      <pointLight ref={light} position-y={0.6} color="#ff9a3c" intensity={30} distance={14} decay={2} castShadow shadow-mapSize={[1024, 1024]} />      <Sparkles count={40} scale={[1, 2.4, 1]} position-y={1.3} size={3} speed={0.6} color="#ffb060" />    </group>  );}

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Light နဲ့ မီးလျှံ group ကို ref တွေနဲ့ ကိုင်ထားတာမို့ useFrame က တိုက်ရိုက် ပြောင်းနိုင်ပါတယ်။
  2. Canvas စကတည်းက ကြာခဲ့တဲ့ စက္ကန့်ပါ။ နောက်ဆုံး frame ဘယ်လောက် ရွေ့သွားလဲပေါ် မမူတည်ဘဲ အချိန်ပေါ် မူတည်တဲ့ effect တွေအတွက် ကောင်းပါတယ်။
  3. Vanilla တောအုပ်ထဲကလိုပဲ sine နှစ်ခုနဲ့ တဖျပ်ဖျပ်လုပ်တာပါ — re-render တစ်ခါမှ မပါပါဘူး။
  4. မီးလျှံတွေက အလင်းနဲ့ အချိန်ကိုက် နည်းနည်း ဆန့်သွားတာမို့ အလင်းရောင်နဲ့ ပုံသဏ္ဌာန်က ကိုက်ညီနေပါတယ်။
  5. ထင်းချောင်း သုံးချောင်းပါ — တစ်ချောင်းချင်းက လှဲထားတဲ့ cylinder ဖြစ်ပြီး အရင်တစ်ချောင်းကနေ 60° လှည့်ထားပါတယ်။ ရိုးရိုး React list တွေက 3D မှာလည်း အလုပ်လုပ်ပါတယ်။
  6. Emissive မီးလျှံတွေက light မလိုဘဲ လင်းပါတယ်။ toneMapped={false} က အဖြူမှာ ကန့်သတ်ထားတဲ့ အရောင်တွေထက် ပိုလင်းခွင့်ပေးတာမို့ တကယ် လောင်နေသလို ဖြစ်ပါတယ်။
  7. မီးရောင်ပါ။ castShadow နဲ့ shadow-mapSize (dash prop) က တဲနဲ့ ထင်းချောင်းတွေကို တကယ့် shadow တွေ ပေးပါတယ်။
  8. drei ပါ — 1 × 2.4 × 1 box ထဲမှာ အပေါ်ကို လွင့်တက်နေတဲ့ လင်းနေသော point ၄၀။ မီးပွားတွေကို တစ်ကြောင်းတည်းနဲ့ ရပါတယ်။

တဲနဲ့ မီးအိမ်

tsx
// src/components/Tent.tsximport { useState } from 'react';import { useCursor } from '@react-three/drei';import { useCamp } from '../store'; export function Tent(props: { position: [number, number, number] }) {  const lantern = useCamp((state) => state.lantern);  const toggleLantern = useCamp((state) => state.toggleLantern);  const [hovered, setHovered] = useState(false);  useCursor(hovered);   return (    <group {...props} rotation-y={Math.PI / 4}>      <mesh        position-y={0.75}        castShadow        receiveShadow        onClick={(event) => {          event.stopPropagation();          toggleLantern();        }}        onPointerOver={() => setHovered(true)}        onPointerOut={() => setHovered(false)}      >        {/* a cone with 4 sides is a pyramid: our tent */}        <coneGeometry args={[1.2, 1.5, 4]} />        <meshStandardMaterial color={hovered ? '#d9a35f' : '#b5773d'} roughness={0.8} flatShading />      </mesh>      {/* the lantern, outside the door */}      <group position={[0.75, 0.12, 0.75]}>        <mesh>          <sphereGeometry args={[0.08, 16, 16]} />          <meshStandardMaterial color="#ffe2a8" emissive="#ffc46a" emissiveIntensity={lantern ? 4 : 0} toneMapped={false} />        </mesh>        {lantern && <pointLight color="#ffcf8a" intensity={6} distance={5} />}      </group>    </group>  );}

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. တန်ဖိုး တစ်ခုကိုပဲ subscribe လုပ်ပါတယ်။ မီးအိမ် ပြောင်းတဲ့အခါ အဲဒါကို ဖတ်တဲ့ component တွေပဲ re-render ဖြစ်ပါတယ်။
  2. ထောင့်မဟုတ်ဘဲ မျက်နှာပြင်ပြားက မီးပုံကို မျက်နှာမူအောင် တဲကို 45° လှည့်ထားပါတယ်။
  3. တဲကို click လုပ်ရင် shared store ထဲက မီးအိမ်ကို ပြောင်းပါတယ်။ Canvas အပြင်က button လည်း လိုက် update ဖြစ်ပါမယ်။
  4. ဘေး ၄ ဘက်ပဲပါတဲ့ cone က ပိရမစ်ပါ။ ဒီလို low-poly shape တွေက ဈေးပေါပြီး သူ့ကိုယ်ပိုင် style ရှိပါတယ်။
  5. Face တစ်ခုချင်းကို အရောင်ပြား တစ်ခုတည်းနဲ့ shade လုပ်ပေးတာမို့ ချိုးထားတဲ့ ရွက်ဖျင်လို ပြတ်သားတဲ့ ပုံပေါက်ပါတယ်။
  6. မီးအိမ်က တံခါးအပြင်မှာ ရှိပါတယ်။ ပိတ်ထားတဲ့ mesh အတွင်းက light က အတွင်းဘက် face တွေကိုပဲ လင်းစေတာမို့ ဘယ်တော့မှ မမြင်ရပါဘူး။
  7. မီးအိမ် ဖွင့်ထားချိန်မှာပဲ မီးသီးက လင်းပါတယ်။
  8. Conditional rendering က light တွေမှာလည်း အလုပ်လုပ်ပါတယ်။ Light ထည့်တာ၊ ဖယ်တာက light ထိတဲ့ material တွေကို three က တစ်ခါ ပြန် compile လုပ်ရစေပါတယ်။ Click တစ်ချက်အတွက်တော့ ရပေမဲ့ frame တိုင်း မလုပ်ပါနဲ့။

Scene ကို ပေါင်းစပ်ခြင်း

tsx
// src/App.tsximport { Suspense, useState } from 'react';import { Canvas } from '@react-three/fiber';import { OrbitControls, Stars, PerformanceMonitor, Loader } from '@react-three/drei';import { Forest } from './components/Forest';import { Campfire } from './components/Campfire';import { Tent } from './components/Tent';import { useCamp } from './store'; // Plain React DOM, outside the Canvas; the store connects it to the 3D tentfunction Hud() {  const lantern = useCamp((state) => state.lantern);  const toggleLantern = useCamp((state) => state.toggleLantern);  return (    <button className="hud" onClick={toggleLantern} aria-pressed={lantern}>      {lantern ? 'Lantern on' : 'Lantern off'}    </button>  );} export default function App() {  const [dpr, setDpr] = useState(1.5);   return (    <>      <Canvas        shadows="percentage"        dpr={dpr}        camera={{ position: [4.5, 3, 5.5], fov: 50 }}        gl={{ antialias: true }}      >        <PerformanceMonitor onIncline={() => setDpr(2)} onDecline={() => setDpr(1)} />        <color attach="background" args={['#0b1220']} />        <fog attach="fog" args={['#0b1220', 12, 30]} />         <hemisphereLight args={['#6d86c9', '#120c08', 0.5]} />        <Stars radius={60} depth={30} count={2500} factor={3} fade speed={0.5} />         <Suspense fallback={null}>          <mesh rotation-x={-Math.PI / 2} receiveShadow>            <circleGeometry args={[30, 64]} />            <meshStandardMaterial color="#1c2418" roughness={1} />          </mesh>          <Campfire />          <Tent position={[-2.2, 0, -1.2]} />          <Forest count={600} />        </Suspense>         <OrbitControls          makeDefault          target={[0, 0.6, 0]}          enableDamping          minDistance={3}          maxDistance={14}          maxPolarAngle={Math.PI / 2.15}        />      </Canvas>      <Hud />      <Loader />    </>  );}

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Canvas အပြင်မှာ ရှိတဲ့ ရိုးရိုး React DOM component ပါ။ zustand store က 3D scene နဲ့ ချိတ်ပေးပါတယ်။
  2. Toggle button ဖြစ်တာမို့ screen reader တွေက "pressed" ဒါမှမဟုတ် "not pressed" လို့ ကြေညာပါတယ်။ 3D scene တွေမှာလည်း accessible ဖြစ်တဲ့ control တွေ လိုပါတယ်။
  3. Render လုပ်မယ့် device pixel ratio ပါ။ PerformanceMonitor က အောက်မှာ နိမ့်ချ ဒါမှမဟုတ် မြှင့်တင်ပေးပါတယ်။
  4. PCF filtering နဲ့ shadow map တွေကို ဖွင့်ပါတယ်။ ရိုးရိုး shadows (true) က လက်ရှိ three မှာ မရှိတော့တဲ့ PCFSoftShadowMap ကို တောင်းတာမို့ warning ထွက်ပါတယ်။
  5. ကွင်းပြင်ထဲမှာ ခေါင်းအမြင့်ထက် နည်းနည်းမြင့်တဲ့နေရာကနေ မီးပုံဘက်ကို ကြည့်ပြီး စပါတယ်။
  6. drei က frame rate ကို စောင့်ကြည့်ပါတယ်။ ရုန်းကန်နေတဲ့ device မှာ onDecline ကို ခေါ်ပြီး pixel 1× ကို ချလိုက်ပါတယ် — ဖုန်းတွေမှာ အကြီးဆုံး အမြန်နှုန်းတိုးမှု ဖြစ်တတ်ပါတယ်။
  7. ပထမပိုင်းကလိုပဲ fog ပါ၊ scene.fog ပေါ် attach လုပ်ထားပါတယ်။ အရောင်က နောက်ခံနဲ့ တူတာမို့ တောအုပ်က ညထဲ မှိန်ပျောက်သွားပါတယ်။
  8. လရောင် fill ပါ — အပေါ်က အပြာ၊ အောက်က အမည်းနီးပါး။
  9. drei ပါ — စက်လုံးကြီးပေါ်မှာ ကြယ် ၂၅၀၀၊ draw call တစ်ခု။
  10. Load လုပ်ရမယ့် အရာမှန်သမျှ (model၊ texture၊ font) ဒီမှာ suspend ဖြစ်ပါတယ်။ ဒီနေ့ ဘာမှ load မလုပ်ပေမဲ့ နောက်မှ useGLTF ထည့်ရင် ဘာမှ ပြင်စရာ မလိုပါဘူး။
  11. တောအုပ်ကြမ်းပြင်ပါ — rotation-x နဲ့ ပြားပြား ချထားပြီး shadow လက်ခံပါတယ်။
  12. makeDefault က တခြား drei helper တွေ ရှာတွေ့အောင် ဒီ controls ကို မှတ်ပုံတင်ပါတယ်။ Target က မီးပုံပါ။
  13. Camera ကို မြေပြင်အောက် မရောက်အောင် တားပါတယ်။ ဒီလို ကန့်သတ်ချက်လေးတွေက scene ကို ပြီးပြည့်စုံသလို ခံစားရစေပါတယ်။
  14. Canvas ဘေးမှာ၊ အပေါ်က ထပ်ပြီး render လုပ်ပါတယ်။ ရိုးရိုး DOM၊ ရိုးရိုး CSS၊ ရိုးရိုး accessibility ပါ။
  15. drei ရဲ့ loading overlay ပါ။ Suspense ထဲက တစ်ခုခု load ဖြစ်နေချိန်မှာပဲ ပေါ်ပါတယ်။

npm run dev ကို run လိုက်ရင် camp ပေါ်လာပါမယ်။ ဆွဲပြီး မီးပုံကို ပတ်လျှောက်ကြည့်ပါ၊ scroll လုပ်ပြီး နီးနီးကပ်ကပ် သွားပါ၊ တဲကို click လုပ်ပါ။ ဖုန်းပေါ်မှာလည်း code တူတူက touch နဲ့ အလုပ်လုပ်ပါတယ် — လက်တစ်ချောင်းနဲ့ ပတ်လည်၊ လက်နှစ်ချောင်းနဲ့ zoom။

React Three Fiber မှာ performance

နှေးတဲ့ 3D site အများစုက အကြောင်းရင်း တစ်ဆုပ်စာလောက်တည်းကြောင့် နှေးတာပါ။ ဘယ်လောက် အထောက်အကူဖြစ်လဲ အလိုက် အကြမ်းဖျင်း စီထားပါတယ် —

  1. Draw call နည်းပါစေ။ ထပ်ခါထပ်ခါ ပါတဲ့ object တွေကို instance လုပ်၊ မလှုပ်တဲ့ mesh တွေကို ပေါင်း၊ geometry နဲ့ material တွေကို မျှသုံးပါ။
  2. အားနည်းတဲ့ device တွေမှာ pixel ratio နိမ့်ပါစေ။ dpr={[1, 2]} က ကန့်သတ်ပေးပြီး PerformanceMonitor က live ချိန်ညှိပေးပါတယ်။
  3. Asset တွေ သေးပါစေ။ Model တွေကို Draco ဒါမှမဟုတ် Meshopt နဲ့၊ texture တွေကို KTX2 ဒါမှမဟုတ် WebP နဲ့ compress လုပ်ပါ။ 4K မဟုတ်ဘဲ 1K texture တွေ ပို့ပါ။
  4. Frame တိုင်း React အလုပ် မလုပ်ပါနဲ့။ useFrame ထဲမှာ ref ကနေ ပြောင်းပြီး setState ကို user action တွေအတွက်ပဲ ထားပါ။
  5. လိုမှပဲ ဆွဲပါ။ အချိန်အများစု ငြိမ်နေတဲ့ scene တွေအတွက် on demand render လုပ်ပါ (အောက်မှာ)။
  6. Shadow ချတဲ့ light နည်းပါစေ။ Shadow ချတဲ့ light တိုင်းက scene ကို ထပ် render လုပ်ပါတယ်။ မလှုပ်တဲ့ အရာတွေအတွက် shadow တွေကို texture ထဲ bake လုပ်ပါ။
  7. Scene ကို lazy-load လုပ်ပါ။ 3D bundle က လေးပါတယ်။ အဓိက content ပြီးမှ load လုပ်ပါ၊ မတိုင်ခင် မဟုတ်ပါ။

Product viewer က on demand rendering အတွက် ဥပမာကောင်းပါ။ User က ဆွဲတာ ဒါမှမဟုတ် တစ်ခုခု ပြောင်းတာ မလုပ်မချင်း ဘာမှ မလှုပ်တာမို့ ပုံတူတူကို တစ်စက္ကန့် frame ၆၀ ဆွဲနေတာက battery ကို ကုန်စေရုံပါပဲ —

tsx
// src/snippets/OnDemand.tsximport { Canvas, useThree } from '@react-three/fiber';import { OrbitControls } from '@react-three/drei'; function Swatch({ color }: { color: string }) {  const invalidate = useThree((state) => state.invalidate);  return (    <mesh onClick={() => invalidate()}>      <sphereGeometry args={[1, 64, 32]} />      <meshStandardMaterial color={color} />    </mesh>  );} // Draws only when something changes: props, controls, or invalidate()export function ProductViewer({ color }: { color: string }) {  return (    <Canvas frameloop="demand" dpr={[1, 2]}>      <ambientLight intensity={0.6} />      <directionalLight position={[3, 4, 2]} />      <Swatch color={color} />      <OrbitControls />    </Canvas>  );}

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. useThree က Canvas store ကနေ ဖတ်ပါတယ်။ invalidate() က frame အသစ် တစ်ခု တောင်းပါတယ်။
  2. React props အပြင်ကနေ ကိုယ်တိုင် တစ်ခုခု ပြောင်းပြီးတဲ့အခါ (ဥပမာ ref ကနေ လက်နဲ့ ပြောင်းတာ) invalidate ကို ခေါ်ပါ။
  3. Props ပြောင်းမှ၊ controls ရွေ့မှ ဒါမှမဟုတ် invalidate() ခေါ်မှပဲ render လုပ်ပါတယ်။ ငြိမ်နေတဲ့ scene က GPU အချိန် လုံးဝ မသုံးပါဘူး။
  4. Device pixel ratio ကို သုံးပေမဲ့ 2 ထက် ဘယ်တော့မှ မကျော်ပါ။
  5. drei controls က ဆွဲနေချိန်နဲ့ damping ဖြစ်နေချိန်မှာ invalidate ကို ကိုယ့်ကိုယ်စား ခေါ်ပေးပါတယ်။

Next.js မှာ အသုံးပြုခြင်း

R3F က Next.js မှာ စည်းမျဉ်း တစ်ခုတည်းနဲ့ အလုပ်လုပ်ပါတယ် — WebGL က browser ထဲမှာပဲ ရှိတာမို့ Canvas နဲ့ သူ့အထဲက အရာအားလုံးက client-side ဖြစ်ရပါမယ်။ Scene ကို 'use client' လို့ မှတ်ထားတဲ့ file ထဲထည့်ပါ — ပြီးရင် Server Component page က တခြား component တွေလိုပဲ render လုပ်နိုင်ပါတယ်။

tsx
// app/camp/scene.tsx'use client'; import { Canvas } from '@react-three/fiber';import { OrbitControls } from '@react-three/drei';import { Campfire } from '@/components/Campfire'; export default function Scene() {  return (    <Canvas shadows="percentage" camera={{ position: [4, 3, 5] }}>      <Campfire />      <OrbitControls makeDefault />    </Canvas>  );}

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. ဒီ file က import လုပ်တာ အားလုံး browser bundle ထဲ ရောက်ပါတယ်။ useFrame လို hook တွေက client component တွေမှာပဲ အလုပ်လုပ်ပါတယ်။
  2. ရိုးရိုး component ပါ။ ပတ်ပတ်လည်က page က Server Component အဖြစ် ဆက်ရှိနေပြီး စာသား၊ SEO နဲ့ link တွေကို server မှာ render လုပ်နိုင်ပါတယ်။
tsx
// app/camp/lazy-scene.tsx'use client'; import dynamic from 'next/dynamic'; const Scene = dynamic(() => import('./scene'), {  ssr: false,  loading: () => <p className="scene-placeholder">Lighting the fire…</p>,}); export default function LazyScene() {  return <Scene />;}

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. Three.js နဲ့ scene ကို သီးခြား chunk အဖြစ် ခွဲထုတ်တာမို့ page ရဲ့ ကိုယ်ပိုင် code ပြီးမှ load ဖြစ်ပါတယ်။
  2. Scene အတွက် server rendering ကို ကျော်ပါတယ်။ ဒီ option ကို client component ထဲမှာပဲ ခွင့်ပြုတာမို့ ဒီ file မှာ ကိုယ်ပိုင် use client ရှိနေတာပါ။
  3. Chunk download ဖြစ်နေချိန်မှာ ပြပါတယ်။ Page မခုန်အောင် သူ့ container ကို canvas နဲ့ အမြင့်တူတူ ပေးထားပါ။

အဖြစ်များတဲ့ အမှားတွေနဲ့ အမြန်ပြင်နည်း

  • Screen မည်းနေပြီး error မရှိ။ Light မရှိဘဲ Standard material သုံးထားတာ၊ camera က object အထဲ ရောက်နေတာ ဒါမှမဟုတ် object က camera ရဲ့ near/far အပြင်မှာ ရှိနေတာပါ။ စမ်းဖို့ MeshNormalMaterial နဲ့ လဲကြည့်ပါ။
  • R3F မှာ ဘာမှ မပေါ်။ Canvas က parent ကို ဖြည့်တာဖြစ်ပြီး parent ရဲ့ height က 0 ပါ။ Height တစ်ခု ပေးပါ — height: 100dvh ဒါမှမဟုတ် အရွယ်အစား အသေ။
  • အရောင်တွေ ဖျော့နေ။ colorSpace = SRGBColorSpace မပါတဲ့ အရောင် texture ပါ။ (R3F နဲ့ useTexture က များသောအားဖြင့် ဒါကို သတ်မှတ်ပေးပါတယ်။)
  • ပုံ ဆွဲဆန့်ပြီး ဝါးနေ (vanilla)။ Resize handler မရှိတာ ဒါမှမဟုတ် aspect ပြောင်းပြီး updateProjectionMatrix() မခေါ်တာပါ။
  • Animation ထစ်ထစ်။ delta အစား frame တိုင်း ပမာဏ အသေ ပေါင်းထားတာ ဒါမှမဟုတ် useFrame ထဲမှာ setState ခေါ်ထားတာပါ။
  • ဖုန်းမှာ နှေး။ Draw call အရမ်းများတာ၊ pixel ratio 3၊ 4K texture တွေ ဒါမှမဟုတ် shadow ချတဲ့ light အများကြီးပါ။
  • Memory တိုးနေ။ Vanilla Three.js မှာ dispose() မလုပ်ဘဲ ဖယ်ထားတဲ့ object တွေပါ။ R3F ကတော့ component unmount ဖြစ်တဲ့အခါ ဒါကို လုပ်ပေးပါတယ်။
  • Model က သေးလွန်း၊ ကြီးလွန်း ဒါမှမဟုတ် ပျောက်နေ။ Model တွေက scale အမျိုးမျိုးနဲ့ လာပါတယ်။ drei ရဲ့ <Center> နဲ့ <Bounds> ကို သုံးပါ၊ ဒါမှမဟုတ် new THREE.Box3().setFromObject(model) နဲ့ တိုင်းပါ။

နောက်ထပ် ဘယ်ကို ဆက်သွားမလဲ

အခု အနှစ်သာရကို သိသွားပါပြီ။ ဒီအောက်က တစ်ခုချင်းက နယ်ပယ်သစ် တစ်ခုစီ ဖွင့်ပေးပြီး အားလုံးက အခုလေ့လာခဲ့တာပေါ်မှာ အခြေခံပါတယ် —

  • Shader တွေ။ ကိုယ်ပိုင် material တွေကို ShaderMaterial နဲ့ GLSL ဖြင့် ရေးပါ၊ ဒါမှမဟုတ် WebGL ရော WebGPU အတွက်ပါ compile လုပ်ပေးတဲ့ Three.js ရဲ့ node-based shading language TSL နဲ့ ရေးပါ။
  • WebGPU။ three/webgpu က WebGPURenderer က browser မှာ WebGPU ရှိရင် သုံးပြီး မရှိရင် WebGL 2 ကို ကိုယ့်ဘာသာ ပြန်သုံးပါတယ်။ R3F မှာ gl prop ကနေ ပေးပါ (အောက်က ဥပမာ)။
  • Post-processing။ @react-three/postprocessing နဲ့ bloom၊ depth of field နဲ့ color grading။ ကျွန်တော်တို့ရဲ့ emissive မီးလျှံတွေပေါ် bloom ထည့်တာက နှစ်ကြောင်းတည်းပါ။
  • Physics။ @react-three/rapier က <RigidBody> လို component တွေနဲ့ ဆွဲအား၊ တိုက်မိမှုနဲ့ joint တွေကို ပေးပါတယ်။
  • Scroll scene တွေ။ drei ရဲ့ <ScrollControls> ဒါမှမဟုတ် camera ကို မောင်းတဲ့ GSAP ScrollTrigger။
  • VR နဲ့ AR။ @react-three/xr က scene တူတူကို immersive ဖြစ်အောင် ပြောင်းပေးပါတယ်။
tsx
// src/snippets/WebGPU.tsximport { Canvas } from '@react-three/fiber';import { WebGPURenderer } from 'three/webgpu'; // WebGPU where the browser has it; three falls back to WebGL 2 by itselfexport function WebGPUCanvas({ children }: { children: React.ReactNode }) {  return (    <Canvas      gl={async (props) => {        const renderer = new WebGPURenderer({ canvas: props.canvas as HTMLCanvasElement, antialias: true });        await renderer.init();        return renderer;      }}    >      {children}    </Canvas>  );}

တစ်ကြောင်းချင်း ရှင်းလင်းချက်

  1. three ရဲ့ WebGPU build ပါ။ WebGPU မရှိတဲ့ browser တွေမှာ WebGL 2 ကို ကိုယ့်ဘာသာ ပြန်သုံးပါတယ်။
  2. R3F 9 က renderer ဒါမှမဟုတ် renderer ရဲ့ promise ကို ပြန်ပေးတဲ့ function ကို လက်ခံတာမို့ async setup က အဆင်ပြေပါတယ်။
  3. R3F က <canvas> ကို ဆောက်ပြီးသားပါ — renderer အသစ်ကို ပေးလိုက်ပါ။
  4. WebGPU က ပထမ frame မတိုင်ခင် async စတင်ရပါတယ် (browser ဆီကနေ GPU device တောင်းတာ)။

ကိုးကားဖို့နဲ့ လေ့ကျင့်ဖို့ — run လို့ရတဲ့ ဥပမာ ရာနဲ့ချီ ပါတဲ့ threejs.org က official documentation နဲ့ manual၊ r3f.docs.pmnd.rs က R3F docs နဲ့ helper တိုင်းကို live စမ်းလို့ရတဲ့ drei storybook။ ပိတ်မိနေရင် three.js forum နဲ့ pmndrs Discord က ဖော်ရွေပြီး မြန်ပါတယ်။

သေးသေးလေးကနေ စပါ။ Campsite ကို မှတ်ဉာဏ်ကနေ ပြန်ဆောက်ကြည့်ပြီး တစ်ခုခုကို ပြောင်းကြည့်ပါ — လ၊ မြစ်၊ ဒုတိယ တဲ ဒါမှမဟုတ် ကိုယ်ပိုင် model တစ်ခု။ Programming မှာ တခြားအရာတွေလိုပဲ 3D လည်း အလုပ်လုပ်တဲ့ scene အသေးလေး တစ်ခုချင်းနဲ့ လွယ်လာပါလိမ့်မယ်။ မီးပုံဘေးမှာ ပြန်ဆုံကြမယ်။ 🔥

Filed underthreejsreact-three-fiberwebglwebgpu3dreactdrei

Written byZin Min Htun (Wine Chanz)Senior Full-Stack Developer · Da Nang, VietnamSay hello at campMore entries