Skip to content

Commit d743b79

Browse files
committed
Latest
1 parent ce2719d commit d743b79

9 files changed

Lines changed: 942 additions & 27 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ Undocumented APIs should be considered internal and may change without warning.
88

99
### Added
1010

11-
- `animate` for Three.js supporting objects, materials, shader uniforms, TSL uniform nodes and node material slots like `colorNode`.
12-
- `animate` for vgpu supporting shader uniforms.
11+
- `animate` for Three.js supporting objects, materials, shader uniforms, TSL uniform nodes and more.
12+
- `animate` for vgpu supporting shared uniforms, `Effect`/`Draw`/`Compute` bindings (`"params.time"`), scene nodes, cameras, lights, materials, orbit controls, CSS colors and vector components.
1313

1414
### Changed
1515

‎dev/html/main.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,6 @@ document.querySelector("#app").innerHTML = `
88
<a href="/three-effects.html">Three.js effects</a>
99
<a href="/three-tsl.html">Three.js TSL (WebGPU)</a>
1010
<a href="/vgpu.html">vgpu uniforms</a>
11+
<a href="/vgpu-scene.html">vgpu scene</a>
1112
</div>
1213
`

‎dev/html/src/vgpu-scene.js‎

Lines changed: 239 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,239 @@
1+
import { cancelFrame, frame as motionFrame } from "motion"
2+
import { animate } from "motion/vgpu"
3+
import {
4+
clock,
5+
draw,
6+
effect,
7+
frame as vgpuFrame,
8+
geometry,
9+
init,
10+
sampler,
11+
surface,
12+
target,
13+
} from "vgpu"
14+
import {
15+
box,
16+
directionalLight,
17+
mesh,
18+
orbitControls,
19+
perspectiveCamera,
20+
srgb,
21+
unlitMaterial,
22+
} from "vgpu/scene"
23+
import "./gpu-adapters.css"
24+
25+
const stage = document.querySelector(".stage")
26+
const canvas = document.querySelector("canvas")
27+
const status = document.querySelector("#status")
28+
29+
const objectShader = `
30+
struct Camera { viewProjection: mat4x4f }
31+
struct Model { model: mat4x4f }
32+
struct Material { color: vec3f, opacity: f32 }
33+
struct Light { direction: vec3f, intensity: f32, color: vec3f }
34+
35+
@group(0) @binding(0) var<uniform> camera: Camera;
36+
@group(0) @binding(1) var<uniform> model: Model;
37+
@group(0) @binding(2) var<uniform> material: Material;
38+
@group(0) @binding(3) var<uniform> light: Light;
39+
40+
struct VertexOut {
41+
@builtin(position) position: vec4f,
42+
@location(0) normal: vec3f,
43+
}
44+
45+
@vertex
46+
fn vs_main(
47+
@location(0) position: vec3f,
48+
@location(1) normal: vec3f
49+
) -> VertexOut {
50+
var out: VertexOut;
51+
out.position = camera.viewProjection * model.model * vec4f(position, 1.0);
52+
out.normal = (model.model * vec4f(normal, 0.0)).xyz;
53+
return out;
54+
}
55+
56+
@fragment
57+
fn fs_main(@location(0) normal: vec3f) -> @location(0) vec4f {
58+
let n = normalize(normal);
59+
let l = normalize(-light.direction);
60+
let diffuse = max(dot(n, l), 0.0) * light.intensity * light.color;
61+
let shade = material.color * (vec3f(0.12) + diffuse);
62+
return vec4f(shade * material.opacity, material.opacity);
63+
}
64+
`
65+
66+
const presentShader = `
67+
@group(0) @binding(0) var scene: texture_2d<f32>;
68+
@group(0) @binding(1) var sceneSampler: sampler;
69+
70+
// Material colors are linear (srgb() / animate()), so encode for the canvas.
71+
@fragment
72+
fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
73+
let color = textureSampleLevel(scene, sceneSampler, uv, 0.0);
74+
return vec4f(pow(color.rgb, vec3f(1.0 / 2.2)), color.a);
75+
}
76+
`
77+
78+
async function start() {
79+
if (!navigator.gpu) {
80+
stage.innerHTML =
81+
'<div class="error">This example needs a browser with WebGPU enabled.</div>'
82+
return
83+
}
84+
85+
const gpu = await init()
86+
const time = clock(gpu)
87+
const canvasSurface = surface(gpu, canvas, { dpr: [1, 2] })
88+
const sceneTarget = target(gpu, { size: canvasSurface.size, depth: true })
89+
90+
const material = unlitMaterial({ color: srgb("#8b5cf6") })
91+
const cube = mesh(box({ size: 1.4 }), material, { position: [-1, 0, 0] })
92+
const light = directionalLight({
93+
direction: [-1, -2, -1],
94+
intensity: 1.2,
95+
})
96+
const camera = perspectiveCamera({
97+
fov: 42,
98+
aspect: canvasSurface.size[0] / canvasSurface.size[1],
99+
position: [2.5, 2, 5],
100+
target: [0, 0, 0],
101+
})
102+
const controls = orbitControls(camera, { element: canvas, damping: 0.1 })
103+
104+
const cubeDraw = draw(gpu, {
105+
shader: objectShader,
106+
geometry: geometry(gpu, box({ size: 1 })),
107+
cull: "back",
108+
blend: "premultiplied",
109+
})
110+
const present = effect(gpu, presentShader, {
111+
set: {
112+
scene: sceneTarget,
113+
sceneSampler: sampler(gpu, {
114+
minFilter: "linear",
115+
magFilter: "linear",
116+
}),
117+
},
118+
})
119+
120+
canvasSurface.onResize(({ width, height }) => {
121+
sceneTarget.resize([width, height])
122+
camera.set({ aspect: width / height })
123+
})
124+
125+
let meshActive = false
126+
document.querySelector("#move").addEventListener("click", () => {
127+
meshActive = !meshActive
128+
status.textContent = "Animating node transform and material"
129+
130+
const transition = { type: "spring", visualDuration: 0.7, bounce: 0.25 }
131+
132+
Promise.all([
133+
animate(
134+
cube,
135+
meshActive
136+
? { x: -0.3, rotateX: 35, rotateY: 180, scale: 1.25 }
137+
: { x: -1, rotateX: 0, rotateY: 0, scale: 1 },
138+
transition
139+
),
140+
animate(
141+
material,
142+
meshActive
143+
? { color: "#f43f5e", opacity: 0.65 }
144+
: { color: "#8b5cf6", opacity: 1 },
145+
transition
146+
),
147+
]).then(() => {
148+
status.textContent = "Node animation complete"
149+
})
150+
})
151+
152+
let lightActive = false
153+
document.querySelector("#light").addEventListener("click", () => {
154+
lightActive = !lightActive
155+
status.textContent = "Animating light direction, color and intensity"
156+
157+
animate(
158+
light,
159+
lightActive
160+
? {
161+
directionX: 1,
162+
directionZ: 1,
163+
intensity: 2,
164+
color: "#ffd27a",
165+
}
166+
: {
167+
directionX: -1,
168+
directionZ: -1,
169+
intensity: 1.2,
170+
color: "#ffffff",
171+
},
172+
{ duration: 1.2, ease: "easeInOut" }
173+
).then(() => {
174+
status.textContent = "Light animation complete"
175+
})
176+
})
177+
178+
let cameraActive = false
179+
document.querySelector("#camera").addEventListener("click", () => {
180+
cameraActive = !cameraActive
181+
status.textContent = "Animating orbit controls and fov"
182+
183+
Promise.all([
184+
animate(
185+
controls,
186+
cameraActive
187+
? { yaw: controls.yaw + Math.PI, pitch: 0.9, distance: 9 }
188+
: { yaw: controls.yaw - Math.PI, pitch: 0.4, distance: 6 },
189+
{ duration: 1.4, ease: "easeInOut" }
190+
),
191+
animate(camera, { fov: cameraActive ? 70 : 42 }, { duration: 1.4 }),
192+
]).then(() => {
193+
status.textContent = "Camera animation complete"
194+
})
195+
})
196+
197+
function update({ delta }) {
198+
// Motion owns the timeline, so it drives vgpu's clock (see vgpu's
199+
// "External ticker" guide) and the orbit controls damping.
200+
time.advance(Math.max(0, delta) / 1000)
201+
controls.update(time.deltaTime)
202+
}
203+
204+
function render() {
205+
cubeDraw.set({
206+
camera: { viewProjection: camera.viewProjection },
207+
model: { model: cube.worldMatrix },
208+
material: { color: material.color, opacity: material.opacity },
209+
light: {
210+
direction: light.direction,
211+
intensity: light.intensity,
212+
color: light.color,
213+
},
214+
})
215+
216+
vgpuFrame(gpu, (currentFrame) => {
217+
currentFrame.pass(
218+
{ target: sceneTarget, clear: [0.003, 0.003, 0.0035, 1] },
219+
(pass) => pass.draw(cubeDraw)
220+
)
221+
currentFrame.pass(canvasSurface, present)
222+
})
223+
}
224+
225+
motionFrame.update(update, true)
226+
motionFrame.render(render, true)
227+
228+
window.addEventListener("pagehide", () => {
229+
cancelFrame(update)
230+
cancelFrame(render)
231+
controls.dispose()
232+
gpu.dispose()
233+
})
234+
}
235+
236+
start().catch((error) => {
237+
stage.innerHTML = `<div class="error">${error.message}</div>`
238+
throw error
239+
})

‎dev/html/src/vgpu.js‎

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ const canvas = document.querySelector("canvas")
88
const intensityInput = document.querySelector("#intensity")
99
const status = document.querySelector("#status")
1010

11+
const tints = ["#0cc2e0", "#fbbf24"]
12+
1113
async function start() {
1214
if (!navigator.gpu) {
1315
stage.innerHTML =
@@ -29,26 +31,47 @@ async function start() {
2931
intensity: f32,
3032
}
3133
34+
struct Params {
35+
tint: vec3f,
36+
mouse: vec2f,
37+
}
38+
3239
@group(0) @binding(0)
3340
var<uniform> globals: Globals;
3441
42+
@group(0) @binding(1)
43+
var<uniform> params: Params;
44+
3545
@fragment
3646
fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
37-
let center = vec2f(0.5, 0.5);
38-
let distance = length(uv - center);
47+
let distance = length(uv - params.mouse);
3948
let wave = 0.5 + 0.5 * cos(
4049
distance * 24.0 - globals.progress * 12.0
4150
);
4251
let purple = vec3f(0.32, 0.12, 0.72);
43-
let cyan = vec3f(0.05, 0.76, 0.88);
44-
let color = mix(purple, cyan, wave) * globals.intensity;
52+
let glow = smoothstep(0.35, 0.0, distance) * 0.35;
53+
let color = (mix(purple, params.tint, wave) + glow) * globals.intensity;
4554
4655
return vec4f(color, 1.0);
4756
}
4857
`,
4958
{ set: { globals } }
5059
)
5160

61+
/**
62+
* Effects have no getters, so the first animation of a binding needs
63+
* explicit keyframes. This one also writes the initial values before the
64+
* first frame renders, so `params` never needs a vgpu-side set().
65+
*/
66+
animate(
67+
gradient,
68+
{
69+
"params.tint": [tints[0], tints[0]],
70+
"params.mouse": ["0.5 0.5", "0.5 0.5"],
71+
},
72+
{ duration: 0 }
73+
)
74+
5275
const intensity = motionValue(1)
5376
const cancelUniformEffect = uniformEffect(globals, { intensity })
5477

@@ -71,6 +94,33 @@ async function start() {
7194
})
7295
})
7396

97+
let tintIndex = 0
98+
document.querySelector("#tint").addEventListener("click", () => {
99+
tintIndex = (tintIndex + 1) % tints.length
100+
status.textContent = "Animating params.tint as a CSS color"
101+
102+
animate(
103+
gradient,
104+
{ "params.tint": tints[tintIndex] },
105+
{ duration: 1, ease: "easeInOut" }
106+
).then(() => {
107+
status.textContent = `tint ${tints[tintIndex]}`
108+
})
109+
})
110+
111+
canvas.addEventListener("pointermove", (event) => {
112+
const rect = canvas.getBoundingClientRect()
113+
114+
animate(
115+
gradient,
116+
{
117+
"params.mouseX": (event.clientX - rect.left) / rect.width,
118+
"params.mouseY": (event.clientY - rect.top) / rect.height,
119+
},
120+
{ type: "spring", stiffness: 120, damping: 20 }
121+
)
122+
})
123+
74124
function render() {
75125
vgpuFrame(gpu, (currentFrame) => {
76126
currentFrame.pass(canvasSurface, gradient)

‎dev/html/vgpu-scene.html‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>Motion vgpu scene</title>
7+
</head>
8+
<body>
9+
<main>
10+
<header>
11+
<div>
12+
<h1>vgpu scene</h1>
13+
<p>
14+
animate() on scene nodes (x, rotateY, scale), materials,
15+
lights, cameras and orbit controls. Drag to orbit.
16+
</p>
17+
</div>
18+
<nav>
19+
<a href="/vgpu.html">vgpu uniforms</a>
20+
<a href="/three-animate.html">Three animate</a>
21+
</nav>
22+
</header>
23+
<section class="stage">
24+
<canvas></canvas>
25+
<div class="panel">
26+
<div class="controls">
27+
<button class="primary" id="move">
28+
Animate node + material
29+
</button>
30+
<button id="light">Animate light</button>
31+
<button id="camera">Animate camera</button>
32+
</div>
33+
<output id="status">Ready</output>
34+
</div>
35+
</section>
36+
</main>
37+
<script type="module" src="/src/vgpu-scene.js"></script>
38+
</body>
39+
</html>

0 commit comments

Comments
 (0)