flutter3d
Showcase Changelog 62 packages API reference

A scene written as widgets

since 1.0.0-rc.1 Widgets and the rest

Every other page builds its scene by hand: make a MeshNode, add it, keep a reference to move it later. flutter3d_app also lets a scene be written the way the rest of a Flutter app is, as a tree of widgets that says what should be there now. Each widget owns one node of an ordinary Scene. A rebuild gives the node the widget's new properties, Flutter's keys decide which node is which, and a widget that leaves the tree takes its node out of the scene.

Step 1: Describe the scene #

Light3D, Mesh3D, Node3D, Camera3D and Model3D are the nodes. Material3D is a material as a widget: every Mesh3D below it without a material of its own is drawn with the one engine material it makes, so the boxes here share it and the renderer can still batch them. Node3D is an empty node with a transform, and what hangs below it moves with it. The names end in 3D because SceneNode and Material are already the engine's.

The whole scene is one function of three fields of the page: how many boxes, which paint, and the pivot's angle.

/// The whole scene, as a function of the page's three fields. Nothing here
/// makes a node: each widget owns one, and a rebuild changes it.
List<Widget> _children() => <Widget>[
  // Lux: about 14 500, a bright overcast-to-hazy sun.
  Light3D.directional(
    direction: Vector3(-0.4, -0.8, -0.5),
    intensity: 14500.0,
  ),
  Mesh3D(
    shape: CuboidShape(size: Vector3(6.0, 0.2, 3.0)),
    material: _floor,
    position: Vector3(0.0, -0.1, 0.0),
    name: 'floor',
  ),
  Material3D(
    name: 'paint',
    baseColor: _warm
        ? LinearColor.fromSrgb(0.9, 0.45, 0.2, 1.0)
        : LinearColor.fromSrgb(0.2, 0.5, 0.9, 1.0),
    roughness: 0.6,
    children: <Widget>[
      for (var i = 0; i < _boxes; i++)
        Mesh3D(
          key: ValueKey<String>('box $i'),
          shape: CuboidShape(size: Vector3.all(0.6)),
          position: Vector3(-2.2 + i * 0.9, 0.3, -0.6),
          name: 'box $i',
        ),
    ],
  ),
  Node3D(
    name: 'pivot',
    position: Vector3(0.0, 0.0, 0.8),
    rotation: Quaternion.axisAngle(Vector3(0.0, 1.0, 0.0), _angle),
    children: <Widget>[
      Mesh3D(
        shape: SphereShape(radius: 0.3, segments: 32, rings: 16),
        material: _ball,
        position: Vector3(1.0, 0.3, 0.0),
        name: 'ball',
      ),
    ],
  ),
];

Each box has a key. Without one, removing the first box would hand its node to the second widget and so on down the row; with one, the node of box 0 stays box 0. A shape made fresh on every build, as these are, is built again but uploaded again only when its vertices change.

Step 2: Mount it into a scene somebody else draws #

An app that only wants a picture puts the same children in a Scene3D, which opens a device, makes a renderer and draws every frame. The showcase already has all of that, so this page uses SceneWidgets.mount, which builds the widgets into a scene it is given and draws nothing. It is also how a test or a game with its own loop uses them.

Every frame the page turns the pivot a little and calls update with the new tree, which is what setState would do under a Scene3D. The slider and the switch only change a field, and the next rebuild shows it.

@override
Scene build(DemoContext context) {
  final Scene scene = Scene()
    ..ambientColor = LinearColor(0.5, 0.55, 0.65)
    ..ambientIntensity = 0.3 * LightNode.legacyUnit;
  _mount = SceneWidgets.mount(
    scene: scene,
    renderer: context.renderer,
    device: context.device,
    children: _children(),
  );
  return scene;
}

@override
void update(DemoContext context, double dt) {
  _angle += dt * 0.8;
  // A rebuild, as `setState` would cause under a `Scene3D`: the same nodes,
  // given the widgets' new properties.
  _mount.update(_children());
}

Step 3: What the page checks #

There have to be as many meshes as there are mesh widgets, and the boxes have to share one material. Then the page rebuilds with one more box and the other paint: box 0 has to be the same node as before, still holding the same material, now in the new colour, and the new box has to be in the scene. A rebuild with that box gone has to take its node out again.

final List<MeshNode> before = _meshes(scene);
if (before.length != 2 + _boxes) {
  throw StateError('${before.length} meshes for ${2 + _boxes} widgets');
}
final MeshNode first = _named(scene, 'box 0')!;
final RenderMaterial shared = first.material;
if (!identical(_named(scene, 'box 1')!.material, shared)) {
  throw StateError('the boxes under one Material3D do not share it');
}
// A rebuild with one more box and the other paint: box 0 keeps its node
// and its material, which changes in place.
final (int boxes, bool warm) = (_boxes, _warm);
_boxes = boxes + 1;
_warm = !warm;
_mount.update(_children());
if (!identical(_named(scene, 'box 0'), first) ||
    !identical(first.material, shared) ||
    _named(scene, 'box $boxes') == null ||
    (shared.baseColor.toSrgb().b - (warm ? 0.9 : 0.2)).abs() > 1e-6) {
  throw StateError('a rebuild did not keep and change the nodes it owns');
}
// And one box fewer takes that box's node out of the scene.
_boxes = boxes;
_warm = warm;
_mount.update(_children());
if (_named(scene, 'box $boxes') != null) {
  throw StateError('a box whose widget went is still in the scene');
}

Note. A widget sets only the properties it is given. A transform left null leaves the node where the game put it, so a node moved by hand is not put back by a rebuild that does not say where it goes. The widgets cover meshes, models, lights, cameras, materials, reflection probes, decals, mirrors and particles; anything else is added by Contributor3D or by reaching the scene in Scene3D.onCreated.