Scene Basics
Steps for the AniGraph pages. Two conventions for every step:
- Every class you add goes in its own file in
nodes/, re-exported fromnodes/index.ts(export * from "./TutShapeModel";). Every model class gets@ASerializable("ItsClassName"). - Every node the scene model creates is stored in a field of the scene model, with the name the step gives (
shape,groupA, ...), declared likeshape!: TutShapeModel;. Later steps refer to these names.
Part 1: Node models and views
1.1 A node model
Concept: Node models, @ASerializable, Geometry.
Add a helper class for building polygons, then your first node model: a hexagon.
export class TutFactories{
// A regular polygon, with its vertices CLOCKWISE (a negative angle step), as polygons must be.
static RegularPolygon(nSides: number, radius: number, color: Color, startAngle: number = Math.PI/2): Polygon2D{
const polygon = Polygon2D.CreateForRendering(true);
for(let i=0;i<nSides;i++){
const theta = startAngle - i*2*Math.PI/nSides;
polygon.addVertex(V2(Math.cos(theta), Math.sin(theta)).times(radius), color);
}
return polygon;
}
}
@ASerializable("TutShapeModel")
export class TutShapeModel extends PolygonModel2D{
static Radius = 1.2;
constructor(){ // model classes must be constructible with no arguments
super();
const color = Color.FromString("#3377ff");
this.setVerts(TutFactories.RegularPolygon(6, TutShapeModel.Radius, color));
this.setMaterial(AssetManager.CreateBasicMaterial(color));
}
}
shape!: TutShapeModel;
async initScene(){
this.shape = new TutShapeModel();
this.addNode(this.shape);
}
Run it: the console says Unsure how to create view for ... TutShapeModel. That's expected; the next step fixes it.
1.2 A model–view spec
Concept: Views and model–view specs, Drawing overview.
initModelViewSpecs(){
super.initModelViewSpecs();
this.addModelViewSpec(TutShapeModel, PolygonView2D);
}
Run it: a blue hexagon at the center. The controller only creates views for model classes it has a spec for, and a spec for a parent class doesn't cover a subclass with its own @ASerializable label: every labeled class needs its own line.
Part 2: The scene model and the scene graph
2.1 Time and the frame loop
Concept: The frame loop, The scene model.
timeUpdate(t: number, ...args: any[]){
super.timeUpdate(t, ...args);
this.prsa.rotation = t; // prsa is the node's transform; see step 4.1
}
timeUpdate(t: number){
this.shape.timeUpdate(t);
}
Run it: the hexagon spins. Try it: comment out the line in the scene model's timeUpdate. Nothing moves: node timeUpdates aren't called for you.
2.2 A group node
Concept: Group nodes, The scene graph, and "You don't always need your own class" in Drawing overview.
A plain square doesn't need its own class, so add a factory function for it. The group node does need one, because it has behavior: it turns.
static FlatPolygon(verts: Polygon2D, color: Color): PolygonModel2D{
const polygon = new PolygonModel2D(verts);
polygon.setMaterial(AssetManager.CreateBasicMaterial(color));
return polygon;
}
static Square(size: number, color: Color): PolygonModel2D{
return TutFactories.FlatPolygon(TutFactories.RegularPolygon(4, size*Math.SQRT1_2, color, Math.PI/4), color);
}
@ASerializable("TutGroupModel")
export class TutGroupModel extends AGroupNodeModel2D{
static Speed = 0.5;
direction: number;
squares: PolygonModel2D[] = [];
constructor(direction: number = 1, color: Color = Color.FromString("#29a36a")){
super();
this.direction = direction;
for(const x of [-1, 1]){
const square = TutFactories.Square(0.7, color);
square.prsa.position = V2(x, 0);
this.addChild(square);
this.squares.push(square);
}
}
timeUpdate(t: number, ...args: any[]){
super.timeUpdate(t, ...args);
this.prsa.rotation = this.direction*TutGroupModel.Speed*t;
}
}
In the scene model, add a groupA field, create it in initScene at V2(5, 2) (this.groupA.prsa.position = V2(5, 2)), add it with addNode, and call this.groupA.timeUpdate(t) in timeUpdate. In the controller:
this.addModelViewSpec(TutGroupModel, AGroupNodeView);
this.addModelViewSpec(PolygonModel2D, PolygonView2D); // the plain squares
Run it: two green squares turn around a point that isn't drawn. Try it: remove the TutGroupModel spec. There is a built-in spec for AGroupNodeModel2D, but it doesn't apply to your subclass.
2.3 A child of a child
Concept: The scene graph.
this.nested = TutFactories.Square(0.35, Color.FromString("#1b5e20")); // field: nested!: PolygonModel2D;
this.nested.prsa.position = V2(0.8, 0);
this.groupA.squares[1].addChild(this.nested);
Run it: a small square rides on one of the squares. Its position is relative to its parent square, whose position is relative to the group.
2.4 Finding nodes by type and tag
Concept: Selecting/Filtering for groups of node models.
Add a second group, groupB, at V2(5, -2), turning the other way: new TutGroupModel(-1, Color.FromString("#2e86c1")). Then tag the nested square, and update every group by type instead of one at a time:
// in initScene, after creating the nested square:
this.nested.addTag("highlight");
for(const node of this.getNodesWithTag("highlight")){
node.material.setValue("color", Color.White().asThreeJS());
}
// in timeUpdate, replacing this.groupA.timeUpdate(t):
for(const group of this.getNodesOfType(TutGroupModel)){
group.timeUpdate(t);
}
Run it: a blue group turns the other way with no timeUpdate line of its own, and the nested square is white.
2.5 Reparenting
Concept: the reparenting bullet in The scene graph.
A button takes one of groupA's squares out of the group, or puts it back. (Buttons are covered in Part 3; for now, copy the initAppState lines.)
traveler!: PolygonModel2D; // in initScene: this.traveler = this.groupA.squares[0];
initAppState(appState: AppState){
super.initAppState(appState);
appState.addButton("MoveSquare", ()=>this.moveTraveler());
}
moveTraveler(){
const newParent = (this.traveler.parent === this.groupA) ? this.modelGraph : this.groupA;
const oldWorld = this.traveler.getWorldTransform();
this.traveler.reparent(newParent);
const newParentWorld = (newParent instanceof ANodeModel2D) ? newParent.getWorldTransform() : Mat3.Identity();
this.traveler.setTransform(newParentWorld.getInverse().times(oldWorld));
}
this.modelGraph is the root of the scene. Run it: press MoveSquare. The square stays where it is while the group keeps turning; press it again and the square turns with the group again. Try it: remove the setTransform line, and the square jumps.
Part 3: Controls and events
3.1 Adding and reading controls
Concept: The app state, The control panel.
static ControlKeys = {
SpinSpeed: "SpinSpeed",
}
static SetAppState(appState: AppState){
appState.addSliderIfMissing(TutShapeModel.ControlKeys.SpinSpeed, 1, -5, 5, 0.01);
}
// in timeUpdate, replacing the rotation line:
const speed: number = GetAppState().getState(TutShapeModel.ControlKeys.SpinSpeed);
this.prsa.rotation = speed*t;
Call TutShapeModel.SetAppState(appState) from the scene model's initAppState, right after super.initAppState(appState). Controls appear in the panel in the order they're added.
Run it: the slider changes the speed, and the hexagon jumps when you move it. Step 7.1 explains why and fixes it.
3.2 Subscribing, and setting a control from code
Concept: "Subscribe to changes" and "Setting a control from code" in The control panel.
static ControlKeys = {
SpinSpeed: "SpinSpeed",
Color: "ShapeColor",
Sides: "ShapeSides",
ResetSpeed: "ResetSpeed",
}
static SetAppState(appState: AppState){
const keys = TutShapeModel.ControlKeys;
appState.addSliderIfMissing(keys.SpinSpeed, 1, -5, 5, 0.01);
appState.addColorControl(keys.Color, Color.FromString("#3377ff"));
appState.addSliderIfMissing(keys.Sides, 6, 3, 12, 1);
appState.addButton(keys.ResetSpeed, ()=>{
GetAppState().setControlPanelStateValue(keys.SpinSpeed, 1); // also moves the slider
});
}
// replaces the constructor
constructor(){
super();
const appState = GetAppState();
this.setMaterial(AssetManager.CreateBasicMaterial(appState.getState(TutShapeModel.ControlKeys.Color)));
this.rebuild(appState.getState(TutShapeModel.ControlKeys.Sides));
// Subscriptions only fire on changes, so the lines above applied the current values once.
this.subscribeToAppState(TutShapeModel.ControlKeys.Color, ()=>this.applyColor());
this.subscribeToAppState(TutShapeModel.ControlKeys.Sides, (nSides: number)=>this.rebuild(nSides));
}
rebuild(nSides: number){
this.setVerts(TutFactories.RegularPolygon(Math.round(nSides), TutShapeModel.Radius, Color.White()));
}
applyColor(){
const color: Color = GetAppState().getState(TutShapeModel.ControlKeys.Color);
this.material.setValue("color", color.asThreeJS());
}
Run it: ShapeColor and ShapeSides change the shape; ResetSpeed snaps SpinSpeed back to 1.
3.3 Custom events
Concept: Events and subscriptions.
The hexagon signals a "Ping" event. It doesn't know who listens; the scene model connects groupA to it.
static Events = {
Ping: "TutShapePing",
}
ping(){
this.signalEvent(TutShapeModel.Events.Ping);
}
addPingListener(callback: CallbackType, handle?: string){
return this.addEventListener(TutShapeModel.Events.Ping, callback, handle);
}
recolor(){
const color = Color.Random();
for(const square of this.squares){
square.material.setValue("color", color.asThreeJS());
}
}
// in initAppState. The node doesn't exist yet, so the arrow function looks it up when clicked.
appState.addButton("Ping", ()=>this.shape?.ping());
// in initScene, after both nodes exist:
this.groupA.subscribe(this.shape.addPingListener(()=>this.groupA.recolor()));
Run it: Ping recolors groupA's squares.
Part 4: Transforms
4.1 Position, rotation, scale and anchor
Concept: Transforms, Changing a transform.
@ASerializable("TutPivotModel")
export class TutPivotModel extends PolygonModel2D{
static HalfSize = 0.6;
constructor(){
super();
const color = Color.FromString("#8e44ad");
this.setVerts(TutFactories.RegularPolygon(4, TutPivotModel.HalfSize*Math.SQRT2, color, Math.PI/4));
this.setMaterial(AssetManager.CreateBasicMaterial(color));
this.prsa.anchor = V2(TutPivotModel.HalfSize, TutPivotModel.HalfSize); // the upper-right corner
}
timeUpdate(t: number, ...args: any[]){
super.timeUpdate(t, ...args);
this.prsa.rotation = t;
}
}
Add it as pivot at V2(-5, 3), register it with PolygonView2D, and call this.pivot.timeUpdate(t).
Run it: a purple square swings around its corner. Try it: other anchors, or a scale.
4.2 Using a Mat3
Concept: Using a Mat3.
static Triangle(): PolygonModel2D{
const color = Color.FromString("#e4572e");
return TutFactories.FlatPolygon(TutFactories.RegularPolygon(3, 0.9, color), color);
}
this.triangle = TutFactories.Triangle(); // field: triangle!: PolygonModel2D;
this.triangle.setTransform(Mat3.Translation2D(V2(-5, 0)).times(Mat3.Rotation(Math.PI/6)));
this.triangle.prsa.scale = V2(1.2, 1.2); // prsa still works after setTransform
this.addNode(this.triangle);
Run it: a tilted orange triangle. Try it: comment out the prsa.scale line, multiply a shear into the matrix, .times(Mat3.FromRows(V3(1, 0.5, 0), V3(0, 1, 0), V3(0, 0, 1))), and read the console warning: no position, rotation and scale can make a shear, so the node's transform becomes a Mat3, and prsa would now throw. Undo both changes.
4.3 World transforms
Concept: World transforms.
Add a Marker() factory, like Triangle() but with RegularPolygon(8, 0.09, color) and color #111111. Add one to the scene as marker with zValue = 0.2, and in timeUpdate, after the groups:
this.marker.prsa.position = this.nested.getWorldTransform().times(V2(0, 0));
Run it: the dot sits on the nested square even though it's a top-level node: getWorldTransform() maps the square's origin all the way out to world coordinates.
Part 5: Checkpoint
5.1 Compare with Creating a Scene
Your scene now has every piece that Creating a Scene describes. Go through its Checklist. Several Common mistakes you've already seen on purpose: the missing view spec (1.1, 2.2), nothing moving (2.1), and the ignored background color (0.2).
TutShapeModel.ts, TutGroupModel.ts and TutorialSceneModel.ts in the finished scene show where this code ends up. They also include later steps.