Recursive ziggurat

In the previous page, we built a ziggurat by iteratively translating and scaling each block in turn. We could instead build one using recursion.

function zigguratRec(nbrLevels, nbrSides, height, sfactor) {
    if (nbrLevels == 0)
        return new THREE.Object3D();  // empty node
    let zig = zigguratRec(nbrLevels-1, nbrSides, height, sfactor);
    zig.position.y = height;
    zig.scale.set(sfactor, 1, sfactor);
    let base = zigguratBase(nbrSides, height);
    let root = new THREE.Object3D();
    root.add(zig, base);
    return root;
}

An empty ziggurat consisting of no blocks is represented by an empty node. Alternatively, to build an n-block ziggurat (where n > 0), we recursively build an n–1-block ziggurat zig, and then lift zig vertically along the y-axis (line 5) and scale zig in x and z (line 6). Then we construct a new base (line 7) and combine it with zig (lines 8 and 9) to produce an n-block ziggurat.

Although the scene rendered by zigguratRec is the same as the one produced by ziggurat, its scene graph is very different, having depth equal to the total number of blocks.