BVH and frustum culling: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: visible (line 40), offscreen (line 52), light (line 64), check (line 73).
1/// A large scene where most mesh boxes sit outside the current frustum.
2library;
4import 'package:flutter3d/flutter3d.dart';
5import 'package:flutter3d_showcase/src/demo/demo.dart';
7/// The `culling` page: a few cubes in view and a warehouse of cubes behind
8/// the camera. Its check is that the frame culled the offscreen field and
9/// drew the visible cubes.
10final class CullingDemo extends ShowcaseDemo {
11 /// How many cubes stand inside the starting frustum.
12 static const int visibleCount = 16;
14 /// How many cubes stand outside it, every one of which the check expects
15 /// culled.
16 static const int hiddenCount = 304;
18 late final SceneNode _offscreenBranch;
21 void configureView(DemoContext context) {
22 context.orbit
23 ..distance = 12.0
24 ..pitch = 0.42
25 ..yaw = 0.55;
26 }
29 Scene build(DemoContext context) {
30 final DeviceMesh cube = DeviceMesh.upload(
31 context.device,
32 CuboidShape(size: Vector3.all(0.72)).build(),
33 );
34 final RenderMaterial material = RenderMaterial(
35 name: 'culling markers',
36 baseColor: LinearColor.fromSrgb(0.25, 0.62, 0.86, 1.0),
37 roughness: 0.58,
38 );
40 final Scene scene = Scene()
41 ..ambientColor = LinearColor(0.44, 0.53, 0.7)
42 ..ambientIntensity = 0.14 * LightNode.legacyUnit;
43 for (var i = 0; i < visibleCount; i++) {
44 final int x = i % 4;
45 final int z = i ~/ 4;
46 scene.add(
47 MeshNode(cube, material, name: 'visible cube $i')
48 ..setPosition((x - 1.5) * 1.35, 0.0, (z - 1.5) * 1.35),
49 );
50 }
52 _offscreenBranch = SceneNode(name: 'offscreen warehouse')
53 ..setPosition(120.0, 0.0, 80.0);
54 for (var i = 0; i < hiddenCount; i++) {
55 final int x = i % 19;
56 final int z = i ~/ 19;
57 _offscreenBranch.add(
58 MeshNode(cube, material, name: 'offscreen cube $i')
59 ..setPosition(x * 1.1, 0.0, z * 1.1),
60 );
61 }
62 scene.add(_offscreenBranch);
64 scene.add(
65 LightNode(name: 'sun', intensity: 3.1 * LightNode.legacyUnit)
66 ..setLocalForward(Vector3(-0.5, -0.8, -0.3)),
67 );
68 return scene;
69 }
72 void verify(Scene scene, FrameResult frame) {
73 final int total = visibleCount + hiddenCount;
74 if (scene.meshes.length != total ||
75 _offscreenBranch.subtreeBounds == null ||
76 frame.culled < hiddenCount ||
77 frame.drawCalls < visibleCount) {
78 throw StateError('the offscreen mesh field was not culled');
79 }
80 }
81}