1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
//! Port of `three.js/examples/webgpu_postprocessing_ca.html`, calling the
//! three-rs API in the same order the page's `init()` / `animate()` do.
//!
//! Under the e2e harness the viewport is `400 * 2` x `250 * 2` with no
//! `deviceScaleFactor`, so `window.innerWidth` / `innerHeight` /
//! `devicePixelRatio` are 800, 500 and 1, and `performance.now()` is pinned to
//! 0. The page's `animate()` reads `timer.getElapsed()`, so every rotation it
//! assigns is `0` and every `position.y` it assigns is the one `createShapes()`
//! already set — the graded frame is the scene exactly as `init()` built it.
//!
//! `controls.autoRotate` is on, and `update()` runs twice (once in `init()`,
//! once in `animate()`). With `deltaTime` null the auto-rotation angle is
//! `2π/3600 * -0.1`, and damping takes a tenth of the accumulated delta each
//! time, so the camera's azimuth moves 5.1e-5 rad in total: 2e-3 world units
//! at a radius of 42, a fiftieth of a pixel. The port runs the real
//! `OrbitControls` for both updates, so that sliver of rotation is there; what
//! `controls.update()` does that actually shows is aim the camera at
//! `( 0, 0.5, 0 )`, which nothing else in the page does.
//!
//! `Math.random` is the harness's seeded sequence
//! ([`three_rs::testing::DeterministicRandom`]). `new Inspector()` runs
//! **before** `createShapes()` here and draws five times (four tab `List`s plus
//! the built-in `Parameters` group), so the 200 particles take draws 5..604 —
//! the same five as `webgpu_tsl_galaxy`'s `INSPECTOR_RANDOM_DRAWS`, counted
//! again from the real page because a different order would move every
//! particle.
//!
//! `PointsMaterial.size` and `sizeAttenuation` are *not* modelled, and that is
//! three's own behaviour, not a gap: "WebGPU only supports point primitives
//! with a pixel size of 1", so `PointsNodeMaterial.setupVertexSprite()` — the
//! only reader of either — runs for a `Sprite`, never for a `Points`.
use std::cell::RefCell;
use std::rc::Rc;
use three_rs::addons::controls::OrbitControls;
use three_rs::core::BufferAttribute;
use three_rs::geometries::{
box_geometry, cone_geometry, cylinder_geometry, icosahedron_geometry, octahedron_geometry,
sphere_geometry, torus_geometry, torus_knot_geometry,
};
use three_rs::materials::render_output;
use three_rs::nodes::display::{chromatic_aberration, convert_to_texture, RttNode};
use three_rs::nodes::pmrem_node::PmremEnvironment;
use three_rs::nodes::tsl::uniform_value;
use three_rs::nodes::Type;
use three_rs::testing::DeterministicRandom;
use three_rs::Timer;
use three_rs::{
pass, BufferGeometry, Color, GridHelper, Group, Mesh, MeshStandardNodeMaterial, PassNode,
PerspectiveCamera, Points, PointsNodeMaterial, RenderPipeline, Renderer, RendererParameters,
RoomEnvironment, Scene, Vector3,
};
pub const INNER_WIDTH: f64 = 800.0;
pub const INNER_HEIGHT: f64 = 500.0;
/// `renderer.setPixelRatio( window.devicePixelRatio )`.
pub const DPR: f64 = 1.0;
/// `Math.random()` draws `new Inspector()` makes before `createShapes()` — see
/// the module docs and `webgpu_tsl_galaxy`'s `INSPECTOR_RANDOM_DRAWS`.
const INSPECTOR_RANDOM_DRAWS: usize = 5;
/// `const particlesCount = 200`.
const PARTICLES_COUNT: usize = 200;
/// `params.strength` / `params.center` / `params.scale`.
const STRENGTH: f64 = 1.5;
const CENTER: [f64; 2] = [0.5, 0.5];
const SCALE: f64 = 1.2;
pub struct App {
pub renderer: Renderer,
/// Shared with `scene_pass`, which renders it from `updateBefore()`.
pub scene: Rc<RefCell<Scene>>,
/// Shared with `scene_pass`.
pub camera: Rc<RefCell<PerspectiveCamera>>,
/// The page's `controls`.
pub controls: OrbitControls,
/// The page's `mainGroup`, whose children `animate()` turns.
pub main_group: three_rs::ObjectRef,
/// The page's module-level `timer`.
pub timer: Timer,
pub scene_pass: PassNode,
pub ca_input: RttNode,
pub render_pipeline: RenderPipeline,
}
/// `createShapes()`' eight materials: `roughness 0.2, metalness 0.8` over the
/// page's eight colours.
fn shape_materials() -> Vec<MeshStandardNodeMaterial> {
const COLORS: [u32; 8] = [
0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff, 0xffffff, 0xff8800,
];
COLORS
.iter()
.map(|&color| MeshStandardNodeMaterial::standard(Color::from_hex(color), 0.2, 0.8))
.collect()
}
/// `createShapes()`' eight geometries, in the page's order.
fn shape_geometries() -> Vec<Rc<BufferGeometry>> {
vec![
Rc::new(box_geometry(3.0, 3.0, 3.0, 1, 1, 1)),
Rc::new(sphere_geometry(2.0, 32, 16)),
Rc::new(cone_geometry(2.0, 4.0, 8, 1)),
Rc::new(cylinder_geometry(1.5, 1.5, 4.0, 8)),
Rc::new(torus_geometry(2.0, 0.8, 8, 16)),
Rc::new(octahedron_geometry(2.5, 0)),
Rc::new(icosahedron_geometry(2.5, 0)),
Rc::new(torus_knot_geometry(1.5, 0.5, 64, 8, 2.0, 3.0)),
]
}
fn create_shapes(
scene: &mut Scene,
main_group: &three_rs::ObjectRef,
random: &mut DeterministicRandom,
) {
let materials = shape_materials();
let geometries = shape_geometries();
// Central showcase.
let central_group = Group::new();
let mut torus_material =
MeshStandardNodeMaterial::standard(Color::from_hex(0xffffff), 0.1, 1.0);
torus_material.emissive = Color::from_hex(0x222222);
let central_torus = Mesh::new(Rc::new(torus_geometry(5.0, 1.5, 16, 32)), torus_material);
central_group.add(¢ral_torus);
// Inner rotating shapes.
for i in 0..6 {
let angle = (i as f64 / 6.0) * std::f64::consts::PI * 2.0;
let radius = 3.0;
let mesh = Mesh::new(
geometries[i % geometries.len()].clone(),
materials[i % materials.len()].clone(),
);
{
let mut object = mesh.borrow_mut();
object
.position
.set(angle.cos() * radius, 0.0, angle.sin() * radius);
object.scale.set_scalar(0.5);
}
central_group.add(&mesh);
}
main_group.add(¢ral_group);
// Outer ring of shapes. Each one is a `Group` with a single mesh in it,
// which is what makes `animate()`'s `child.children.length > 0` branch —
// not the `child.type === 'Group'` one — fire for them.
const NUM_SHAPES: usize = 12;
const OUTER_RADIUS: f64 = 15.0;
for i in 0..NUM_SHAPES {
let angle = (i as f64 / NUM_SHAPES as f64) * std::f64::consts::PI * 2.0;
let shapes_group = Group::new();
let mesh = Mesh::new(
geometries[i % geometries.len()].clone(),
materials[i % materials.len()].clone(),
);
shapes_group.add(&mesh);
shapes_group.borrow_mut().position.set(
angle.cos() * OUTER_RADIUS,
(i as f64 * 0.5).sin() * 2.0,
angle.sin() * OUTER_RADIUS,
);
main_group.add(&shapes_group);
}
// Floating particles.
let mut positions = vec![0.0f32; PARTICLES_COUNT * 3];
for i in (0..PARTICLES_COUNT * 3).step_by(3) {
let radius = 25.0 + random.next() * 10.0;
let theta = random.next() * std::f64::consts::PI * 2.0;
let phi = random.next() * std::f64::consts::PI;
positions[i] = (radius * phi.sin() * theta.cos()) as f32;
positions[i + 1] = (radius * phi.cos()) as f32;
positions[i + 2] = (radius * phi.sin() * theta.sin()) as f32;
}
let mut particles_geometry = BufferGeometry::new();
particles_geometry.set_attribute("position", BufferAttribute::new(positions, 3));
// `new THREE.PointsMaterial( { color: 0xffffff, size: 0.5,
// sizeAttenuation: true } )` — the last two are dead on a `Points` under
// WebGPU; see the module docs.
let particles = Points::new(Rc::new(particles_geometry), PointsNodeMaterial::points());
main_group.add(&particles);
let _ = scene;
}
pub fn init() -> App {
let mut parameters = RendererParameters::default();
parameters.antialias = true;
let mut renderer = Renderer::new(parameters).unwrap();
renderer.set_pixel_ratio(DPR);
renderer.set_size(INNER_WIDTH, INNER_HEIGHT);
let mut camera = PerspectiveCamera::new(45.0, INNER_WIDTH / INNER_HEIGHT, 0.1, 200.0);
camera.node.borrow_mut().position.set(0.0, 15.0, 40.0);
// `controls.target.set( 0, 0.5, 0 ); controls.update()`.
camera.look_at(&Vector3::new(0.0, 0.5, 0.0));
// `controls = new OrbitControls( camera, renderer.domElement )`, built
// here because the page builds it here, between the camera and the scene.
let mut controls = OrbitControls::new(&mut camera);
// The canvas the example renders at, standing in for the element's
// `clientWidth` / `clientHeight`.
controls.set_element_size(INNER_WIDTH, INNER_HEIGHT);
controls.enable_damping = true;
controls.damping_factor = 0.1;
controls.auto_rotate = true;
controls.auto_rotate_speed = -0.1;
controls.target.set(0.0, 0.5, 0.0);
// `controls.update();` — the `camera.look_at` above stands in for its
// effect on the pose.
controls.update(&mut camera, None);
let mut scene = Scene::new();
scene.set_background(Color::from_hex(0x0a0a0a));
// `scene.environment = pmremGenerator.fromScene( new RoomEnvironment(), 0.04 ).texture`.
let mut room = RoomEnvironment::new();
let environment = PmremEnvironment::from_scene(&mut renderer, &mut room, 0.04).unwrap();
scene.environment = Some(environment.handle());
let main_group = Group::new();
scene.add(&main_group);
let mut random = DeterministicRandom::new();
random.skip(INSPECTOR_RANDOM_DRAWS);
create_shapes(&mut scene, &main_group, &mut random);
let grid_helper = GridHelper::new(
40.0,
20,
Color::from_hex(0x444444),
Color::from_hex(0x222222),
);
grid_helper.borrow_mut().position.y = -10.0;
scene.add(&grid_helper);
// post processing
// `pass( scene, camera )` — the pass holds both, and the renderer renders
// it the first time a draw samples its texture (`docs/nodes.md` §57).
let scene = Rc::new(RefCell::new(scene));
let camera = Rc::new(RefCell::new(camera));
let scene_pass = pass(scene.clone(), camera.clone());
// `const outputPass = renderOutput( scenePass )` — then
// `chromaticAberration()` calls `convertToTexture()` on it, which is an
// `RTTNode`: the effect samples its input at four different uvs, so the
// whole `renderOutput( pass )` graph is drawn into a texture of its own
// first.
let ca_input = convert_to_texture(render_output(scene_pass.node(), renderer.tone_mapping));
let ca_pass = chromatic_aberration(
&ca_input.texture(),
uniform_value(Type::F32, vec![STRENGTH]),
uniform_value(Type::Vec2, CENTER.to_vec()),
uniform_value(Type::F32, vec![SCALE]),
);
let mut render_pipeline = RenderPipeline::new();
// `renderPipeline.outputColorTransform = false`: the transform is already
// inside the RTT pass, so the output quad must not add a second one.
render_pipeline.output_color_transform = false;
render_pipeline.output_node = Some(ca_pass);
App {
main_group,
// `const timer = new THREE.Timer();`
timer: Timer::new(),
renderer,
scene,
camera,
controls,
scene_pass,
ca_input,
render_pipeline,
}
}
/// The page's `animate()`, run once by the harness's single RAF. Every value
/// it assigns is derived from `timer.getElapsed()`, which is 0, so the scene
/// is untouched. `renderPipeline.render()`'s output quad's draw runs the
/// scene pass's and the RTT's `updateBefore()` first (`docs/nodes.md` §57).
pub fn animate(app: &mut App) {
app.timer.update();
let time = app.timer.get_elapsed();
// `controls.update();`
app.controls.update(&mut app.camera.borrow_mut(), None);
// `if ( params.animated )` — true, and the GUI that could turn it off is
// not ported.
//
// Transcribed as written, including the branch that never fires: the page
// tests `child.children.length > 0` first and only falls through to the
// "outer shapes" branch for a `Group` with no children, which `mainGroup`
// never holds. So every group under it takes the first branch, and the
// `Points` cloud takes neither.
for child in app.main_group.children() {
let children = child.children();
if children.is_empty() {
continue;
}
{
let mut object = child.borrow_mut();
let rotation = object.rotation;
object.set_rotation(rotation.x, time * 0.5, rotation.z);
}
for (sub_index, sub_child) in children.into_iter().enumerate() {
let mut object = sub_child.borrow_mut();
if object.geometry().is_none() {
continue;
}
let rotation = object.rotation;
object.set_rotation(
time * (1.0 + sub_index as f64 * 0.1),
rotation.y,
time * (1.0 - sub_index as f64 * 0.1),
);
}
}
app.render_pipeline.render(&mut app.renderer);
}
/// The page's `onWindowResize()`.
///
/// The rung harness never calls this — the graded frame is always
/// 800 x 500 — but the viewer and the browser shell do, so the example
/// owns its own reaction to a resized canvas instead of the host
/// guessing at one.
pub fn resize(app: &mut App, width: f64, height: f64) {
let mut camera = app.camera.borrow_mut();
camera.aspect = width / height;
camera.update_projection_matrix();
app.renderer.set_size(width, height);
}
/// The example's controls, for a host that has a pointer. `None` when the
/// page creates none — the signature is the same for every example so the
/// viewer and the browser shell can drive any of them through one call.
pub fn controls(app: &mut App) -> Option<&mut OrbitControls> {
Some(&mut app.controls)
}
/// The controls and the camera at once, which every one of the controls'
/// event handlers needs: the JS holds the camera as `this.object` and Rust
/// cannot, so `pointer_move` and the rest take it as an argument.
///
/// They are two fields of the same `App`, so borrowing both is sound — but
/// only this module can say so; a host holding `&mut App` and calling
/// [`controls`] and then reaching for the camera cannot. Hence the pair.
pub fn controls_and_camera(
app: &mut App,
) -> Option<(&mut OrbitControls, std::cell::RefMut<'_, PerspectiveCamera>)> {
Some((&mut app.controls, app.camera.borrow_mut()))
}
fn main() {
// Pin both clocks to zero, as three.js' `test/e2e/deterministic-injection.js`
// does to the page, so that the frame this writes is the frame the rung
// grades no matter how long `init()` took.
three_rs::testing::pin_time(Some(0.0));
let mut app = init();
println!("adapter: {:?}", app.renderer.adapter_info());
animate(&mut app);
let (width, height, pixels) = app.renderer.read_canvas_pixels().unwrap();
let path = std::env::args()
.nth(1)
.unwrap_or_else(|| "target/webgpu_postprocessing_ca.png".to_string());
three_rs::testing::write_png(&path, width, height, &pixels);
println!("wrote {path} ({width}x{height})");
}