Families to IFC

A block of flats on two storeys, authored as families and projected into a BimModel with familiesToBim: spatial containment, wall openings as IfcOpeningElement relationships with IfcDoor and IfcWindow fillers, and GlobalIds derived from key paths. The console shows that every GlobalId is the same after the tree is reversed. Families with no IFC mapping, the door leaves and the glass panes, go out as proxies. The BIM panel shows the spatial tree and the IFC button downloads the file. The stair rise, going and landing are published figures. The plan and the sizes are a display model.
Code
This is the full program. The playground runs it in your browser without a change.
import { compound, csg, unwrap } from 'brepjs/quick';
import { color, present } from 'brepjs/playground';
import { family, el, resolve, tTranslate, type Element } from 'brepjs-families';
import { familiesToBim, placedSolids, toIfc } from 'brepjs-bim';
// A block of flats on two storeys, authored as families and projected to a BIM model and an IFC file.
// Units are millimetres, Z is up. The stair figures are published. The plan and the sizes are a display model.
interface BlockParams {
flats?: number; // flats on each storey: the facades, the gallery and the roof follow
pitch?: number; // roof pitch in degrees
}
type Vec3 = readonly [number, number, number];
type Shape = Parameters<typeof compound>[0][number];
const X: Vec3 = [1, 0, 0];
const Y: Vec3 = [0, 1, 0];
// ---- published figures (general access stair)
const STAIR = { rise: 170, going: 280, flights: [9, 8], landing: 1200 }; // rise 150 to 170, going 250 to 400, 12 risers at most
// ---- display model
const STOREY = (STAIR.flights[0]! + STAIR.flights[1]!) * STAIR.rise; // floor to floor
const FLAT = 6000; // along X
const DEPTH = 7000; // along Y
const WALL = { thickness: 300, party: 200 };
const SLAB = 250;
const GALLERY = { depth: 1500, slab: 200, post: 200 };
const STAIR_WIDTH = 1100;
const GUARD = { height: 1100, thickness: 50 };
// Spec-shaped families: the prop names feed the IFC element specs 1:1, so the adapter can make real
// building elements. The IFC placement of a wall is its origin and its axisX, and its thickness goes
// along axisZ x axisX. bar() makes the same solid, so the viewer and the IFC file agree.
const bar = (axisX: Vec3, length: number, thickness: number, height: number): csg.IRNode => {
const pt = (u: number, v: number): [number, number, number] => [u * axisX[0] - v * axisX[1], u * axisX[1] + v * axisX[0], 0];
return csg.extrude(csg.polygon([pt(0, 0), pt(length, 0), pt(length, thickness), pt(0, thickness)]), [0, 0, height]);
};
const Wall = family<{
length: number;
height: number;
thickness: number;
at: Vec3;
axisX: Vec3;
voids?: readonly Element[];
materialName: string;
isExternal?: boolean;
loadBearing?: boolean;
}>('Wall', (p) =>
el('Geometry', { node: bar(p.axisX, p.length, p.thickness, p.height), voids: p.voids ?? [], transform: [tTranslate(p.at)] })
);
// role 'fill': in the voids of a wall, these become IfcOpeningElement with IfcDoor or IfcWindow as the filler.
// The translate is [along the wall, sill] in the frame of the wall: the adapter reads the offsets from it.
type FillProps = { width: number; height: number; at: readonly [number, number]; depth: number; axisX: Vec3; materialName: string; isExternal: boolean };
const fillBox = (p: FillProps): Element =>
el('Geometry', {
node: bar(p.axisX, p.width, p.depth, p.height),
transform: [tTranslate([p.at[0] * p.axisX[0], p.at[0] * p.axisX[1], p.at[1]])],
});
const Door = family<FillProps>('Door', fillBox, { role: 'fill' });
const Window = family<FillProps>('Window', fillBox, { role: 'fill' });
const Slab = family<{ length: number; width: number; thickness: number; at: Vec3; predefinedType: 'FLOOR' | 'LANDING' | 'BASESLAB'; materialName: string }>(
'Slab',
(p) => el('Box', { size: [p.length, p.width, p.thickness], transform: [tTranslate(p.at)] })
);
// A Storey has an elevation. Its elements are authored from its own floor level: the IFC storey
// placement lifts them, and placedSolids() gets the same lift as its parent frame.
const Storey = family<{ elevation: number; items: readonly Element[] }>('Storey', (p) => el('Group', {}, p.items));
const Building = family<{ storeys: readonly Element[] }>('Building', (p) => el('Group', {}, p.storeys));
function tree(flats: number, pitch: number, reversed: boolean) {
const length = flats * FLAT;
const order = <T,>(items: T[]): T[] => (reversed ? [...items].reverse() : items);
const out = 600; // the ground slab and the roof go past the walls
const top = STOREY - SLAB; // wall height
const posts = Array.from({ length: flats + 1 }, (_, i) =>
Column({ key: 'post-' + i, height: STOREY - GALLERY.slab, profile: POST, at: [Math.max(i * FLAT, GALLERY.post / 2), -GALLERY.depth + GALLERY.post / 2, 0], materialName: 'Concrete' })
);
return resolve(
Building({
key: 'block',
storeys: order([
Storey({
key: 'ground',
elevation: 0,
items: order([
Slab({ key: 'base', length: length + STAIR_WIDTH + 2 * out, width: DEPTH + GALLERY.depth + 2 * out, thickness: SLAB, at: [-out, -GALLERY.depth - out, -SLAB], predefinedType: 'BASESLAB', materialName: 'Concrete' }),
Shell({ key: 'shell', flats, height: top, upper: false }),
...posts,
...access(length),
]),
}),
Storey({
key: 'first',
elevation: STOREY,
items: order([
Slab({ key: 'floor', length, width: DEPTH, thickness: SLAB, at: [0, 0, -SLAB], predefinedType: 'FLOOR', materialName: 'Concrete' }),
Slab({ key: 'gallery', length: length + STAIR_WIDTH, width: GALLERY.depth, thickness: GALLERY.slab, at: [0, -GALLERY.depth, -GALLERY.slab], predefinedType: 'FLOOR', materialName: 'Concrete' }),
Shell({ key: 'shell', flats, height: top, upper: true }),
...guards(length),
Roof({ key: 'roof', length: length + 2 * out, width: DEPTH + 2 * out, thickness: 200, at: [-out, -out, top], predefinedType: 'GABLE_ROOF', pitch, materialName: 'Slate' }),
]),
}),
]),
})
);
}
function block({ flats = 2, pitch = 25 }: BlockParams = {}) {
// Project the tree into a BimModel: storeys, walls, slabs, openings, psets and materials.
// Leaf and Pane have no IFC mapping: proxyEvaluator sends them out as IfcBuildingElementProxy.
const ev = new csg.Evaluator();
const options = {
project: { name: 'Families playground demo', projectId: 'families-playground-demo' },
siteName: 'Site',
buildingName: 'Block A',
proxyEvaluator: ev,
};
const projected = familiesToBim(tree(flats, pitch, false), options);
if (!projected.ok) throw projected.error;
const { model, idByKeyPath, proxied } = projected.value;
// GlobalIds come from the key paths, so they stay the same when the tree is in another order.
const again = familiesToBim(tree(flats, pitch, true), options);
if (!again.ok) throw again.error;
const same = [...idByKeyPath].filter(([path, id]) => {
const other = again.value.idByKeyPath.get(path);
return other !== undefined && again.value.model.getElement(other)?.guid === model.getElement(id)?.guid;
}).length;
again.value.model[Symbol.dispose]();
ev[Symbol.dispose]();
console.log(model.getWalls().length + ' walls, ' + model.getDoors().length + ' doors, ' + model.getWindows().length + ' windows, ' + model.getSlabs().length + ' slabs, ' + proxied.length + ' proxies');
console.log('GlobalIds: ' + same + ' of ' + idByKeyPath.size + ' are the same after the tree is reversed');
// placedSolids() puts each element where its IFC placement says. An IfcDoor and an IfcWindow have no
// body of their own: the wall has the real hole, and the proxy in the hole is the leaf or the pane.
const kind = new Map(proxied.map((p) => [p.keyPath, p.type]));
const groups = new Map<string, Shape[]>();
const temp: Shape[] = [];
for (const [path, id] of idByKeyPath) {
const element = model.getElement(id);
if (!element) continue;
const lift = path.startsWith('block/first') ? STOREY : 0;
const solids = unwrap(placedSolids(element, { parentFrame: { origin: [0, 0, lift], axisX: [1, 0, 0], axisZ: [0, 0, 1] } }));
temp.push(...solids);
const tone = kind.get(path) ?? element.category;
if (solids.length > 0) groups.set(tone, [...(groups.get(tone) ?? []), ...solids]);
}
const bodies = [...groups.entries()].map(([tone, shapes]) => color(compound(shapes), COLORS[tone] ?? '#f5f2ea'));
temp.forEach((s) => s.delete()); // compound() copied the solids
return { model, bodies };
}
const COLORS: Record<string, string> = {
WALL: '#f5f2ea',
SLAB: '#c3c9d1',
ROOF: '#5b6470',
STAIR: '#d8d4c8',
COLUMN: '#c3c9d1',
RAILING: '#48515c',
Leaf: '#12b5b0',
Pane: '#9fd3e6',
};
// ---- the rest of the families
// A wall with its holes, and a leaf or a pane in each hole. The leaf and the pane are siblings of the
// wall, not children of the fill, because the adapter maps a fill to one IfcDoor or IfcWindow.
type Hole = { door?: boolean; along: number; width: number; height: number; sill: number };
const Leaf = family<{ size: Vec3; at: Vec3; materialName: string }>('Leaf', (p) => el('Box', { size: p.size, transform: [tTranslate(p.at)] }));
const Pane = family<{ size: Vec3; at: Vec3; materialName: string }>('Pane', (p) => el('Box', { size: p.size, transform: [tTranslate(p.at)] }));
const Facade = family<{ length: number; height: number; at: Vec3; axisX: Vec3; holes: readonly Hole[] }>('Facade', (p) => {
const t = WALL.thickness;
const alongY = p.axisX[1] !== 0;
const fills = p.holes.map((h, i) =>
(h.door ? Door : Window)({
key: (h.door ? 'door-' : 'window-') + i,
width: h.width,
height: h.height,
at: [h.along, h.sill],
depth: t,
axisX: p.axisX,
materialName: h.door ? 'Timber' : 'Aluminium + Glazing',
isExternal: true,
})
);
const infill = p.holes.map((h, i) => {
const d = h.door ? 44 : 24;
const inset = (t - d) / 2;
const size: Vec3 = alongY ? [d, h.width, h.height] : [h.width, d, h.height];
const at: Vec3 = alongY ? [p.at[0] - t + inset, p.at[1] + h.along, p.at[2] + h.sill] : [p.at[0] + h.along, p.at[1] + inset, p.at[2] + h.sill];
return h.door ? Leaf({ key: 'leaf-' + i, size, at, materialName: 'Timber' }) : Pane({ key: 'pane-' + i, size, at, materialName: 'Glass' });
});
const wall = Wall({ key: 'wall', length: p.length, height: p.height, thickness: t, at: p.at, axisX: p.axisX, voids: fills, materialName: 'Masonry', isExternal: true, loadBearing: true });
return el('Group', {}, [wall, ...infill]);
});
// The four facades of one storey and the party walls between the flats.
const Shell = family<{ flats: number; height: number; upper: boolean }>('Shell', (p) => {
const t = WALL.thickness;
const length = p.flats * FLAT;
const window = (along: number, width: number): Hole => ({ along, width, height: 1200, sill: 900 });
const each = (holes: (x: number) => Hole[]): Hole[] => Array.from({ length: p.flats }, (_, i) => holes(i * FLAT)).flat();
const south = each((x) => [{ door: true, along: x + 700, width: 910, height: 2100, sill: 0 }, window(x + 2300, 1200), window(x + 4100, 1200)]);
const north = each((x) => [window(x + 900, 1500), window(x + 3600, 1500)]);
const end = DEPTH - 2 * t;
const party = Array.from({ length: p.flats - 1 }, (_, i) =>
Wall({ key: 'party-' + i, length: end, height: p.height, thickness: WALL.party, at: [(i + 1) * FLAT + WALL.party / 2, t, 0], axisX: Y, materialName: 'Masonry', loadBearing: true })
);
return el('Group', {}, [
Facade({ key: 'south', length, height: p.height, at: [0, 0, 0], axisX: X, holes: south }),
Facade({ key: 'north', length, height: p.height, at: [0, DEPTH - t, 0], axisX: X, holes: north }),
// The stair runs along the east wall, so only the upper storey has a window there.
Facade({ key: 'east', length: end, height: p.height, at: [length, t, 0], axisX: Y, holes: p.upper ? [window(3900, 1500)] : [] }),
Facade({ key: 'west', length: end, height: p.height, at: [t, t, 0], axisX: Y, holes: [window(2450, 1500)] }),
...party,
]);
});
type Profile = { kind: 'RECTANGULAR'; width: number; height: number };
const POST: Profile = { kind: 'RECTANGULAR', width: GALLERY.post, height: GALLERY.post };
const Column = family<{ height: number; profile: Profile; at: Vec3; materialName: string }>('Column', (p) => {
const w = p.profile.width / 2;
const d = p.profile.height / 2;
// The section is centred on the placement point, the same as the IFC column.
return el('Geometry', { node: csg.extrude(csg.polygon([[-w, -d, 0], [w, -d, 0], [w, d, 0], [-w, d, 0]]), [0, 0, p.height]), transform: [tTranslate(p.at)] });
});
const Roof = family<{ length: number; width: number; thickness: number; at: Vec3; predefinedType: 'GABLE_ROOF'; pitch: number; materialName: string }>('Roof', (p) => {
const ridge = (p.width / 2) * Math.tan((p.pitch * Math.PI) / 180);
const section = csg.polygon([[0, 0, 0], [0, p.width, 0], [0, p.width, p.thickness], [0, p.width / 2, p.thickness + ridge], [0, 0, p.thickness]]);
return el('Geometry', { node: csg.extrude(section, [p.length, 0, 0]), transform: [tTranslate(p.at)] });
});
const Railing = family<{ length: number; height: number; thickness: number; at: Vec3; axisX: Vec3; infill: 'POSTED'; predefinedType: 'GUARDRAIL'; materialName: string }>(
'Railing',
(p) => el('Geometry', { node: bar(p.axisX, p.length, p.thickness, p.height), transform: [tTranslate(p.at)] })
);
// One stepped solid for each flight. A flight has its own placement: its width goes along axisZ x axisX.
type Flight = { width: number; riserHeight: number; treadLength: number; numberOfRisers: number; origin: Vec3; axisX: Vec3; axisZ: Vec3; materialName: string };
const Stair = family<{ flights: readonly Flight[]; at: Vec3; predefinedType: 'TWO_STRAIGHT_RUN_STAIR'; materialName: string }>('Stair', (p) => {
const flight = (f: Flight): csg.IRNode => {
const pts: Array<[number, number, number]> = [[f.origin[0], f.origin[1], f.origin[2]]];
for (let i = 1; i <= f.numberOfRisers; i++) {
const z = f.origin[2] + i * f.riserHeight;
pts.push([f.origin[0] + (i - 1) * f.treadLength * f.axisX[0], f.origin[1] + (i - 1) * f.treadLength * f.axisX[1], z]);
pts.push([f.origin[0] + i * f.treadLength * f.axisX[0], f.origin[1] + i * f.treadLength * f.axisX[1], z]);
}
const run = f.numberOfRisers * f.treadLength;
pts.push([f.origin[0] + run * f.axisX[0], f.origin[1] + run * f.axisX[1], f.origin[2]]);
return csg.extrude(csg.polygon(pts), [-f.axisX[1] * f.width, f.axisX[0] * f.width, 0]);
};
return el('Geometry', { node: csg.compound(p.flights.map(flight)), transform: [tTranslate(p.at)] });
});
// The way up: two flights along the east wall, with a landing on a post between them.
function access(length: number): Element[] {
const [first, second] = [STAIR.flights[0]!, STAIR.flights[1]!];
const half = first * STAIR.rise;
const y2 = second * STAIR.going; // the upper flight ends at the gallery, at y = 0
const y1 = y2 + STAIR.landing;
const flight = { width: STAIR_WIDTH, riserHeight: STAIR.rise, treadLength: STAIR.going, axisX: [0, -1, 0] as Vec3, axisZ: [0, 0, 1] as Vec3, materialName: 'Concrete' };
return [
Stair({
key: 'stair',
at: [0, 0, 0],
predefinedType: 'TWO_STRAIGHT_RUN_STAIR',
materialName: 'Concrete',
flights: [
{ ...flight, numberOfRisers: first, origin: [length, y1 + first * STAIR.going, 0] },
{ ...flight, numberOfRisers: second, origin: [length, y2, half] },
],
}),
Slab({ key: 'landing', length: STAIR_WIDTH, width: STAIR.landing, thickness: 200, at: [length, y2, half - 200], predefinedType: 'LANDING', materialName: 'Concrete' }),
Column({ key: 'landing-post', height: half - 200, profile: POST, at: [length + STAIR_WIDTH - GALLERY.post / 2, y2 + STAIR.landing / 2, 0], materialName: 'Concrete' }),
Railing({ key: 'landing-guard', length: STAIR.landing, ...GUARD, at: [length + STAIR_WIDTH, y2, half], axisX: Y, infill: 'POSTED', predefinedType: 'GUARDRAIL', materialName: 'Steel' }),
];
}
// Guard rails on the open edges of the gallery.
function guards(length: number): Element[] {
const rail = { ...GUARD, infill: 'POSTED' as const, predefinedType: 'GUARDRAIL' as const, materialName: 'Steel' };
const side = GALLERY.depth - GUARD.thickness;
return [
Railing({ key: 'guard-south', ...rail, length: length + STAIR_WIDTH, at: [0, -GALLERY.depth, 0], axisX: X }),
Railing({ key: 'guard-east', ...rail, length: side, at: [length + STAIR_WIDTH, -side, 0], axisX: Y }),
Railing({ key: 'guard-west', ...rail, length: side, at: [GUARD.thickness, -side, 0], axisX: Y }),
];
}
const built = block();
// The ifc thunk runs only when you click the IFC download button.
export default present(built.bodies, {
bimTree: built.model.toTreeSummary(),
ifc: async () => {
const result = await toIfc(built.model, { applicationName: 'brepjs playground', applicationVersion: '1.0' });
if (!result.ok) throw result.error;
return result.value;
},
});Functions used
compound csg unwrap color present family el resolve tTranslate familiesToBim placedSolids toIfc