Skip to content

Declarative Building ​

Declarative Building, rendered in the brepjs playground
Families · 256 lines▶ Run it in the playground

A small house authored as one tree of typed families: walls, gables, a floor slab, trussed rafters, a roof covering and a chimney stack. Each door and window is a fill-role element in the voids of its wall, so the tree holds a real opening with a Fills relationship, and its frame, glass and leaf are children that move with it. Each element has an order-independent key path, and the model is drawn by type from that index. The door leaf and the truss spacing are published figures. The plan, the walls, the windows and the roof are a display model.

Code ​

This is the full program. The playground runs it in your browser without a change.

ts
import { compound, csg, unwrap } from 'brepjs/quick';
import { color } from 'brepjs/playground';
import { family, el, resolve, evaluateModel, tRotate, tTranslate, type Element } from 'brepjs-families';

// A small house as one tree of typed families. Units are millimetres, Z is up, the front door looks to +X.
// The door leaf and the truss spacing are published figures. The plan, the walls, the windows, the truss
// members and the roof covering are a display model.
interface HouseParams {
  length?: number; // along X: the long walls get one window for each 2.4 m
  pitch?: number; // roof pitch in degrees
  cover?: number; // part of the roof that has its covering, from the west end: 1 closes the roof
  open?: number; // swing of the front door in degrees
}

type Vec3 = readonly [number, number, number];
type Shape = Parameters<typeof compound>[0][number];

// ---- published figures
const LEAF = { width: 838, height: 1981, thickness: 44 }; // standard external door leaf
const TRUSS_SPACING = 600; // largest spacing of trussed rafters

// ---- display model
const WIDTH = 5400; // across Y
const WALL = { height: 2400, thickness: 300 };
const FRAME = 60; // door and window frame section
const WINDOW = { width: 1200, height: 1200, sill: 900 };
const ROOF = { thickness: 120, eaves: 350, verge: 300 };
const TRUSS = { thickness: 47, rafter: 170, tie: 120, post: 100 };
const STACK = 440; // side of the chimney stack

// Families are typed constructors that return elements. A wall is built along its own X, with its
// outer face at y = 0, and then turned into place: its openings ride with it.
const Wall = family<{ length: number; height: number; at: Vec3; turn: number; voids?: readonly Element[] }>('Wall', (p) =>
  el('Box', {
    size: [p.length, WALL.thickness, p.height],
    voids: p.voids ?? [],
    transform: [tRotate(p.turn), tTranslate(p.at)],
  })
);

// role 'fill' turns an element in the voids of a wall into an Opening with a Fills relationship.
// The box is the hole. Its children are what you see: they are placed from the corner of the hole.
const Window = family<{ at: readonly [number, number]; width: number; height: number }>(
  'Window',
  (p) =>
    el('Box', { size: [p.width, WALL.thickness, p.height], transform: [tTranslate([p.at[0], 0, p.at[1]])] }, [
      Frame({ key: 'frame', width: p.width, height: p.height, depth: 90, inset: 60 }),
      Glass({ key: 'glass', size: [p.width - 2 * FRAME, 24, p.height - 2 * FRAME], at: [FRAME, 93, FRAME] }),
      Sill({ key: 'sill', size: [p.width + 120, 60, 50], at: [-60, -60, -50] }),
    ]),
  { role: 'fill' }
);
const Door = family<{ at: readonly [number, number]; open: number }>(
  'Door',
  (p) => {
    const width = LEAF.width + 2 * FRAME;
    const height = LEAF.height + FRAME;
    return el('Box', { size: [width, WALL.thickness, height], transform: [tTranslate([p.at[0], 0, p.at[1]])] }, [
      Frame({ key: 'frame', width, height, depth: 100, inset: 100, threshold: false }),
      // The leaf hangs on the inner face of the frame and swings into the house.
      Leaf({ key: 'leaf', at: [FRAME, 200 - LEAF.thickness, 0], open: p.open }),
    ]);
  },
  { role: 'fill' }
);

const Slab = family<{ size: Vec3; at: Vec3 }>('Slab', (p) => el('Box', { size: p.size, transform: [tTranslate(p.at)] }));
const Storey = family<{ items: readonly Element[] }>('Storey', (p) => el('Group', {}, p.items));

function house({ length = 7800, pitch = 38, cover = 0.5, open = 25 }: HouseParams = {}) {
  const t = WALL.thickness;
  const h = WALL.height;
  const windows = (key: string, run: number): Element[] => {
    const count = Math.max(1, Math.floor(run / 2400));
    const gap = (run - count * WINDOW.width) / (count + 1);
    return Array.from({ length: count }, (_, i) =>
      Window({ key: key + i, ...WINDOW, at: [gap + i * (gap + WINDOW.width), WINDOW.sill] })
    );
  };
  const end = WIDTH - 2 * t; // the end walls stand between the long walls
  const doorAt = (end - LEAF.width - 2 * FRAME) / 2;
  const rise = (WIDTH / 2) * Math.tan((pitch * Math.PI) / 180);

  const tree = resolve(
    Storey({
      key: 'ground',
      items: [
        Slab({ key: 'floor', size: [length, WIDTH, 250], at: [0, 0, -250] }),
        Wall({ key: 'south', length, height: h, at: [0, 0, 0], turn: 0, voids: windows('win-', length) }),
        Wall({ key: 'north', length, height: h, at: [length, WIDTH, 0], turn: 180, voids: windows('win-', length) }),
        Wall({ key: 'east', length: end, height: h, at: [length, t, 0], turn: 90, voids: [Door({ key: 'entry', at: [doorAt, 0], open })] }),
        Wall({ key: 'west', length: end, height: h, at: [0, WIDTH - t, 0], turn: 270, voids: windows('win-', end) }),
        Wall({
          key: 'partition',
          length: end,
          height: h,
          at: [length * 0.45, t, 0],
          turn: 90,
          voids: [Door({ key: 'inner', at: [end - 1400, 0], open: 20 })],
        }),
        ...scenery(length, rise, Math.min(1, Math.max(0, cover))),
      ],
    })
  );

  // Materialize against the content-addressed evaluator. Shapes are opt-in.
  const ev = new csg.Evaluator();
  const model = evaluateModel(tree, ev, {}, { shapes: true });

  // byKeyPath is the identity axis: a stable address for each element, not an array index.
  // A void slot is host/voids:slot, the element that fills it is its /fill child.
  const entry = model.byKeyPath.get('ground/east/voids:entry');
  if (!entry || !model.byKeyPath.has('ground/east/voids:entry/fill/leaf')) throw new Error('door missing');
  const nodes = [...model.byKeyPath.values()];
  const count = (type: string): number => nodes.filter((n) => n.type === type).length;
  console.log(nodes.length + ' key paths: ' + count('Wall') + ' walls, ' + count('Opening') + ' openings, ' + count('Window') + ' windows, ' + count('Door') + ' doors');
  console.log(entry.keyPath + ' ' + entry.relationships.map((r) => r.kind + ' ' + r.target).join(', '));

  // Render along the same axis, with a colour for each type. Opening, Door and Window nodes are
  // the cut bodies of the holes, so they have no colour and are not drawn.
  const groups = new Map<string, Shape[]>();
  for (const n of nodes) {
    if (COLORS[n.type] && n.shape) groups.set(n.type, [...(groups.get(n.type) ?? []), unwrap(n.shape)]);
  }
  const bodies = [...groups.entries()].map(([type, shapes]) => color(compound(shapes), COLORS[type] ?? '#f5f2ea'));
  ev[Symbol.dispose](); // compound() copied the shapes
  return bodies;
}

const COLORS: Record<string, string> = {
  Wall: '#f5f2ea',
  Gable: '#f5f2ea',
  Slab: '#c3c9d1',
  Frame: '#c3c9d1',
  Glass: '#9fd3e6',
  Sill: '#c3c9d1',
  Leaf: '#12b5b0',
  Roof: '#5b6470',
  Ridge: '#48515c',
  Truss: '#d3a956',
  Stack: '#b5694a',
  Step: '#c3c9d1',
  Canopy: '#48515c',
};

// ---- the smaller families

const Box = (type: string) =>
  family<{ size: Vec3; at: Vec3 }>(type, (p) => el('Box', { size: p.size, transform: [tTranslate(p.at)] }));
const Glass = Box('Glass');
const Sill = Box('Sill');
const Step = Box('Step');
const Stack = Box('Stack');
const Canopy = Box('Canopy');

// A frame around a hole: the outline of the hole less the clear opening, as one extruded ring.
const Frame = family<{ width: number; height: number; depth: number; inset: number; threshold?: boolean }>('Frame', (p) => {
  const low = p.threshold === false ? 0 : FRAME; // a door frame has no bottom rail
  const outer = csg.translate(csg.box(p.width, p.depth, p.height), [0, p.inset, 0]);
  const inner = csg.translate(csg.box(p.width - 2 * FRAME, p.depth, p.height - FRAME - low), [FRAME, p.inset, low]);
  return el('Geometry', { node: csg.cut(outer, inner) });
});

// The leaf turns about its hinge edge before it moves to the frame.
const Leaf = family<{ at: Vec3; open: number }>('Leaf', (p) =>
  el('Box', {
    size: [LEAF.width, LEAF.thickness, LEAF.height],
    transform: [tRotate(p.open, { at: [0, LEAF.thickness, 0] }), tTranslate(p.at)],
  })
);

// A section in the YZ plane, extruded along X.
const along = (pts: ReadonlyArray<readonly [number, number]>, x: number, len: number): csg.IRNode =>
  csg.extrude(csg.polygon(pts.map(([y, z]): [number, number, number] => [x, y, z])), [len, 0, 0]);

// The gable is the triangle of wall above an end wall, in the frame of that wall. It takes a window too.
const Gable = family<{ rise: number; at: Vec3; turn: number; voids: readonly Element[] }>('Gable', (p) => {
  const t = WALL.thickness;
  const h = WALL.height;
  const face = csg.polygon([[-t, 0, h], [WIDTH - t, 0, h], [WIDTH / 2 - t, 0, h + p.rise]]);
  return el('Geometry', { node: csg.extrude(face, [0, t, 0]), voids: p.voids, transform: [tRotate(p.turn), tTranslate(p.at)] });
});

// Trussed rafter: a triangle of two rafters and a tie, with a king post and two queen posts.
// Every truss is the same recipe, so the evaluator builds one and places the rest.
const Truss = family<{ x: number; rise: number }>('Truss', (p) => {
  const h = WALL.height;
  const mid = WIDTH / 2;
  const slope = p.rise / mid;
  const under = (y: number): number => h + slope * Math.min(y, WIDTH - y) - TRUSS.rafter; // underside of the rafters
  const foot = (TRUSS.tie + TRUSS.rafter) / slope;
  const d = TRUSS.thickness;
  const post = (y: number): csg.IRNode => {
    const a = y - TRUSS.post / 2;
    const b = y + TRUSS.post / 2;
    const top: Array<[number, number]> = y === mid ? [[b, under(b)], [mid, under(mid)], [a, under(a)]] : [[b, under(b)], [a, under(a)]];
    return along([[a, h + TRUSS.tie], [b, h + TRUSS.tie], ...top], 0, d);
  };
  const frame = csg.cut(
    along([[0, h], [WIDTH, h], [mid, h + p.rise]], 0, d),
    along([[foot, h + TRUSS.tie], [WIDTH - foot, h + TRUSS.tie], [mid, under(mid)]], -d, 3 * d)
  );
  return el('Geometry', { node: csg.compound([frame, post(mid), post(WIDTH / 4), post((3 * WIDTH) / 4)]), transform: [tTranslate([p.x, 0, 0])] });
});

// A plain element in voids is an anonymous cut: the roof covering gets a hole for the chimney stack.
const Roof = family<{ length: number; rise: number; voids: readonly Element[] }>('Roof', (p) => {
  const slope = p.rise / (WIDTH / 2);
  const low = WALL.height - ROOF.eaves * slope;
  const d = ROOF.thickness;
  const section: Array<[number, number]> = [
    [-ROOF.eaves, low], [WIDTH / 2, WALL.height + p.rise], [WIDTH + ROOF.eaves, low],
    [WIDTH + ROOF.eaves, low + d], [WIDTH / 2, WALL.height + p.rise + d], [-ROOF.eaves, low + d],
  ];
  return el('Geometry', { node: along(section, -ROOF.verge, p.length), voids: p.voids });
});
const Ridge = family<{ node: csg.IRNode }>('Ridge', (p) => el('Geometry', { node: p.node }));

// Gables, trusses, roof covering, chimney stack, door step and canopy.
function scenery(length: number, rise: number, cover: number): Element[] {
  const t = WALL.thickness;
  const mid = WIDTH / 2;
  const slope = rise / mid;
  const top = WALL.height + rise + ROOF.thickness;
  // Trusses between the gables, not more than the published spacing apart.
  const bays = Math.ceil((length - 2 * t - TRUSS.thickness) / TRUSS_SPACING);
  const pitch = (length - 2 * t - TRUSS.thickness) / bays;
  const trusses = Array.from({ length: bays + 1 }, (_, i) => Truss({ key: 'truss-' + i, x: t + i * pitch, rise }));
  // The stack stands between two trusses, next to the partition.
  const bay = Math.floor((length * 0.45 - t - STACK) / pitch) - 1;
  const stack: Vec3 = [STACK, STACK, top + 600];
  const at: Vec3 = [t + bay * pitch + TRUSS.thickness + (pitch - TRUSS.thickness - STACK) / 2, mid - STACK - 400, 0];
  const covered = ROOF.verge + cover * (length + ROOF.verge);
  const cap: Array<[number, number]> = [
    [mid - 150, top - 150 * slope], [mid, top], [mid + 150, top - 150 * slope],
    [mid + 150, top - 150 * slope + 70], [mid, top + 70], [mid - 150, top - 150 * slope + 70],
  ];
  const doorY = (WIDTH - LEAF.width - 2 * FRAME) / 2;
  const attic = Window({ key: 'attic', width: 700, height: 700, at: [mid - t - 350, WALL.height + 350] });
  return [
    Gable({ key: 'gable-west', rise, at: [0, WIDTH - t, 0], turn: 270, voids: [attic] }),
    Gable({ key: 'gable-east', rise, at: [length, t, 0], turn: 90, voids: [attic] }),
    ...trusses,
    Stack({ key: 'stack', size: stack, at }),
    ...(cover > 0
      ? [
          Roof({ key: 'roof', length: covered, rise, voids: [Stack({ key: 'hole', size: stack, at })] }),
          Ridge({ key: 'ridge', node: along(cap, -ROOF.verge, covered) }),
        ]
      : []),
    Step({ key: 'step', size: [900, LEAF.width + 700, 150], at: [length, doorY - 350 + FRAME, -150] }),
    Canopy({ key: 'canopy', size: [800, LEAF.width + 500, 80], at: [length, doorY - 250 + FRAME, LEAF.height + 2 * FRAME + 120] }),
  ];
}

export default house();

Functions used ​

compound csg unwrap color family el resolve evaluateModel tRotate tTranslate

▶ Run Declarative Building in the playground

Released under the Apache 2.0 License.