# Use wall types

> A wall type of brick, insulation, block and plaster on an L and a T of walls. The plan draws one hatched strip for each layer. The button makes the insulation 80 mm thick in one step.

- Live example: https://floorkit-examples.ploterr.com/floorkit/guides/wall-types
- Docs page: https://docs.ploterr.com/floorkit/guides/wall-types
- Category: Model a building
- API: `BuildingSession`
- Tags: wall, wall type, layers, session
- Package: `@opengeometry/floorkit`
- Source: `examples/src/guides/wall-types.example.ts`

Each example is one module exporting `meta` and `setup(ctx)`. The examples shell renders it in 3D and as a 2D plan (on a sheet surface for drawing examples, and as a tabbed building page for demos) and builds its controls from the element schema.

## Source

### examples/src/guides/wall-types.example.ts

```ts
import type { ExampleContext, ExampleMeta, ExampleResult } from '../app/lib/example';
import { closeBuilding, startBuilding } from './code/start-a-building';
import { addCavityType, drawTypedWalls, thickenInsulation } from './code/wall-types';
import { action, planOf } from './support';

export const meta: ExampleMeta = {
  title: 'Use wall types',
  description:
    'A wall type of brick, insulation, block and plaster on an L and a T of walls. The plan draws one hatched strip for each layer. The button makes the insulation 80 mm thick in one step.',
  tags: ['wall', 'wall type', 'layers', 'session'],
  api: ['BuildingSession'],
  view: '2d',
  camera: { position: [13, 9, 15], target: [3, 1.2, 2] },
};

export function setup({ scene }: ExampleContext): ExampleResult {
  const session = startBuilding(scene);
  addCavityType(session);
  drawTypedWalls(session);
  return {
    plan: planOf(() => session),
    controls: [
      action('thicken-insulation', 'Insulation to 80 mm', () => thickenInsulation(session)),
    ],
    expose: { session },
    dispose: () => closeBuilding(scene, session),
  };
}
```

### examples/src/app/lib/example.ts

```ts
import type { ReactNode } from 'react';
import type * as THREE from 'three';
import type { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import type {
  createModelRenderer,
  EditorChange,
  OPControl,
  SelectedPart,
  VectorDrawing,
  WallNetwork,
} from '@opengeometry/floorkit';
import type { SceneHandle } from './scene';

export type EditTarget = THREE.Object3D & { ogType: string };

export type PlanRenderer = Awaited<ReturnType<typeof createModelRenderer>>;

export interface ExampleMeta {
  title: string;
  description: string;
  tags?: readonly string[];
  api?: readonly string[];
  camera?: { position: [number, number, number]; target: [number, number, number] };
  view?: '3d' | '2d';
  surface?: 'dom';
  grid?: false | { size: number; y?: number };
  notes?: readonly string[];
}

export interface SurfaceContext {
  container: HTMLElement;
  refresh: () => void;
  /** Show the message of an error in the error banner of the page, as a refused action does. */
  showError: (error: unknown) => void;
}

export interface ExampleContext extends SurfaceContext {
  scene: THREE.Scene;
  camera: THREE.PerspectiveCamera;
  controls: OrbitControls;
  renderer: THREE.WebGLRenderer;
  onFrame: (callback: () => void) => void;
}

export interface PlanSource {
  getDrawing: () => VectorDrawing;
  getElementById?: (ogid: string) => unknown;
  getChangedDrawing?: (ogids: readonly string[]) => VectorDrawing;
  subscribeInvalidation?: (callback: (ogids: readonly string[]) => void) => () => void;
}

export interface PlanElement {
  ogid: string;
}

export type InputControl =
  | { kind: 'text'; input: 'date' | 'password' }
  | { kind: 'file'; accept: string };

export interface ValueControl {
  key: string;
  label: string;
  group?: string;
  control: OPControl | InputControl;
  get: () => unknown;
  set?: (value: unknown) => void;
  commit?: (value: unknown) => void;
}

export type ActionIcon = 'undo' | 'redo';

export interface ActionControl {
  key: string;
  label: string;
  group?: string;
  icon?: ActionIcon;
  run: () => unknown;
}

export type ControlOverride = ValueControl | ActionControl;

export type Verdict = 'pass' | 'fail';

export interface ReportSection {
  title: string;
  verdict?: Verdict;
  columns?: readonly string[];
  rows?: ReadonlyArray<{ cells: ReadonlyArray<string | number>; verdict?: Verdict }>;
  note?: string;
}

export interface EditChoice {
  label: string;
  target: EditTarget;
}

/**
 * A managed project's selection and its saved fields: the inspector shows the selected element and
 * writes each field as one saved step, so a field change is undone and reloaded like a gesture.
 */
export interface ManagedInspector {
  /** The selected managed element, as its current live object. */
  selected(): EditTarget | undefined;
  /** Save fields of a managed element (editable-schema paths); throws when they cannot be saved. */
  replaceFields(liveId: string, patch: Record<string, unknown>, part?: SelectedPart): unknown;
  selectedPart?(): SelectedPart | undefined;
  /** Call `callback` after a selection change or a saved step; returns the unsubscribe. */
  subscribe(callback: () => void): () => void;
}

/** A tab of the properties panel that the example draws itself, beside Properties. */
export interface ExamplePane {
  key: string;
  label: string;
  content: ReactNode;
}

export interface ExampleResult {
  edit?: EditTarget | (() => EditTarget | undefined);
  managed?: ManagedInspector;
  targets?: readonly EditChoice[] | (() => readonly EditChoice[]);
  pick?: boolean;
  plan?: WallNetwork | readonly PlanElement[] | PlanSource;
  controls?: false | readonly ControlOverride[] | ((target: EditTarget | undefined) => readonly ControlOverride[]);
  report?: () => readonly ReportSection[];
  panes?: () => readonly ExamplePane[];
  onEdit?: (change: EditorChange) => void;
  onChange?: () => void;
  onPlan?: (renderer: PlanRenderer) => void;
  expose?: Record<string, unknown>;
  scene?: SceneHandle;
  dispose?: () => void;
}

export interface ExampleModule {
  meta: ExampleMeta;
  setup: (context: ExampleContext) => Promise<ExampleResult> | ExampleResult;
}
```

### examples/src/guides/code/start-a-building.ts

```ts
import * as THREE from 'three';
import { BuildingSession, type BuildingModel } from '@opengeometry/floorkit';

export const emptyBuilding: BuildingModel = {
  schema: 'floorkit.building-model',
  version: 3,
  units: 'meters',
  upAxis: 'y',
  id: 'my-building',
  buildings: [
    {
      id: 'building',
      storeys: [{ id: 'ground', name: 'Ground floor', elevation: 0, height: 3 }],
    },
  ],
};

export function startBuilding(scene: THREE.Scene): BuildingSession {
  const session = new BuildingSession(emptyBuilding);
  scene.add(session.root);
  return session;
}

import type { ElementLists } from '@opengeometry/floorkit';

export function removeElement(
  session: BuildingSession,
  list: keyof ElementLists,
  elementId: string,
): void {
  session.apply(
    { kind: 'remove-element', buildingId: 'building', storeyId: 'ground', list, elementId },
    session.revision,
  );
}

export function replaceBuilding(
  scene: THREE.Scene,
  current: BuildingSession,
  change: (model: BuildingModel) => void,
): BuildingSession {
  const model = current.snapshot();
  change(model);
  const next = new BuildingSession(model);
  scene.remove(current.root);
  current.dispose();
  scene.add(next.root);
  return next;
}

export function closeBuilding(scene: THREE.Scene, session: BuildingSession): void {
  scene.remove(session.root);
  session.dispose();
}
```

### examples/src/guides/code/wall-types.ts

```ts
import type { BmWallType, BuildingSession } from '@opengeometry/floorkit';

export const cavityWall: BmWallType = {
  name: 'Cavity 315',
  layers: [
    { material: 'BRICK', thickness: 0.1, function: 'finishOutside' },
    { material: 'INSULATION', thickness: 0.05, function: 'thermal' },
    { material: 'BLOCK', thickness: 0.15, function: 'structure' },
    { material: 'PLASTER', thickness: 0.015, function: 'finishInside' },
  ],
};

export function addCavityType(session: BuildingSession): void {
  session.apply(
    { kind: 'add-wall-type', typeId: 'cavity', definition: cavityWall },
    session.revision,
  );
}

export function drawTypedWalls(session: BuildingSession): void {
  const walls: Array<{ id: string; points: [number, number][] }> = [
    {
      id: 'typed-l',
      points: [
        [0, 0],
        [6, 0],
        [6, 4],
      ],
    },
    {
      id: 'typed-t',
      points: [
        [3, 0],
        [3, 4],
      ],
    },
  ];
  for (const { id, points } of walls) {
    session.apply(
      {
        kind: 'create-wall',
        buildingId: 'building',
        storeyId: 'ground',
        wall: { id, points, typeRef: 'cavity' },
      },
      session.revision,
    );
  }
}

export function thickenInsulation(session: BuildingSession): void {
  session.apply(
    {
      kind: 'replace-wall-type',
      typeId: 'cavity',
      definition: {
        ...cavityWall,
        layers: cavityWall.layers.map((layer) =>
          layer.material === 'INSULATION' ? { ...layer, thickness: 0.08 } : layer,
        ),
      },
    },
    session.revision,
  );
}
```

### examples/src/guides/support.ts

```ts
import type * as THREE from 'three';
import {
  drawProjectView,
  type BmRailing,
  type BmSlab,
  type BmStair,
  type BmStorey,
  type BuildingSession,
  type ElementListCommand,
  type ElementLists,
  type PaperScreenRenderer,
  type ProjectFile,
} from '@opengeometry/floorkit';
import type { ActionControl, ActionIcon, PlanSource } from '../app/lib/example';
import { addDoor } from './code/add-a-door';
import { addFloorSlab, groundFloor } from './code/add-a-floor-slab';
import { addRoof } from './code/add-a-roof';
import { addWindow } from './code/add-a-window';
import { mainStair } from './code/add-a-stair';
import { createProject } from './code/create-a-plan-view';
import { addSectionMark, addSectionViews } from './code/cut-a-section';
import { drawRoom } from './code/draw-a-wall';
import { startBuilding } from './code/start-a-building';

export const ring = (x0: number, z0: number, x1: number, z1: number): [number, number][] => [
  [x0, z0],
  [x1, z0],
  [x1, z1],
  [x0, z1],
];

// The "Stair with hole" of the plan editor and the 3D editor: a stair next to the house
// (0..6 x 0..4 m), the floor above it at the top of the storey with a hole round the flight
// (+ margin), and a rail. The floor is large enough for the flight in each layout and turn
// that the panel offers, so the hole can follow it.
const stairFloor: BmSlab = {
  ...groundFloor,
  id: 'stair-floor',
  profile: { outerRing: ring(7, 6, 13, 13), holes: [ring(7.45, 10.05, 12.31, 8.95)] },
  baseOffset: 2.8,
};
const stair: BmStair = {
  ...mainStair,
  id: 'stair-b1',
  origin: [7.5, 9.5],
  slabHole: { storeyId: 'ground', slabId: stairFloor.id, holeIndex: 0, margin: 0.05 },
};
const stairRail: BmRailing = {
  id: 'stair-rail',
  host: { stairId: stair.id, side: 'left', inset: 0.05 },
};
export const addToGround = <List extends 'slabs' | 'stairs' | 'railings' | 'roomSeparators'>(
  list: List,
  element: ElementLists[List],
): ElementListCommand =>
  ({
    kind: 'add-element',
    buildingId: 'building',
    storeyId: 'ground',
    list,
    element,
  }) as ElementListCommand;

export const stairWithHole = {
  /** The stair first, then its floor and its rail. */
  ids: [stair.id, stairFloor.id, stairRail.id],
  /** One step that adds the three. */
  command: {
    kind: 'batch' as const,
    commands: [
      addToGround('slabs', stairFloor),
      addToGround('stairs', stair),
      addToGround('railings', stairRail),
    ],
  },
};

// The "Room separator" of the plan editor and the 3D editor: a line on the ground east of the
// house, clear of the stair and its floor.
const separator: ElementLists['roomSeparators'] = {
  id: 'separator-1',
  points: [
    [7.5, 1.5],
    [11, 1.5],
  ],
};

export const roomSeparator = {
  id: separator.id,
  /** One step that adds the line. */
  command: addToGround('roomSeparators', separator),
};

export function groundOf(session: BuildingSession): BmStorey | undefined {
  return session.snapshot().buildings[0]?.storeys.find((storey) => storey.id === 'ground');
}

export function hasWall(session: BuildingSession, wallId: string): boolean {
  return groundOf(session)?.walls?.some((wall) => wall.id === wallId) ?? false;
}

export function hasOpening(session: BuildingSession, wallId: string, openingId: string): boolean {
  return (
    groundOf(session)
      ?.walls?.find((wall) => wall.id === wallId)
      ?.openings?.some((opening) => opening.id === openingId) ?? false
  );
}

export function planOf(session: () => BuildingSession): PlanSource {
  // The project gives the view; the session gives the model and its live build. No rebuild and
  // no copy of the model after each edit. A new session (a reopened file) gets a new project.
  let drawn: { session: BuildingSession; project: ProjectFile } | undefined;
  return {
    getDrawing: () => {
      const current = session();
      if (drawn?.session !== current)
        drawn = { session: current, project: createProject(current.snapshot()) };
      return drawProjectView(drawn.project, 'ground-plan', { session: current });
    },
  };
}

export function action(
  key: string,
  label: string,
  run: () => unknown,
  icon?: ActionIcon,
): ActionControl {
  return icon ? { key, label, icon, run } : { key, label, run };
}

export function buildHouse(scene: THREE.Scene): BuildingSession {
  const session = startBuilding(scene);
  drawRoom(session);
  addDoor(session);
  addWindow(session);
  addFloorSlab(session);
  addRoof(session);
  return session;
}

export function houseDrawings(session: BuildingSession): ProjectFile {
  return addSectionMark(addSectionViews(createProject(session.snapshot())));
}

export function fitSheet(renderer: PaperScreenRenderer, container: HTMLElement): () => void {
  const sizes = new ResizeObserver(() => {
    renderer.resize(container.clientWidth, container.clientHeight);
    renderer.fitToPage();
  });
  sizes.observe(container);
  return () => sizes.disconnect();
}
```

### examples/src/app/lib/scene.ts

```ts
import * as THREE from 'three';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { OpenGeometry, Sheet, Solid, Wire } from 'opengeometry';
import { checkViewWatermark } from '@opengeometry/floorkit';
import { fitScene } from './fit-scene';
import { createFrameSampler, type SceneMetrics } from './scene-metrics';

export interface SceneHandle {
  scene: THREE.Scene;
  camera: THREE.PerspectiveCamera;
  renderer: THREE.WebGLRenderer;
  controls: OrbitControls;
  onFrame: (callback: () => void) => void;
  requestRender: () => void;
  metrics: () => SceneMetrics;
  fit: () => void;
  dispose: () => void;
}

export interface SceneOptions {
  camera: { position: [number, number, number]; target: [number, number, number] };
  grid?: false | { size: number; y?: number };
}

const SETTLE_MS = 250;
const IDLE_GAP_MS = 100;
const WATERMARK_CHECK_MS = 1000;
const ORBIT_DAMPING = 0.2;
const CONTAINER_INPUT = ['pointerdown', 'pointermove', 'pointerup', 'wheel'] as const;
const PAGE_INPUT = ['keydown', 'keyup', 'click', 'input', 'change'] as const;

export function createScene(
  container: HTMLElement,
  { camera, grid = { size: 40 } }: SceneOptions,
): SceneHandle {
  const scene = new THREE.Scene();
  scene.background = new THREE.Color(0xfbfaf9);
  const perspective = new THREE.PerspectiveCamera(60, 1, 0.1, 1000);
  perspective.position.set(...camera.position);
  const renderer = new THREE.WebGLRenderer({ antialias: true, logarithmicDepthBuffer: true });
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.0;
  const pmrem = new THREE.PMREMGenerator(renderer);
  const environment = pmrem.fromScene(new RoomEnvironment(), 0.04);
  scene.environment = environment.texture;
  container.appendChild(renderer.domElement);
  const controls = new OrbitControls(perspective, renderer.domElement);
  controls.target.set(...camera.target);
  controls.enableDamping = true;
  controls.dampingFactor = ORBIT_DAMPING;
  controls.update();
  scene.add(new THREE.HemisphereLight(0xffffff, 0x888888, 1.1));
  const sun = new THREE.DirectionalLight(0xffffff, 1.3);
  sun.position.set(6, 10, 4);
  scene.add(sun);
  if (grid) {
    const helper = new THREE.GridHelper(grid.size, grid.size, 0xbab9b8, 0xe4e3e1);
    helper.position.y = grid.y ?? 0;
    scene.add(helper);
  }

  const frameCallbacks: Array<() => void> = [];
  const sampler = createFrameSampler();
  let frame = 0;
  let requested = false;
  let continuous = false;
  let lastFrameEnd = -Infinity;
  let pass: 'change' | 'settle' | 'catch-up' = 'change';
  let settle: ReturnType<typeof setTimeout> | undefined;
  const kernelRecords = () => {
    const records = new Map<Solid | Sheet | Wire, unknown>();
    scene.traverseVisible((object) => {
      if (object instanceof Solid || object instanceof Sheet || object instanceof Wire)
        records.set(object, object.record);
    });
    return records;
  };
  const catchUp = (records: Map<Solid | Sheet | Wire, unknown>) => {
    for (const [body, record] of records)
      if (body.record !== record) {
        pass = 'catch-up';
        requestRender();
        return;
      }
  };
  const settled = () => {
    pass = 'settle';
    requestRender();
  };
  const animate = () => {
    requested = false;
    const current = pass;
    pass = 'change';
    controls.update();
    const records = current === 'settle' ? kernelRecords() : undefined;
    sampler.begin();
    renderer.render(scene, perspective);
    sampler.end(renderer, continuous);
    lastFrameEnd = performance.now();
    for (const callback of frameCallbacks) callback();
    if (records) queueMicrotask(() => catchUp(records));
    if (current !== 'change') return;
    clearTimeout(settle);
    settle = setTimeout(settled, SETTLE_MS);
  };
  const requestRender = () => {
    if (requested) return;
    requested = true;
    continuous = pass === 'change' && performance.now() - lastFrameEnd < IDLE_GAP_MS;
    frame = requestAnimationFrame(animate);
  };

  let interacted = false;
  const preserveView = () => {
    interacted = true;
  };
  renderer.domElement.addEventListener('pointerdown', preserveView);
  renderer.domElement.addEventListener('wheel', preserveView, { passive: true });
  const fit = () => {
    fitScene(scene, perspective, controls);
    requestRender();
  };
  const resize = () => {
    const { clientWidth, clientHeight } = container;
    if (!clientWidth || !clientHeight) return;
    perspective.aspect = clientWidth / clientHeight;
    perspective.updateProjectionMatrix();
    renderer.setSize(clientWidth, clientHeight);
    if (!interacted && perspective.aspect < 1) fit();
    requestRender();
  };
  resize();
  const observer = new ResizeObserver(resize);
  observer.observe(container);

  controls.addEventListener('change', requestRender);
  scene.addEventListener('childadded', requestRender);
  scene.addEventListener('childremoved', requestRender);
  const stopGeometry = OpenGeometry.on('geometry', requestRender);
  const page = container.ownerDocument;
  for (const type of CONTAINER_INPUT) container.addEventListener(type, requestRender);
  for (const type of PAGE_INPUT) page.addEventListener(type, requestRender);
  let blocked = checkViewWatermark(renderer);
  const watermark = setInterval(() => {
    const now = checkViewWatermark(renderer);
    if (now === blocked) return;
    blocked = now;
    requestRender();
  }, WATERMARK_CHECK_MS);
  requestRender();

  return {
    scene,
    camera: perspective,
    renderer,
    controls,
    onFrame: (callback) => {
      frameCallbacks.push(callback);
      requestRender();
    },
    requestRender,
    metrics: () => sampler.read(scene),
    fit,
    dispose: () => {
      cancelAnimationFrame(frame);
      clearTimeout(settle);
      clearInterval(watermark);
      stopGeometry();
      controls.removeEventListener('change', requestRender);
      scene.removeEventListener('childadded', requestRender);
      scene.removeEventListener('childremoved', requestRender);
      for (const type of CONTAINER_INPUT) container.removeEventListener(type, requestRender);
      for (const type of PAGE_INPUT) page.removeEventListener(type, requestRender);
      observer.disconnect();
      sampler.dispose();
      renderer.domElement.removeEventListener('pointerdown', preserveView);
      renderer.domElement.removeEventListener('wheel', preserveView);
      controls.dispose();
      environment.dispose();
      pmrem.dispose();
      renderer.dispose();
      renderer.forceContextLoss();
      renderer.domElement.remove();
    },
  };
}
```

### examples/src/guides/code/add-a-door.ts

```ts
import type { BuildingSession } from '@opengeometry/floorkit';

export function addDoor(session: BuildingSession): void {
  session.apply(
    {
      kind: 'add-hosted-opening',
      buildingId: 'building',
      storeyId: 'ground',
      wallId: 'room-walls',
      opening: {
        id: 'entry-door',
        kind: 'door',
        offset: 2,
        width: 0.9,
        height: 2.1,
        doorQuadrant: 1,
      },
    },
    session.revision,
  );
}

export function moveDoor(session: BuildingSession): void {
  session.apply(
    {
      kind: 'move-hosted-opening',
      buildingId: 'building',
      storeyId: 'ground',
      wallId: 'room-walls',
      openingId: 'entry-door',
      offset: 3,
    },
    session.revision,
  );
}

export function removeDoor(session: BuildingSession): void {
  session.apply(
    {
      kind: 'remove-hosted-opening',
      buildingId: 'building',
      storeyId: 'ground',
      wallId: 'room-walls',
      openingId: 'entry-door',
    },
    session.revision,
  );
}

export function moveDoorToWall(session: BuildingSession): void {
  session.apply(
    {
      kind: 'rehost-hosted-opening',
      buildingId: 'building',
      storeyId: 'ground',
      wallId: 'room-walls',
      openingId: 'entry-door',
      toWallId: 'garden-wall',
      offset: 3,
    },
    session.revision,
  );
}
```

### examples/src/guides/code/add-a-floor-slab.ts

```ts
import type { BmSlab, BuildingSession } from '@opengeometry/floorkit';

export const groundFloor: BmSlab = {
  id: 'ground-floor',
  role: 'slab',
  profile: {
    outerRing: [
      [-0.1, -0.1],
      [6.1, -0.1],
      [6.1, 4.1],
      [-0.1, 4.1],
    ],
  },
  thickness: 0.2,
  baseOffset: -0.2,
};

export function addFloorSlab(session: BuildingSession): void {
  session.apply(
    {
      kind: 'add-element',
      buildingId: 'building',
      storeyId: 'ground',
      list: 'slabs',
      element: groundFloor,
    },
    session.revision,
  );
}

import { SlabMaterial } from '@opengeometry/floorkit';

export const balcony: BmSlab = {
  ...groundFloor,
  id: 'balcony',
  thickness: 0.3,
  baseOffset: -0.3,
  edgeProfile: {
    points: [
      [0, 0],
      [0.106, -0.044],
      [0.15, -0.15],
      [0.106, -0.256],
      [0, -0.3],
    ],
    edges: [0, 1, 2],
  },
  material: SlabMaterial.CONCRETE,
  edgeMaterial: SlabMaterial.CONCRETE,
  soffitMaterial: SlabMaterial.TIMBER,
};

export const curvedBalcony: BmSlab = {
  id: 'curved-balcony',
  thickness: 0.3,
  baseOffset: -0.3,
  profile: {
    outerRing: [
      [0, 0],
      [16, 0],
      [16, -1.2],
      [0, -0.6],
    ],
  },
  arcs: { outerRing: [null, null, { through: [8, -2.2] }, null] },
};

export function moveSlab(session: BuildingSession): void {
  session.apply(
    {
      kind: 'transform-slab',
      buildingId: 'building',
      storeyId: 'ground',
      slabId: 'ground-floor',
      origin: [0, 0],
      translation: [1, 0],
      yawDeg: 0,
    },
    session.revision,
  );
}
```

### examples/src/guides/code/add-a-roof.ts

```ts
import { RoofType, type BmRoof, type BuildingSession } from '@opengeometry/floorkit';

export const mainRoof: BmRoof = {
  id: 'main-roof',
  profile: {
    outerRing: [
      [-0.1, -0.1],
      [6.1, -0.1],
      [6.1, 4.1],
      [-0.1, 4.1],
    ],
  },
  roofType: RoofType.GABLE,
  pitch: 30,
  overhang: 0.3,
  thickness: 0.2,
  baseOffset: 3,
};

export function addRoof(session: BuildingSession): void {
  session.apply(
    {
      kind: 'add-element',
      buildingId: 'building',
      storeyId: 'ground',
      list: 'roofs',
      element: mainRoof,
    },
    session.revision,
  );
}

export function replaceRoof(session: BuildingSession, roof: BmRoof): void {
  session.apply(
    {
      kind: 'replace-element',
      buildingId: 'building',
      storeyId: 'ground',
      list: 'roofs',
      elementId: roof.id,
      element: { ...roof, pitch: 40, overhang: 0.5 },
    },
    session.revision,
  );
}

export function moveRoof(session: BuildingSession): void {
  session.apply(
    {
      kind: 'transform-roof',
      buildingId: 'building',
      storeyId: 'ground',
      roofId: 'main-roof',
      origin: [3, 2],
      translation: [1, 0],
      yawDeg: 90,
    },
    session.revision,
  );
}

export function removeRoof(session: BuildingSession): void {
  session.apply(
    {
      kind: 'remove-element',
      buildingId: 'building',
      storeyId: 'ground',
      list: 'roofs',
      elementId: 'main-roof',
    },
    session.revision,
  );
}

export function raiseWallsToRoof(session: BuildingSession): void {
  const storey = session.snapshot().buildings[0]?.storeys.find(({ id }) => id === 'ground');
  const wall = storey?.walls?.find(({ id }) => id === 'room-walls');
  if (!wall) throw new Error('There is no room wall to raise.');
  const {
    id,
    points: _points,
    closed: _closed,
    arcs: _arcs,
    openings: _openings,
    ...settings
  } = wall;
  session.apply(
    {
      kind: 'replace-wall-settings',
      buildingId: 'building',
      storeyId: 'ground',
      wallId: id,
      settings: { ...settings, topFollowsRoof: true },
    },
    session.revision,
  );
}
```

### examples/src/guides/code/add-a-window.ts

```ts
import type { BuildingSession } from '@opengeometry/floorkit';

export function addWindow(session: BuildingSession): void {
  session.apply(
    {
      kind: 'add-hosted-opening',
      buildingId: 'building',
      storeyId: 'ground',
      wallId: 'room-walls',
      opening: {
        id: 'south-window',
        kind: 'window',
        offset: 4.5,
        width: 1.2,
        height: 1.2,
        sillHeight: 0.9,
      },
    },
    session.revision,
  );
}
```

### examples/src/guides/code/add-a-stair.ts

```ts
import { StairLayout, type BmStair, type BuildingSession } from '@opengeometry/floorkit';

export const mainStair: BmStair = {
  id: 'main-stair',
  layout: StairLayout.STRAIGHT,
  origin: [1, 1],
  rotation: 0,
  baseOffset: 0,
  width: 1,
  treadDepth: 0.28,
};

export function addStair(session: BuildingSession): void {
  session.apply(
    {
      kind: 'add-element',
      buildingId: 'building',
      storeyId: 'ground',
      list: 'stairs',
      element: mainStair,
    },
    session.revision,
  );
}

export const fanStair: BmStair = {
  id: 'fan-stair',
  layout: StairLayout.FAN,
  origin: [6.3, -3.32],
  rotation: -45,
  baseOffset: 0,
  width: 1.8,
  totalRise: 0.9,
  innerRadius: 1.5,
  sweepAngle: 90,
  turnDirection: 'right',
};

export const winderStair: BmStair = {
  id: 'winder-stair',
  layout: StairLayout.WINDER,
  origin: [1, 1],
  baseOffset: 0,
  turnDirection: 'left',
  winderCount: 3,
};

import type { SavedDrawingView } from '@opengeometry/floorkit';

export const groundPlan: SavedDrawingView = {
  id: 'ground-plan',
  name: 'Ground floor',
  kind: 'plan',
  storeyId: 'ground',
  cutHeightAboveStorey: 1.2,
  hideStairAboveCut: true,
};

export const waistStair: BmStair = {
  ...mainStair,
  id: 'waist-stair',
  structureDepth: 0.15,
};

export const linkedStair: BmStair = {
  ...mainStair,
  id: 'linked-stair',
  slabHole: { storeyId: 'first', slabId: 'first-floor', holeIndex: 0, margin: 0.05 },
};
```

### examples/src/guides/code/create-a-plan-view.ts

```ts
import {
  drawProjectView,
  type BuildingModel,
  type BuildingSession,
  type ProjectFile,
  type SavedDrawingView,
} from '@opengeometry/floorkit';

export const groundPlan: SavedDrawingView = {
  id: 'ground-plan',
  name: 'Ground floor plan',
  kind: 'plan',
  storeyId: 'ground',
  cutHeightAboveStorey: 1.2,
};

export function createProject(buildingModel: BuildingModel): ProjectFile {
  return {
    schema: 'floorkit.project',
    version: 3,
    buildingModel,
    views: [groundPlan],
    paper: { version: 1, unitSystem: 'metric', sheets: [] },
  };
}

export function planLinework(project: ProjectFile, session: BuildingSession) {
  const drawing = drawProjectView(project, 'ground-plan', { session });
  console.log(`${drawing.primitives.length} primitives`, drawing.bounds);
  return drawing;
}
```

### examples/src/guides/code/cut-a-section.ts

```ts
import type { ProjectFile, SavedDrawingView } from '@opengeometry/floorkit';

export const sectionA: SavedDrawingView = {
  id: 'section-a',
  name: 'Section A',
  kind: 'section',
  line: { start: [4.5, -1], end: [4.5, 5] },
  lookSide: 'right',
  depth: 5,
  verticalCrop: { minY: -0.5, maxY: 6 },
  settings: { levelLabels: { datum: 0, unit: 'm' } },
};

export const southElevation: SavedDrawingView = {
  id: 'elevation-south',
  name: 'South elevation',
  kind: 'elevation',
  origin: [3, -2],
  lookDirection: [0, 1],
  crop: { left: -4, right: 4, bottom: -6, top: 0.5 },
};

export function addSectionViews(project: ProjectFile): ProjectFile {
  return { ...project, version: 3, views: [...project.views, sectionA, southElevation] };
}

import type { ProjectViewMarker } from '@opengeometry/floorkit';

export const sectionMark: ProjectViewMarker = {
  id: 'section-a-mark',
  kind: 'source',
  parentViewId: 'ground-plan',
  target: { viewId: 'section-a' },
};

export function addSectionMark(project: ProjectFile): ProjectFile {
  return { ...project, version: 3, markers: [...(project.markers ?? []), sectionMark] };
}
```

### examples/src/guides/code/draw-a-wall.ts

```ts
import type { BuildingSession } from '@opengeometry/floorkit';

export function drawWall(session: BuildingSession): void {
  session.apply(
    {
      kind: 'create-wall',
      buildingId: 'building',
      storeyId: 'ground',
      wall: {
        id: 'garden-wall',
        points: [
          [0, 7],
          [6, 7],
        ],
        thickness: 0.2,
      },
    },
    session.revision,
  );
}

export function drawRoom(session: BuildingSession): void {
  session.apply(
    {
      kind: 'create-wall',
      buildingId: 'building',
      storeyId: 'ground',
      wall: {
        id: 'room-walls',
        points: [
          [0, 0],
          [6, 0],
          [6, 4],
          [0, 4],
        ],
        closed: true,
        thickness: 0.2,
      },
    },
    session.revision,
  );
}

export function drawFaceWall(session: BuildingSession): void {
  session.apply(
    {
      kind: 'create-wall',
      buildingId: 'building',
      storeyId: 'ground',
      wall: {
        id: 'corridor-wall',
        points: [
          [0, 10],
          [6, 10],
        ],
        thickness: 0.1,
        locationLine: 'left',
      },
    },
    session.revision,
  );
}

export function drawButtJoinedWall(session: BuildingSession): void {
  session.apply(
    {
      kind: 'create-wall',
      buildingId: 'building',
      storeyId: 'ground',
      wall: {
        id: 'butt-wall',
        points: [
          [6, 0],
          [6, -3],
        ],
        thickness: 0.2,
        joins: { start: { allow: true, type: 'butt' }, end: { allow: false } },
      },
    },
    session.revision,
  );
}

export function drawCurvedWall(session: BuildingSession): void {
  session.apply(
    {
      kind: 'create-wall',
      buildingId: 'building',
      storeyId: 'ground',
      wall: {
        id: 'curved-wall',
        points: [
          [0, 10],
          [4, 10],
        ],
        arcs: [{ through: [2, 11] }],
        thickness: 0.2,
      },
    },
    session.revision,
  );
}

import type { BmWall, BuildingEditCommand } from '@opengeometry/floorkit';

export function bendWall(
  session: BuildingSession,
  wallId: string,
  through: [number, number] | null,
): void {
  session.apply(
    {
      kind: 'bend-wall',
      buildingId: 'building',
      storeyId: 'ground',
      wallId,
      segmentIndex: 0,
      through,
    },
    session.revision,
  );
}

export function straightenWall(session: BuildingSession, wallId: string): void {
  bendWall(session, wallId, null);
}

export function drawCorner(session: BuildingSession): void {
  for (const [id, points] of [
    [
      'long-wall',
      [
        [0, 0],
        [6, 0],
      ],
    ],
    [
      'short-wall',
      [
        [6, 0],
        [6, 4],
      ],
    ],
  ] as const)
    session.apply(
      {
        kind: 'create-wall',
        buildingId: 'building',
        storeyId: 'ground',
        wall: { id, points: points.map(([x, z]) => [x, z]), thickness: 0.2 },
      },
      session.revision,
    );
}

export function filletCorner(session: BuildingSession, radius: number): void {
  session.apply(
    {
      kind: 'fillet-walls',
      buildingId: 'building',
      storeyId: 'ground',
      wallIdA: 'long-wall',
      endA: 'end',
      wallIdB: 'short-wall',
      endB: 'start',
      radius,
      newWallId: 'corner-wall',
    },
    session.revision,
  );
}

export function groundWalls(session: BuildingSession): BmWall[] {
  return session.snapshot().buildings[0].storeys[0].walls ?? [];
}

export function cornerRadius(session: BuildingSession): number | undefined {
  const radius = groundWalls(session).find((wall) => wall.id === 'corner-wall')?.propertySets?.Parti
    ?.filletRadius;
  return typeof radius === 'number' ? radius : undefined;
}

export function roundCorner(session: BuildingSession, radius: number): void {
  const steps: Exclude<BuildingEditCommand, { kind: 'batch' }>[] = [];
  if (cornerRadius(session) !== undefined) {
    const at = { buildingId: 'building', storeyId: 'ground' };
    steps.push(
      { kind: 'delete-wall', ...at, wallId: 'corner-wall' },
      { kind: 'bend-wall', ...at, wallId: 'long-wall', segmentIndex: 0, through: null },
      { kind: 'move-wall-point', ...at, wallId: 'long-wall', pointIndex: 1, position: [6, 0] },
      { kind: 'move-wall-point', ...at, wallId: 'short-wall', pointIndex: 0, position: [6, 0] },
    );
  }
  steps.push({
    kind: 'fillet-walls',
    buildingId: 'building',
    storeyId: 'ground',
    wallIdA: 'long-wall',
    endA: 'end',
    wallIdB: 'short-wall',
    endB: 'start',
    radius,
    newWallId: 'corner-wall',
  });
  session.apply({ kind: 'batch', commands: steps }, session.revision);
}

export function filletInsideRun(
  session: BuildingSession,
  wallId: string,
  station: number,
  radius: number,
): void {
  session.apply(
    {
      kind: 'split-wall',
      buildingId: 'building',
      storeyId: 'ground',
      wallId,
      station,
      newWallId: `${wallId}-after`,
    },
    session.revision,
  );
  session.apply(
    {
      kind: 'fillet-walls',
      buildingId: 'building',
      storeyId: 'ground',
      wallIdA: wallId,
      endA: 'end',
      wallIdB: `${wallId}-after`,
      endB: 'start',
      radius,
      newWallId: `${wallId}-corner`,
    },
    session.revision,
  );
}

export function removeWall(session: BuildingSession): void {
  session.apply(
    { kind: 'delete-wall', buildingId: 'building', storeyId: 'ground', wallId: 'garden-wall' },
    session.revision,
  );
}

export function removeWallAndListVoids(session: BuildingSession): string[] {
  session.apply(
    { kind: 'delete-wall', buildingId: 'building', storeyId: 'ground', wallId: 'room-walls' },
    session.revision,
  );
  return session.currentBuild.warnings
    .filter((warning) => warning.code === 'void-deleted-with-wall')
    .map((warning) => warning.message);
}
```

### examples/src/app/lib/fit-scene.ts

```ts
import { Box3, InstancedMesh, Line, Mesh, PerspectiveCamera, Points, Scene, Vector3 } from 'three';
import type { OrbitControls } from 'three/addons/controls/OrbitControls.js';

/** Fit visible model content while preserving the viewing direction. */
export function fitScene(scene: Scene, camera: PerspectiveCamera, controls: OrbitControls): void {
  const bounds = new Box3();
  scene.updateMatrixWorld(true);
  scene.traverseVisible((object) => {
    if (!(object instanceof Mesh || object instanceof Line || object instanceof Points)) return;
    if (object.type === 'GridHelper') return;
    // Fully transparent helpers (such as the glyph library's 100 m pick plane) are not content.
    const materials = [object.material].flat();
    if (materials.every((material) => material.transparent && material.opacity === 0)) return;
    if (object instanceof InstancedMesh) object.computeBoundingBox();
    else if (!object.geometry.boundingBox) object.geometry.computeBoundingBox();
    const local =
      object instanceof InstancedMesh ? object.boundingBox : object.geometry.boundingBox;
    if (!local) return;
    const box = local.clone().applyMatrix4(object.matrixWorld);
    if (!box.isEmpty() && [...box.min.toArray(), ...box.max.toArray()].every(Number.isFinite))
      bounds.union(box);
  });
  if (bounds.isEmpty()) return;
  const center = bounds.getCenter(new Vector3());
  const radius = bounds.getSize(new Vector3()).length() / 2;
  if (radius <= 0) return;
  const vertical = (camera.getEffectiveFOV() * Math.PI) / 180;
  const horizontal = 2 * Math.atan(Math.tan(vertical / 2) * camera.aspect);
  const distance = (radius / Math.sin(Math.min(vertical, horizontal) / 2)) * 1.08;
  const direction = camera.position.clone().sub(controls.target).normalize();
  if (direction.lengthSq() === 0) direction.set(1, 1, 1).normalize();
  camera.position.copy(center).addScaledVector(direction, distance);
  controls.target.copy(center);
  controls.update();
}
```

### examples/src/app/lib/scene-metrics.ts

```ts
import * as THREE from 'three';

export interface SceneMetrics {
  idle: boolean;
  fps: number;
  frameMs: number;
  worstFrameMs: number;
  renderMs: number;
  blockedMs: number;
  drawCalls: number;
  triangles: number;
  geometries: number;
  textures: number;
  programs: number;
  meshes: number;
  instancedMeshes: number;
  instances: number;
  lines: number;
  heapMb?: number;
}

export interface FrameSampler {
  begin(): void;
  end(renderer: THREE.WebGLRenderer, continuous: boolean): void;
  read(scene: THREE.Object3D): SceneMetrics;
  dispose(): void;
}

interface FrameSample {
  at: number;
  interval: number;
  render: number;
}

const WINDOW_MS = 1000;

function heapMegabytes(): number | undefined {
  const memory: unknown = Reflect.get(performance, 'memory');
  if (typeof memory !== 'object' || memory === null) return undefined;
  const used: unknown = Reflect.get(memory, 'usedJSHeapSize');
  return typeof used === 'number' ? used / 1048576 : undefined;
}

function observeLongTasks(
  into: { at: number; duration: number }[],
): PerformanceObserver | undefined {
  if (!PerformanceObserver.supportedEntryTypes?.includes('longtask')) return undefined;
  const observer = new PerformanceObserver((list) => {
    for (const entry of list.getEntries())
      into.push({ at: entry.startTime + entry.duration, duration: entry.duration });
  });
  observer.observe({ type: 'longtask' });
  return observer;
}

export function createFrameSampler(): FrameSampler {
  const frames: FrameSample[] = [];
  const longTasks: { at: number; duration: number }[] = [];
  const observer = observeLongTasks(longTasks);
  let started = 0;
  let previous: number | undefined;
  let last = { calls: 0, triangles: 0, geometries: 0, textures: 0, programs: 0 };

  const recent = <T extends { at: number }>(items: T[], now: number): T[] => {
    while (items.length > 0 && now - items[0].at > WINDOW_MS) items.shift();
    return items;
  };

  return {
    begin: () => {
      started = performance.now();
    },
    end: (renderer, continuous) => {
      const now = performance.now();
      frames.push({
        at: now,
        interval: continuous && previous !== undefined ? now - previous : 0,
        render: now - started,
      });
      previous = now;
      recent(frames, now);
      recent(longTasks, now);
      const { render, memory, programs } = renderer.info;
      last = {
        calls: render.calls,
        triangles: render.triangles,
        geometries: memory.geometries,
        textures: memory.textures,
        programs: programs?.length ?? 0,
      };
    },
    read: (scene) => {
      const now = performance.now();
      const drawn = recent(frames, now);
      const sampled = drawn.filter(({ interval }) => interval > 0);
      const intervals = sampled.map(({ interval }) => interval);
      const average = (values: number[]) =>
        values.length === 0 ? 0 : values.reduce((sum, value) => sum + value, 0) / values.length;
      let meshes = 0;
      let instancedMeshes = 0;
      let instances = 0;
      let lines = 0;
      scene.traverseVisible((object) => {
        if (!object.layers.isEnabled(0)) return;
        if (object instanceof THREE.InstancedMesh) {
          instancedMeshes += 1;
          instances += object.count;
        } else if (object instanceof THREE.Mesh) meshes += 1;
        else if (object instanceof THREE.Line) lines += 1;
      });
      return {
        idle: drawn.length === 0,
        fps: intervals.length,
        frameMs: average(intervals),
        worstFrameMs: intervals.length === 0 ? 0 : Math.max(...intervals),
        renderMs: average(sampled.map(({ render }) => render)),
        blockedMs: recent(longTasks, now).reduce((sum, { duration }) => sum + duration, 0),
        drawCalls: last.calls,
        triangles: last.triangles,
        geometries: last.geometries,
        textures: last.textures,
        programs: last.programs,
        meshes,
        instancedMeshes,
        instances,
        lines,
        heapMb: heapMegabytes(),
      };
    },
    dispose: () => observer?.disconnect(),
  };
}
```
