@adatechnology/game-floorplan-structure 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/MIGRATION.md +94 -0
- package/README.md +14 -2
- package/dist/index.d.ts +480 -0
- package/dist/index.global.js +3690 -0
- package/dist/index.global.js.map +1 -0
- package/dist/index.js +2658 -0
- package/dist/index.js.map +1 -0
- package/package.json +62 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/registry.ts","../src/geometry.ts","../src/presets.ts","../src/construction.ts","../src/locales/en.json","../src/locales/pt-BR.json","../src/types.ts","../src/density.ts","../src/structure/builder.ts","../src/structure/legacy-key.ts","../src/structure/context.ts","../src/structure/balconies.ts","../src/structure/canvas.ts","../src/structure/extras.ts","../src/structure/floor-deck.ts","../src/structure/foundation.ts","../src/structure/plates.ts","../src/structure/porch.ts","../src/structure/porch-roof.ts","../src/structure/roof.ts","../src/structure/stairs.ts","../src/structure/openings.ts","../src/structure/steps.ts","../src/structure/tank-parts.ts","../src/structure/upper-floor.ts","../src/structure/walls.ts","../src/structure/index.ts","../src/utilities/content-tables.ts","../src/utilities/content.ts","../src/utilities/shared.ts","../src/utilities/wall-points.ts","../src/utilities/electrical-outlets.ts","../src/utilities/electrical-entrance.ts","../src/utilities/electrical-circuits.ts","../src/utilities/electrical.ts","../src/utilities/gas.ts","../src/utilities/plumbing.ts","../src/utilities/solar.ts","../src/utilities/index.ts","../src/utilities/outbuildings.ts","../src/water-tank.ts","../src/viewer-layer.ts","../src/register.ts","../../game-destruction/src/chain.ts","../../game-destruction/src/math.ts","../../game-destruction/src/fracture.ts","../../game-destruction/src/breach.ts","../../game-destruction/src/layers.ts","../../game-destruction/src/rebar.ts","../../game-destruction/src/data/materials.json","../../game-destruction/src/data/material-hints.json","../../game-destruction/src/materials.ts","../../game-destruction/src/world.ts","../../game-destruction/src/data/assemblies.json","../../game-destruction/src/assemblies.ts","../../game-destruction/src/frame.ts","../../game-destruction/src/size.ts","../../game-destruction/src/locale.ts","../../game-destruction/src/contracts.ts","../src/loads.ts","../src/wall-detail/apply.ts","../src/wall-detail/courses.ts","../src/wall-detail/panels.ts","../src/wall-detail/index.ts","../src/to-destructible-spec.ts","../src/wall-specimen.ts"],"sourcesContent":["export const version = '0.1.0'\n\nexport { register } from './register'\nexport type { StructurePackOptions } from './register'\nexport { buildStructure } from './structure'\nexport { toDestructibleSpec } from './to-destructible-spec'\nexport type { DestructibleSpecOptions } from './to-destructible-spec'\nexport { buildWallSpecimen } from './wall-specimen'\nexport type { WallSpecimenOptions } from './wall-specimen'\nexport { planWaterTank } from './water-tank'\nexport type { TankPlanOptions } from './water-tank'\nexport {\n CONSTRUCTION_SYSTEMS, CONSTRUCTIONS, ROOF_COVERINGS, registerConstruction, registerConstructionSystem, registerRoofCovering,\n} from './registry'\nexport type { ConstructionBuild, ConstructionBuilder, ConstructionSystemDef, RoofCoveringDef } from './registry'\nexport { campConstruction, chaletConstruction, constructionOfSystem, logCabinConstruction, masonryConstruction, shackConstruction, woodFrameConstruction } from './presets'\nexport type { ChaletOptions, ShackOptions, WoodFrameOptions } from './presets'\nexport { structureLayer } from './viewer-layer'\nexport { DENSITY } from './density'\nexport { GROUND } from './types'\nexport type * from './types'\n","import type { JointKind } from '@adatechnology/game-contracts'\n\nimport type { Construction, ConstructionSystem, PlanContext, StructureExtras } from './types'\n\n/** What a wall system is made of and how its parts are tied. Timber systems sit on joists, carry the roof on timber plates and have wooden porch posts. */\nexport interface ConstructionSystemDef {\n /** Wall assembly of `game-destruction` (`registerAssembly`) the detailed wall is built from. Empty: no walls (a tent). */\n walls: string\n joints: Record<'wall' | 'slab' | 'beam' | 'column' | 'truss', JointKind>\n /** Thickness of the structural floor under each storey (m). */\n slabThickness: number\n /** Height of the top plate or bond beam (m). */\n plateThickness: number\n timber: boolean\n /** `rules`: bearing when external, under another wall or beside a porch; `bearing`: every wall (logs); `partition`: none (posts carry the roof). */\n wallRole: 'rules' | 'bearing' | 'partition'\n /** Solid fraction of a bearing wall in the structure weight (studs and air). */\n wallFill: number\n studs?: { spacing: number; section: string }\n}\n\nconst uniform = (joint: JointKind): ConstructionSystemDef['joints'] => ({ wall: joint, slab: joint, beam: joint, column: joint, truss: joint })\n\nexport const CONSTRUCTION_SYSTEMS = new Map<string, ConstructionSystemDef>([\n ['masonry', { walls: 'brick_wall_plastered', joints: { wall: 'mortar', slab: 'rebar', beam: 'mortar', column: 'rebar', truss: 'bolt' }, slabThickness: 0.12, plateThickness: 0.2, timber: false, wallRole: 'rules', wallFill: 1 }],\n ['wood_frame', { walls: 'wood_frame_wall', joints: uniform('nail'), slabThickness: 0.28, plateThickness: 0.1, timber: true, wallRole: 'rules', wallFill: 0.35, studs: { spacing: 0.4, section: '38x89' } }],\n ['log', { walls: 'log_wall', joints: { wall: 'bolt', slab: 'nail', beam: 'bolt', column: 'bolt', truss: 'bolt' }, slabThickness: 0.2, plateThickness: 0.1, timber: true, wallRole: 'bearing', wallFill: 1 }],\n ['improvised', { walls: 'sheet_metal_shack', joints: uniform('nail'), slabThickness: 0.2, plateThickness: 0.1, timber: true, wallRole: 'partition', wallFill: 1 }],\n ['canvas', { walls: '', joints: uniform('tie'), slabThickness: 0, plateThickness: 0, timber: false, wallRole: 'partition', wallFill: 1 }],\n])\n\n/** Adds or replaces a construction system (`id` is a `ConstructionSystem` or any name a construction refers to). */\nexport function registerConstructionSystem(id: ConstructionSystem | string, def: ConstructionSystemDef): void {\n CONSTRUCTION_SYSTEMS.set(id, def)\n}\n\nexport interface RoofCoveringDef {\n material: string\n /** How the covering is fixed to the trusses. */\n joint: JointKind\n}\n\nexport const ROOF_COVERINGS = new Map<string, RoofCoveringDef>([\n ['colonial', { material: 'ceramic', joint: 'resting' }],\n ['fiber_cement', { material: 'concrete', joint: 'bolt' }],\n ['slab', { material: 'concrete', joint: 'rebar' }],\n ['asphalt', { material: 'plastic', joint: 'nail' }],\n ['zinc', { material: 'steel', joint: 'nail' }],\n ['wood', { material: 'wood_soft', joint: 'nail' }],\n ['canvas', { material: 'fabric', joint: 'tie' }],\n ['thatch', { material: 'foliage', joint: 'tie' }],\n])\n\nexport function registerRoofCovering(id: string, def: RoofCoveringDef): void {\n ROOF_COVERINGS.set(id, def)\n}\n\nexport interface ConstructionBuild {\n construction: Construction\n extras?: StructureExtras\n}\nexport type ConstructionBuilder = (context: PlanContext) => ConstructionBuild\n\nexport const CONSTRUCTIONS = new Map<string, ConstructionBuilder>()\n\n/** Registers how a template's building is made: `TemplateDef.construction` names it. A template without one gets the masonry default. */\nexport function registerConstruction(id: string, builder: ConstructionBuilder): void {\n CONSTRUCTIONS.set(id, builder)\n}\n","import type { Rect, SourceWall } from './types'\n\nexport const WALL_THICKNESS = 0.15\n\nexport const round2 = (value: number): number => Math.round(value * 100) / 100\n\nexport function touches(a: Rect, b: Rect, tolerance: number): boolean {\n return a[0] < b[2] + tolerance && a[2] > b[0] - tolerance && a[1] < b[3] + tolerance && a[3] > b[1] - tolerance\n}\n\nexport function distanceBetween(a: Rect, b: Rect): number {\n return Math.hypot(Math.max(a[0] - b[2], b[0] - a[2], 0), Math.max(a[1] - b[3], b[1] - a[3], 0))\n}\n\nexport function unionOf(rects: readonly Rect[]): Rect {\n const out: Rect = [1e9, 1e9, -1e9, -1e9]\n for (const rect of rects) {\n out[0] = Math.min(out[0], rect[0])\n out[1] = Math.min(out[1], rect[1])\n out[2] = Math.max(out[2], rect[2])\n out[3] = Math.max(out[3], rect[3])\n }\n return out\n}\n\n/** The wall's centre line thickened to its box in the plan. */\nexport function wallBox(wall: Pick<SourceWall, 'u0' | 'v0' | 'u1' | 'v1' | 'thickness'>): Rect {\n const half = (wall.thickness ?? WALL_THICKNESS) / 2\n return [Math.min(wall.u0, wall.u1) - half, Math.min(wall.v0, wall.v1) - half, Math.max(wall.u0, wall.u1) + half, Math.max(wall.v0, wall.v1) + half]\n}\n\nexport const centreOf = (rect: Rect): [number, number] => [(rect[0] + rect[2]) / 2, (rect[1] + rect[3]) / 2]\n\n/** The nearest `count` of `candidates` to `target`, nearest first. */\nexport function nearestTo<T extends { aabb: Rect }>(target: Rect, candidates: readonly T[], count: number): T[] {\n return candidates.slice().sort((a, b) => distanceBetween(target, a.aabb) - distanceBetween(target, b.aabb)).slice(0, count)\n}\n","import type { Construction, FoundationType, StructureSource } from './types'\nimport { WALL_THICKNESS } from './geometry'\nimport { ROOF_COVERINGS } from './registry'\n\nconst SLAB_COVERING = 'slab'\nconst PLASTERED_FINISHES = ['plaster', 'partial_plaster']\n\n/** Masonry house of the engine's own templates: brick with plaster, concrete frame, tiles by facade; a unit in a building gets a flat slab roof. */\nexport function masonryConstruction(source: StructureSource): Construction {\n const unit = source.floorNumber !== undefined\n const covering = unit ? SLAB_COVERING : (source.facade.roof ?? 'colonial')\n const finish = source.facade.finish ?? 'roughcast'\n const budget = source.style === 'budget'\n const flat = unit || covering === SLAB_COVERING\n return {\n system: 'masonry',\n walls: { material: 'brick', cladding: PLASTERED_FINISHES.includes(finish) ? 'plaster' : null, finish, thickness: WALL_THICKNESS, ...(finish === 'exposed_block' ? { assembly: 'concrete_block_wall' } : {}) },\n floor: { material: budget ? 'concrete' : 'ceramic', finish: budget ? 'burnt_cement' : 'ceramic_tile' },\n roof: { material: ROOF_COVERINGS.get(covering)?.material ?? 'ceramic', covering, shape: flat ? 'slab' : 'gable', pitch: flat ? 0 : covering === 'colonial' ? 30 : 15, timber: 'wood_soft' },\n frame: { material: 'concrete', pillars: 'concrete', beams: 'concrete', slabs: 'concrete', timber: 'wood_soft', rebar: 'steel' },\n foundation: { type: unit ? 'building' : 'strip_footing', material: 'concrete', elevation: 0 },\n }\n}\n\nexport interface WoodFrameOptions {\n foundation?: 'basement' | 'crawl_space' | 'raft'\n covering?: string\n finish?: string\n /** Cladding of the outer face (default soft wood). */\n cladding?: string\n}\n\nconst FOUNDATIONS: Record<NonNullable<WoodFrameOptions['foundation']>, Construction['foundation']> = {\n basement: { type: 'basement', material: 'concrete', elevation: 0.5, depth: 2.4 },\n crawl_space: { type: 'crawl_space', material: 'concrete', elevation: 0.6 },\n raft: { type: 'raft', material: 'concrete', elevation: 0.2 },\n}\n\nconst TIMBER_FRAME: Construction['frame'] = { material: 'wood_soft', pillars: 'wood_soft', beams: 'wood_soft', slabs: 'plywood', timber: 'wood_soft', rebar: null }\n\n/** American wood frame house: 38x89 studs every 40 cm, plaster inside, wood outside, asphalt shingles. */\nexport function woodFrameConstruction(options: WoodFrameOptions = {}): Construction {\n const covering = options.covering ?? 'asphalt'\n return {\n system: 'wood_frame',\n walls: { material: 'wood_soft', interior: 'plaster', cladding: options.cladding ?? 'wood_soft', finish: options.finish ?? 'wood_siding', thickness: WALL_THICKNESS, studs: '38x89 every 40 cm', insulation: 'foam' },\n floor: { material: 'wood_hard', finish: 'wood_boards' },\n roof: { material: ROOF_COVERINGS.get(covering)?.material ?? 'plastic', covering, shape: 'gable', pitch: 28, timber: 'wood_soft', eave: 0.5 },\n frame: { ...TIMBER_FRAME },\n foundation: { ...FOUNDATIONS[options.foundation ?? 'raft'] },\n }\n}\n\nexport interface ChaletOptions {\n covering?: string\n finish?: string\n piles?: boolean\n}\n\n/** Mountain chalet: A-frame roof at 52 degrees with gables front and back, 38x140 studs. */\nexport function chaletConstruction(options: ChaletOptions = {}): Construction {\n const covering = options.covering ?? 'colonial'\n return {\n system: 'wood_frame',\n walls: { material: 'wood_soft', interior: 'wood_soft', cladding: 'wood_hard', finish: options.finish ?? 'vertical_boards', thickness: WALL_THICKNESS, studs: '38x140 every 40 cm' },\n floor: { material: 'wood_hard', finish: 'wood_boards' },\n roof: { material: ROOF_COVERINGS.get(covering)?.material ?? 'wood_soft', covering, shape: 'gable', pitch: 52, timber: 'wood_soft', eave: 0.8, axis: 'v', profile: 'a_frame', gables: ['front', 'back'] },\n frame: { ...TIMBER_FRAME },\n foundation: options.piles ? { type: 'piles', material: 'stone', elevation: 0.9 } : { type: 'raft', material: 'concrete', elevation: 0.2 },\n }\n}\n\n/** Log cabin: every wall is a stack of 26 cm logs, notched at the corners, on stone piles. */\nexport function logCabinConstruction(options: { covering?: string } = {}): Construction {\n const covering = options.covering ?? 'wood'\n return {\n system: 'log',\n walls: { material: 'wood_hard', interior: 'wood_hard', cladding: null, finish: 'log', thickness: WALL_THICKNESS, logDiameter: 0.26, joint: 'notched_corners' },\n floor: { material: 'wood_hard', finish: 'wood_boards' },\n roof: { material: ROOF_COVERINGS.get(covering)?.material ?? 'wood_soft', covering, shape: 'gable', pitch: 32, timber: 'wood_hard', eave: 0.6 },\n frame: { material: 'wood_hard', pillars: 'wood_hard', beams: 'wood_hard', slabs: 'wood_hard', timber: 'wood_hard', rebar: null },\n foundation: { type: 'piles', material: 'stone', elevation: 0.5 },\n }\n}\n\nexport interface ShackOptions {\n material?: 'wood' | 'zinc' | 'mixed'\n floor?: 'soil' | 'concrete'\n}\n\nconst MIXED_SCRAP = ['wood_soft', 'steel', 'plywood', 'steel', 'wood_soft']\n\n/** Shack of scrap boards and zinc sheets: timber posts carry the roof, the walls only close. */\nexport function shackConstruction(options: ShackOptions = {}): Construction {\n const material = options.material === 'zinc' ? 'steel' : 'wood_soft'\n const onSoil = options.floor === 'soil'\n return {\n system: 'improvised',\n walls: { material, interior: options.material === 'zinc' ? 'plywood' : material, cladding: null, finish: 'scrap', thickness: WALL_THICKNESS, ...(options.material === 'mixed' ? { mixed: MIXED_SCRAP } : {}) },\n floor: onSoil ? { material: 'soil', finish: 'packed_earth' } : { material: 'concrete', finish: 'burnt_cement' },\n roof: { material: 'steel', covering: 'zinc', shape: 'gable', pitch: 12, timber: 'wood_soft', eave: 0.3, fastening: 'nails_and_stones' },\n frame: { material: 'wood_soft', pillars: 'wood_soft', beams: 'wood_soft', slabs: 'concrete', timber: 'wood_soft', rebar: null },\n foundation: onSoil ? { type: 'ground', material: 'soil', elevation: 0 } : { type: 'raft', material: 'concrete', elevation: 0.08 },\n }\n}\n\n/** Camping: canvas over aluminium poles on the ground; there are no walls. */\nexport function campConstruction(): Construction {\n return {\n system: 'canvas',\n walls: { material: 'fabric', interior: 'fabric', cladding: null, finish: 'nylon', thickness: 0.002 },\n floor: { material: 'plastic', finish: 'waterproof_mat' },\n roof: { material: 'fabric', covering: 'canvas', shape: 'tent', pitch: 0, timber: 'aluminium', eave: 0 },\n frame: { material: 'aluminium', pillars: 'aluminium', beams: 'aluminium', slabs: 'plastic', timber: 'aluminium', rebar: null },\n foundation: { type: 'ground', material: 'soil', elevation: 0 },\n }\n}\n\n/** The construction a system gets on any plan when the options force it (`options.construction`). */\nexport function constructionOfSystem(system: string, source: StructureSource): Construction | undefined {\n const covering = source.facade.roof\n const keep = covering && covering !== SLAB_COVERING ? { covering } : {}\n switch (system) {\n case 'masonry':\n return masonryConstruction(source)\n case 'wood_frame':\n return woodFrameConstruction(keep)\n case 'log':\n return logCabinConstruction(keep)\n case 'improvised':\n return shackConstruction()\n case 'canvas':\n return campConstruction()\n default:\n return undefined\n }\n}\n\nexport type { FoundationType }\n","import { CONSTRUCTIONS } from './registry'\nimport type { ConstructionBuild } from './registry'\nimport { constructionOfSystem, masonryConstruction } from './presets'\nimport type { PlanContext, StructureSource, Tent } from './types'\n\n/** The construction of a plan: the one it already carries, else the masonry default of the engine's templates. */\nexport function resolveConstruction(source: StructureSource): ConstructionBuild {\n const extras = source.structureExtras ?? {}\n return { construction: source.construction ?? masonryConstruction(source), extras }\n}\n\nconst TENT_LABEL = /^tent_(dome|tunnel)(?:_|$)/\n\n/**\n * Tents of a plan whose template names the `canvas` construction and registers none of its own: one per room of type `tent`, standing on the room's footprint\n * (a label `tent_<kind>_<people>` names the kind, any other is a long tunnel) as high as the room's ceiling.\n */\nexport function tentsOf(source: StructureSource): Tent[] {\n const tents: Tent[] = []\n for (const room of source.rooms) {\n if (room.type !== 'tent' || room.floor !== 0 || !room.parts[0]) continue\n const { label } = room as { label?: unknown }\n tents.push({ id: room.id, kind: TENT_LABEL.exec(typeof label === 'string' ? label : '')?.[1] ?? 'tunnel', height: room.ceiling ?? source.floors[0]?.ceiling ?? 2.4, aabb: room.parts[0] })\n }\n return tents\n}\n\n/**\n * Picks the construction for a plan being generated: `options.construction` (a registered construction or a system name) wins over the template's\n * own (`TemplateDef.construction`), which wins over the masonry default.\n */\nexport function constructionFor(context: PlanContext): ConstructionBuild {\n const forced = context.options?.construction\n const named = typeof forced === 'string' ? forced : (context.template?.construction as string | undefined)\n if (named === undefined) return { construction: masonryConstruction(context.result) }\n const registered = CONSTRUCTIONS.get(named)\n if (registered) return registered(context)\n const preset = constructionOfSystem(named, context.result)\n if (preset) return { construction: preset, ...(named === 'canvas' ? { extras: { tents: tentsOf(context.result) } } : {}) }\n throw new Error(`Unknown construction \"${named}\": register it with registerConstruction`)\n}\n","{\n \"ui\": {\n \"structure_layer\": \"Structure\",\n \"structure_column_concrete\": \"Concrete pillar\",\n \"structure_column_steel\": \"Steel post\",\n \"structure_column_masonry\": \"Masonry pillar\",\n \"structure_column_wood\": \"Wood post\",\n \"structure_beam_concrete\": \"Bond beam / beam (concrete)\",\n \"structure_beam_wood\": \"Plate / beam (wood)\",\n \"structure_roof_frame\": \"Trusses, rafters and ridge (roof view)\"\n }\n}\n","{\n \"ui\": {\n \"structure_layer\": \"Estrutura\",\n \"structure_column_concrete\": \"Pilar de concreto\",\n \"structure_column_steel\": \"Poste de aço\",\n \"structure_column_masonry\": \"Pilar de alvenaria\",\n \"structure_column_wood\": \"Pilar de madeira\",\n \"structure_beam_concrete\": \"Cinta / viga (concreto)\",\n \"structure_beam_wood\": \"Prato / viga (madeira)\",\n \"structure_roof_frame\": \"Tesouras, caibros e cumeeira (vista do telhado)\"\n }\n}\n","import type { JointKind, MaterialId, StructureRole } from '@adatechnology/game-contracts'\n\n/** Axis-aligned rectangle `[u0, v0, u1, v1]` in the plan (metres). */\nexport type Rect = [number, number, number, number]\n\nexport type ConstructionSystem = 'masonry' | 'wood_frame' | 'log' | 'improvised' | 'canvas'\nexport type WallDetail = 'coarse' | 'panels' | 'units'\n/** What a structural part is called in a plan: a column is a pillar, `wall` is a bearing wall, `partition` a wall that only closes. */\nexport type PartRole = Exclude<StructureRole, 'foundation'>\n\nexport const GROUND = 'ground'\n\n/** A piece of the structure with its box in the plan, its height range and the mass it weighs. `y` is absolute: the ground floor sits at `foundation.elevation`. */\nexport interface StructurePart {\n id: string\n role: PartRole\n material: MaterialId\n aabb: Rect\n y0: number\n y1: number\n floor: number\n mass: number\n /** Part this one is cut out of (a pier of a wall in `panels` detail). */\n host?: string\n /** Wall assembly of `game-destruction` the part is built from in the destructible spec (layers, units, rebar, breach). */\n assembly?: string\n /** A brick, block or log: the unit of a wall (`units` detail, log courses), not a piece of it. */\n unit?: true\n /** Distance between repeated members (joists, ceiling joists). */\n spacing?: number\n /** `plate` (timber top plate) or `bond_beam` (masonry bond beam). */\n beamKind?: 'plate' | 'bond_beam'\n steps?: number\n door?: string\n /** Slab that is the roof (flat roof). */\n cover?: boolean\n /** Litres a tank holds. */\n liters?: number\n studs?: { spacing: number; section: string }\n pitch?: number\n tent?: string\n form?: string\n}\n\n/** `part` rests on `on` (`GROUND` or another part) through `joint`. `bears: false` ties the two without carrying load. */\nexport interface Support {\n part: string\n on: string\n joint: JointKind\n bears?: false\n}\n\nexport interface RoofPane {\n id: string\n aabb: Rect\n y0: number\n y1: number\n flat?: true\n}\n\nexport type RoofShape = 'gable' | 'slab' | 'tent'\n\nexport interface Roof {\n shape: RoofShape\n covering: string\n material: MaterialId\n pitch: number\n /** Floor the roof rests on. */\n bearingFloor: number\n panes: (RoofPane | string)[]\n trusses: number\n axis?: 'u' | 'v'\n ridge?: number\n eave?: number\n y0?: number\n aabb?: Rect\n}\n\n/** A window in a wall (the doors are gaps between walls: a lintel part bridges them). Heights are absolute. */\nexport interface Opening {\n id: string\n kind: 'window' | 'door'\n wall: string\n /** Along the wall (u for a wall along u, v for one along v). */\n from: number\n to: number\n y0: number\n y1: number\n}\n\nexport interface Structure {\n parts: StructurePart[]\n supports: Support[]\n openings: Opening[]\n /** Absolute height of the floor level of each storey. */\n levels: number[]\n elevation: number\n roof: Roof\n construction: Construction\n /** A reinforced concrete frame carries the building (apartments, commercial buildings, three storeys or more); the walls are infill. */\n framed: boolean\n}\n\nexport interface WallMaterials {\n material: MaterialId\n interior?: MaterialId\n cladding?: MaterialId | null\n finish?: string\n /** Wall assembly of `game-destruction` (default by system, and by finish in masonry). */\n assembly?: string\n thickness: number\n studs?: string\n /** Materials drawn per wall by a hash of its legacy key (the improvised shack). */\n mixed?: MaterialId[]\n [extra: string]: unknown\n}\n\nexport interface Construction {\n system: ConstructionSystem\n walls: WallMaterials\n floor: { material: MaterialId; finish: string }\n roof: {\n material: MaterialId\n covering: string\n shape: RoofShape\n pitch: number\n timber: MaterialId\n eave?: number\n axis?: 'u' | 'v'\n bearingFloor?: number\n profile?: string\n gables?: string[]\n fastening?: string\n }\n frame: { material: MaterialId; pillars: MaterialId; beams: MaterialId; slabs: MaterialId; timber: MaterialId; rebar: MaterialId | null }\n foundation: { type: FoundationType; material: MaterialId; elevation: number; depth?: number }\n guard?: MaterialId\n stairs?: MaterialId\n}\n\nexport type FoundationType = 'strip_footing' | 'building' | 'raft' | 'crawl_space' | 'piles' | 'basement' | 'ground'\n\nexport interface Chimney {\n kind: 'fireplace' | 'flue'\n material: MaterialId\n aabb: Rect\n flue?: boolean\n top?: number\n height?: number\n}\n\nexport interface Tent {\n id: string\n kind: string\n height: number\n aabb: Rect\n}\n\n/** What a construction needs besides walls and roof, from the template: a chimney, a well, an attic floor, tents. */\nexport interface StructureExtras {\n chimney?: Chimney\n well?: { aabb: Rect; height?: number }\n attic?: boolean\n tents?: Tent[]\n [extra: string]: unknown\n}\n\nexport interface TankPlatform {\n aabb: Rect\n baseY: number\n height: number\n thickness: number\n topY: number\n pillars: { u: number; v: number; side: number }[]\n ladder: boolean\n}\n\nexport interface WaterTank {\n id: 'water_tank'\n kind: 'water_tank'\n itemType: string\n place: 'slab' | 'attic' | 'raised_slab' | 'trestle' | string\n floor: number\n room: string\n u: number\n v: number\n y: number\n w: number\n d: number\n h: number\n capacity: number\n material?: MaterialId\n aabb: Rect\n platform?: TankPlatform\n /** Trestle tank (a stand of its own: rural water). */\n stand?: { pillars: { u: number; v: number; side: number }[]; material: MaterialId; height: number; baseJoint?: JointKind; joint?: JointKind; tie?: JointKind; braces?: boolean }\n}\n\n/** The fields of a generated plan the structure reads. */\nexport interface StructureSource {\n floors: { y0: number; ceiling: number }[]\n rooms: { id: string; type: string; floor: number; parts: Rect[]; ceiling?: number | null }[]\n walls: SourceWall[]\n doors: SourceDoor[]\n windows?: SourceWindow[]\n items: { id?: string; type: string; category?: string; floor: number; aabb?: Rect; link?: { from: number; to: number } | null }[]\n facade: { roof?: string; finish?: string; [extra: string]: unknown }\n style?: string\n template?: string\n lot?: unknown\n w: number\n d: number\n floorNumber?: number\n waterTank?: WaterTank | null\n construction?: Construction\n structureExtras?: StructureExtras\n [extra: string]: unknown\n}\n\nexport interface SourceWall {\n floor: number\n axis: 'u' | 'v'\n u0: number\n v0: number\n u1: number\n v1: number\n thickness?: number\n sides: string[]\n exterior: boolean\n type: string\n h?: number\n /** Gable wall: the plate does not sit on top of it. */\n gable?: boolean\n structureHeight?: number\n}\n\nexport interface SourceWindow {\n id: string\n floor: number\n axis: 'u' | 'v'\n /** Coordinate of the wall line across its axis. */\n pos: number\n /** Centre along the wall. */\n at: number\n width: number\n y0: number\n y1: number\n}\n\nexport interface SourceDoor {\n id: string\n floor: number\n a: string\n b: string\n exterior?: boolean\n model?: string\n type?: string\n u: number\n v: number\n width: number\n side?: string\n axis: 'u' | 'v'\n steps?: number\n}\n\nexport interface StructureOptions {\n construction?: Construction\n extras?: StructureExtras\n tank?: WaterTank | null\n /** The porch roof is carried by its posts alone (the tie to the house wall carries nothing). Default: when the detail is not `coarse`. */\n porchRoofOnPostsOnly?: boolean\n /** Gable roofs as rafters of each side and a ridge beam (a side falls with the wall it rests on) instead of whole trusses. Default: when the detail is not `coarse`. */\n rafterRoof?: boolean\n wallDetail?: WallDetail\n}\n\n/** What a construction builder and the tank get to see: the generated plan, its seed and the template. */\nexport interface PlanContext {\n result: StructureSource\n seed: number | string\n /** The template definition (`TemplateDef`) when known: it may carry `tank` and `tankLocation` hooks. */\n template?: Record<string, unknown>\n options?: { floors?: number; [extra: string]: unknown }\n}\n","import type { MaterialId } from '@adatechnology/game-contracts'\n\n/** kg/m3 the plan structure weighs its parts with (the table of the Visor de casas 3D; a material outside it weighs like soft wood). */\nexport const DENSITY: Readonly<Record<string, number>> = {\n steel: 7850, cast_iron: 7200, aluminium: 2700, copper: 8900, wood_soft: 500, wood_hard: 800, plywood: 600, mdf: 750, glass: 2500,\n tempered_glass: 2500, ceramic: 2000, concrete: 2400, brick: 1800, plaster: 1000, stone: 2600, plastic: 950, rubber: 1100, fabric: 400,\n foam: 30, leather: 900, paper: 800, foliage: 100, green_wood: 900, cactus: 700, flesh_fruit: 900, wax: 900, soil: 1600,\n}\nexport const DEFAULT_DENSITY = 500\n\nexport const densityOf = (material: MaterialId): number => DENSITY[material] ?? DEFAULT_DENSITY\n","import type { JointKind, MaterialId } from '@adatechnology/game-contracts'\n\nimport { densityOf } from '../density'\nimport { round2 } from '../geometry'\nimport { GROUND } from '../types'\nimport type { PartRole, Rect, StructurePart, Support } from '../types'\n\nexport type PartExtras = Partial<Pick<StructurePart, 'host' | 'spacing' | 'beamKind' | 'steps' | 'door' | 'cover' | 'studs' | 'pitch' | 'tent' | 'form' | 'liters' | 'assembly'>>\nexport interface PartOptions extends PartExtras {\n floor?: number\n /** Solid fraction of the box (studs, trusses, tile roofs). */\n fill?: number\n}\n\nexport interface PartDraft {\n id: string\n role: PartRole\n material: MaterialId\n aabb: Rect\n y0: number\n y1: number\n}\n\n/** Collects the parts and what each rests on. A part id is unique: a second one is a bug of the builder. */\nexport class StructureBuilder {\n readonly parts: StructurePart[] = []\n readonly supports: Support[] = []\n private readonly ids = new Set<string>()\n\n add(draft: PartDraft, options: PartOptions = {}): StructurePart {\n const { id, role, material, aabb, y0, y1 } = draft\n if (this.ids.has(id)) throw new Error(`Part repeated in the structure: ${id}`)\n this.ids.add(id)\n const { floor, fill, ...extras } = options\n const volume = Math.max(0, (aabb[2] - aabb[0]) * (aabb[3] - aabb[1]) * (y1 - y0)) * (fill ?? 1)\n const part: StructurePart = {\n id, role, material, aabb: aabb.map(round2) as Rect, y0: round2(y0), y1: round2(y1), floor: floor ?? 0,\n mass: Math.max(1, Math.round(volume * densityOf(material))),\n }\n for (const [key, value] of Object.entries(extras)) if (value !== undefined) (part as unknown as Record<string, unknown>)[key] = value\n this.parts.push(part)\n return part\n }\n\n rest(part: StructurePart | string, on: StructurePart | string, joint: JointKind): void {\n const id = typeof part === 'string' ? part : part.id\n const base = typeof on === 'string' ? on : on.id\n this.supports.push({ part: id, on: base === GROUND ? GROUND : base, joint })\n }\n\n has(id: string): boolean {\n return this.ids.has(id)\n }\n\n find(id: string): StructurePart | undefined {\n return this.parts.find((part) => part.id === id)\n }\n}\n","/** The string hash of the floor plan engine (`engine.hashString`), copied so that this package never imports the engine at run time. */\nexport function hashLegacyKey(key: string): number {\n let hash = 1779033703 ^ key.length\n for (let i = 0; i < key.length; i++) {\n hash = Math.imul(hash ^ key.charCodeAt(i), 3432918353)\n hash = (hash << 13) | (hash >>> 19)\n }\n hash = Math.imul(hash ^ (hash >>> 16), 2246822507)\n hash = Math.imul(hash ^ (hash >>> 13), 3266489909)\n return (hash ^ (hash >>> 16)) >>> 0\n}\n","import type { MaterialId } from '@adatechnology/game-contracts'\n\nimport { unionOf, wallBox, round2 } from '../geometry'\nimport { CONSTRUCTION_SYSTEMS } from '../registry'\nimport type { ConstructionSystemDef } from '../registry'\nimport { GROUND } from '../types'\nimport type { Construction, PartRole, Rect, Roof, StructureExtras, StructurePart, StructureSource, WaterTank, SourceWall } from '../types'\nimport { StructureBuilder } from './builder'\nimport { hashLegacyKey } from './legacy-key'\n\nexport const OPEN_ROOM_TYPES: readonly string[] = ['balcony', 'terrace', 'porch']\nconst GUARD_HEIGHT = 1.1\n\nexport interface BuildWall extends SourceWall {\n id: string\n /** The id the Visor de casas 3D gave the wall (`w<floor>_<index>`); seeded choices hash it so old seeds keep their draws. */\n legacyKey: string\n role: PartRole\n material: MaterialId\n box: Rect\n}\n\nexport interface PorchPosts {\n posts: StructurePart[]\n ceilingY: number\n}\n\ntype Base = StructurePart | typeof GROUND | undefined\n\n/** Everything the steps that build the structure share: the plan, the construction, the parts so far and what each storey rests on. */\nexport interface BuildContext {\n source: StructureSource\n construction: Construction\n system: ConstructionSystemDef\n extras: StructureExtras\n tank: WaterTank | null\n builder: StructureBuilder\n porchRoofOnPostsOnly: boolean\n /** Gable roofs are built as rafters of each side plus a ridge beam, so a side falls with the wall it rests on. */\n rafterRoof: boolean\n floorCount: number\n isUnit: boolean\n elevation: number\n isTimber: boolean\n walls: BuildWall[]\n wallParts: Map<string, StructurePart>\n carriers: Map<number, StructurePart[]>\n plates: Map<number, StructurePart[]>\n pillars: Map<number, StructurePart[]>\n porches: Map<string, PorchPosts>\n base0: Base\n houseBox: Rect\n topBox: Rect\n hasBasement: boolean\n topSlab?: StructurePart\n ceilingJoists?: StructurePart[]\n roof: Roof\n level(floor: number): number\n ceilingOf(floor: number): number\n topOf(floor: number): number\n rectsOf(floor: number, exclude?: readonly string[]): Rect[]\n baseOf(floor: number): Base\n}\n\nexport interface ContextOptions {\n porchRoofOnPostsOnly: boolean\n rafterRoof: boolean\n}\n\nexport function createContext(source: StructureSource, construction: Construction, extras: StructureExtras, tank: WaterTank | null, options: ContextOptions): BuildContext {\n const system = CONSTRUCTION_SYSTEMS.get(construction.system)\n if (!system) throw new Error(`Unknown construction system \"${construction.system}\"`)\n const floorCount = source.floors.length\n const isUnit = source.floorNumber !== undefined\n const elevation = construction.foundation.elevation || 0\n const level = (floor: number): number => round2(elevation + (source.floors[floor]?.y0 ?? 0))\n const ceilingOf = (floor: number): number => source.floors[floor]?.ceiling ?? 0\n const topOf = (floor: number): number => (floor < floorCount - 1 && !isUnit ? level(floor + 1) - system.slabThickness : level(floor) + ceilingOf(floor))\n const rectsOf = (floor: number, exclude: readonly string[] = []): Rect[] =>\n source.rooms.filter((room) => room.floor === floor && !exclude.includes(room.type)).flatMap((room) => room.parts)\n const builder = new StructureBuilder()\n const context: BuildContext = {\n source, construction, system, extras, tank, builder, porchRoofOnPostsOnly: options.porchRoofOnPostsOnly, rafterRoof: options.rafterRoof, floorCount, isUnit, elevation, isTimber: system.timber,\n walls: [], wallParts: new Map(), carriers: new Map(), plates: new Map(), pillars: new Map(), porches: new Map(), base0: GROUND,\n houseBox: [0, 0, 0, 0], topBox: [0, 0, 0, 0], hasBasement: false,\n roof: { shape: 'slab', covering: '', material: '', pitch: 0, bearingFloor: 0, panes: [], trusses: 0 },\n level, ceilingOf, topOf, rectsOf,\n baseOf: (floor) => (floor === 0 ? context.base0 : builder.find(`slab_${floor}`)),\n }\n const closed = rectsOf(0, ['balcony', 'porch'])\n context.houseBox = unionOf(closed.length ? closed : rectsOf(0))\n context.walls = classifyWalls(context)\n return context\n}\n\nconst isBearingOnTop = (wall: BuildWall, walls: readonly BuildWall[]): boolean => {\n const along = (w: SourceWall, pick: (a: number, b: number) => number): number => (w.axis === 'u' ? pick(w.u0, w.u1) : pick(w.v0, w.v1))\n const across = (w: SourceWall): number => (w.axis === 'u' ? w.v0 : w.u0)\n return walls.some(\n (other) =>\n other.floor === wall.floor + 1 && other.type === 'wall' && other.axis === wall.axis && Math.abs(across(other) - across(wall)) < 0.2 &&\n Math.min(along(wall, Math.max), along(other, Math.max)) - Math.max(along(wall, Math.min), along(other, Math.min)) > 0.3,\n )\n}\n\nfunction roleOf(context: BuildContext, wall: BuildWall, walls: readonly BuildWall[], porchIds: ReadonlySet<string>): PartRole {\n if (wall.type === 'railing') return 'partition'\n const { wallRole } = context.system\n if (wallRole === 'bearing') return 'wall'\n if (wallRole === 'partition') return 'partition'\n const bearingFloor = context.construction.roof.bearingFloor ?? context.floorCount - 1\n if (wall.floor > bearingFloor) return 'partition'\n if (wall.exterior || wall.sides.some((id) => porchIds.has(id))) return 'wall'\n return wall.floor < context.floorCount - 1 && isBearingOnTop(wall, walls) ? 'wall' : 'partition'\n}\n\nfunction materialOf(context: BuildContext, wall: BuildWall): MaterialId {\n const { walls, guard } = context.construction\n if (wall.type === 'railing') return guard ?? (context.isTimber ? 'wood_soft' : 'steel')\n if (walls.mixed?.length) return walls.mixed[hashLegacyKey(wall.legacyKey) % walls.mixed.length] as MaterialId\n return wall.exterior ? walls.material : (walls.interior ?? walls.material)\n}\n\nfunction classifyWalls(context: BuildContext): BuildWall[] {\n const countByFloor = new Map<number, number>()\n const all: BuildWall[] = context.source.walls.map((wall) => {\n const index = countByFloor.get(wall.floor) ?? 0\n countByFloor.set(wall.floor, index + 1)\n return { ...wall, id: `wall_${wall.floor}_${index}`, legacyKey: `w${wall.floor}_${index}`, role: 'wall', material: '', box: wallBox(wall) }\n })\n const built = all.filter((wall) => wall.type === 'wall' || wall.type === 'railing')\n const porchIds = new Set(context.source.rooms.filter((room) => room.type === 'porch').map((room) => room.id))\n for (const wall of built) {\n wall.role = roleOf(context, wall, built, porchIds)\n wall.material = materialOf(context, wall)\n }\n return built\n}\n\nexport const guardHeightOf = (wall: BuildWall): number => wall.h || GUARD_HEIGHT\n","import { GROUND } from '../types'\nimport { unionOf } from '../geometry'\nimport type { BuildContext } from './context'\n\n/** Cantilevered balconies: a slab tied to the floor of its storey, or on a pillar of its own when it is at ground level. */\nexport function addBalconies(context: BuildContext): void {\n const { builder, construction, system } = context\n for (const room of context.source.rooms.filter((r) => r.type === 'balcony' && r.floor >= 0)) {\n const floor = room.floor\n const box = unionOf(room.parts)\n const base = floor === 0 ? undefined : context.baseOf(floor)\n const deck = builder.add({ id: `slab_${floor}_${room.id}`, role: 'slab', material: construction.frame.slabs, aabb: box, y0: context.level(floor) - system.slabThickness, y1: context.level(floor) }, { floor })\n if (base) {\n builder.rest(deck, base, system.joints.slab)\n continue\n }\n const pillar = builder.add({ id: `balcony_column_${room.id}`, role: 'column', material: construction.frame.pillars, aabb: [box[0] - 0.08, box[1] - 0.08, box[0] + 0.08, box[1] + 0.08], y0: 0, y1: context.level(floor) - system.slabThickness }, { floor: 0 })\n builder.rest(pillar, GROUND, 'rebar')\n builder.rest(deck, pillar, 'rebar')\n }\n}\n","import { GROUND } from '../types'\nimport type { Construction, Rect, Roof, Structure, StructureExtras } from '../types'\nimport { StructureBuilder } from './builder'\n\nconst GROUNDSHEET = 0.02\n\n/** Camping tents: canvas over aluminium poles, a plastic groundsheet and pegs with guy ropes; no walls. */\nexport function buildCanvasStructure(construction: Construction, extras: StructureExtras): Structure {\n const builder = new StructureBuilder()\n const panes: string[] = []\n for (const tent of extras.tents ?? []) {\n const [u0, v0, u1, v1] = tent.aabb\n const centreU = (u0 + u1) / 2\n const centreV = (v0 + v1) / 2\n const sheet = builder.add({ id: `groundsheet_${tent.id}`, role: 'slab', material: 'plastic', aabb: tent.aabb, y0: 0, y1: GROUNDSHEET }, { floor: 0, tent: tent.id })\n builder.rest(sheet, GROUND, 'resting')\n const canvas = builder.add({ id: `canvas_${tent.id}`, role: 'roof', material: 'fabric', aabb: tent.aabb, y0: GROUNDSHEET, y1: tent.height }, { floor: 0, fill: 0.04, tent: tent.id, form: tent.kind })\n panes.push(canvas.id)\n const poles: [Rect, number][] =\n tent.kind === 'tunnel'\n ? [0.25, 0.75].map((fraction, k): [Rect, number] => [[u0 + (u1 - u0) * fraction - 0.015, v0 + 0.05, u0 + (u1 - u0) * fraction + 0.015, v1 - 0.05], k])\n : [[[u0 + 0.05, centreV - 0.015, u1 - 0.05, centreV + 0.015], 0], [[centreU - 0.015, v0 + 0.05, centreU + 0.015, v1 - 0.05], 1]]\n for (const [aabb, k] of poles) {\n const pole = builder.add({ id: `pole_${tent.id}_${k}`, role: 'column', material: construction.frame.pillars, aabb, y0: GROUNDSHEET, y1: tent.height - GROUNDSHEET }, { floor: 0, fill: 0.05, tent: tent.id })\n builder.rest(pole, GROUND, 'resting')\n builder.rest(canvas, pole, 'tie')\n }\n const corners: [number, number][] = [[u0 - 0.2, v0 - 0.2], [u1 + 0.2, v0 - 0.2], [u0 - 0.2, v1 + 0.2], [u1 + 0.2, v1 + 0.2]]\n corners.forEach(([u, v], k) => {\n const peg = builder.add({ id: `peg_${tent.id}_${k}`, role: 'column', material: 'wood_soft', aabb: [u - 0.02, v - 0.02, u + 0.02, v + 0.02], y0: 0, y1: 0.2 }, { floor: 0 })\n builder.rest(peg, GROUND, 'nail')\n builder.rest(canvas, peg, 'tie')\n })\n }\n const roof: Roof = { shape: 'tent', covering: 'canvas', material: 'fabric', pitch: 0, bearingFloor: 0, panes, trusses: 0 }\n return { parts: builder.parts, supports: builder.supports, levels: [0], elevation: 0, roof, construction, framed: false, openings: [] }\n}\n","import { GROUND } from '../types'\nimport { round2, touches } from '../geometry'\nimport type { BuildContext } from './context'\n\nconst CHIMNEY_CLEARANCE_ABOVE_RIDGE = 0.6\n\n/** A masonry chimney or a stove flue next to the house, tied to the wall it touches, rising above the ridge. */\nexport function addChimney(context: BuildContext): void {\n const chimney = context.extras.chimney\n if (!chimney) return\n const { builder } = context\n const top = context.floorCount - 1\n const ridge = context.roof.ridge || context.level(top) + context.ceilingOf(top)\n const height = Math.max(ridge, chimney.top || 0) + CHIMNEY_CLEARANCE_ABOVE_RIDGE\n const part = builder.add({ id: 'chimney', role: 'column', material: chimney.material || 'brick', aabb: chimney.aabb, y0: chimney.flue ? context.level(0) : 0, y1: height }, { floor: 0, fill: chimney.flue ? 0.15 : 0.7 })\n if (chimney.flue) builder.rest(part, context.base0 ?? GROUND, 'resting')\n else builder.rest(part, GROUND, 'mortar')\n const walls = builder.parts.filter((wall) => wall.role === 'wall' && wall.floor === 0 && !wall.id.startsWith('basement') && touches(wall.aabb, part.aabb, 0.1))\n for (const wall of walls) builder.rest(part, wall, 'bolt')\n chimney.height = round2(height)\n}\n\n/** The stone mouth of a well. */\nexport function addWell(context: BuildContext): void {\n const well = context.extras.well\n if (!well) return\n const part = context.builder.add({ id: 'well', role: 'column', material: 'stone', aabb: well.aabb, y0: -0.5, y1: well.height || 0.9 }, { floor: 0, fill: 0.5 })\n context.builder.rest(part, GROUND, 'mortar')\n}\n","import type { JointKind, MaterialId } from '@adatechnology/game-contracts'\n\nimport { distanceBetween, touches } from '../geometry'\nimport type { Rect, StructurePart } from '../types'\nimport type { BuildContext } from './context'\n\nexport interface JoistOptions {\n floor: number\n box: Rect\n thickness: number\n carriers: readonly StructurePart[]\n material: MaterialId\n joint: JointKind\n suffix?: string\n}\n\nconst JOIST_PITCH = 0.6\n\n/** Joists every 0.6 m under the floor of `floor`, each resting on what touches it from below (or the nearest carrier). */\nexport function addJoists(context: BuildContext, options: JoistOptions): StructurePart[] {\n const { floor, box, thickness, carriers, material, joint, suffix = '' } = options\n const length = box[2] - box[0]\n const depth = box[3] - box[1]\n const alongU = length >= depth\n const span = alongU ? length : depth\n const count = Math.max(2, Math.round(span / JOIST_PITCH) + 1)\n const top = context.level(floor) - thickness * 0.15\n const out: StructurePart[] = []\n for (let k = 0; k < count; k++) {\n const centre = (alongU ? box[0] : box[1]) + 0.05 + (k * (span - 0.1)) / (count - 1)\n const aabb: Rect = alongU ? [centre - 0.025, box[1], centre + 0.025, box[3]] : [box[0], centre - 0.025, box[2], centre + 0.025]\n const joist = context.builder.add({ id: `joist_${floor}${suffix}_${k}`, role: 'beam', material, aabb, y0: context.level(floor) - thickness, y1: top }, { floor, fill: 1, spacing: JOIST_PITCH })\n out.push(joist)\n const below = carriers.filter((carrier) => carrier.y0 <= top + 0.05)\n const touching = below.filter((carrier) => touches(aabb, carrier.aabb, 0.2))\n const pool = below.length ? below : carriers\n const chosen = touching.length ? touching : pool.slice().sort((a, b) => distanceBetween(aabb, a.aabb) - distanceBetween(aabb, b.aabb)).slice(0, 1)\n for (const carrier of chosen) context.builder.rest(joist, carrier, joint)\n }\n return out\n}\n\n/** The deck (floor boards, slab) of `floor` on its joists. */\nexport function addDeck(context: BuildContext, id: string, material: MaterialId, options: Pick<JoistOptions, 'floor' | 'box' | 'thickness' | 'joint'>, joists: readonly StructurePart[]): StructurePart {\n const { floor, box, thickness, joint } = options\n const deck = context.builder.add({ id, role: 'slab', material, aabb: box, y0: context.level(floor) - thickness * 0.15, y1: context.level(floor) }, { floor })\n for (const joist of joists) context.builder.rest(deck, joist, joint)\n return deck\n}\n","import type { StructurePart, Rect } from '../types'\nimport { GROUND } from '../types'\nimport type { BuildContext } from './context'\nimport { addDeck, addJoists } from './floor-deck'\n\nconst raft = (context: BuildContext, thickness: number, material: string): StructurePart => {\n const [u0, v0, u1, v1] = context.houseBox\n const part = context.builder.add({ id: 'foundation_raft', role: 'slab', material, aabb: [u0 - 0.1, v0 - 0.1, u1 + 0.1, v1 + 0.1], y0: 0, y1: thickness }, { floor: 0 })\n context.builder.rest(part, GROUND, 'resting')\n return part\n}\n\n/** A unit in a building: the building's pillars go down to the ground and carry a slab under the unit. */\nfunction addBuildingBase(context: BuildContext): void {\n const { builder, construction, houseBox: box } = context\n const corners: [number, number][] = [[box[0], box[1]], [box[2], box[1]], [box[0], box[3]], [box[2], box[3]]]\n const top = context.level(0) - context.system.slabThickness\n const pillars = corners.map(([u, v], k) => {\n const pillar = builder.add({ id: `building_column_${k}`, role: 'column', material: construction.frame.pillars, aabb: [u - 0.15, v - 0.15, u + 0.15, v + 0.15], y0: 0, y1: top }, { floor: 0 })\n builder.rest(pillar, GROUND, 'rebar')\n return pillar\n })\n const slab = builder.add({ id: 'slab_base', role: 'slab', material: construction.frame.slabs, aabb: box, y0: top, y1: context.level(0) }, { floor: 0 })\n for (const pillar of pillars) builder.rest(slab, pillar, 'rebar')\n context.base0 = slab\n}\n\nfunction addBasement(context: BuildContext): StructurePart[] {\n const { builder, houseBox: box, elevation } = context\n const depth = context.construction.foundation.depth || 2.4\n const floor = builder.add({ id: 'basement_slab', role: 'slab', material: 'concrete', aabb: box, y0: -depth - 0.15, y1: -depth }, { floor: -1 })\n builder.rest(floor, GROUND, 'resting')\n const sides: [string, Rect][] = [\n ['front', [box[0], box[1] - 0.1, box[2], box[1] + 0.1]], ['back', [box[0], box[3] - 0.1, box[2], box[3] + 0.1]],\n ['left', [box[0] - 0.1, box[1], box[0] + 0.1, box[3]]], ['right', [box[2] - 0.1, box[1], box[2] + 0.1, box[3]]],\n ]\n const carried: StructurePart[] = []\n for (const [name, aabb] of sides) {\n const wall = builder.add({ id: `basement_wall_${name}`, role: 'wall', material: 'concrete', aabb, y0: -depth, y1: elevation }, { floor: -1 })\n builder.rest(wall, GROUND, 'rebar')\n builder.rest(wall, floor, 'rebar')\n carried.push(wall)\n }\n const count = Math.max(1, Math.floor((box[2] - box[0]) / 3.0))\n for (let k = 0; k < count; k++) {\n const u = box[0] + ((k + 0.5) * (box[2] - box[0])) / count\n const v = (box[1] + box[3]) / 2\n const column = builder.add({ id: `basement_column_${k}`, role: 'column', material: 'concrete', aabb: [u - 0.15, v - 0.15, u + 0.15, v + 0.15], y0: -depth, y1: elevation - 0.3 }, { floor: -1 })\n builder.rest(column, floor, 'rebar')\n builder.rest(column, GROUND, 'rebar')\n carried.push(column)\n }\n context.hasBasement = true\n return carried\n}\n\n/** Pier footings every ~2 m with a base beam through each line of them (crawl space, piles). */\nfunction addPiers(context: BuildContext): StructurePart[] {\n const { builder, houseBox: box, elevation, construction } = context\n const columns = Math.max(2, Math.ceil((box[2] - box[0]) / 2.0) + 1)\n const rows = Math.max(2, Math.ceil((box[3] - box[1]) / 2.0) + 1)\n const height = Math.max(0.1, elevation - context.system.slabThickness - 0.15)\n const piers: StructurePart[] = []\n for (let j = 0; j < rows; j++) {\n for (let i = 0; i < columns; i++) {\n const u = box[0] + (i * (box[2] - box[0])) / (columns - 1)\n const v = box[1] + (j * (box[3] - box[1])) / (rows - 1)\n const pier = builder.add({ id: `footing_pier_${j}_${i}`, role: 'column', material: construction.foundation.material || 'concrete', aabb: [u - 0.12, v - 0.12, u + 0.12, v + 0.12], y0: 0, y1: height }, { floor: 0 })\n builder.rest(pier, GROUND, 'resting')\n piers.push(pier)\n }\n }\n const alongU = box[2] - box[0] >= box[3] - box[1]\n const beams: StructurePart[] = []\n const lines = alongU ? rows : columns\n for (let line = 0; line < lines; line++) {\n const at = alongU ? box[1] + (line * (box[3] - box[1])) / (rows - 1) : box[0] + (line * (box[2] - box[0])) / (columns - 1)\n const aabb: Rect = alongU ? [box[0], at - 0.07, box[2], at + 0.07] : [at - 0.07, box[1], at + 0.07, box[3]]\n const beam = builder.add({ id: `base_beam_${line}`, role: 'beam', material: construction.frame.timber, aabb, y0: height, y1: elevation - context.system.slabThickness }, { floor: 0 })\n const centre = (q: StructurePart): number => (alongU ? (q.aabb[1] + q.aabb[3]) / 2 : (q.aabb[0] + q.aabb[2]) / 2)\n for (const pier of piers.filter((q) => Math.abs(centre(q) - at) < 0.05)) builder.rest(beam, pier, 'bolt')\n beams.push(beam)\n }\n return beams\n}\n\nfunction addRaisedFloor(context: BuildContext): void {\n const { construction, system, houseBox: box } = context\n const carriers = construction.foundation.type === 'basement' ? addBasement(context) : addPiers(context)\n const thickness = system.slabThickness\n const joists = addJoists(context, { floor: 0, box, thickness, carriers, material: construction.frame.timber, joint: construction.foundation.type === 'basement' ? 'bolt' : 'nail' })\n const deckMaterial = context.isTimber ? (construction.floor.material === 'wood_hard' ? 'wood_hard' : 'plywood') : construction.frame.slabs\n context.base0 = addDeck(context, 'slab_0', deckMaterial, { floor: 0, box, thickness, joint: 'nail' }, joists)\n}\n\n/** Foundation and floor of the ground storey: raft, crawl space, piles, basement, a unit's building base or nothing (strip footing). */\nexport function addFoundation(context: BuildContext): void {\n const { type, material } = context.construction.foundation\n if (context.isUnit) return addBuildingBase(context)\n if (type === 'raft') context.base0 = raft(context, Math.max(0.1, context.elevation), material || 'concrete')\n else if (type === 'crawl_space' || type === 'piles' || type === 'basement') addRaisedFloor(context)\n else if (context.isTimber && type !== 'ground') context.base0 = raft(context, Math.max(0.12, context.elevation), 'concrete')\n}\n","import { GROUND } from '../types'\nimport type { Rect, StructurePart } from '../types'\nimport { round2, touches } from '../geometry'\nimport type { BuildContext, BuildWall } from './context'\n\nconst MAX_GAP_WITHIN_RUN = 3.2\nconst POST_SPACING = 2.4\nconst POST_SIDE = 0.05\n\ninterface Run {\n from: number\n to: number\n walls: BuildWall[]\n}\n\nconst alongOf = (wall: BuildWall, pick: (a: number, b: number) => number): number => (wall.axis === 'u' ? pick(wall.u0, wall.u1) : pick(wall.v0, wall.v1))\nconst acrossOf = (wall: BuildWall): number => (wall.axis === 'u' ? wall.v0 : wall.u0)\n\n/** Continuous runs of exterior wall on one line and height: a plate or bond beam runs along each. */\nfunction runsOf(context: BuildContext, walls: readonly BuildWall[], floor: number): Run[][] {\n const lines = new Map<string, BuildWall[]>()\n for (const wall of walls) {\n if (!wall.exterior || wall.type !== 'wall') continue\n const top = round2(context.wallParts.get(wall.id)!.y1)\n const key = `${floor}|${wall.axis}|${acrossOf(wall).toFixed(2)}|${top.toFixed(2)}`\n lines.set(key, [...(lines.get(key) ?? []), wall])\n }\n return [...lines.values()].map((line) => {\n const sorted = line.slice().sort((a, b) => alongOf(a, Math.min) - alongOf(b, Math.min))\n const runs: Run[] = []\n for (const wall of sorted) {\n const from = alongOf(wall, Math.min)\n const to = alongOf(wall, Math.max)\n const last = runs[runs.length - 1]\n if (last && from - last.to <= MAX_GAP_WITHIN_RUN) {\n last.to = Math.max(last.to, to)\n last.walls.push(wall)\n } else runs.push({ from, to, walls: [wall] })\n }\n return runs\n })\n}\n\n/** Timber posts of a shack: the corner and every ~2.4 m carry the plate; the sheet walls only close. */\nfunction addShackPosts(context: BuildContext, run: Run, plate: StructurePart, floor: number, index: number): StructurePart[] {\n const first = run.walls[0]!\n const across = acrossOf(first)\n const top = context.wallParts.get(first.id)!.y1\n const count = Math.max(1, Math.ceil((run.to - run.from) / POST_SPACING))\n const posts: StructurePart[] = []\n for (let k = 0; k <= count; k++) {\n const along = run.from + ((run.to - run.from) * k) / count\n const [u, v] = first.axis === 'u' ? [along, across] : [across, along]\n const half = 0.05 + POST_SIDE / 2\n const post = context.builder.add({ id: `post_${floor}_${index}_${k}`, role: 'column', material: 'wood_soft', aabb: [u - half, v - half, u + half, v + half], y0: context.level(floor), y1: top }, { floor })\n const base = context.baseOf(floor)\n if (base === GROUND || !base) context.builder.rest(post, GROUND, 'tie')\n else context.builder.rest(post, base, 'nail')\n context.builder.rest(plate, post, 'nail')\n posts.push(post)\n }\n return posts\n}\n\nexport interface PlatesResult {\n plates: StructurePart[]\n pillars: StructurePart[]\n}\n\nfunction addPlates(context: BuildContext, walls: readonly BuildWall[], floor: number): PlatesResult {\n const { builder, system, construction } = context\n const plates: StructurePart[] = []\n const pillars: StructurePart[] = []\n let counter = 0\n for (const runs of runsOf(context, walls, floor)) {\n for (const run of runs) {\n const first = run.walls[0]!\n const half = (first.thickness ?? 0.15) / 2\n const across = acrossOf(first)\n const top = context.wallParts.get(first.id)!.y1\n const aabb: Rect = first.axis === 'u' ? [run.from - half, across - half, run.to + half, across + half] : [across - half, run.from - half, across + half, run.to + half]\n const material = context.isTimber ? construction.frame.timber : construction.frame.beams\n const plate = builder.add({ id: `plate_${floor}_${counter++}`, role: 'beam', material, aabb, y0: top, y1: top + system.plateThickness }, { floor, beamKind: context.isTimber ? 'plate' : 'bond_beam' })\n if (construction.system === 'improvised') pillars.push(...addShackPosts(context, run, plate, floor, counter))\n else for (const wall of run.walls) builder.rest(plate, context.wallParts.get(wall.id)!, system.joints.beam)\n plates.push(plate)\n }\n }\n return { plates, pillars }\n}\n\nfunction cornerPoints(walls: readonly BuildWall[]): [number, number][] {\n const ends = walls\n .filter((wall) => wall.exterior && wall.type === 'wall')\n .flatMap((wall): [number, number, string][] =>\n wall.axis === 'u'\n ? [[Math.min(wall.u0, wall.u1), wall.v0, 'u'], [Math.max(wall.u0, wall.u1), wall.v0, 'u']]\n : [[wall.u0, Math.min(wall.v0, wall.v1), 'v'], [wall.u0, Math.max(wall.v0, wall.v1), 'v']],\n )\n const points: [number, number][] = []\n for (const a of ends) {\n const joinsOtherAxis = ends.some((b) => b[2] !== a[2] && Math.hypot(a[0] - b[0], a[1] - b[1]) < 0.12)\n if (joinsOtherAxis && !points.some((q) => Math.hypot(q[0] - a[0], q[1] - a[1]) < 0.12)) points.push([a[0], a[1]])\n }\n return points\n}\n\n/** Concrete corner pillars of a masonry storey where two exterior walls of different axes meet; they run up to the highest plate they touch. */\nfunction addCornerPillars(context: BuildContext, walls: readonly BuildWall[], floor: number, plates: readonly StructurePart[]): StructurePart[] {\n const { builder } = context\n const topOfFloor = context.topOf(floor)\n return cornerPoints(walls).map(([u, v], k) => {\n const box: Rect = [u - 0.1, v - 0.1, u + 0.1, v + 0.1]\n const top = Math.max(topOfFloor, ...plates.filter((plate) => touches(plate.aabb, box, 0.05)).map((plate) => plate.y0))\n const pillar = builder.add({ id: `column_${floor}_${k}`, role: 'column', material: context.construction.frame.pillars, aabb: box, y0: context.level(floor), y1: top }, { floor })\n const base = context.baseOf(floor)\n builder.rest(pillar, base === GROUND || !base ? GROUND : base, 'rebar')\n for (const plate of plates.filter((p) => touches(p.aabb, pillar.aabb, 0.05))) builder.rest(plate, pillar, 'rebar')\n return pillar\n })\n}\n\n/** Plates (bond beams) over the exterior walls of a storey and, in masonry, the corner pillars; records what carries the storey above. */\nexport function addPlatesAndPillars(context: BuildContext, floor: number): void {\n const walls = context.walls.filter((wall) => wall.floor === floor)\n const { plates, pillars } = addPlates(context, walls, floor)\n if (context.construction.system === 'masonry') pillars.push(...addCornerPillars(context, walls, floor, plates))\n context.pillars.set(floor, pillars)\n context.plates.set(floor, plates)\n const innerBearing = walls.filter((wall) => wall.role === 'wall' && !wall.exterior).map((wall) => context.wallParts.get(wall.id)!)\n context.carriers.set(floor, [...plates, ...pillars, ...innerBearing])\n}\n","import { GROUND } from '../types'\nimport type { Rect, StructurePart } from '../types'\nimport { touches } from '../geometry'\nimport type { BuildContext } from './context'\n\nconst POST_HALF = 0.08\nconst FOOTING_HALF = 0.12\nconst BEAM_DEPTH = 0.2\nconst BEAM_WIDTH = 0.16\n\n/** Footings and posts under the porch roof: two at the front corners and one more in the middle of a wide porch. */\nfunction addPosts(context: BuildContext, porchId: string, rect: Rect, deck: StructurePart, floor: number): StructurePart[] {\n const { builder, construction } = context\n const hasUpperFloor = floor < context.floorCount - 1\n const ceilingY = hasUpperFloor ? context.level(floor + 1) - context.system.slabThickness : context.level(floor) + context.ceilingOf(floor)\n const deckDepth = Math.min(0.2, Math.max(0.06, context.elevation * 0.5))\n const spots: [number, number][] = [[rect[0] + 0.1, rect[1] + 0.1], [rect[2] - 0.1, rect[1] + 0.1]]\n if (rect[2] - rect[0] > 4.5) spots.push([(rect[0] + rect[2]) / 2, rect[1] + 0.1])\n const posts = spots.map(([u, v], k) => {\n const footing = builder.add({ id: `porch_footing_${porchId}_${k}`, role: 'column', material: 'concrete', aabb: [u - FOOTING_HALF, v - FOOTING_HALF, u + FOOTING_HALF, v + FOOTING_HALF], y0: 0, y1: context.level(floor) - deckDepth }, { floor: 0 })\n builder.rest(footing, GROUND, 'resting')\n builder.rest(deck, footing, 'resting')\n const material = context.isTimber ? construction.frame.timber : construction.frame.pillars\n const post = builder.add({ id: `porch_post_${porchId}_${k}`, role: 'column', material, aabb: [u - POST_HALF, v - POST_HALF, u + POST_HALF, v + POST_HALF], y0: context.level(floor), y1: hasUpperFloor ? ceilingY - BEAM_DEPTH : ceilingY }, { floor })\n builder.rest(post, deck, context.isTimber ? 'nail' : 'rebar')\n return post\n })\n context.porches.set(porchId, { posts, ceilingY })\n return posts\n}\n\n/** With a storey above the porch, a head beam over the posts and two side beams carry the floor of that storey. */\nfunction addUpperBeams(context: BuildContext, porchId: string, rect: Rect, posts: StructurePart[], floor: number): void {\n const { builder, construction } = context\n const material = context.isTimber ? construction.frame.timber : construction.frame.beams\n const joint = context.isTimber ? 'nail' : 'rebar'\n const ceilingY = context.porches.get(porchId)!.ceilingY\n const y0 = ceilingY - BEAM_DEPTH\n const carriers = context.carriers.get(floor)!\n const head = builder.add({ id: `porch_beam_${porchId}`, role: 'beam', material, aabb: [rect[0], rect[1], rect[2], rect[1] + BEAM_WIDTH], y0, y1: ceilingY }, { floor })\n for (const post of posts) builder.rest(head, post, joint)\n carriers.push(head)\n const sides: [string, Rect, StructurePart][] = [['e', [rect[0], rect[1], rect[0] + BEAM_WIDTH, rect[3]], posts[0]!], ['d', [rect[2] - BEAM_WIDTH, rect[1], rect[2], rect[3]], posts[1]!]]\n for (const [name, aabb, post] of sides) {\n const side = builder.add({ id: `porch_beam_${porchId}_${name}`, role: 'beam', material, aabb, y0, y1: ceilingY }, { floor })\n builder.rest(side, post, joint)\n builder.rest(side, head, joint)\n for (const wall of context.walls.filter((w) => w.floor === floor && w.role === 'wall' && touches(w.box, side.aabb, 0.3))) builder.rest(side, context.wallParts.get(wall.id)!, joint)\n carriers.push(side)\n }\n}\n\n/** Deck, footings, posts (concrete in masonry, wood in timber houses) and, with a storey above, the beams of every porch of the storey. */\nexport function addPorches(context: BuildContext, floor: number): void {\n const { builder, construction } = context\n for (const room of context.source.rooms.filter((r) => r.type === 'porch' && r.floor === floor)) {\n const rect = room.parts[0]!\n const base = context.baseOf(floor)\n const deckDepth = Math.min(0.2, Math.max(0.06, context.elevation * 0.5))\n const deck = builder.add({ id: `porch_floor_${room.id}`, role: 'slab', material: context.isTimber ? 'wood_soft' : construction.frame.slabs, aabb: rect, y0: context.level(floor) - deckDepth, y1: context.level(floor) }, { floor })\n if (base && base !== GROUND) builder.rest(deck, base, context.isTimber ? 'nail' : context.system.joints.slab)\n const posts = addPosts(context, room.id, rect, deck, floor)\n if (floor < context.floorCount - 1) addUpperBeams(context, room.id, rect, posts, floor)\n }\n}\n","import { ROOF_COVERINGS } from '../registry'\nimport type { BuildContext } from './context'\n\nconst ROOF_RISE = 0.6\n\n/** A porch under the top storey has a roof of its own, resting on its posts and on the wall of the house. */\nexport function addPorchRoofs(context: BuildContext): void {\n const { builder, construction } = context\n for (const room of context.source.rooms.filter((r) => r.type === 'porch')) {\n const floor = room.floor\n const rect = room.parts[0]!\n const posts = context.porches.get(room.id)\n if (floor !== context.floorCount - 1 || !posts) continue\n const material = ROOF_COVERINGS.get(construction.roof.covering)?.material ?? 'ceramic'\n const roof = builder.add({ id: `porch_roof_${room.id}`, role: 'roof', material, aabb: [rect[0] - 0.3, rect[1] - 0.5, rect[2] + 0.3, rect[3]], y0: posts.ceilingY, y1: posts.ceilingY + ROOF_RISE }, { floor })\n for (const post of posts.posts) builder.rest(roof, post, context.isTimber ? 'nail' : 'bolt')\n const housewalls = context.walls.filter((w) => w.floor === floor && !w.exterior && w.sides.includes(room.id) && w.type === 'wall')\n for (const wall of housewalls) {\n if (context.porchRoofOnPostsOnly) builder.supports.push({ part: roof.id, on: wall.id, joint: 'nail', bears: false })\n else builder.rest(roof, context.wallParts.get(wall.id)!, 'nail')\n }\n }\n}\n","import type { JointKind } from '@adatechnology/game-contracts'\n\nimport { distanceBetween, round2, touches, unionOf } from '../geometry'\nimport { ROOF_COVERINGS } from '../registry'\nimport type { Rect, RoofPane, StructurePart } from '../types'\nimport type { BuildContext } from './context'\nimport { OPEN_ROOM_TYPES } from './context'\n\nconst TRUSS_PITCH = 1.2\nconst DEFAULT_PITCH = 20\nconst DEFAULT_EAVE = 0.4\nconst CLOSED_ONLY: readonly string[] = [...OPEN_ROOM_TYPES, 'void']\n\ninterface RoofUnit {\n suffix: string\n box: Rect\n floor: number\n annex: boolean\n}\n\n/** The main roof, plus an own roof for every room of a lower storey that the storey above does not cover (a ground floor wider than the upper one). */\nfunction roofUnits(context: BuildContext, bearing: number): RoofUnit[] {\n const units: RoofUnit[] = [{ suffix: '', box: context.topBox, floor: bearing, annex: false }]\n if (context.floorCount <= 1 || context.isUnit || bearing !== context.floorCount - 1) return units\n for (let floor = 0; floor < context.floorCount - 1; floor++) {\n const above = context.source.rooms.filter((room) => room.floor === floor + 1).flatMap((room) => room.parts)\n const rooms = context.source.rooms.filter((room) => room.floor === floor && !OPEN_ROOM_TYPES.includes(room.type) && room.type !== 'void' && room.type !== 'elevator')\n for (const room of rooms) {\n const area = room.parts.reduce((total, part) => total + (part[2] - part[0]) * (part[3] - part[1]), 0)\n const covered = room.parts.reduce((total, part) => total + above.reduce((sum, other) => sum + Math.max(0, Math.min(part[2], other[2]) - Math.max(part[0], other[0])) * Math.max(0, Math.min(part[3], other[3]) - Math.max(part[1], other[1])), 0), 0)\n if (covered < area * 0.7) units.push({ suffix: `_${room.id}`, box: unionOf(room.parts), floor, annex: true })\n }\n }\n return units\n}\n\n/** Everything that carries the roof of one unit: the plates at its height, the pillars and the inner bearing walls under it. */\nfunction roofCarriers(context: BuildContext, unit: RoofUnit): StructurePart[] {\n const platesHere = context.plates.get(unit.floor) ?? []\n const allPlates = [...context.plates.values()].flat()\n const eaveHeight = platesHere.length ? Math.max(...platesHere.map((plate) => plate.y1)) : 0\n const plates = allPlates.filter((plate) => Math.abs(plate.y1 - eaveHeight) < 0.4 && touches(plate.aabb, unit.box, 0.3))\n const pillars = (context.pillars.get(unit.floor) ?? []).filter((pillar) => touches(pillar.aabb, unit.box, 0.3))\n const walls = context.walls.filter((wall) => wall.floor === unit.floor && wall.role === 'wall' && !wall.exterior && touches(wall.box, unit.box, 0.2)).map((wall) => context.wallParts.get(wall.id)!)\n return [...plates, ...pillars, ...walls]\n}\n\nfunction addFlatRoof(context: BuildContext, unit: RoofUnit, carriers: StructurePart[]): RoofPane {\n const { builder, construction, system } = context\n const top = context.level(unit.floor) + context.ceilingOf(unit.floor)\n const [u0, v0, u1, v1] = unit.box\n const slab = builder.add({ id: `slab_top${unit.suffix}`, role: 'slab', material: construction.frame.slabs, aabb: [u0 - 0.15, v0 - 0.15, u1 + 0.15, v1 + 0.15], y0: top, y1: top + 0.12 }, { floor: unit.floor, cover: true })\n for (const carrier of carriers.length ? carriers : (context.plates.get(unit.floor) ?? [])) builder.rest(slab, carrier, system.joints.slab)\n if (unit.suffix === '') context.topSlab = slab\n return { id: slab.id, aabb: slab.aabb, y0: slab.y0, y1: slab.y1, flat: true }\n}\n\nfunction addTrusses(context: BuildContext, unit: RoofUnit, carriers: StructurePart[], geometry: GableGeometry): StructurePart[] {\n const { builder, construction, system } = context\n const { box } = unit\n const { axis, length, eave, rise, eaveY } = geometry\n const count = Math.max(2, Math.ceil(length / TRUSS_PITCH) + 1)\n const trusses: StructurePart[] = []\n for (let k = 0; k < count; k++) {\n const at = (axis === 'u' ? box[0] : box[1]) + (k * length) / (count - 1)\n const aabb: Rect = axis === 'u' ? [at - 0.04, box[1] - eave * 0.5, at + 0.04, box[3] + eave * 0.5] : [box[0] - eave * 0.5, at - 0.04, box[2] + eave * 0.5, at + 0.04]\n const truss = builder.add({ id: `truss${unit.suffix}_${k}`, role: 'beam', material: construction.frame.timber, aabb, y0: eaveY, y1: eaveY + rise }, { floor: unit.floor, fill: 0.25 })\n const touching = carriers.filter((carrier) => touches(aabb, carrier.aabb, 0.2) && carrier.role !== 'slab')\n const chosen = touching.length ? touching : carriers.slice().sort((a, b) => distanceBetween(aabb, a.aabb) - distanceBetween(aabb, b.aabb)).slice(0, 2)\n for (const carrier of chosen) builder.rest(truss, carrier, system.joints.truss)\n trusses.push(truss)\n }\n return trusses\n}\n\ninterface GableGeometry {\n axis: 'u' | 'v'\n length: number\n eave: number\n rise: number\n eaveY: number\n}\n\nfunction geometryOf(context: BuildContext, unit: RoofUnit): GableGeometry {\n const { box } = unit\n const roof = context.construction.roof\n const platesHere = context.plates.get(unit.floor) ?? []\n const width = box[2] - box[0]\n const depth = box[3] - box[1]\n const axis = roof.axis ?? (width >= depth ? 'u' : 'v')\n const span = axis === 'u' ? depth : width\n const pitch = unit.annex ? Math.min(roof.pitch || DEFAULT_PITCH, 20) : roof.pitch || DEFAULT_PITCH\n const eaveY = platesHere.length ? Math.max(...platesHere.map((plate) => plate.y1)) : context.level(unit.floor) + context.ceilingOf(unit.floor)\n return { axis, length: axis === 'u' ? width : depth, eave: roof.eave ?? DEFAULT_EAVE, rise: round2((span / 2) * Math.tan((pitch * Math.PI) / 180)), eaveY }\n}\n\ninterface Frames {\n all: StructurePart[]\n sideA: StructurePart[]\n sideB: StructurePart[]\n}\n\n/** Rafters of each side at the truss positions, each resting only on what is under its own side, and a ridge beam that rests on all of them. */\nfunction addRafters(context: BuildContext, unit: RoofUnit, carriers: StructurePart[], geometry: GableGeometry): Frames {\n const { builder, construction, system } = context\n const { box } = unit\n const { axis, length, eave, rise, eaveY } = geometry\n const count = Math.max(2, Math.ceil(length / TRUSS_PITCH) + 1)\n const middle = axis === 'u' ? (box[1] + box[3]) / 2 : (box[0] + box[2]) / 2\n const frames: Frames = { all: [], sideA: [], sideB: [] }\n for (let k = 0; k < count; k++) {\n const at = (axis === 'u' ? box[0] : box[1]) + (k * length) / (count - 1)\n const halves: [string, Rect][] =\n axis === 'u'\n ? [['a', [at - 0.04, box[1] - eave * 0.5, at + 0.04, middle]], ['b', [at - 0.04, middle, at + 0.04, box[3] + eave * 0.5]]]\n : [['a', [box[0] - eave * 0.5, at - 0.04, middle, at + 0.04]], ['b', [middle, at - 0.04, box[2] + eave * 0.5, at + 0.04]]]\n for (const [side, aabb] of halves) {\n const rafter = builder.add({ id: `rafter${unit.suffix}_${side}_${k}`, role: 'beam', material: construction.frame.timber, aabb, y0: eaveY, y1: eaveY + rise }, { floor: unit.floor, fill: 0.25 })\n const touching = carriers.filter((carrier) => touches(aabb, carrier.aabb, 0.2) && carrier.role !== 'slab')\n const chosen = touching.length ? touching : carriers.slice().sort((x, y) => distanceBetween(aabb, x.aabb) - distanceBetween(aabb, y.aabb)).slice(0, 2)\n for (const carrier of chosen) builder.rest(rafter, carrier, system.joints.truss)\n frames.all.push(rafter)\n if (side === 'a') frames.sideA.push(rafter)\n else frames.sideB.push(rafter)\n }\n }\n if (!unit.annex) {\n const ridgeBox: Rect = axis === 'u' ? [box[0] - eave, middle - 0.05, box[2] + eave, middle + 0.05] : [middle - 0.05, box[1] - eave, middle + 0.05, box[3] + eave]\n const ridge = builder.add({ id: `ridge${unit.suffix}`, role: 'beam', material: construction.frame.timber, aabb: ridgeBox, y0: eaveY + rise - 0.12, y1: eaveY + rise }, { floor: unit.floor })\n for (const rafter of frames.all) builder.rest(ridge, rafter, system.joints.truss)\n }\n context.roof.trusses += count\n return frames\n}\n\nfunction panesOf(unit: RoofUnit, geometry: GableGeometry): Rect[] {\n const [u0, v0, u1, v1] = unit.box\n const { eave, axis } = geometry\n if (unit.annex) return [[u0 - eave, v0 - eave, u1 + eave, v1 + eave]]\n const midV = (v0 + v1) / 2\n const midU = (u0 + u1) / 2\n return axis === 'u'\n ? [[u0 - eave, v0 - eave, u1 + eave, midV], [u0 - eave, midV, u1 + eave, v1 + eave]]\n : [[u0 - eave, v0 - eave, midU, v1 + eave], [midU, v0 - eave, u1 + eave, v1 + eave]]\n}\n\nfunction coarseFrames(context: BuildContext, unit: RoofUnit, carriers: StructurePart[], geometry: GableGeometry): Frames {\n const trusses = addTrusses(context, unit, carriers, geometry)\n context.roof.trusses += trusses.length\n return { all: trusses, sideA: trusses, sideB: trusses }\n}\n\nfunction addGableRoof(context: BuildContext, unit: RoofUnit, carriers: StructurePart[], covering: JointKind): RoofPane[] {\n const { builder, construction } = context\n const geometry = geometryOf(context, unit)\n const frames: Frames = context.rafterRoof ? addRafters(context, unit, carriers, geometry) : coarseFrames(context, unit, carriers, geometry)\n const panes: RoofPane[] = []\n panesOf(unit, geometry).forEach((aabb, k) => {\n const name = unit.annex ? 'annex' : k === 0 ? 'a' : 'b'\n const options = { floor: unit.floor, fill: construction.roof.covering === 'colonial' ? 0.12 : 0.05, ...(construction.roof.pitch === undefined ? {} : { pitch: construction.roof.pitch }) }\n const pane = builder.add({ id: `roof${unit.suffix}_${name}`, role: 'roof', material: construction.roof.material, aabb, y0: geometry.eaveY, y1: geometry.eaveY + geometry.rise + 0.05 }, options)\n const carried = unit.annex || !context.rafterRoof ? frames.all : k === 0 ? frames.sideA : frames.sideB\n for (const frame of carried) builder.rest(pane, frame, covering)\n panes.push({ id: pane.id, aabb: pane.aabb, y0: pane.y0, y1: pane.y1 })\n })\n if (!unit.annex) {\n const roof = context.roof\n roof.axis = geometry.axis\n roof.ridge = round2(geometry.eaveY + geometry.rise)\n roof.eave = geometry.eave\n roof.y0 = round2(geometry.eaveY)\n roof.aabb = [unit.box[0] - geometry.eave, unit.box[1] - geometry.eave, unit.box[2] + geometry.eave, unit.box[3] + geometry.eave].map(round2) as Rect\n }\n return panes\n}\n\n/** Roof of a timber house: ceiling joists every 0.6 m tie the trusses and carry the attic floor. */\nfunction addCeilingJoists(context: BuildContext): void {\n const { builder, construction } = context\n const bearing = context.roof.bearingFloor\n const rects = context.rectsOf(bearing, CLOSED_ONLY)\n const box = unionOf(rects.length ? rects : [context.topBox])\n const carriers = [...(context.plates.get(bearing) ?? []), ...context.walls.filter((w) => w.floor === bearing && w.role === 'wall' && !w.exterior).map((w) => context.wallParts.get(w.id)!)]\n const length = box[2] - box[0]\n const depth = box[3] - box[1]\n const alongU = length >= depth\n const span = alongU ? length : depth\n const count = Math.max(2, Math.round(span / 0.6) + 1)\n const beamTops = carriers.filter((carrier) => carrier.role === 'beam').map((carrier) => carrier.y0)\n const y0 = carriers.length ? Math.max(...beamTops, context.level(bearing) + 1) : context.topOf(bearing)\n const joists: StructurePart[] = []\n for (let k = 0; k < count; k++) {\n const at = (alongU ? box[0] : box[1]) + 0.05 + (k * (span - 0.1)) / (count - 1)\n const aabb: Rect = alongU ? [at - 0.025, box[1], at + 0.025, box[3]] : [box[0], at - 0.025, box[2], at + 0.025]\n const joist = builder.add({ id: `ceiling_joist_${k}`, role: 'beam', material: construction.frame.timber, aabb, y0: y0 - 0.02, y1: y0 + context.system.plateThickness - 0.02 }, { floor: bearing, spacing: 0.6 })\n const beams = carriers.filter((carrier) => carrier.role === 'beam' && touches(aabb, carrier.aabb, 0.2))\n for (const carrier of beams.length ? beams : carriers.slice(0, 2)) builder.rest(joist, carrier, 'nail')\n joists.push(joist)\n }\n context.ceilingJoists = joists\n}\n\n/** The roof over the top storey: a flat slab or trusses and two panes, and the ceiling joists of a timber house. */\nexport function addRoof(context: BuildContext): void {\n const { construction } = context\n const covering = ROOF_COVERINGS.get(construction.roof.covering)\n const bearing = construction.roof.bearingFloor ?? context.floorCount - 1\n const open = context.rectsOf(context.floorCount - 1, OPEN_ROOM_TYPES)\n const topRects = context.rectsOf(context.floorCount - 1, CLOSED_ONLY)\n const body = unionOf(open.length ? open : topRects)\n context.topBox = context.floorCount - 1 === bearing ? body : unionOf(context.rectsOf(bearing, OPEN_ROOM_TYPES))\n context.roof = { shape: construction.roof.shape, covering: construction.roof.covering, material: construction.roof.material, pitch: construction.roof.pitch || 0, bearingFloor: bearing, panes: [], trusses: 0 }\n for (const unit of roofUnits(context, bearing)) {\n const carriers = roofCarriers(context, unit)\n if (construction.roof.shape === 'slab') context.roof.panes.push(addFlatRoof(context, unit, carriers))\n else context.roof.panes.push(...addGableRoof(context, unit, carriers, covering?.joint ?? 'nail'))\n }\n if (context.isTimber && construction.roof.shape !== 'slab') addCeilingJoists(context)\n}\n","import { GROUND } from '../types'\nimport type { StructureSource } from '../types'\nimport type { BuildContext } from './context'\n\ntype StairItem = StructureSource['items'][number]\n\n/** One flight per pair of linked storeys, taken from the item of the lower storey when both are present. */\nfunction flightsOf(items: readonly StairItem[]): Map<string, StairItem> {\n const flights = new Map<string, StairItem>()\n for (const item of items.filter((it) => it.category === 'stairs' && it.link)) {\n const key = `${item.link!.from}_${item.link!.to}`\n if (!flights.has(key) || item.floor === item.link!.from) flights.set(key, item)\n }\n return flights\n}\n\n/** Interior stairs between storeys, resting on the floor below and tied to the one above, plus the basement stairs. */\nexport function addStairs(context: BuildContext): void {\n const { builder, construction } = context\n const material = context.isTimber ? construction.frame.timber : (construction.stairs ?? 'concrete')\n for (const [key, item] of flightsOf(context.source.items)) {\n const { from, to } = item.link!\n const flight = builder.add({ id: `stairs_${key}`, role: 'stair', material, aabb: item.aabb!, y0: context.level(from), y1: context.level(to) }, { floor: from, steps: Math.round((context.level(to) - context.level(from)) / 0.18) })\n const base = context.baseOf(from)\n builder.rest(flight, !base || base === GROUND ? GROUND : base, !base || base === GROUND ? 'resting' : context.isTimber ? 'nail' : 'mortar')\n const upper = context.baseOf(to)\n if (upper && upper !== GROUND) builder.rest(flight, upper, context.isTimber ? 'nail' : 'bolt')\n }\n if (!context.hasBasement) return\n const item = context.source.items.find((it) => it.type === 'basement_stairs')\n if (!item?.aabb) return\n const depth = construction.foundation.depth || 2.4\n const flight = builder.add({ id: 'basement_stairs', role: 'stair', material: 'wood_soft', aabb: item.aabb, y0: -depth, y1: context.level(0) }, { floor: -1, steps: Math.round((context.level(0) + depth) / 0.18) })\n builder.rest(flight, builder.find('basement_slab')!, 'resting')\n if (context.base0 && context.base0 !== GROUND) builder.rest(flight, context.base0, 'nail')\n}\n","import type { Opening, Rect, StructurePart } from '../types'\nimport type { BuildContext, BuildWall } from './context'\n\nconst TOLERANCE = 0.02\n/** Height of a door leaf, which the plan does not store (m). */\nexport const DOOR_HEIGHT = 2.1\nconst LINTEL_DEPTH = 0.2\nconst LINTEL_BEARING = 0.2\n\nconst crossOf = (wall: BuildWall): number => (wall.axis === 'u' ? wall.v0 : wall.u0)\nconst alongRange = (wall: BuildWall): [number, number] => (wall.axis === 'u' ? [Math.min(wall.u0, wall.u1), Math.max(wall.u0, wall.u1)] : [Math.min(wall.v0, wall.v1), Math.max(wall.v0, wall.v1)])\n\n/** The windows of the plan, each in the wall it sits in. */\nexport function findOpenings(context: BuildContext): Opening[] {\n const openings: Opening[] = []\n for (const window of context.source.windows ?? []) {\n const from = window.at - window.width / 2\n const to = window.at + window.width / 2\n const wall = context.walls.find((w) => {\n if (w.floor !== window.floor || w.axis !== window.axis || w.type !== 'wall' || Math.abs(crossOf(w) - window.pos) > TOLERANCE) return false\n const [low, high] = alongRange(w)\n return from >= low - TOLERANCE && to <= high + TOLERANCE\n })\n if (!wall) continue\n const base = context.level(window.floor)\n openings.push({ id: window.id, kind: 'window', wall: wall.id, from, to, y0: base + window.y0, y1: base + window.y1 })\n }\n return openings\n}\n\n/**\n * A lintel over every door gap, 0.2 m deep, bearing 0.2 m on the wall at each side (a concrete beam in masonry, a header in timber houses). The bond beam or\n * plate over the door rests on it as well as on the walls beside it.\n */\nexport function addDoorLintels(context: BuildContext): void {\n const { builder, construction, system } = context\n for (const door of context.source.doors.filter((d) => d.a !== undefined && d.type !== 'zipper')) {\n const along = door.axis === 'u' ? door.u : door.v\n const cross = door.axis === 'u' ? door.v : door.u\n const from = along - door.width / 2\n const to = along + door.width / 2\n const beside = context.walls.filter((w) => w.floor === door.floor && w.axis === door.axis && w.type === 'wall' && Math.abs(crossOf(w) - cross) <= TOLERANCE && (Math.abs(alongRange(w)[1] - from) <= 0.05 || Math.abs(alongRange(w)[0] - to) <= 0.05))\n if (!beside.length) continue\n const half = (beside[0]!.thickness ?? 0.15) / 2\n const lo = from - LINTEL_BEARING\n const hi = to + LINTEL_BEARING\n const box: Rect = door.axis === 'u' ? [lo, cross - half, hi, cross + half] : [cross - half, lo, cross + half, hi]\n const y0 = context.level(door.floor) + DOOR_HEIGHT\n const lintel = builder.add({ id: `lintel_${door.id}`, role: 'beam', material: system.timber ? construction.frame.timber : 'concrete', aabb: box, y0, y1: y0 + LINTEL_DEPTH }, { floor: door.floor, ...(system.timber ? {} : { assembly: 'reinforced_concrete' }) })\n for (const wall of beside) builder.rest(lintel, context.wallParts.get(wall.id) as StructurePart, system.joints.beam)\n for (const plate of context.plates.get(door.floor) ?? []) if (overlapsInPlan(plate.aabb, box)) builder.rest(plate, lintel, system.joints.beam)\n }\n}\n\nconst overlapsInPlan = (a: Rect, b: Rect): boolean => a[0] < b[2] && a[2] > b[0] && a[1] < b[3] && a[3] > b[1]\n","import { GROUND } from '../types'\nimport type { Rect } from '../types'\nimport type { BuildContext } from './context'\n\nconst RISER = 0.18\nconst TREAD = 0.28\n\nconst stepCount = (elevation: number): number => Math.max(1, Math.ceil(elevation / RISER))\n\n/** Steps from each porch door down to the ground: concrete in masonry, wood otherwise, resting on the porch floor. */\nfunction addPorchSteps(context: BuildContext): void {\n const { builder } = context\n for (const room of context.source.rooms.filter((r) => r.type === 'porch')) {\n const deck = builder.find(`porch_floor_${room.id}`)\n for (const door of context.source.doors.filter((d) => d.floor === room.floor && d.b === 'outside' && d.a === room.id)) {\n const count = stepCount(context.elevation)\n const depth = count * TREAD\n const aabb: Rect = [door.u - door.width / 2, door.v - depth, door.u + door.width / 2, door.v]\n const flight = builder.add({ id: `steps_${door.id}`, role: 'stair', material: context.isTimber ? 'wood_soft' : 'concrete', aabb, y0: 0, y1: context.level(room.floor) }, { floor: 0, steps: count, door: door.id })\n builder.rest(flight, GROUND, 'resting')\n if (deck) builder.rest(flight, deck, context.isTimber ? 'nail' : 'mortar')\n }\n }\n}\n\nfunction boxOfSteps(door: { u: number; v: number; width: number; axis: string; side?: string }, depth: number): Rect {\n const direction = door.axis === 'u' ? (door.side === 'front' ? -1 : 1) : door.side === 'left' ? -1 : 1\n if (door.axis === 'u') return [door.u - door.width / 2, Math.min(door.v, door.v + direction * depth), door.u + door.width / 2, Math.max(door.v, door.v + direction * depth)]\n return [Math.min(door.u, door.u + direction * depth), door.v - door.width / 2, Math.max(door.u, door.u + direction * depth), door.v + door.width / 2]\n}\n\n/** Steps at the other outside doors of the ground storey when the floor sits above the ground. */\nfunction addDoorSteps(context: BuildContext): void {\n if (context.elevation <= 0.1) return\n const { builder } = context\n const doors = context.source.doors.filter((d) => d.floor === 0 && d.exterior && d.model !== 'steel' && d.type !== 'steps' && d.type !== 'zipper')\n for (const door of doors) {\n const count = stepCount(context.elevation)\n const depth = Math.min(TREAD * count, 0.9)\n const flight = builder.add({ id: `steps_${door.id}`, role: 'stair', material: context.isTimber ? 'wood_soft' : 'concrete', aabb: boxOfSteps(door, depth), y0: 0, y1: context.level(0) }, { floor: 0, steps: count, door: door.id })\n builder.rest(flight, GROUND, 'resting')\n const base = context.base0\n if (base && base !== GROUND) builder.rest(flight, base, context.isTimber ? 'nail' : 'mortar')\n }\n}\n\nexport function addExteriorSteps(context: BuildContext): void {\n addPorchSteps(context)\n addDoorSteps(context)\n}\n","import { GROUND } from '../types'\nimport type { Rect, StructurePart, WaterTank } from '../types'\nimport { touches } from '../geometry'\nimport type { BuildContext } from './context'\n\nconst TANK_FILL = 0.08\n\nconst squareAround = (u: number, v: number, side: number): Rect => [u - side / 2, v - side / 2, u + side / 2, v + side / 2]\n\nfunction addTank(context: BuildContext, tank: WaterTank, floor: number, y0: number): StructurePart {\n return context.builder.add({ id: 'water_tank', role: 'none', material: tank.material ?? 'plastic', aabb: tank.aabb, y0, y1: y0 + tank.h }, { floor, fill: TANK_FILL, liters: tank.capacity })\n}\n\n/** The slab under the roof that carries a tank in the attic or on a raised platform: a ceiling slab on the top plates, pillars and bearing walls. */\nfunction ensureCeilingSlab(context: BuildContext, y: number): StructurePart {\n const { builder, construction, system } = context\n const existing = builder.find('slab_ceiling')\n if (existing) return existing\n const top = context.floorCount - 1\n const box = context.topBox\n const carriers = builder.parts.filter(\n (part) =>\n ((part.role === 'beam' && part.id.startsWith(`plate_${top}_`)) || (part.role === 'column' && part.floor === top) || (part.role === 'wall' && part.floor === top && !part.id.startsWith('basement'))) &&\n touches(box, part.aabb, 0.1),\n )\n const slab = builder.add({ id: 'slab_ceiling', role: 'slab', material: construction.frame.slabs, aabb: box, y0: y - 0.12, y1: y }, { floor: top })\n for (const carrier of carriers) builder.rest(slab, carrier, system.joints.slab)\n return slab\n}\n\nfunction addRaisedPlatform(context: BuildContext, tank: WaterTank): void {\n const { builder, construction } = context\n const platform = tank.platform!\n const top = context.floorCount - 1\n const ceiling = ensureCeilingSlab(context, platform.baseY)\n const pillars = platform.pillars.map((q, k) => {\n const pillar = builder.add({ id: `tank_column_${k}`, role: 'column', material: construction.frame.pillars, aabb: squareAround(q.u, q.v, q.side), y0: platform.baseY, y1: platform.topY - platform.thickness }, { floor: top })\n builder.rest(pillar, ceiling, 'rebar')\n return pillar\n })\n const slab = builder.add({ id: 'tank_slab', role: 'slab', material: construction.frame.slabs, aabb: platform.aabb, y0: platform.topY - platform.thickness, y1: platform.topY }, { floor: top })\n for (const pillar of pillars) builder.rest(slab, pillar, 'rebar')\n builder.rest(addTank(context, tank, top, tank.y), slab, 'resting')\n}\n\nfunction addAtticTank(context: BuildContext, tank: WaterTank): void {\n const { builder } = context\n const top = context.floorCount - 1\n if (!context.isTimber) {\n const ceiling = ensureCeilingSlab(context, tank.y)\n builder.rest(addTank(context, tank, top, tank.y), ceiling, 'resting')\n return\n }\n const supports = context.topSlab ? [context.topSlab] : (context.ceilingJoists ?? builder.parts.filter((part) => part.role === 'beam' && part.id.startsWith(`plate_${top}_`)))\n const y0 = supports[0] ? supports[0].y1 : tank.y - 0.03\n const floor = builder.add({ id: 'attic_floor', role: 'slab', material: 'plywood', aabb: context.topBox, y0, y1: y0 + 0.03 }, { floor: top })\n for (const support of supports) if (touches(floor.aabb, support.aabb, 0.1)) builder.rest(floor, support, 'nail')\n builder.rest(addTank(context, tank, top, tank.y), floor, 'resting')\n}\n\nfunction addSlabTank(context: BuildContext, tank: WaterTank): void {\n const { builder } = context\n const supports = builder.parts.filter((part) => part.role === 'slab' && Math.abs(part.y1 - tank.y) < 0.3 && touches(part.aabb, tank.aabb, 0.1))\n const carrier = supports.sort((a, b) => Math.abs(a.y1 - tank.y) - Math.abs(b.y1 - tank.y))[0] ?? context.topSlab\n const part = addTank(context, tank, tank.floor, tank.y)\n builder.rest(part, carrier ?? GROUND, 'resting')\n}\n\nfunction addTrestleTank(context: BuildContext, tank: WaterTank): void {\n const { builder } = context\n const stand = tank.stand!\n const columns = stand.pillars.map((q, k) => {\n const column = builder.add({ id: `trestle_column_${k}`, role: 'column', material: stand.material, aabb: squareAround(q.u, q.v, q.side), y0: 0, y1: stand.height }, { floor: 0 })\n builder.rest(column, GROUND, stand.baseJoint ?? 'resting')\n return column\n })\n const [u0, v0, u1, v1] = tank.aabb\n const beams = ([[u0 - 0.1, v0 - 0.1, u1 + 0.1, v0 + 0.05], [u0 - 0.1, v1 - 0.05, u1 + 0.1, v1 + 0.1]] as Rect[]).map((aabb, k) => {\n const beam = builder.add({ id: `trestle_beam_${k}`, role: 'beam', material: stand.material, aabb, y0: stand.height - 0.12, y1: stand.height }, { floor: 0 })\n for (const column of columns.filter((c) => touches(beam.aabb, c.aabb, 0.15))) builder.rest(beam, column, stand.joint ?? 'nail')\n return beam\n })\n const part = addTank(context, tank, 0, stand.height)\n for (const beam of beams) builder.rest(part, beam, stand.tie ?? 'resting')\n}\n\n/** The water tank as a part (role `none`: it weighs on what holds it and carries nothing) with whatever holds it up. */\nexport function addWaterTank(context: BuildContext): void {\n const tank = context.tank\n if (!tank) return\n switch (tank.place) {\n case 'slab':\n return addSlabTank(context, tank)\n case 'raised_slab':\n return addRaisedPlatform(context, tank)\n case 'attic':\n return addAtticTank(context, tank)\n case 'trestle':\n return addTrestleTank(context, tank)\n }\n}\n","import { touches, unionOf } from '../geometry'\nimport type { BuildContext } from './context'\nimport { addDeck, addJoists } from './floor-deck'\n\n/** The floor of the storey above `floor`: a concrete slab, or joists and boards in timber, resting on what carries `floor`. */\nexport function addUpperFloor(context: BuildContext, floor: number): void {\n if (floor >= context.floorCount - 1 || context.isUnit) return\n const next = floor + 1\n const rects = context.rectsOf(next, ['balcony', 'porch', 'void'])\n const box = rects.length ? unionOf(rects) : context.houseBox\n const carriers = context.carriers.get(floor)!\n const { system, construction, builder } = context\n const thickness = system.slabThickness\n if (context.isTimber) {\n const joists = addJoists(context, { floor: next, box, thickness, carriers, material: construction.frame.timber, joint: system.joints.beam })\n addDeck(context, `slab_${next}`, construction.frame.slabs, { floor: next, box, thickness, joint: system.joints.slab }, joists)\n return\n }\n const slab = builder.add({ id: `slab_${next}`, role: 'slab', material: construction.frame.slabs, aabb: box, y0: context.level(next) - thickness, y1: context.level(next) }, { floor: next })\n const below = carriers.filter((carrier) => carrier.y0 <= slab.y0 + 0.05)\n const touching = below.filter((carrier) => touches(slab.aabb, carrier.aabb, 0.2))\n for (const carrier of touching.length ? touching : below) builder.rest(slab, carrier, system.joints.slab)\n}\n","import { GROUND } from '../types'\nimport type { StructurePart } from '../types'\nimport type { BuildContext, BuildWall } from './context'\nimport { guardHeightOf, OPEN_ROOM_TYPES } from './context'\n\n/** Highest ceiling among the rooms the wall touches (a double-height room lifts its outer wall to the eave). */\nexport function wallCeiling(context: BuildContext, wall: BuildWall): number {\n const rooms = wall.sides.map((id) => context.source.rooms.find((room) => room.id === id && room.floor === wall.floor)).filter((room) => room !== undefined)\n return Math.max(context.ceilingOf(wall.floor), ...rooms.map((room) => room.ceiling || 0))\n}\n\nfunction wallTop(context: BuildContext, wall: BuildWall, floor: number): number {\n const y0 = context.level(floor)\n if (wall.type === 'railing') return y0 + guardHeightOf(wall)\n const ceiling = wallCeiling(context, wall)\n const height = wall.structureHeight || wall.h || context.ceilingOf(floor)\n if (wall.exterior && floor < context.floorCount - 1 && !context.isUnit && ceiling > context.ceilingOf(floor) + 0.01) return y0 + ceiling\n if (floor === context.floorCount - 1 || context.isUnit) return y0 + Math.max(height, ceiling)\n const top = context.topOf(floor)\n return Math.max(y0 + height, y0 + ceiling > top ? top : y0 + ceiling)\n}\n\n/** What a railing rests on: the slab of its own balcony or the floor of its porch. */\nfunction railingBase(context: BuildContext, wall: BuildWall, floor: number): StructurePart | string | undefined {\n const open = wall.sides\n .map((id) => context.source.rooms.find((room) => room.id === id && room.floor === floor))\n .find((room) => room && (room.type === 'balcony' || room.type === 'porch'))\n if (!open) return context.baseOf(floor)\n return open.type === 'porch' ? `porch_floor_${open.id}` : `slab_${floor}_${open.id}`\n}\n\nconst assemblyOf = (context: BuildContext): string | undefined => context.construction.walls.assembly ?? (context.system.walls || undefined)\n\nfunction addWallPart(context: BuildContext, wall: BuildWall, floor: number): void {\n const { system, builder } = context\n const isRailing = wall.type === 'railing'\n const y0 = context.level(floor)\n const top = wallTop(context, wall, floor)\n const y1 = isRailing ? top : wall.exterior && !wall.gable ? top - system.plateThickness : top\n const framed = system.studs !== undefined && !isRailing\n const part = builder.add(\n { id: wall.id, role: wall.role, material: wall.material, aabb: wall.box, y0, y1: Math.max(y1, y0 + 0.2) },\n { floor, fill: context.isTimber && wall.role === 'wall' ? system.wallFill : 1, ...(framed ? { studs: system.studs } : {}), ...(isRailing ? {} : { assembly: assemblyOf(context) }) },\n )\n context.wallParts.set(wall.id, part)\n const base = isRailing ? railingBase(context, wall, floor) : context.baseOf(floor)\n const joint = isRailing ? 'nail' : system.joints.wall\n if (base === GROUND || (floor === 0 && !base)) builder.rest(part, GROUND, joint)\n else if (base) builder.rest(part, base, joint)\n}\n\n/** One part per wall of the storey, resting on the floor below it (or the ground). */\nexport function addWalls(context: BuildContext, floor: number): void {\n for (const wall of context.walls.filter((w) => w.floor === floor)) addWallPart(context, wall, floor)\n}\n\nexport const isOpenRoomType = (type: string): boolean => OPEN_ROOM_TYPES.includes(type)\n","import { createContext } from './context'\nimport type { BuildContext } from './context'\nimport { addBalconies } from './balconies'\nimport { buildCanvasStructure } from './canvas'\nimport { addChimney, addWell } from './extras'\nimport { addFoundation } from './foundation'\nimport { addPlatesAndPillars } from './plates'\nimport { addPorches } from './porch'\nimport { addPorchRoofs } from './porch-roof'\nimport { addRoof } from './roof'\nimport { addStairs } from './stairs'\nimport { addDoorLintels, findOpenings } from './openings'\nimport { addExteriorSteps } from './steps'\nimport { addWaterTank } from './tank-parts'\nimport { addUpperFloor } from './upper-floor'\nimport { addWalls } from './walls'\nimport { resolveConstruction } from '../construction'\nimport type { Structure, StructureOptions, StructureSource } from '../types'\n\nfunction buildFloors(context: BuildContext): void {\n for (let floor = 0; floor < context.floorCount; floor++) {\n addWalls(context, floor)\n addPlatesAndPillars(context, floor)\n addPorches(context, floor)\n addUpperFloor(context, floor)\n }\n}\n\n/**\n * The structure of a generated plan: every part that carries load (foundation, floors, walls, plates and bond beams, pillars, porch posts, trusses,\n * roof, stairs, tank) with what each rests on. The plan itself is not modified.\n */\nexport function buildStructure(source: StructureSource, options: StructureOptions = {}): Structure {\n const refined = options.wallDetail !== 'coarse'\n const built = options.construction ? { construction: options.construction, extras: options.extras ?? {} } : resolveConstruction(source)\n const construction = built.construction\n const extras = options.extras ?? built.extras ?? {}\n if (construction.system === 'canvas') return buildCanvasStructure(construction, extras)\n const tank = options.tank !== undefined ? options.tank : (source.waterTank ?? null)\n const context = createContext(source, construction, extras, tank, { porchRoofOnPostsOnly: options.porchRoofOnPostsOnly ?? refined, rafterRoof: options.rafterRoof ?? refined })\n addFoundation(context)\n buildFloors(context)\n addBalconies(context)\n addPorchRoofs(context)\n addExteriorSteps(context)\n addStairs(context)\n addRoof(context)\n if (refined) addDoorLintels(context)\n addWaterTank(context)\n addChimney(context)\n addWell(context)\n const levels = source.floors.map((_, floor) => context.level(floor))\n const framed = construction.system === 'masonry' && (context.isUnit || source.style === 'commercial' || context.floorCount >= 3)\n return { parts: context.builder.parts, supports: context.builder.supports, levels, elevation: context.elevation, roof: context.roof, construction, framed, openings: findOpenings(context) }\n}\n","export type ContentGroup = 'food' | 'water' | 'medicine' | 'tool' | 'cleaning' | 'improvised_weapon' | 'clothes' | 'document' | 'utensil' | 'trash'\n\nexport interface ContentEntry {\n itemId: string\n min: number\n max: number\n group: ContentGroup\n pickable: boolean\n weight: number\n}\n\nconst entry = (itemId: string, min: number, max: number, group: ContentGroup, pickable: boolean, weight: number): ContentEntry => ({ itemId, min, max, group, pickable, weight })\n\nconst FRIDGE = [\n entry('water_bottle', 1, 3, 'water', true, 3), entry('milk_carton', 1, 2, 'food', true, 2), entry('eggs', 1, 1, 'food', true, 2), entry('packed_meat', 1, 2, 'food', true, 1.5), entry('fruit', 1, 4, 'food', true, 2),\n entry('yogurt', 1, 3, 'food', true, 1), entry('soda', 1, 2, 'water', true, 1), entry('cheese', 1, 1, 'food', true, 1), entry('insulin', 1, 1, 'medicine', true, 0.4), entry('leftovers', 1, 2, 'food', true, 1),\n]\nconst BEDSIDE = [entry('medicine', 1, 2, 'medicine', true, 2), entry('book', 1, 2, 'document', true, 1.5), entry('charger', 1, 1, 'tool', true, 1), entry('flashlight', 1, 1, 'tool', true, 0.7), entry('glasses', 1, 1, 'tool', true, 0.7)]\nconst WARDROBE = [\n entry('shirt', 2, 6, 'clothes', true, 3), entry('trousers', 1, 4, 'clothes', true, 3), entry('coat', 1, 2, 'clothes', true, 1.5), entry('sneakers', 1, 2, 'clothes', true, 1.5),\n entry('shoes', 1, 2, 'clothes', true, 1), entry('blanket', 1, 2, 'clothes', true, 1.5), entry('backpack', 1, 1, 'tool', true, 0.8),\n]\nconst DRESSER = [entry('underwear', 2, 6, 'clothes', true, 3), entry('socks', 2, 6, 'clothes', true, 2), entry('t_shirt', 1, 4, 'clothes', true, 2), entry('documents', 1, 2, 'document', true, 1), entry('flashlight', 1, 1, 'tool', true, 0.7), entry('batteries', 1, 2, 'tool', true, 0.7)]\nconst FILING = [entry('documents', 1, 4, 'document', true, 3), entry('pen', 1, 3, 'tool', true, 1.5), entry('keys', 1, 2, 'tool', true, 1), entry('stapler', 1, 1, 'improvised_weapon', true, 0.5)]\nconst TRASH = [entry('full_trash_bag', 1, 1, 'trash', false, 2), entry('packaging', 1, 4, 'trash', true, 3), entry('empty_can', 1, 3, 'trash', true, 2), entry('crumpled_paper', 1, 3, 'trash', true, 1)]\n\n/** What each kind of container may hold, by category (or by type when a type differs from its category). */\nexport const CONTENT_TABLES: Record<string, ContentEntry[]> = {\n fridge: FRIDGE,\n display_fridge: [entry('soda', 2, 6, 'water', true, 3), entry('water_bottle', 2, 6, 'water', true, 3), entry('yogurt', 2, 5, 'food', true, 2)],\n freezer: [entry('frozen_meat', 2, 5, 'food', true, 3), entry('ice_cream', 1, 2, 'food', true, 1)],\n kitchen_cabinet: [\n entry('pot', 1, 2, 'tool', true, 1.5), entry('kitchen_knife', 1, 2, 'improvised_weapon', true, 1.5), entry('dish_soap', 1, 2, 'cleaning', true, 2), entry('sponge', 1, 2, 'cleaning', true, 1), entry('rice', 1, 2, 'food', true, 1.5),\n entry('beans', 1, 2, 'food', true, 1.5), entry('pasta', 1, 2, 'food', true, 1), entry('cooking_oil', 1, 1, 'food', true, 1), entry('canned_tuna', 1, 3, 'food', true, 1.5), entry('disinfectant', 1, 1, 'cleaning', true, 1), entry('trash_bag', 1, 2, 'trash', true, 0.7),\n ],\n overhead_cabinet: [entry('plates', 4, 8, 'utensil', false, 3), entry('glasses', 3, 6, 'utensil', false, 3), entry('mug', 1, 3, 'utensil', true, 1.5), entry('coffee', 1, 2, 'food', true, 1.5), entry('canned_corn', 1, 3, 'food', true, 1.5), entry('spices', 1, 3, 'food', true, 1)],\n washbasin: [\n entry('painkiller', 1, 2, 'medicine', true, 2), entry('bandages', 1, 2, 'medicine', true, 2), entry('soap', 1, 3, 'cleaning', true, 2), entry('toilet_paper', 1, 4, 'cleaning', true, 2), entry('shampoo', 1, 2, 'cleaning', true, 1),\n entry('toothbrush', 1, 2, 'cleaning', true, 1), entry('scissors', 1, 1, 'improvised_weapon', true, 0.5), entry('rubbing_alcohol', 1, 1, 'medicine', true, 1),\n ],\n wardrobe: WARDROBE,\n wardrobe_large: WARDROBE,\n dresser: DRESSER,\n console_table: DRESSER,\n nightstand: BEDSIDE,\n filing_cabinet: FILING,\n pantry: [\n entry('rice', 2, 4, 'food', true, 2), entry('beans', 2, 4, 'food', true, 2), entry('canned_tuna', 2, 5, 'food', true, 2), entry('water_jug', 1, 2, 'water', true, 2), entry('flour', 1, 2, 'food', true, 1),\n entry('sugar', 1, 2, 'food', true, 1), entry('cooking_oil', 1, 2, 'food', true, 1), entry('biscuits', 1, 4, 'food', true, 1.5),\n ],\n tv_unit: [entry('remote_control', 1, 1, 'tool', true, 2), entry('dvds', 1, 4, 'document', true, 1), entry('cables', 1, 3, 'tool', true, 1.5), entry('batteries', 1, 2, 'tool', true, 1)],\n laundry_cabinet: [entry('washing_powder', 1, 2, 'cleaning', true, 3), entry('bleach', 1, 2, 'cleaning', true, 2), entry('disinfectant', 1, 2, 'cleaning', true, 2), entry('bucket', 1, 1, 'tool', true, 1), entry('broom', 1, 1, 'improvised_weapon', true, 1), entry('rubber_gloves', 1, 2, 'cleaning', true, 1)],\n laundry_shelf: [entry('washing_powder', 1, 1, 'cleaning', true, 2), entry('softener', 1, 2, 'cleaning', true, 2), entry('clothespins', 1, 1, 'tool', true, 1)],\n workbench: [entry('hammer', 1, 1, 'improvised_weapon', true, 2), entry('screwdriver', 1, 2, 'tool', true, 2), entry('pliers', 1, 1, 'tool', true, 1.5), entry('insulating_tape', 1, 2, 'tool', true, 1), entry('screws', 1, 2, 'tool', true, 1)],\n tool_shelf: [entry('hammer', 1, 1, 'improvised_weapon', true, 1.5), entry('hand_saw', 1, 1, 'improvised_weapon', true, 1), entry('paint_can', 1, 3, 'trash', true, 1.5), entry('rope', 1, 1, 'tool', true, 1), entry('nails', 1, 2, 'tool', true, 1.5)],\n mailbox: [entry('letter', 1, 4, 'document', true, 3), entry('bill', 1, 2, 'document', true, 2), entry('flyer', 1, 4, 'trash', true, 2)],\n trash_bin: TRASH,\n outdoor_bin: TRASH,\n china_cabinet: [entry('china_plates', 3, 6, 'utensil', false, 3), entry('wine_glasses', 2, 5, 'utensil', false, 2)],\n}\n\n/** Groups of things somebody who locked themselves in would have stocked up. */\nexport const SUPPLY_GROUPS: readonly ContentGroup[] = ['food', 'water', 'medicine', 'tool']\n","import type { FindStack } from '@adatechnology/game-floorplan'\n\nimport { CONTENT_TABLES, SUPPLY_GROUPS } from './content-tables'\nimport type { ContentEntry } from './content-tables'\nimport type { Rng } from './shared'\n\nexport interface ContentStack extends FindStack {\n group: string\n pickable: boolean\n}\n\nexport interface ContentQuery {\n /** Category or type of the container (`fridge`, `kitchen_cabinet`, `overhead_cabinet`...). */\n container: string\n state: string\n rng: Rng\n /** Footprint of the container in m2. */\n footprint: number\n}\n\n/** How a state changes what a container holds: how many kinds, how likely each is, how many of each, and what is left over. */\nexport interface ContentStateRule {\n kinds(base: number, available: number, rng: Rng): number\n weight(entry: ContentEntry): number\n extraQuantity(entry: ContentEntry): number\n leftovers?(found: ContentStack[], container: string, rng: Rng): void\n}\n\nconst FRIDGES = ['fridge', 'display_fridge', 'freezer']\nconst isSupply = (entry: ContentEntry): boolean => SUPPLY_GROUPS.includes(entry.group)\n\n/** The normal world is the base; `fortified` and `abandoned` are the genre's rules, kept here until the item catalogue and the genre pack own them. */\nexport const CONTENT_STATES: Record<string, ContentStateRule> = {\n normal: { kinds: (base) => base, weight: (entry) => entry.weight, extraQuantity: () => 0 },\n fortified: { kinds: (base, available) => Math.min(available, base + 2), weight: (entry) => (isSupply(entry) ? entry.weight * 2.5 : entry.weight), extraQuantity: (entry) => (isSupply(entry) ? 1 : 0) },\n abandoned: {\n kinds: (_base, _available, rng) => (rng() < 0.4 ? 0 : 1),\n weight: (entry) => entry.weight,\n extraQuantity: () => 0,\n leftovers(found, container, rng) {\n if (found.length === 0 && rng() < 0.5) found.push({ itemId: 'scraps_and_papers', count: 1, pickable: false, group: 'trash' })\n if (FRIDGES.includes(container)) found.push({ itemId: 'spoiled_food', count: 1, pickable: false, group: 'trash' })\n },\n },\n}\n\nexport function registerContentState(state: string, rule: ContentStateRule): void {\n CONTENT_STATES[state] = rule\n}\n\n/** Weighted draw without replacement. */\nfunction weightedOrder<T extends { weight: number }>(candidates: T[], rng: Rng): T[] {\n const pool = candidates.slice()\n const out: T[] = []\n while (pool.length) {\n let x = rng() * pool.reduce((sum, c) => sum + c.weight, 0)\n let i = 0\n for (; i < pool.length - 1; i++) {\n x -= pool[i]!.weight\n if (x < 0) break\n }\n out.push(pool.splice(i, 1)[0]!)\n }\n return out\n}\n\n/** What a container holds in a state: a few kinds of thing from the table of its category, more of the useful ones when fortified, almost nothing when abandoned. */\nexport function contentOf(query: ContentQuery): ContentStack[] {\n const pool = CONTENT_TABLES[query.container]\n if (!pool) return []\n const rule = CONTENT_STATES[query.state] ?? CONTENT_STATES.normal!\n const { rng } = query\n const base = Math.max(2, Math.min(5, Math.round(1.5 + query.footprint * 3 + rng() * 1.5)))\n const kinds = rule.kinds(base, pool.length, rng)\n const found: ContentStack[] = []\n for (const candidate of weightedOrder(pool.map((entry) => ({ entry, weight: rule.weight(entry) })), rng).slice(0, kinds)) {\n const { entry } = candidate\n const count = entry.min + Math.floor(rng() * (entry.max - entry.min + 1)) + rule.extraQuantity(entry)\n found.push({ itemId: entry.itemId, count, pickable: entry.pickable, group: entry.group })\n }\n rule.leftovers?.(found, query.container, rng)\n return found\n}\n\nexport const hasContent = (container: string): boolean => container in CONTENT_TABLES\n\n","import type { Rect } from '../types'\n\n/** Loosely typed plan data: the engine's own plan and its items (`result.items`), which the utilities read and some of them annotate. */\nexport type Json = any\nexport type Rng = () => number\n\nexport const HALF_WALL = 0.075\nexport const round2 = (value: number): number => Math.round(value * 100) / 100\nexport const clamp = (value: number, low: number, high: number): number => Math.max(low, Math.min(high, value))\n\nexport const overlaps = (a: Rect, b: Rect, epsilon = 1e-6): boolean => a[0] < b[2] - epsilon && a[2] > b[0] + epsilon && a[1] < b[3] - epsilon && a[3] > b[1] + epsilon\n\nexport const inner = (rect: Rect): Rect => [rect[0] + HALF_WALL, rect[1] + HALF_WALL, rect[2] - HALF_WALL, rect[3] - HALF_WALL]\n\n/** A solid item: not a rug, not resting on something, and not decoration unless it stands on the floor. */\nexport const isSolid = (item: Json): boolean => !item.flat && !item.on && (!item.decor || item.mount === 'floor')\n\nexport const distanceToRect = (u: number, v: number, rect: Rect): number => Math.hypot(Math.max(rect[0] - u, 0, u - rect[2]), Math.max(rect[1] - v, 0, v - rect[3]))\n\n/** Room types without sockets, switches or circuits. */\nexport const NO_SOCKET_ROOMS: readonly string[] = ['void', 'elevator', 'stairs', 'balcony', 'terrace', 'porch', 'tent']\n\n/** Unit vector pointing out of the house from a wall (`sides[0]` or `sides[1]` is `outside`). */\nexport const outwardOf = (wall: Json): [number, number] => {\n const sign = wall.sides[0] === 'outside' ? -1 : 1\n return wall.axis === 'u' ? [0, sign] : [sign, 0]\n}\n\nexport const sideNameOf = (vector: [number, number]): string => (Math.abs(vector[0]) > Math.abs(vector[1]) ? (vector[0] > 0 ? 'right' : 'left') : vector[1] > 0 ? 'back' : 'front')\n\nexport const alongRange = (wall: Json): [number, number] => (wall.axis === 'u' ? [Math.min(wall.u0, wall.u1), Math.max(wall.u0, wall.u1)] : [Math.min(wall.v0, wall.v1), Math.max(wall.v0, wall.v1)])\n\n/** Exterior ground-floor wall at least 1 m long, the front one first when there is one (a gas meter and an inverter go on them). */\nexport function groundExteriorWalls(plan: Json): Json[] {\n return plan.walls.filter((wall: Json) => wall.exterior && wall.floor === 0 && wall.type === 'wall' && Math.hypot(wall.u1 - wall.u0, wall.v1 - wall.v0) >= 1.0)\n}\n","import type { Json } from './shared'\nimport { HALF_WALL, isSolid, round2 } from './shared'\n\nexport interface WallPoint {\n u: number\n v: number\n /** Position along the wall. */\n c: number\n axis: 'u' | 'v'\n pos: number\n side: number\n nu: number\n nv: number\n a0: number\n a1: number\n exterior: boolean\n windows: Json[]\n /** A solid item within 12 cm of the point reaches higher than `height`. */\n blocked(height: number): boolean\n}\n\nconst STEP = 0.05\nconst SURFACE_OFFSET = 0.012\n\n/** Points on the inner face of the walls of a room, away from corners (`margin`), where sockets, switches and a panel may go. */\nexport function wallPointsOf(plan: Json, room: Json, items: Json[], margin = 0.3): WallPoint[] {\n const points: WallPoint[] = []\n const windows = plan.windows.filter((w: Json) => w.floor === room.floor)\n const solids = items.filter((m) => m.floor === room.floor && !m.outdoor && m.room === room.id && isSolid(m))\n for (const wall of plan.walls) {\n if (wall.floor !== room.floor || wall.type !== 'wall' || !wall.sides.includes(room.id)) continue\n const side = wall.sides[1] === room.id ? 1 : -1\n const a0 = wall.axis === 'u' ? Math.min(wall.u0, wall.u1) : Math.min(wall.v0, wall.v1)\n const a1 = wall.axis === 'u' ? Math.max(wall.u0, wall.u1) : Math.max(wall.v0, wall.v1)\n const pos = wall.axis === 'u' ? wall.v0 : wall.u0\n const nearby = windows.filter((w: Json) => w.axis === wall.axis && Math.abs(w.pos - pos) < 1e-3 && w.at + w.width / 2 > a0 && w.at - w.width / 2 < a1)\n for (let c = a0 + margin; c <= a1 - margin + 1e-9; c += STEP) {\n const u = wall.axis === 'u' ? c : pos + side * (HALF_WALL + SURFACE_OFFSET)\n const v = wall.axis === 'u' ? pos + side * (HALF_WALL + SURFACE_OFFSET) : c\n points.push({\n u: round2(u), v: round2(v), c: round2(c), axis: wall.axis, pos, side, nu: wall.axis === 'u' ? 0 : side, nv: wall.axis === 'u' ? side : 0, a0, a1, exterior: wall.exterior, windows: nearby,\n blocked: (height) => solids.some((m) => m.aabb && Math.hypot(Math.max(m.aabb[0] - u, 0, u - m.aabb[2]), Math.max(m.aabb[1] - v, 0, v - m.aabb[3])) < 0.12 && (m.y || 0) + m.h > height),\n })\n }\n }\n return points\n}\n\nexport const hasWindowAt = (point: WallPoint, y: number, clearance = 0.2): boolean =>\n point.windows.some((w) => y + 0.1 > w.y0 - 0.05 && y - 0.1 < w.y1 + 0.05 && Math.abs(point.c - w.at) < w.width / 2 + clearance)\n\nexport const atDoor = (plan: Json, room: Json, point: WallPoint, clearance: number): boolean =>\n plan.doors.some((d: Json) => d.floor === room.floor && d.axis === point.axis && Math.abs(d.pos - point.pos) < 1e-3 && Math.abs(d.at - point.c) < d.width / 2 + clearance)\n","import type { Layout } from './electrical'\nimport { keyOf } from './electrical'\nimport type { Json } from './shared'\nimport { distanceToRect } from './shared'\nimport { atDoor, hasWindowAt } from './wall-points'\nimport type { WallPoint } from './wall-points'\n\n/** Categories that need a socket of their own. */\nconst APPLIANCES = ['fridge', 'display_fridge', 'freezer', 'tv', 'appliance', 'washing_machine', 'air_conditioner', 'cash_register', 'table_light']\nconst COUNTERS = ['kitchen_cabinet', 'workbench', 'checkout_counter']\nconst LAMPS = ['table_light', 'lamp']\n\nconst needsSocket = (item: Json): boolean => APPLIANCES.includes(item.category) || item.category === 'shower'\n\ninterface Pick {\n point: WallPoint\n y: number\n score: number\n}\n\n/** Sockets: one for each appliance (the shower heater too), then enough for the size of each room, two at counter height in a kitchen with a counter. */\nexport function addOutlets(layout: Layout): void {\n const { plan, items, rooms, electrical, pointsOf } = layout\n let counter = 0\n const outletsOf = (room: Json): Json[] => electrical.outlets.filter((t) => t.room === room.id && t.floor === room.floor)\n const newOutlet = (room: Json, point: WallPoint, y: number): Json => {\n const outlet = { id: `outlet${++counter}`, room: room.id, floor: room.floor, u: point.u, v: point.v, y, c: point.c, axis: point.axis, pos: point.pos, frontU: point.nu, frontV: point.nv, type: '2P+T', voltage: 127 }\n electrical.outlets.push(outlet)\n return outlet\n }\n const counters = items.filter((m) => COUNTERS.includes(m.category) && !m.outdoor)\n const heightFor = (room: Json, point: WallPoint): number =>\n room.type === 'kitchen' && counters.some((m) => m.floor === room.floor && m.room === room.id && distanceToRect(point.u, point.v, m.aabb) < 0.45) ? 1.1 : 0.3\n const valid = (room: Json, point: WallPoint, y: number): boolean =>\n !hasWindowAt(point, y, 0.25) && !atDoor(plan, room, point, 0.45) && !outletsOf(room).some((t) => Math.hypot(t.u - point.u, t.v - point.v) < 0.5 && t.y === y)\n const pick = (room: Json, score: (point: WallPoint) => number, fixedY: number | null, ignoreBlocked?: boolean): Pick | null => {\n let best: Pick | null = null\n for (const point of pointsOf.get(keyOf(room)) ?? []) {\n const y = fixedY ?? heightFor(room, point)\n if (!valid(room, point, y)) continue\n const total = score(point) + (point.blocked(y) && !ignoreBlocked ? 5 : 0)\n if (!best || total < best.score) best = { point, y, score: total }\n }\n return best\n }\n const roomOf = (item: Json): Json | undefined => rooms.find((x) => x.id === item.room && x.floor === item.floor)\n const appliances = items.filter((m) => !m.outdoor && needsSocket(m) && rooms.some((c) => c.id === m.room && c.floor === m.floor) && m.category !== 'table_light')\n for (const item of appliances) connectAppliance(item)\n function connectAppliance(item: Json): void {\n const room = roomOf(item)!\n const target = item.aabb\n const nearest = outletsOf(room).map((t) => ({ t, d: distanceToRect(t.u, t.v, target) })).filter((o) => o.d <= 1.2 && o.t.y <= 1.1).sort((a, b) => a.d - b.d)[0]\n const isShower = item.category === 'shower'\n let outlet: Json | null = nearest && !isShower ? nearest.t : null\n if (!outlet) {\n const height = isShower ? 1.1 : item.y > 0.7 ? 1.1 : null\n const best = pick(room, (p) => { const d = distanceToRect(p.u, p.v, target); return isShower && d < 0.6 ? 50 + d : d }, height)\n let chosen = best\n if (!isShower && (!best || distanceToRect(best.point.u, best.point.v, target) > 1.4)) {\n const behind = pick(room, (p) => distanceToRect(p.u, p.v, target), item.y > 0.7 ? 1.1 : null, true)\n if (behind && (!best || distanceToRect(behind.point.u, behind.point.v, target) < distanceToRect(best.point.u, best.point.v, target))) chosen = behind\n }\n if (chosen) outlet = newOutlet(room, chosen.point, chosen.y)\n }\n if (!outlet) return\n item.outlet = outlet.id\n if (isShower) item.showerHeater = { electric: true, powerW: 5500, outlet: outlet.id }\n }\n for (const room of rooms) {\n const area = room.parts.reduce((sum: number, q: number[]) => sum + (q[2]! - q[0]!) * (q[3]! - q[1]!), 0)\n const wanted = Math.max(room.type === 'kitchen' ? 3 : 2, Math.min(6, Math.round(area / 7)))\n const farthest = (existing: Json[]) => (p: WallPoint) => -Math.min(9, ...existing.map((t) => Math.hypot(t.u - p.u, t.v - p.v)))\n for (let guard = 0; outletsOf(room).length < wanted && guard < 12; guard++) {\n const best = pick(room, farthest(outletsOf(room)), null)\n if (!best) break\n newOutlet(room, best.point, best.y)\n }\n if (room.type !== 'kitchen' || !counters.some((m) => m.room === room.id)) continue\n for (let guard = 0; outletsOf(room).filter((t) => t.y === 1.1).length < 2 && guard < 4; guard++) {\n const existing = outletsOf(room)\n const best = pick(room, (p) => (heightFor(room, p) === 1.1 ? 0 : 20) - Math.min(9, ...existing.map((t) => Math.hypot(t.u - p.u, t.v - p.v))), 1.1)\n if (!best) break\n newOutlet(room, best.point, 1.1)\n }\n }\n for (const item of appliances) {\n if (item.category === 'shower' || !item.outlet) continue\n const room = roomOf(item)!\n const current = outletsOf(room).find((t) => t.id === item.outlet)\n if (!current || distanceToRect(current.u, current.v, item.aabb) <= 1.2) continue\n const other = outletsOf(room).filter((t) => t.y <= 1.1).map((t) => ({ t, d: distanceToRect(t.u, t.v, item.aabb) })).sort((a, b) => a.d - b.d)[0]\n if (other && other.d < distanceToRect(current.u, current.v, item.aabb) && other.d <= 1.2) item.outlet = other.t.id\n }\n for (const item of items.filter((m) => LAMPS.includes(m.category) && !m.outdoor)) {\n const room = roomOf(item)\n if (!room) continue\n const nearest = outletsOf(room).map((t) => ({ t, d: distanceToRect(t.u, t.v, item.aabb) })).sort((a, b) => a.d - b.d)[0]\n if (nearest) item.outlet = nearest.t.id\n }\n}\n\n","import type { Layout } from './electrical'\nimport { heightOf, keyOf } from './electrical'\nimport type { Json } from './shared'\nimport { clamp, round2 } from './shared'\nimport { atDoor, hasWindowAt } from './wall-points'\n\nconst METER_SIZE = { w: 0.35, d: 0.2, h: 0.5 }\n\nexport const mainDoorOf = (plan: Json): Json | undefined => plan.doors.find((p: Json) => p.floor === 0 && p.exterior && p.side === 'front') || plan.doors.find((p: Json) => p.floor === 0 && p.exterior)\n\n/** Pole, drop, meter and descent: the meter on the gate pillar (or the facade without a gate); an apartment or shop has it on the facade. */\nexport function placeEntrance(layout: Layout): void {\n const { plan, electrical } = layout\n const gate = plan.gates.find((g: Json) => g.type === 'pedestrian')\n const door = mainDoorOf(plan)\n const lot = plan.lot\n if (lot && plan.style !== 'commercial') {\n const rect = lot.rect\n const poleU = clamp(gate ? gate.u + 3 : plan.w / 2, rect[0] + 0.5, rect[2] - 0.5)\n const poleV = rect[1] - 0.6\n let meter: Json\n if (gate) {\n const direction = gate.u - gate.width / 2 - 0.4 >= rect[0] + 0.3 ? -1 : 1\n meter = { place: 'gate_pillar', u: round2(gate.u + direction * (gate.width / 2 + 0.25)), v: round2(gate.v), y: 1.4, side: 'front', ...METER_SIZE }\n } else meter = { place: 'facade', u: round2(door ? door.at + 1.2 : plan.w / 2), v: -0.1, y: 1.4, side: 'front', ...METER_SIZE }\n meter.id = 'meter'\n electrical.serviceEntrance = { pole: { u: round2(poleU), v: round2(poleV), h: 7.5 }, drop: [[round2(poleU), round2(poleV), 6.5], [meter.u, meter.v, 2.6]], meter, descent: [[meter.u, meter.v, 2.6], [meter.u, meter.v, 1.65]], internalRun: null }\n } else if (lot === null || plan.style === 'commercial') {\n const front = door ? { u: round2(door.at + 1.0), v: -0.1 } : { u: round2(plan.w / 2), v: -0.1 }\n electrical.serviceEntrance = {\n pole: { u: round2(front.u + 2), v: -3, h: 7.5 }, drop: [[round2(front.u + 2), -3, 6.5], [front.u, front.v, 3.2]],\n meter: { id: 'meter', place: 'facade', u: front.u, v: front.v, y: 1.4, side: 'front', ...METER_SIZE }, descent: [[front.u, front.v, 3.2], [front.u, front.v, 1.65]], internalRun: null,\n }\n }\n}\n\n/** The distribution panel in the room of the main door, on the wall nearest the meter, clear of doors and windows and of tall furniture. */\nexport function placePanel(layout: Layout): void {\n const { plan, rooms, electrical, pointsOf } = layout\n const door = mainDoorOf(plan)\n const room = (door && rooms.find((c) => c.id === door.a && c.floor === 0)) || rooms.find((c) => c.floor === 0) || rooms[0]\n if (!room) return\n const meter = electrical.serviceEntrance?.meter\n const targetU = meter ? meter.u : plan.w / 2\n const targetV = meter ? Math.max(0, meter.v) : 0\n let best: { point: Json; score: number } | null = null\n for (const point of pointsOf.get(keyOf(room)) ?? []) {\n if (point.blocked(1.5) || hasWindowAt(point, 1.5, 0.3) || atDoor(plan, room, point, 0.8)) continue\n const score = Math.hypot(point.u - targetU, point.v - targetV) + (point.exterior ? 0 : 3)\n if (!best || score < best.score) best = { point, score }\n }\n if (!best) best = { point: (pointsOf.get(keyOf(room)) ?? [])[0] as Json, score: 0 }\n if (best.point) {\n const p = best.point\n electrical.panel = { id: 'panel', room: room.id, floor: room.floor, u: p.u, v: p.v, y: 1.5, c: p.c, axis: p.axis, pos: p.pos, frontU: p.nu, frontV: p.nv, w: 0.3, h: 0.4, breakers: 0 }\n }\n if (electrical.serviceEntrance && electrical.panel) {\n const entrance = electrical.serviceEntrance\n entrance.internalRun = [[entrance.meter.u, entrance.meter.v, 0.1], [electrical.panel.u, electrical.panel.v, heightOf(plan, electrical.panel.floor, electrical.panel.y)]]\n }\n}\n","import type { Layout } from './electrical'\nimport { heightOf, keyOf } from './electrical'\nimport { mainDoorOf } from './electrical-entrance'\nimport type { Json } from './shared'\nimport { round2 } from './shared'\nimport { atDoor, hasWindowAt, wallPointsOf } from './wall-points'\n\nconst LAMP_CATEGORIES = ['ceiling_light', 'lamp', 'table_light']\n\nconst lampsOf = (layout: Layout): Json[] => layout.items.filter((m) => !m.outdoor && LAMP_CATEGORIES.includes(m.category))\n\n/** A switch by the latch of the main door of each room that has a lamp (and of the room of the front door, for the outside lamp), at 1.10 m. */\nexport function addSwitches(layout: Layout): void {\n const { plan, items, rooms, electrical, pointsOf } = layout\n const lamps = lampsOf(layout)\n const door = mainDoorOf(plan)\n let counter = 0\n const positionFor = (room: Json): { point: Json; door: Json; latch: boolean } | null => {\n const doors = plan.doors\n .filter((p: Json) => p.floor === room.floor && (p.a === room.id || p.b === room.id))\n .sort((a: Json, b: Json) => (a.opensTo === room.id ? 0 : 1) - (b.opensTo === room.id ? 0 : 1) || (a.width < b.width ? 1 : -1))\n const points = wallPointsOf(plan, room, items, 0.12)\n for (const tolerance of [0.16, 0.3]) {\n for (const d of doors) {\n for (const direction of [1, -1]) {\n const target = d.at + direction * (d.width / 2 + 0.18)\n const point = points.filter((q) => q.axis === d.axis && Math.abs(q.pos - d.pos) < 1e-3 && !hasWindowAt(q, 1.1, 0.2)).sort((a, b) => Math.abs(a.c - target) - Math.abs(b.c - target))[0]\n if (point && Math.abs(point.c - target) <= tolerance && !atDoor(plan, room, point, 0.0) && Math.abs(point.c - d.at) >= d.width / 2 + 0.12) return { point, door: d, latch: direction === 1 }\n }\n }\n }\n return null\n }\n for (const room of rooms.concat(plan.rooms.filter((x: Json) => ['stairs'].includes(x.type)))) {\n const roomLamps = lamps.filter((m) => m.room === room.id && m.floor === room.floor)\n const extra = door && door.a === room.id && room.floor === 0 && plan.lot ? [`outdoor_${door.id}`] : []\n if (!roomLamps.length && !extra.length) continue\n if (!pointsOf.get(keyOf(room))) pointsOf.set(keyOf(room), wallPointsOf(plan, room, items))\n const found = positionFor(room)\n if (!found) continue\n const p = found.point\n electrical.switches.push({ id: `switch${++counter}`, room: room.id, floor: room.floor, u: p.u, v: p.v, y: 1.1, c: p.c, axis: p.axis, pos: p.pos, frontU: p.nu, frontV: p.nv, door: found.door.id, latchSide: found.latch, controls: roomLamps.map((m) => m.id).concat(extra) })\n }\n if (door && plan.lot) {\n const id = `outdoor_${door.id}`\n electrical.outdoorLamps.push({ id, u: round2(door.at + door.width / 2 + 0.32), v: round2(door.pos), y: 2.15, door: door.id, switch: electrical.switches.find((s) => s.controls.includes(id))?.id ?? null })\n }\n}\n\n/** One circuit per room with sockets or switches, and the conduits: from the panel up to the ceiling, along it to the room and down to each point. */\nexport function addConduits(layout: Layout): void {\n const { plan, rooms, electrical } = layout\n const panel = electrical.panel\n const lamps = lampsOf(layout)\n for (const room of rooms) {\n const outlets = electrical.outlets.filter((t) => t.room === room.id && t.floor === room.floor)\n const switches = electrical.switches.filter((i) => i.room === room.id && i.floor === room.floor)\n const roomLamps = lamps.filter((m) => m.room === room.id && m.floor === room.floor)\n if (!outlets.length && !switches.length) continue\n const ceiling = (room.ceiling || plan.floors[room.floor].ceiling) - 0.12\n const part = room.parts[0]\n const centreU = round2((part[0] + part[2]) / 2)\n const centreV = round2((part[1] + part[3]) / 2)\n const circuit = { id: `circuit_${room.id}_${room.floor}`, room: room.id, floor: room.floor, outlets: outlets.map((t) => t.id), switches: switches.map((i) => i.id), lamps: roomLamps.map((m) => m.id), exposed: electrical.exposed, gauge_mm2: outlets.length > 3 ? 2.5 : 1.5 }\n electrical.circuits.push(circuit)\n const base = heightOf(plan, room.floor, 0)\n const riser = panel ? [[panel.u, panel.v, heightOf(plan, panel.floor, panel.y)], [panel.u, panel.v, heightOf(plan, panel.floor, 0) + ceiling]] : []\n if (panel) electrical.conduits.push({ id: `conduit_${circuit.id}`, circuit: circuit.id, from: 'panel', to: room.id, exposed: electrical.exposed, diameter: 0.025, points: riser.concat([[centreU, centreV, base + ceiling]]) })\n for (const point of outlets.concat(switches)) {\n electrical.conduits.push({ id: `conduit_${point.id}`, circuit: circuit.id, from: circuit.id, to: point.id, exposed: electrical.exposed, diameter: 0.02, points: [[centreU, centreV, base + ceiling], [point.u, point.v, base + ceiling], [point.u, point.v, base + point.y]] })\n }\n }\n if (panel) panel.breakers = electrical.circuits.length + 1\n}\n","import type { Json, Rng } from './shared'\nimport { NO_SOCKET_ROOMS } from './shared'\nimport { addOutlets } from './electrical-outlets'\nimport { addConduits, addSwitches } from './electrical-circuits'\nimport { placeEntrance, placePanel } from './electrical-entrance'\nimport { wallPointsOf } from './wall-points'\nimport type { WallPoint } from './wall-points'\n\nexport type EnergyMode = 'grid' | 'tap' | 'offgrid'\n\n/** What a template says about its energy (a shack taps the grid without a meter, a cabin may run off-grid on solar). */\nexport interface EnergyConfig {\n mode: EnergyMode\n solar?: boolean\n}\n\nexport interface Electrical {\n mode: EnergyMode\n serviceEntrance: Json | null\n panel: Json | null\n outlets: Json[]\n switches: Json[]\n circuits: Json[]\n conduits: Json[]\n exposed: boolean\n outdoorLamps: Json[]\n source?: 'solar' | 'lamp'\n}\n\nexport interface ElectricalContext {\n plan: Json\n items: Json[]\n rng: Rng\n energy?: EnergyConfig\n}\n\n/** Shared state of the steps that lay the installation out. */\nexport interface Layout {\n plan: Json\n items: Json[]\n rooms: Json[]\n electrical: Electrical\n pointsOf: Map<string, WallPoint[]>\n}\n\nexport const keyOf = (room: Json): string => `${room.id}@${room.floor}`\n\nconst absolute = (plan: Json, floor: number, y: number): number => (plan.floors[floor] ? plan.floors[floor].y0 : 0) + y\nexport const heightOf = absolute\n\n/**\n * The electrical installation: sockets for the appliances and by room size, the service entrance (pole, drop, meter, descent; a tap without meter for a shack),\n * the panel near the entrance, switches by the door latch, circuits and conduits. Items that plug in are annotated (`outlet`, `showerHeater`).\n */\nexport function planElectrical(context: ElectricalContext): Electrical {\n const { plan, items, rng, energy } = context\n const mode: EnergyMode = energy?.mode ?? 'grid'\n const electrical: Electrical = { mode, serviceEntrance: null, panel: null, outlets: [], switches: [], circuits: [], conduits: [], exposed: false, outdoorLamps: [] }\n electrical.exposed = plan.style === 'budget' ? rng() < 0.65 : plan.style === 'mid' ? rng() < 0.12 : false\n if (mode !== 'grid') electrical.exposed = true\n if (mode === 'offgrid') {\n electrical.source = energy?.solar ? 'solar' : 'lamp'\n return electrical\n }\n const rooms = plan.rooms.filter((room: Json) => !NO_SOCKET_ROOMS.includes(room.type) && !room.outdoor)\n const pointsOf = new Map<string, WallPoint[]>()\n for (const room of rooms) pointsOf.set(keyOf(room), wallPointsOf(plan, room, items))\n const layout: Layout = { plan, items, rooms, electrical, pointsOf }\n addOutlets(layout)\n placeEntrance(layout)\n placePanel(layout)\n addSwitches(layout)\n addConduits(layout)\n if (mode === 'tap' && electrical.serviceEntrance?.meter) {\n const entrance = electrical.serviceEntrance\n const meter = entrance.meter\n entrance.tap = true\n entrance.connection = { u: meter.u, v: meter.v, y: 2.6 }\n entrance.meter = null\n }\n return electrical\n}\n","import type { Rect } from '../types'\nimport type { Json, Rng } from './shared'\nimport { HALF_WALL, clamp, groundExteriorWalls, inner, isSolid, outwardOf, overlaps, round2, sideNameOf } from './shared'\n\nexport const CYLINDER_TYPE = 'cooking_gas_cylinder'\nconst CYLINDER = { w: 0.36, d: 0.36, h: 0.48 }\nconst CYLINDER_KG = 13\n\nexport interface GasMeter {\n id: 'gas.meter'\n u: number\n v: number\n y: number\n side: string\n w: number\n d: number\n h: number\n}\n\nexport interface Gas {\n type: 'piped' | 'cylinder'\n meter: GasMeter | null\n}\n\ninterface Spot {\n mode: 'beside' | 'niche' | 'under'\n x: number\n z: number\n rect: Rect\n outdoor?: boolean\n cabinet?: string\n}\n\n/** Gas meter on the front wall of the ground floor, 1.2 m up. */\nfunction placeMeter(plan: Json): GasMeter | null {\n const segments = groundExteriorWalls(plan).sort((a, b) => (b.sides.includes('outside') ? 1 : 0) - (a.sides.includes('outside') ? 1 : 0) || (a.axis === 'u' && a.v0 === 0 ? -1 : 1))\n const wall = segments.find((w) => w.axis === 'u' && w.v0 === 0) || segments[0]\n if (!wall) return null\n const centre = wall.axis === 'u' ? (wall.u0 + wall.u1) / 2 : (wall.v0 + wall.v1) / 2\n const vector = outwardOf(wall)\n const offset = HALF_WALL + 0.1\n return {\n id: 'gas.meter', u: round2(wall.axis === 'u' ? centre : wall.u0 + vector[0] * offset), v: round2(wall.axis === 'u' ? wall.v0 + vector[1] * offset : centre), y: 1.2, side: sideNameOf(vector), w: 0.3, d: 0.15, h: 0.4,\n }\n}\n\ninterface Context {\n plan: Json\n items: Json[]\n stateItems: Json[]\n rng: Rng\n}\n\nfunction besideStove(context: Context, stove: Json, room: Json, solids: Rect[], doorZones: Rect[]): Spot | undefined {\n const t: [number, number] = [-stove.frontV, stove.frontU]\n const parts = room.parts.map(inner)\n for (const s of context.rng() < 0.5 ? [1, -1] : [-1, 1]) {\n const cx = stove.x + t[0] * s * (stove.w / 2 + CYLINDER.w / 2 + 0.03) - (stove.frontU * (stove.d - CYLINDER.d)) / 2\n const cz = stove.z + t[1] * s * (stove.w / 2 + CYLINDER.w / 2 + 0.03) - (stove.frontV * (stove.d - CYLINDER.d)) / 2\n const rect = [cx - CYLINDER.w / 2, cz - CYLINDER.d / 2, cx + CYLINDER.w / 2, cz + CYLINDER.d / 2].map(round2) as Rect\n const inside = parts.some((q: Rect) => rect[0] >= q[0] - 0.011 && rect[2] <= q[2] + 0.011 && rect[1] >= q[1] - 0.011 && rect[3] <= q[3] + 0.011)\n if (inside && !solids.some((o) => overlaps(rect, o, 0.011)) && !doorZones.some((z) => overlaps(rect, z, 0.011))) return { mode: 'beside', x: cx, z: cz, rect }\n }\n return undefined\n}\n\nfunction inNiche(context: Context, stove: Json, room: Json, doorZones: Rect[]): Spot | undefined {\n const { plan, items, stateItems } = context\n const wall = plan.walls.find(\n (p: Json) =>\n p.exterior && p.floor === stove.floor && p.type === 'wall' && p.sides.includes(room.id) &&\n (p.axis === 'u'\n ? Math.abs(stove.x - clamp(stove.x, p.u0, p.u1)) < 1.6 && Math.abs(stove.z - p.v0) < 1.6\n : Math.abs(stove.z - clamp(stove.z, p.v0, p.v1)) < 1.6 && Math.abs(stove.x - p.u0) < 1.6),\n )\n if (!wall || stove.floor !== 0) return undefined\n const vector = outwardOf(wall)\n const cx = wall.axis === 'u' ? clamp(stove.x, wall.u0 + 0.4, wall.u1 - 0.4) : wall.u0 + vector[0] * (HALF_WALL + CYLINDER.w / 2 + 0.05)\n const cz = wall.axis === 'u' ? wall.v0 + vector[1] * (HALF_WALL + CYLINDER.d / 2 + 0.05) : clamp(stove.z, wall.v0 + 0.4, wall.v1 - 0.4)\n const rect = [cx - CYLINDER.w / 2, cz - CYLINDER.d / 2, cx + CYLINDER.w / 2, cz + CYLINDER.d / 2].map(round2) as Rect\n const blockedByItem = items.some((o) => o.outdoor && isSolid(o) && overlaps(rect, o.aabb, 0.011))\n const blockedByState = stateItems.some((o) => o.outdoor && o.aabb && !o.flat && o.mount !== 'ground' && overlaps(rect, o.aabb, 0.011))\n const blockedByPath = plan.paths.some((c: Json) => c.rects.some((z: Rect) => overlaps(rect, z, 0.011)))\n const blockedByGate = plan.gates.some((g: Json) => g.zones.some((z: Rect) => overlaps(rect, z, 0.011)))\n const blockedByFence = !plan.lot || plan.lot.perimeter.some((q: Json) => overlaps(rect, [Math.min(q.u0, q.u1) - HALF_WALL, Math.min(q.v0, q.v1) - HALF_WALL, Math.max(q.u0, q.u1) + HALF_WALL, Math.max(q.v0, q.v1) + HALF_WALL], 0.011))\n if (blockedByItem || blockedByState || blockedByPath || doorZones.some((z) => overlaps(rect, z, 0.011)) || blockedByGate || blockedByFence) return undefined\n return { mode: 'niche', x: cx, z: cz, rect, outdoor: true }\n}\n\nfunction underCounter(context: Context, stove: Json): Spot | undefined {\n const distance = (m: Json): number => Math.hypot(m.x - stove.x, m.z - stove.z)\n const cabinets = context.items\n .filter(\n (m) => m.floor === stove.floor && m.room === stove.room && !m.outdoor && !m.on && !m.flat && ['kitchen_cabinet', 'workbench'].includes(m.category) && m.aabb && m.id !== stove.id &&\n Math.min(m.aabb[2] - m.aabb[0], m.aabb[3] - m.aabb[1]) >= CYLINDER.d - 0.011 && Math.max(m.aabb[2] - m.aabb[0], m.aabb[3] - m.aabb[1]) >= CYLINDER.w + 0.02,\n )\n .sort((a, b) => (a.category === 'kitchen_cabinet' ? 0 : 1) - (b.category === 'kitchen_cabinet' ? 0 : 1) || distance(a) - distance(b))\n for (const cabinet of cabinets) {\n if (distance(cabinet) > 3) continue\n const box = cabinet.aabb as Rect\n const hw = CYLINDER.w / 2\n const hd = CYLINDER.d / 2\n const cx = clamp(stove.x, box[0] + hw + 0.01, box[2] - hw - 0.01)\n const cz = clamp(stove.z, box[1] + hd + 0.01, box[3] - hd - 0.01)\n const rect = [cx - hw, cz - hd, cx + hw, cz + hd].map(round2) as Rect\n if (rect[0] < box[0] || rect[2] > box[2] || rect[1] < box[1] || rect[3] > box[3] || overlaps(rect, stove.aabb, 0.011)) continue\n return { mode: 'under', x: cx, z: cz, rect, cabinet: cabinet.id }\n }\n return undefined\n}\n\nconst PLACEMENT = { beside: 'beside', niche: 'external_niche', under: 'under_counter' } as const\n\nfunction cylinderItem(stove: Json, spot: Spot): Json {\n const item: Json = {\n id: `${stove.room}.${CYLINDER_TYPE}`, type: CYLINDER_TYPE, category: CYLINDER_TYPE, x: round2(spot.x), z: round2(spot.z), ry: 0, w: CYLINDER.w, d: CYLINDER.d, h: CYLINDER.h, y: 0,\n frontU: -stove.frontU, frontV: -stove.frontV, room: stove.room, floor: stove.floor, outdoor: !!spot.outdoor, slot: 'cylinder', on: null, mode: null, clearance: 0, flat: false, low: false,\n aabb: spot.rect, link: stove.id, placement: PLACEMENT[spot.mode], hose: [[round2(spot.x), round2(spot.z), 0.3], [stove.x, stove.z, 0.5]], capacityKg: CYLINDER_KG,\n }\n if (spot.cabinet) {\n item.on = spot.cabinet\n item.hidden = true\n }\n if (spot.outdoor) item.floor = -1\n item.color = stove.color\n return item\n}\n\n/**\n * Gas for the stoves of the house: a cylinder beside the stove, in an outside niche with a hose or under the counter, or (high-end houses, or when\n * nothing fits) piped gas with a meter on the facade. The cylinders are added to `items`; the stoves are annotated (`gas`, `cylinder`, `gasMeter`).\n */\nexport function planGas(context: Context): Gas | null {\n const { plan, items, stateItems, rng } = context\n const stoves = items.filter((m) => m.category === 'stove' && !m.outdoor)\n if (!stoves.length) return null\n const high = plan.style === 'high'\n const piped = plan.style !== 'commercial' && (high ? rng() < 0.8 : plan.style === 'mid' ? rng() < 0.1 : false)\n const out: Gas = { type: piped ? 'piped' : 'cylinder', meter: null }\n const ensureMeter = (): void => {\n if (!out.meter) out.meter = placeMeter(plan)\n }\n for (const stove of stoves) {\n const room = plan.rooms.find((c: Json) => c.id === stove.room && c.floor === stove.floor)\n if (!room) continue\n stove.gas = piped ? 'piped' : 'cylinder'\n if (piped) {\n ensureMeter()\n stove.gasMeter = 'gas.meter'\n continue\n }\n const solids = items.filter((m) => m.floor === stove.floor && m.room === stove.room && isSolid(m) && m.id !== stove.id).map((m) => m.aabb as Rect)\n .concat(stateItems.filter((m) => m.aabb && m.room === stove.room && m.floor === stove.floor && !m.flat && !m.on && m.mount !== 'window' && m.mount !== 'ground').map((m) => m.aabb as Rect))\n const doorZones = plan.doors.filter((p: Json) => p.floor === stove.floor).flatMap((p: Json) => p.zones as Rect[])\n const order: Spot['mode'][] = rng() < 0.7 ? ['beside', 'niche', 'under'] : ['niche', 'beside', 'under']\n let spot: Spot | undefined\n for (const mode of order) {\n if (spot) break\n spot = mode === 'beside' ? besideStove(context, stove, room, solids, doorZones) : mode === 'niche' ? inNiche(context, stove, room, doorZones) : underCounter(context, stove)\n }\n if (!spot) {\n stove.gas = 'piped'\n out.type = 'piped'\n ensureMeter()\n stove.gasMeter = 'gas.meter'\n continue\n }\n const cylinder = cylinderItem(stove, spot)\n items.push(cylinder)\n stove.cylinder = cylinder.id\n }\n return out\n}\n","import type { Json } from './shared'\nimport { round2 } from './shared'\nimport type { WaterTank } from '../types'\n\nconst FIXTURES: Record<string, string> = { kitchen_cabinet: 'tap', washbasin: 'tap', shower: 'shower', toilet: 'flush', laundry_tub: 'tub', washing_machine: 'machine' }\nconst FLOW_LPM: Record<string, number> = { tap: 6, shower: 9, flush: 6, tub: 8, machine: 12 }\nconst POINT_HEIGHT: Record<string, number> = { shower: 2.1, flush: 0.9, machine: 0.8 }\nconst DEFAULT_CAPACITY = { budget: 500, mid: 1000 }\n\nexport interface PlumbingContext {\n plan: Json\n items: Json[]\n tank: WaterTank | null\n}\n\nconst absolute = (plan: Json, floor: number, y: number): number => (plan.floors[floor] ? plan.floors[floor].y0 : 0) + y\n\n/**\n * Plumbing as logic: a point for every tap, shower, toilet, tub and machine, and the runs you can see: the outlet of the tank, under each sink and in the wall\n * from the tank to every wet room (hidden in the wall, it shows only where the wall breaks).\n */\nexport function planPlumbing(context: PlumbingContext): Json {\n const { plan, items, tank } = context\n const fixtures = items.filter((m) => FIXTURES[m.category] && !m.decor)\n const points: Json[] = []\n const runs: Json[] = []\n const capacity = tank?.capacity ?? (plan.style === 'budget' ? DEFAULT_CAPACITY.budget : plan.style === 'mid' ? DEFAULT_CAPACITY.mid : plan.tpl?.id === 'mansion' ? 3000 : 2000)\n const plumbing: Json = { tank: tank ? 'water_tank' : null, capacityL: tank || !plan.tpl.noWalls ? capacity : 0, points, visibleRuns: runs }\n const top = plan.floors.length - 1\n fixtures.forEach((item, index) => {\n const kind = FIXTURES[item.category]!\n points.push({ id: `pt${index + 1}`, kind, item: item.id, room: item.room, floor: item.outdoor ? -1 : item.floor, u: item.x, v: item.z, y: POINT_HEIGHT[kind] ?? 0.9, flowLpm: FLOW_LPM[kind], run: null })\n })\n if (!tank) return plumbing\n const slabY = absolute(plan, top, plan.floors[top].ceiling)\n const tankY = tank.place === 'raised_slab' ? tank.platform!.topY : tank.place === 'attic' ? slabY + 0.5 : tank.y\n runs.push({ id: 'run_outlet', from: 'water_tank', to: 'ceiling', points: [[tank.u, tank.v, round2(tankY + 0.15)], [tank.u, tank.v, round2(slabY - 0.15)]], diameter: 0.032, exposed: 'tank_outlet' })\n for (const point of points) {\n const item = fixtures.find((x) => x.id === point.item)!\n if (point.kind !== 'tap' || item.outdoor) continue\n const front = [item.frontU || 0, item.frontV || 1]\n const behind = [item.x - front[0]! * (item.d / 2 + 0.02), item.z - front[1]! * (item.d / 2 + 0.02)]\n runs.push({ id: `run_under_${point.id}`, from: 'valve', to: point.id, points: [[round2(behind[0]!), round2(behind[1]!), absolute(plan, item.floor, 0.5)], [item.x, item.z, absolute(plan, item.floor, 0.5)], [item.x, item.z, absolute(plan, item.floor, 0.75)]], diameter: 0.025, exposed: 'under_sink' })\n }\n const wet: { room: string; floor: number; points: Json[] }[] = []\n for (const point of points) {\n if (!wet.some((c) => c.room === point.room && c.floor === point.floor)) wet.push({ room: point.room, floor: point.floor, points: points.filter((q) => q.room === point.room && q.floor === point.floor) })\n }\n for (const room of wet) {\n const found = plan.rooms.find((c: Json) => c.id === room.room && c.floor === room.floor)\n const zone = plan.zones.find((z: Json) => z.id === room.room)\n const parts = (found || zone || { parts: [[tank.u, tank.v, tank.u, tank.v]] }).parts\n const centreU = (parts[0][0] + parts[0][2]) / 2\n const centreV = (parts[0][1] + parts[0][3]) / 2\n const ceiling = found ? found.ceiling || plan.floors[found.floor].ceiling : 2.8\n const y0 = found ? absolute(plan, found.floor, 0) : 0\n const id = `run_wall_${room.room}${room.floor === -1 ? '_outside' : `_${room.floor}`}`\n runs.push({ id, from: 'water_tank', to: room.room, points: [[tank.u, tank.v, round2(slabY - 0.15)], [round2(centreU), round2(centreV), round2(slabY - 0.15)], [round2(centreU), round2(centreV), round2(y0 + ceiling - 0.15)], [round2(centreU), round2(centreV), round2(y0 + 0.6)]], diameter: 0.025, exposed: 'wall' })\n for (const point of room.points) point.run = id\n }\n return plumbing\n}\n","import { outwardOf, groundExteriorWalls, HALF_WALL, round2, sideNameOf } from './shared'\nimport type { Json, Rng } from './shared'\nimport type { EnergyConfig } from './electrical'\n\nconst PANEL_WIDTH = 1.0\nconst PANEL_LENGTH = 1.65\nconst NO_PANELS_UNDER: readonly string[] = ['void', 'elevator', 'stairs', 'balcony', 'terrace', 'porch']\n\nexport interface SolarContext {\n plan: Json\n rng: Rng\n energy?: EnergyConfig\n}\n\n/** Inverter on a side wall of the ground floor, 1.5 m up. */\nfunction placeInverter(plan: Json): Json | null {\n const wall = groundExteriorWalls(plan).filter((q) => q.sides.includes('outside')).sort((a, b) => (a.axis === 'v' ? 0 : 1) - (b.axis === 'v' ? 0 : 1))[0]\n if (!wall) return null\n const vector = outwardOf(wall)\n const centre = wall.axis === 'u' ? (wall.u0 + wall.u1) / 2 : (wall.v0 + wall.v1) / 2\n const offset = HALF_WALL + 0.08\n return { id: 'inverter', u: round2(wall.axis === 'u' ? centre : wall.u0 + vector[0] * offset), v: round2(wall.axis === 'u' ? wall.v0 + vector[1] * offset : centre), y: 1.5, side: sideNameOf(vector), w: 0.4, d: 0.15, h: 0.5, outdoor: true, link: 'panel' }\n}\n\n/**\n * Solar panels: about 6% of budget houses, 25% of mid and 50% of the rest; on the roof slope that faces north or on tilted racks on a flat roof, with the\n * inverter on the wall. A template with its own energy decides (`energy.solar`).\n */\nexport function planSolar(context: SolarContext): Json | null {\n const { plan, rng, energy } = context\n if (!plan.lot || plan.style === 'commercial' || !plan.facade) return null\n const chance = plan.style === 'budget' ? 0.06 : plan.style === 'mid' ? 0.25 : 0.5\n const forced = energy ? (energy.solar ? 1 : 0) : null\n const draw = rng()\n if (forced !== null ? !forced : draw >= chance) return null\n const floor = plan.floors.length - 1\n const level = plan.floors[floor]\n const flat = plan.facade.roof === 'slab'\n const tops = plan.rooms.filter((c: Json) => c.floor === floor && !NO_PANELS_UNDER.includes(c.type))\n if (!tops.length) return null\n const parts: number[][] = tops.flatMap((c: Json) => c.parts)\n const box = [Math.min(...parts.map((q) => q[0]!)), Math.min(...parts.map((q) => q[1]!)), Math.max(...parts.map((q) => q[2]!)), Math.max(...parts.map((q) => q[3]!))] as [number, number, number, number]\n const north = rng() < 0.5 ? 'front' : 'back'\n const angle = flat ? 15 : 25\n const projection = round2(PANEL_LENGTH * Math.cos((angle * Math.PI) / 180))\n const margin = 0.6\n const uStart = box[0] + margin\n const uEnd = box[2] - margin\n const columns = Math.max(1, Math.floor((uEnd - uStart) / (PANEL_WIDTH + 0.05)))\n const vMiddle = (box[1] + box[3]) / 2\n const vArea = flat ? [box[1] + margin, box[3] - margin] : north === 'front' ? [box[1] + 0.4, vMiddle - 0.2] : [vMiddle + 0.2, box[3] - 0.4]\n const step = flat ? projection + 0.5 : projection + 0.05\n const rowsMax = Math.max(1, Math.floor((vArea[1]! - vArea[0]!) / step))\n const wanted = forced !== null ? 1 + Math.floor(rng() * 2) : 3 + Math.floor(rng() * (plan.style === 'high' ? 12 : 8))\n const rows = Math.max(1, Math.min(rowsMax, Math.ceil(wanted / columns)))\n const count = Math.min(wanted, rows * columns)\n const u0 = uStart + (uEnd - uStart - columns * (PANEL_WIDTH + 0.05)) / 2\n const vStart = north === 'front' ? vArea[0]! : vArea[1]! - rows * step\n const panels: Json[] = []\n for (let k = 0; k < count; k++) {\n const row = Math.floor(k / columns)\n const column = k % columns\n panels.push({ id: `pv${k + 1}`, u: round2(u0 + column * (PANEL_WIDTH + 0.05) + PANEL_WIDTH / 2), v: round2(vStart + row * step + (flat ? 0.25 : 0) + projection / 2), w: PANEL_WIDTH, d: projection, length: PANEL_LENGTH })\n }\n const area = [round2(u0), round2(vStart), round2(u0 + columns * (PANEL_WIDTH + 0.05)), round2(vStart + rows * step)]\n return { type: flat ? 'slab_rack' : 'roof', orientation: 'north', north, slopeSide: flat ? null : north, tilt: angle, area, areaM2: round2(count * PANEL_WIDTH * PANEL_LENGTH), count, floor, y: round2(level.y0 + level.ceiling), panels, inverter: placeInverter(plan) }\n}\n","import type { FindsQuery, FindStack } from '@adatechnology/game-floorplan'\n\nimport type { WaterTank } from '../types'\nimport { hasContent } from './content'\nimport type { EnergyConfig, Electrical } from './electrical'\nimport { planElectrical } from './electrical'\nimport { planGas } from './gas'\nimport type { Gas } from './gas'\nimport { planPlumbing } from './plumbing'\nimport type { Json, Rng } from './shared'\nimport { planSolar } from './solar'\n\nexport interface Utilities {\n gas: Gas | null\n electrical: Electrical\n solar: Json | null\n plumbing: Json\n}\n\nexport interface UtilitiesContext {\n plan: Json\n items: Json[]\n stateItems: Json[]\n tank: WaterTank | null\n energy?: EnergyConfig\n /** Seeded stream by name: `gas`, `electrical`, `solar`. */\n rngFor(key: string): Rng\n}\n\n/** Gas, electricity, solar panels and plumbing of a house, in the order that lets the later ones see the cylinders the first adds to `items`. */\nexport function planUtilities(context: UtilitiesContext): Utilities {\n const { plan, items, stateItems, tank, energy, rngFor } = context\n const gas = planGas({ plan, items, stateItems, rng: rngFor('gas') })\n const electrical = planElectrical({ plan, items, rng: rngFor('eletrica'), ...(energy ? { energy } : {}) })\n const solar = planSolar({ plan, rng: rngFor('solar'), ...(energy ? { energy } : {}) })\n const plumbing = planPlumbing({ plan, items, tank })\n return { gas, electrical, solar, plumbing }\n}\n\nconst OVERHEAD = 'overhead_cabinet'\nconst ALWAYS_HOLD: readonly string[] = ['trash_bin', 'outdoor_bin', 'mailbox']\n\nexport interface ContentsContext {\n items: Json[]\n state: string\n place: string\n /** Outbreak days and region of the world, passed to the finds provider. */\n day?: number\n region?: string\n rngFor(key: string): Rng\n findsFor(query: FindsQuery): readonly FindStack[]\n}\n\n/** What every container holds, asked of the registered finds provider: by item id, and `<id>#overhead` for the wall cabinet over a sink. */\nexport function planContents(context: ContentsContext): Record<string, readonly FindStack[]> {\n const out: Record<string, readonly FindStack[]> = {}\n const ask = (item: Json, container: string, key: string): readonly FindStack[] =>\n context.findsFor({ place: context.place, container, state: context.state, rng: context.rngFor(key), footprint: item.w * item.d, key: item.id, ...(context.day === undefined ? {} : { day: context.day }), ...(context.region === undefined ? {} : { region: context.region }) })\n for (const item of context.items) {\n if (item.decor && item.mount !== 'wall_top') continue\n const container = hasContent(item.type) ? item.type : item.category\n if (!hasContent(container)) continue\n if (!ALWAYS_HOLD.includes(container) && item.decor) continue\n out[item.id] = ask(item, container, `content:${item.id}`)\n if (container === 'kitchen_cabinet' && item.overhead !== false) out[`${item.id}#overhead`] = ask(item, OVERHEAD, `content:${item.id}:overhead`)\n }\n return out\n}\n","import type { Rect } from '../types'\nimport type { Json, Rng } from './shared'\nimport { isSolid, overlaps, round2 } from './shared'\n\nconst WALL = 0.15\nconst DOOR_WIDTH = 0.85\nconst DOOR_HEIGHT = 2.1\nconst USES: Record<string, string[]> = { guest_room: ['single_bed', 'nightstand'], office: ['desk', 'shelf_unit_small'], storage: ['tool_shelf', 'crate'], gourmet: ['dining_table_small', 'workbench'] }\nconst USE_WEIGHTS: Record<string, number> = { guest_room: 3, office: 2, storage: 2, gourmet: 2 }\nconst PATH_WIDTH = 1.0\n\nexport interface OutbuildingContext {\n plan: Json\n items: Json[]\n catalog: Record<string, Json>\n rngFor(key: string): Rng\n}\n\n/**\n * Name of the seeded stream of an outbuilding. It is the name the Visor de casas 3D gave it (`edif:<room>.<slot>` in Portuguese: `quintal.edicula`), kept verbatim so that an\n * old seed draws the same use and furniture; it never appears in the output.\n */\nconst LEGACY_ROOMS: Record<string, string> = { backyard: 'quintal' }\nconst LEGACY_SLOTS: Record<string, string> = { outbuilding: 'edicula' }\nexport const streamOf = (itemId: string): string => {\n const [room = '', ...slot] = itemId.split('.')\n return `edif:${LEGACY_ROOMS[room] ?? room}.${slot.map((part) => LEGACY_SLOTS[part] ?? part).join('.')}`\n}\n\nfunction pickWeighted(rng: Rng, weights: Record<string, number>): string {\n const keys = Object.keys(weights)\n let x = rng() * keys.reduce((sum, key) => sum + weights[key]!, 0)\n for (const key of keys) {\n x -= weights[key]!\n if (x < 0) return key\n }\n return keys[keys.length - 1]!\n}\n\nconst sideOf = (x: number, z: number): string => (Math.abs(x) > Math.abs(z) ? (x > 0 ? 'right' : 'left') : z > 0 ? 'back' : 'front')\n\ninterface Frame {\n n: [number, number]\n t: [number, number]\n cx: number\n cz: number\n depth: number\n width: number\n horizontal: boolean\n sideToMiddle: number\n}\n\nconst at = (frame: Frame, a: number, b: number): [number, number] => [frame.cx + frame.n[0] * a + frame.t[0] * b, frame.cz + frame.n[1] * a + frame.t[1] * b]\n\nfunction opening(frame: Frame, id: string, a: number, b: number, vector: [number, number], width: number, extra: Json): Json {\n const [u, v] = at(frame, a, b)\n const alongU = Math.abs(vector[0]) !== 1\n return { id, axis: alongU ? 'u' : 'v', pos: round2(alongU ? v : u), at: round2(alongU ? u : v), u: round2(u), v: round2(v), width: round2(width), side: sideOf(vector[0], vector[1]), ...extra }\n}\n\nfunction wallsOf(box: Rect, door: Json, height: number): Json[] {\n const walls: Json[] = []\n const sides = [\n { axis: 'u', pos: box[1], i0: box[0], i1: box[2], side: 'front' }, { axis: 'u', pos: box[3], i0: box[0], i1: box[2], side: 'back' },\n { axis: 'v', pos: box[0], i0: box[1], i1: box[3], side: 'left' }, { axis: 'v', pos: box[2], i0: box[1], i1: box[3], side: 'right' },\n ]\n for (const w of sides) {\n const cut = w.axis === door.axis && Math.abs(w.pos - door.pos) < 0.02 ? [door.at - door.width / 2, door.at + door.width / 2] : null\n const segments = cut ? [[w.i0, cut[0]!], [cut[1]!, w.i1]] : [[w.i0, w.i1]]\n for (const [x0, x1] of segments) {\n if (x1! - x0! <= 1e-3) continue\n walls.push(w.axis === 'u' ? { axis: 'u', u0: round2(x0!), v0: round2(w.pos), u1: round2(x1!), v1: round2(w.pos), thickness: WALL, h: height, side: w.side } : { axis: 'v', u0: round2(w.pos), v0: round2(x0!), u1: round2(w.pos), v1: round2(x1!), thickness: WALL, h: height, side: w.side })\n }\n }\n return walls\n}\n\nfunction furnish(context: OutbuildingContext, frame: Frame, use: string, interior: Rect, insideDoor: Rect): Json[] {\n const placed: Json[] = []\n USES[use]!.forEach((type, k) => {\n const def = context.catalog[type]!\n const facing: [number, number] = k === 0 ? frame.n : [frame.t[0] * frame.sideToMiddle, frame.t[1] * frame.sideToMiddle]\n const [a, b] = k === 0 ? [-frame.depth / 2 + WALL + def.d / 2, frame.sideToMiddle * -0.4] : [-0.1, -frame.sideToMiddle * (frame.width / 2 - WALL - def.d / 2)]\n const [u, v] = at(frame, a, b)\n const eu = Math.abs(facing[0]) === 1 ? def.d : def.w\n const ev = Math.abs(facing[0]) === 1 ? def.w : def.d\n const box = [u - eu / 2, v - ev / 2, u + eu / 2, v + ev / 2].map(round2) as Rect\n if (box[0] < interior[0] - 0.011 || box[2] > interior[2] + 0.011 || box[1] < interior[1] - 0.011 || box[3] > interior[3] + 0.011 || overlaps(box, insideDoor) || placed.some((o) => overlaps(box, o.aabb))) return\n placed.push({ type, category: def.category, u: round2(u), v: round2(v), w: def.w, d: def.d, h: def.h, ry: Math.atan2(facing[0], facing[1]), frontU: facing[0], frontV: facing[1], aabb: box })\n })\n return placed\n}\n\n/**\n * The outbuilding at the back of the yard is a small building of its own: walls with a gap for the door, a door of 0.85 m facing the yard, two windows and the\n * furniture of a drawn use (guest room, office, storage, gourmet space).\n */\nexport function planOutbuildings(context: OutbuildingContext): Json[] {\n const { plan, items } = context\n const lot = plan.lot\n if (!lot) return []\n const out: Json[] = []\n for (const item of items.filter((m) => m.category === 'outbuilding')) {\n const rng = context.rngFor(streamOf(item.id))\n const [a0, a1, a2, a3] = item.aabb as Rect\n const n: [number, number] = [item.frontU, item.frontV]\n const t: [number, number] = [-item.frontV, item.frontU]\n const horizontal = Math.abs(item.frontU) === 1\n const cx = (a0 + a2) / 2\n const cz = (a1 + a3) / 2\n const depth = horizontal ? a2 - a0 : a3 - a1\n const width = horizontal ? a3 - a1 : a2 - a0\n const sideToMiddle = ((lot.rect[0] + lot.rect[2]) / 2 - cx) * t[0] + ((lot.rect[1] + lot.rect[3]) / 2 - cz) * t[1] >= 0 ? 1 : -1\n const frame: Frame = { n, t, cx, cz, depth, width, horizontal, sideToMiddle }\n const doorOffset = sideToMiddle * (width / 2 - 0.95)\n const door = opening(frame, `${item.id}.d0`, depth / 2, doorOffset, n, DOOR_WIDTH, { height: DOOR_HEIGHT, exterior: true })\n const windowFront = opening(frame, `${item.id}.w0`, depth / 2, -sideToMiddle * (width / 2 - 0.9), n, Math.min(1.0, width / 2 - 0.6), { y0: 1.0, y1: 2.0 })\n const windowSide = opening(frame, `${item.id}.w1`, 0, (sideToMiddle * width) / 2, [t[0] * sideToMiddle, t[1] * sideToMiddle], Math.min(1.0, depth - 0.8), { y0: 1.0, y1: 2.0 })\n const [p, q] = [at(frame, depth / 2, doorOffset), at(frame, depth / 2 - 0.9, doorOffset)]\n door.zone = (horizontal ? [Math.min(p[0], q[0]), p[1] - door.width / 2, Math.max(p[0], q[0]), p[1] + door.width / 2] : [p[0] - door.width / 2, Math.min(p[1], q[1]), p[0] + door.width / 2, Math.max(p[1], q[1])]).map(round2)\n const interior: Rect = [a0 + WALL, a1 + WALL, a2 - WALL, a3 - WALL]\n const use = pickWeighted(rng, USE_WEIGHTS)\n out.push({ id: item.id, type: 'outbuilding', use, floor: 0, aabb: (item.aabb as Rect).slice(), interior: [interior.map(round2)], ceiling: item.h, thickness: WALL, front: n, walls: wallsOf(item.aabb, door, item.h), doors: [door], windows: [windowFront, windowSide], items: furnish(context, frame, use, interior, door.zone) })\n }\n return out\n}\n\n/** A pedestrian path from every door of an outbuilding: a 1 m stub out of the door and an L to the nearest existing path, away from furniture, the building and the fence. */\nexport function addOutbuildingPaths(lot: Json, outbuildings: Json[], items: Json[]): void {\n const half = PATH_WIDTH / 2\n const rect = lot.rect as Rect\n const solids = items.filter((m) => m.outdoor && m.aabb && isSolid(m)).map((m) => m.aabb as Rect)\n const fence = lot.perimeter.map((q: Json) => [Math.min(q.u0, q.u1) - 0.075, Math.min(q.v0, q.v1) - 0.075, Math.max(q.u0, q.u1) + 0.075, Math.max(q.v0, q.v1) + 0.075] as Rect)\n const strip = (p: number[], q: number[]): Rect => [Math.min(p[0]!, q[0]!) - half, Math.min(p[1]!, q[1]!) - half, Math.max(p[0]!, q[0]!) + half, Math.max(p[1]!, q[1]!) + half]\n for (const building of outbuildings) {\n for (const door of building.doors as Json[]) {\n if (lot.paths.some((c: Json) => c.to === door.id)) continue\n const z = door.zone as Rect\n const zc = door.axis === 'v' ? (z[0] + z[2]) / 2 : (z[1] + z[3]) / 2\n const outside = zc > door.pos ? -1 : 1\n const A = door.axis === 'v' ? [door.pos, door.at] : [door.at, door.pos]\n const S = door.axis === 'v' ? [door.pos + outside * PATH_WIDTH, door.at] : [door.at, door.pos + outside * PATH_WIDTH]\n const stub: Rect = door.axis === 'v' ? [Math.min(A[0]!, S[0]!), A[1]! - half, Math.max(A[0]!, S[0]!), A[1]! + half] : [A[0]! - half, Math.min(A[1]!, S[1]!), A[0]! + half, Math.max(A[1]!, S[1]!)]\n const cost = (rs: Rect[]): number => {\n let n = 0\n for (const r of rs) {\n const c: Rect = [r[0] + 0.02, r[1] + 0.02, r[2] - 0.02, r[3] - 0.02]\n for (const q of solids) if (overlaps(c, q, 0.011)) n += 2\n if (overlaps(c, building.aabb, 0.011)) n += 3\n for (const q of fence) if (overlaps(c, q, 0.011)) n += 3\n if (r[0] < rect[0] || r[1] < rect[1] || r[2] > rect[2] || r[3] > rect[3]) n += 3\n }\n return n\n }\n let best: { v: number; k: { rects: Rect[]; points: number[][] }; from: string | null } | null = null\n for (const c of lot.paths.filter((p: Json) => p.type === 'pedestrian' || p.id === 'cargo_path')) {\n for (const r of c.rects as Rect[]) {\n const T = [Math.min(Math.max(S[0]!, r[0] + half), r[2] - half), Math.min(Math.max(S[1]!, r[1] + half), r[3] - half)]\n const candidates: { rects: Rect[]; points: number[][] }[] = []\n if (Math.abs(T[0]! - S[0]!) < 1e-6 && Math.abs(T[1]! - S[1]!) < 1e-6) candidates.push({ rects: [stub], points: [A, S] })\n else for (const via of [[T[0]!, S[1]!], [S[0]!, T[1]!]]) candidates.push({ rects: [stub, strip(S, via), strip(via, T)].filter((q) => q[2] - q[0] > 1e-6), points: [A, S, via, T] })\n for (const k of candidates) {\n const distance = k.points.slice(1).reduce((sum, q, i) => sum + Math.abs(q[0]! - k.points[i]![0]!) + Math.abs(q[1]! - k.points[i]![1]!), 0)\n const value = cost(k.rects.slice(1)) * 100 + distance\n if (!best || value < best.v) best = { v: value, k, from: c.from }\n }\n }\n }\n const chosen = best ? best.k : { rects: [stub], points: [A, S] }\n lot.paths.push({ id: `path_${door.id}`, type: 'pedestrian', from: best ? best.from : null, to: door.id, width: PATH_WIDTH, rects: chosen.rects.map((q) => q.map(round2)), points: chosen.points.map((q) => q.map(round2)) })\n }\n }\n}\n","import { round2 } from './geometry'\nimport type { Rect, StructureSource, WaterTank } from './types'\n\ntype Rng = () => number\n\nconst TANK_SIDE = 1.1\nconst NOT_UNDER_TANK = ['void', 'elevator', 'stairs', 'balcony', 'porch']\nconst WET_ROOMS = ['bathroom', 'kitchen', 'laundry']\nconst ATTIC_CHANCE = 0.12\nconst clamp = (value: number, low: number, high: number): number => Math.max(low, Math.min(high, value))\n\nexport interface TankPlanOptions {\n /** Litres by template id or style id (default: budget 500, mid 1000, mansion 3000, any other 2000). */\n capacities?: Record<string, number>\n /** Where the tank goes; default: on the slab of a flat roof, else on a raised platform (the attic one time in eight). */\n location?: (source: StructureSource, rng: Rng) => WaterTank['place']\n /** A template with its own tank (a trestle for the rural water) answers here instead. */\n custom?: (source: StructureSource, rng: Rng) => WaterTank | null\n}\n\nconst DEFAULT_CAPACITIES: Record<string, number> = { budget: 500, mid: 1000, mansion: 3000 }\n\nfunction capacityOf(source: StructureSource, capacities: Record<string, number>): number {\n return capacities[source.style ?? ''] ?? capacities[source.template ?? ''] ?? 2000\n}\n\n/** Candidate spot: the room part with the least weight (wet rooms first, terraces last, near the reference point or the middle). */\nfunction bestSpot(source: StructureSource, floor: number, reference: { u: number; v: number } | undefined): { roomType: string; roomId: string; rect: Rect } | undefined {\n const centre: [number, number] = reference ? [reference.u, reference.v] : [source.w / 2, source.d / 2]\n let best: { roomType: string; roomId: string; rect: Rect; weight: number } | undefined\n for (const room of source.rooms.filter((r) => r.floor === floor && !NOT_UNDER_TANK.includes(r.type))) {\n for (const part of room.parts) {\n const rect: Rect = [part[0] + 0.4, part[1] + 0.4, part[2] - 0.4, part[3] - 0.4]\n if (rect[2] - rect[0] < TANK_SIDE || rect[3] - rect[1] < TANK_SIDE) continue\n const base = WET_ROOMS.includes(room.type) ? 0 : room.type === 'terrace' ? 500 : 100\n const weight = base + Math.hypot((rect[0] + rect[2]) / 2 - centre[0], (rect[1] + rect[3]) / 2 - centre[1])\n if (!best || weight < best.weight) best = { roomType: room.type, roomId: room.id, rect, weight }\n }\n }\n return best\n}\n\nfunction raisedPlatform(source: StructureSource, u: number, v: number, baseY: number): NonNullable<WaterTank['platform']> {\n const margin = 0.12\n const edge = Math.max(0, Math.min(u, source.w - u, v, source.d - v))\n const rise = round2(clamp(edge * 0.35 + 0.7, 1.1, 2.4))\n const thickness = 0.12\n const reach = TANK_SIDE / 2 + margin - 0.06\n const pillars = ([[-1, -1], [1, -1], [-1, 1], [1, 1]] as const).map(([a, b]) => ({ u: round2(u + a * reach), v: round2(v + b * reach), side: 0.12 }))\n const half = TANK_SIDE / 2 + margin\n return { aabb: [u - half, v - half, u + half, v + half].map(round2) as Rect, baseY, height: rise, thickness, topY: round2(baseY + rise + thickness), pillars, ladder: true }\n}\n\n/**\n * The water tank of a house: on the roof slab, in the attic, or on a platform that rises out of the roof, never in the yard. Null for a plan without\n * a lot (an apartment) or a commercial building, and when no room has space.\n */\nexport function planWaterTank(source: StructureSource, rng: Rng, options: TankPlanOptions = {}): WaterTank | null {\n if (!source.lot || source.style === 'commercial') return null\n if (options.custom) return options.custom(source, rng)\n const floor = source.floors.length - 1\n const level = source.floors[floor]!\n const capacity = capacityOf(source, { ...DEFAULT_CAPACITIES, ...options.capacities })\n const height = capacity >= 2000 ? 1.4 : capacity === 1000 ? 1.0 : 0.85\n const place = options.location ? options.location(source, rng) : source.facade.roof === 'slab' ? 'slab' : rng() < ATTIC_CHANCE ? 'attic' : 'raised_slab'\n const reference = (source.facade.slab as { waterTank?: { u: number; v: number } } | undefined)?.waterTank\n const spot = bestSpot(source, floor, reference)\n if (!spot) return null\n const target = reference ? [reference.u, reference.v] : [(spot.rect[0] + spot.rect[2]) / 2, (spot.rect[1] + spot.rect[3]) / 2]\n const u = clamp(target[0]!, spot.rect[0] + TANK_SIDE / 2, spot.rect[2] - TANK_SIDE / 2)\n const v = clamp(target[1]!, spot.rect[1] + TANK_SIDE / 2, spot.rect[3] - TANK_SIDE / 2)\n const where = spot.roomType === 'terrace' ? 'slab' : place\n const slabY = round2(spot.roomType === 'terrace' ? level.y0 : level.y0 + level.ceiling)\n const tank: WaterTank = {\n id: 'water_tank', kind: 'water_tank', itemType: 'water_tank', place: where, floor, room: spot.roomId, u: round2(u), v: round2(v), y: slabY, w: TANK_SIDE, d: TANK_SIDE, h: height,\n capacity, aabb: [u - TANK_SIDE / 2, v - TANK_SIDE / 2, u + TANK_SIDE / 2, v + TANK_SIDE / 2].map(round2) as Rect,\n }\n if (where === 'raised_slab') {\n tank.platform = raisedPlatform(source, u, v, slabY)\n tank.y = tank.platform.topY\n }\n return tank\n}\n","import type { ViewerLayer, ViewerLayerContext, ViewerLayerLegendEntry } from '@adatechnology/game-floorplan'\n\nimport type { StructurePart } from './types'\n\ntype MaterialGroup = 'concrete' | 'steel' | 'masonry' | 'wood'\n\nconst COLORS: Record<MaterialGroup, string> = { concrete: '#7d8590', steel: '#3d6fb0', masonry: '#b5654b', wood: '#a0693a' }\nconst BEAM_IDS = ['plate_', 'porch_beam', 'base_beam', 'trestle_beam']\n\nexport const LAYER_ID = 'structure'\n\nexport function groupOf(material: string): MaterialGroup {\n if (material === 'concrete') return 'concrete'\n if (material === 'steel' || material === 'aluminium' || material === 'cast_iron') return 'steel'\n if (material === 'brick' || material === 'stone' || material === 'ceramic') return 'masonry'\n return 'wood'\n}\n\nconst isRoofFrame = (part: StructurePart): boolean => ['truss', 'rafter', 'ridge'].some((prefix) => part.id.startsWith(prefix))\nconst isDrawnBeam = (part: StructurePart): boolean => part.role === 'beam' && BEAM_IDS.some((prefix) => part.id.startsWith(prefix))\n\nfunction drawColumns(context: ViewerLayerContext, parts: readonly StructurePart[]): void {\n for (const part of parts.filter((p) => p.role === 'column')) {\n const color = COLORS[groupOf(part.material)]\n if (groupOf(part.material) === 'wood') context.rect(part.aabb, null, color, 2)\n else context.rect(part.aabb, color, null)\n context.hit(part.aabb, `${part.id} · column · ${part.material} · ${part.mass} kg`)\n }\n}\n\nfunction drawBeams(context: ViewerLayerContext, parts: readonly StructurePart[]): void {\n context.g.save()\n context.g.setLineDash([6, 4])\n for (const part of parts.filter(isDrawnBeam)) {\n context.rect(part.aabb, null, COLORS[groupOf(part.material)], 1.5)\n context.hit(part.aabb, `${part.id} · beam · ${part.material} · ${part.mass} kg`)\n }\n context.g.restore()\n}\n\nfunction drawRoofFrames(context: ViewerLayerContext, parts: readonly StructurePart[]): void {\n context.g.save()\n context.g.strokeStyle = COLORS.wood\n context.g.lineWidth = 1\n for (const part of parts.filter(isRoofFrame)) {\n const [u0, v0, u1, v1] = part.aabb\n const alongV = v1 - v0 > u1 - u0\n context.g.beginPath()\n if (alongV) { context.g.moveTo(context.X((u0 + u1) / 2), context.Z(v0)); context.g.lineTo(context.X((u0 + u1) / 2), context.Z(v1)) }\n else { context.g.moveTo(context.X(u0), context.Z((v0 + v1) / 2)); context.g.lineTo(context.X(u1), context.Z((v0 + v1) / 2)) }\n context.g.stroke()\n }\n context.g.restore()\n}\n\nfunction drawPorchRoofs(context: ViewerLayerContext, parts: readonly StructurePart[]): void {\n context.g.save()\n context.g.setLineDash([2, 4])\n for (const part of parts.filter((p) => p.id.startsWith('porch_roof'))) context.rect(part.aabb, null, COLORS.wood, 1)\n context.g.restore()\n}\n\n/** What the viewer draws at one storey: pillars (filled for concrete, steel and masonry, hollow for wood), dashed beams, trusses on the top storey, the porch roof outline. */\nexport function drawStructure(context: ViewerLayerContext): void {\n const structure = context.plan.structure\n if (!structure) return\n const floor = context.all ? 0 : context.floor\n const here = (structure.parts as StructurePart[]).filter((part) => part.floor === floor)\n drawPorchRoofs(context, here)\n if (floor === (context.plan.roof?.bearingFloor ?? 0)) drawRoofFrames(context, structure.parts)\n drawBeams(context, here)\n drawColumns(context, here)\n}\n\nexport function structureLegend(plan: { structure?: { parts: StructurePart[] } }): ViewerLayerLegendEntry[] {\n const parts = plan.structure?.parts ?? []\n const entries: ViewerLayerLegendEntry[] = []\n for (const group of ['concrete', 'steel', 'masonry', 'wood'] as const) {\n const columns = parts.some((p) => p.role === 'column' && groupOf(p.material) === group)\n if (columns) entries.push({ label: `structure_column_${group}`, color: COLORS[group], shape: group === 'wood' ? 'hollow' : 'filled' })\n }\n for (const group of ['concrete', 'wood'] as const) {\n if (parts.some((p) => isDrawnBeam(p) && groupOf(p.material) === group)) entries.push({ label: `structure_beam_${group}`, color: COLORS[group], shape: 'dashed' })\n }\n if (parts.some(isRoofFrame)) entries.push({ label: 'structure_roof_frame', color: COLORS.wood, shape: 'line' })\n return entries\n}\n\nexport const structureLayer: ViewerLayer = {\n id: LAYER_ID,\n label: 'structure_layer',\n defaultOn: false,\n draw: drawStructure,\n legend: structureLegend,\n}\n","import type { FloorplanEngine, ResultExtensionContext } from '@adatechnology/game-floorplan'\n\nimport { constructionFor } from './construction'\nimport enLocale from './locales/en.json'\nimport ptBrLocale from './locales/pt-BR.json'\nimport type { ConstructionBuild } from './registry'\nimport { buildStructure } from './structure'\nimport { contentOf } from './utilities/content'\nimport { planContents, planUtilities } from './utilities'\nimport { addOutbuildingPaths, planOutbuildings } from './utilities/outbuildings'\nimport type { EnergyConfig } from './utilities/electrical'\nimport type { TankPlanOptions } from './water-tank'\nimport { planWaterTank } from './water-tank'\nimport { structureLayer } from './viewer-layer'\nimport type { Roof, StructureOptions, WallDetail } from './types'\n\nexport interface StructurePackOptions {\n /** Litres of the tank by template id or style id. */\n tankCapacities?: Record<string, number>\n}\n\ntype Cache = { build: ConstructionBuild; roof?: Roof }\nconst CACHE = new WeakMap<object, Cache>()\n\nconst cacheOf = (result: object): Cache => {\n const cache = CACHE.get(result)\n if (!cache) throw new Error('The construction extension did not run for this plan')\n return cache\n}\n\nfunction constructionExtension(context: ResultExtensionContext): unknown {\n const build = constructionFor({ result: context.result as never, seed: context.seed, template: context.plan.tpl as never, options: context.options })\n CACHE.set(context.result, { build })\n return build.construction\n}\n\nfunction structureExtension(context: ResultExtensionContext): unknown {\n const cache = cacheOf(context.result)\n const options: StructureOptions = { construction: cache.build.construction, extras: cache.build.extras ?? {}, tank: context.result.waterTank ?? null, wallDetail: (context.options.wallDetail ?? 'panels') as WallDetail }\n const { roof, ...structure } = buildStructure(context.result, options)\n cache.roof = roof\n for (const part of structure.parts) {\n if (part.door === undefined || part.steps === undefined) continue\n const door = context.result.doors.find((d: { id: string }) => d.id === part.door)\n if (door) door.steps = part.steps\n }\n return structure\n}\n\nconst COOKING_CYLINDER = { type: 'cooking_gas_cylinder', category: 'cooking_gas_cylinder', w: 0.36, d: 0.36, h: 0.48 }\n\nfunction energyOf(context: ResultExtensionContext): EnergyConfig | undefined {\n const energy = context.plan.tpl.energy\n return typeof energy === 'function' ? energy(context.options, context.plan.w, context.plan.d) : undefined\n}\n\n/**\n * Registers the structure into the engine: `result.construction`, `result.structureExtras`, `result.waterTank`, `result.structure` and `result.roof` of every plan,\n * and the structure layer of the 2D viewer. Register the content packs first.\n */\nexport function register(engine: FloorplanEngine, options: StructurePackOptions = {}): void {\n engine.registerLocale('en', enLocale)\n engine.registerLocale('pt-BR', ptBrLocale)\n engine.registerResultExtension('construction', constructionExtension)\n engine.registerResultExtension('structureExtras', (context) => cacheOf(context.result).build.extras ?? {}, { after: ['construction'] })\n engine.registerResultExtension(\n 'waterTank',\n (context) => {\n const tank: TankPlanOptions = { capacities: options.tankCapacities, custom: context.plan.tpl.tank, location: context.plan.tpl.tankLocation }\n return planWaterTank(context.result as never, context.rng, tank)\n },\n { after: ['construction'], seedKey: 'caixa' },\n )\n engine.registerResultExtension('structure', structureExtension, { after: ['construction', 'structureExtras', 'waterTank'] })\n engine.registerResultExtension('roof', (context) => cacheOf(context.result).roof ?? null, { after: ['structure'] })\n engine.registerViewerLayer(structureLayer)\n engine.registerItem(COOKING_CYLINDER)\n engine.registerResultExtension('contents', (context) => planContents({ items: context.result.items, state: context.result.state, place: context.plan.tpl.place ?? 'house', ...(typeof context.options.day === 'number' ? { day: context.options.day } : {}), ...(typeof context.options.region === 'string' ? { region: context.options.region } : {}), rngFor: (key) => engine.createRng(context.seed, key), findsFor: (query) => { const answered = engine.findsAnswer(query); return answered ?? contentOf({ container: query.container, state: query.state, rng: query.rng, footprint: query.footprint ?? 0.5 }) } }))\n engine.registerResultExtension('outbuildings', (context) => {\n const outbuildings = planOutbuildings({ plan: context.plan, items: context.result.items, catalog: engine.catalog, rngFor: (key) => engine.createRng(context.seed, key) })\n if (context.result.lot) addOutbuildingPaths(context.result.lot, outbuildings, context.result.items)\n return outbuildings\n }, { after: ['contents'] })\n engine.registerResultExtension('utilities', (context) => planUtilities({ plan: context.plan, items: context.result.items, stateItems: context.result.stateItems, tank: context.result.waterTank ?? null, ...(energyOf(context) ? { energy: energyOf(context) } : {}), rngFor: (key) => engine.createRng(context.seed, key) }), { after: ['outbuildings', 'waterTank'] })\n}\n","import type { ChainDelay, ExplosionChain, PartSpec } from './types'\n\n/** What can set an explosive part off from outside, in the order a hit can carry it. */\nexport type ChainTrigger = 'shot' | 'fire' | 'explosion'\n\n/** Temperature in °C that primes a part with `chain.fire` when its `explodes.atC` is not set. */\nexport const FIRE_PRIME_C = 300\n\n/** Seconds from a trigger to the blast: a number is fixed, `[min, max]` is drawn from the world seed (one draw). */\nexport const drawChainDelay = (delay: ChainDelay, random: () => number): number => {\n if (typeof delay === 'number') return delay\n const [min, max] = delay\n return min + random() * (max - min)\n}\n\n/** The delay `spec` gives for `trigger`, or undefined when the part does not answer to it. */\nexport const chainDelayOf = (spec: PartSpec, trigger: ChainTrigger): ChainDelay | undefined => spec.explodes?.chain?.[trigger]\n\n/** Fraction of the hit points a shot must have taken off before it primes the part. */\nexport const shotDamageFractionOf = (spec: PartSpec): number => spec.explodes?.chain?.shotDamageFraction ?? 0\n\n/** The numbers of an explosive that sits in the world, as `game-weapons` gives them (`ExplosiveDef` fits). */\nexport interface WorldExplosive {\n readonly energy: number\n /** Metres within which the blast reaches other parts (and primes theirs). */\n readonly injuryRadius: number\n readonly chain?: ExplosionChain\n}\n\nexport interface ExplosivePartOptions {\n /** Temperature in °C at which fire primes (or sets off) the part; default `FIRE_PRIME_C` when the explosive answers to fire. */\n readonly atC?: number\n}\n\n/**\n * A part that explodes with the energy and reach of `explosive` and answers to what `explosive.chain` says: a bullet, fire or a blast\n * nearby primes it and it goes off after the delay. `part` is everything else about the part (shape, material, position, fluid inside).\n */\nexport const explosivePart = (explosive: WorldExplosive, part: Omit<PartSpec, 'explodes'>, options: ExplosivePartOptions = {}): PartSpec => ({\n ...part,\n explodes: {\n energy: explosive.energy,\n radius: explosive.injuryRadius,\n ...(options.atC !== undefined ? { atC: options.atC } : {}),\n ...(explosive.chain ? { chain: { ...explosive.chain } } : {}),\n },\n})\n","import type { PartShape, Quat, Vec3 } from './types'\n\nconst EPS = 1e-9\n\n/** Small vector helpers (arrays of three numbers). Pure functions; they allocate a new array. */\nexport const vec = {\n add: (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]],\n sub: (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]],\n scale: (a: Vec3, s: number): Vec3 => [a[0] * s, a[1] * s, a[2] * s],\n dot: (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],\n cross: (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]],\n length: (a: Vec3): number => Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]),\n distance: (a: Vec3, b: Vec3): number => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]),\n normalize: (a: Vec3, fallback: Vec3 = [0, 1, 0]): Vec3 => {\n const l = Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2])\n return l < EPS ? [fallback[0], fallback[1], fallback[2]] : [a[0] / l, a[1] / l, a[2] / l]\n },\n lerp: (a: Vec3, b: Vec3, t: number): Vec3 => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t],\n /** `a + b * s` */\n madd: (a: Vec3, b: Vec3, s: number): Vec3 => [a[0] + b[0] * s, a[1] + b[1] * s, a[2] + b[2] * s],\n}\n\nconst IDENTITY: Quat = [0, 0, 0, 1]\n\n/** Quaternion helpers (`[x, y, z, w]`). */\nexport const quat = {\n identity: (): Quat => [IDENTITY[0], IDENTITY[1], IDENTITY[2], IDENTITY[3]],\n /** Hamilton product `a * b` (apply `b` first, then `a`). */\n mul: (a: Quat, b: Quat): Quat => [\n a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],\n a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],\n a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],\n a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],\n ],\n conjugate: (q: Quat): Quat => [-q[0], -q[1], -q[2], q[3]],\n normalize: (q: Quat): Quat => {\n const l = Math.hypot(q[0], q[1], q[2], q[3])\n return l < EPS ? [0, 0, 0, 1] : [q[0] / l, q[1] / l, q[2] / l, q[3] / l]\n },\n /** Rotation of `angle` radians around a unit `axis`. */\n fromAxisAngle: (axis: Vec3, angle: number): Quat => {\n const s = Math.sin(angle / 2)\n return [axis[0] * s, axis[1] * s, axis[2] * s, Math.cos(angle / 2)]\n },\n /** Rotation matrix, row-major 3x3. */\n toMatrix: (q: Quat): number[] => {\n const [x, y, z, w] = q\n const xx = x * x, yy = y * y, zz = z * z, xy = x * y, xz = x * z, yz = y * z, wx = w * x, wy = w * y, wz = w * z\n return [1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy), 2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx), 2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy)]\n },\n /** Quaternion from three orthonormal columns (the images of the x, y and z axes). */\n fromColumns: (cx: Vec3, cy: Vec3, cz: Vec3): Quat => {\n const m00 = cx[0], m10 = cx[1], m20 = cx[2]\n const m01 = cy[0], m11 = cy[1], m21 = cy[2]\n const m02 = cz[0], m12 = cz[1], m22 = cz[2]\n const tr = m00 + m11 + m22\n let q: Quat\n if (tr > 0) {\n const s = Math.sqrt(tr + 1) * 2\n q = [(m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s, 0.25 * s]\n } else if (m00 > m11 && m00 > m22) {\n const s = Math.sqrt(1 + m00 - m11 - m22) * 2\n q = [0.25 * s, (m01 + m10) / s, (m02 + m20) / s, (m21 - m12) / s]\n } else if (m11 > m22) {\n const s = Math.sqrt(1 + m11 - m00 - m22) * 2\n q = [(m01 + m10) / s, 0.25 * s, (m12 + m21) / s, (m02 - m20) / s]\n } else {\n const s = Math.sqrt(1 + m22 - m00 - m11) * 2\n q = [(m02 + m20) / s, (m12 + m21) / s, 0.25 * s, (m10 - m01) / s]\n }\n return quat.normalize(q)\n },\n}\n\n/** Quaternion from Euler angles in radians, order XYZ (the three.js default). */\nexport const quatFromEuler = (x: number, y: number, z: number): Quat => {\n const c1 = Math.cos(x / 2), c2 = Math.cos(y / 2), c3 = Math.cos(z / 2)\n const s1 = Math.sin(x / 2), s2 = Math.sin(y / 2), s3 = Math.sin(z / 2)\n return [s1 * c2 * c3 + c1 * s2 * s3, c1 * s2 * c3 - s1 * c2 * s3, c1 * c2 * s3 + s1 * s2 * c3, c1 * c2 * c3 - s1 * s2 * s3]\n}\n\n/** Rotate a vector by a quaternion. */\nexport const rotateVec = (q: Quat, v: Vec3): Vec3 => {\n const qx = q[0], qy = q[1], qz = q[2], qw = q[3]\n const tx = 2 * (qy * v[2] - qz * v[1])\n const ty = 2 * (qz * v[0] - qx * v[2])\n const tz = 2 * (qx * v[1] - qy * v[0])\n return [v[0] + qw * tx + (qy * tz - qz * ty), v[1] + qw * ty + (qz * tx - qx * tz), v[2] + qw * tz + (qx * ty - qy * tx)]\n}\n\n/** World point to the local space of a transform (`position`, `rotation`). */\nexport const toLocal = (position: Vec3, rotation: Quat, p: Vec3): Vec3 =>\n rotateVec([-rotation[0], -rotation[1], -rotation[2], rotation[3]], [p[0] - position[0], p[1] - position[1], p[2] - position[2]])\n\n/** Local point of a transform (`position`, `rotation`) to world space. */\nexport const toWorld = (position: Vec3, rotation: Quat, p: Vec3): Vec3 => {\n const r = rotateVec(rotation, p)\n return [r[0] + position[0], r[1] + position[1], r[2] + position[2]]\n}\n\n// ---------------------------------------------------------------------------------------------------------------------------------------------\n// Shapes (part space: centred on the origin, cylinders along +Y)\n// ---------------------------------------------------------------------------------------------------------------------------------------------\n\n/** Dimensions of the bounding box of a shape, in the shape's own axes. */\nexport const shapeDims = (s: PartShape): Vec3 => {\n if (s.kind === 'box') return [s.size[0], s.size[1], s.size[2]]\n if (s.kind === 'cylinder') return [s.radius * 2, s.height, s.radius * 2]\n return [s.radius * 2, s.radius * 2, s.radius * 2]\n}\n\n/** Radius of the sphere that encloses the shape. */\nexport const shapeBound = (s: PartShape): number => {\n if (s.kind === 'box') return 0.5 * Math.hypot(s.size[0], s.size[1], s.size[2])\n if (s.kind === 'cylinder') return Math.hypot(s.radius, s.height / 2)\n return s.radius\n}\n\nexport const shapeArea = (s: PartShape): number => {\n if (s.kind === 'box') return 2 * (s.size[0] * s.size[1] + s.size[1] * s.size[2] + s.size[0] * s.size[2])\n if (s.kind === 'cylinder') return 2 * Math.PI * s.radius * s.height + 2 * Math.PI * s.radius * s.radius\n return 4 * Math.PI * s.radius * s.radius\n}\n\nexport interface ShapeRay {\n /** Entry distance along the ray (negative when the origin is inside). */\n t0: number\n /** Normal at the entry, outward. */\n n0: Vec3\n /** Exit distance. */\n t1: number\n /** Normal at the exit, outward. */\n n1: Vec3\n}\n\n/** Exact ray intersection with a shape in part space. `d` need not be normalised but must be non-zero. */\nexport const rayShape = (s: PartShape, o: Vec3, d: Vec3): ShapeRay | null => {\n if (s.kind === 'box') {\n let tmin = -Infinity, tmax = Infinity\n let a0 = 0, a1 = 0, s0 = 1, s1 = 1\n for (let i = 0; i < 3; i++) {\n const h = s.size[i] / 2\n if (Math.abs(d[i]) < EPS) {\n if (Math.abs(o[i]) > h) return null\n continue\n }\n let ta = (-h - o[i]) / d[i]\n let tb = (h - o[i]) / d[i]\n let sa = -1, sb = 1\n if (ta > tb) {\n const t = ta\n ta = tb\n tb = t\n sa = 1\n sb = -1\n }\n if (ta > tmin) {\n tmin = ta\n a0 = i\n s0 = sa\n }\n if (tb < tmax) {\n tmax = tb\n a1 = i\n s1 = sb\n }\n if (tmin > tmax) return null\n }\n if (tmax < 0 || !Number.isFinite(tmin) || !Number.isFinite(tmax)) return null\n const n0: Vec3 = [0, 0, 0]\n const n1: Vec3 = [0, 0, 0]\n n0[a0] = s0\n n1[a1] = s1\n return { t0: tmin, n0, t1: tmax, n1 }\n }\n if (s.kind === 'sphere') {\n const b = vec.dot(o, d)\n const a = vec.dot(d, d)\n const c = vec.dot(o, o) - s.radius * s.radius\n const disc = b * b - a * c\n if (disc < 0) return null\n const sq = Math.sqrt(disc)\n const t0 = (-b - sq) / a\n const t1 = (-b + sq) / a\n if (t1 < 0) return null\n const p0 = vec.madd(o, d, t0)\n const p1 = vec.madd(o, d, t1)\n return { t0, n0: vec.normalize(p0), t1, n1: vec.normalize(p1) }\n }\n // cylinder along Y: intersection of the infinite cylinder interval and the y slab\n const r = s.radius\n const hh = s.height / 2\n const a = d[0] * d[0] + d[2] * d[2]\n const c = o[0] * o[0] + o[2] * o[2] - r * r\n let tA = -Infinity, tB = Infinity\n if (a > EPS) {\n const b = o[0] * d[0] + o[2] * d[2]\n const disc = b * b - a * c\n if (disc < 0) return null\n const sq = Math.sqrt(disc)\n tA = (-b - sq) / a\n tB = (-b + sq) / a\n } else if (c > 0) return null\n let yA = -Infinity, yB = Infinity\n if (Math.abs(d[1]) > EPS) {\n yA = (-hh - o[1]) / d[1]\n yB = (hh - o[1]) / d[1]\n if (yA > yB) {\n const t = yA\n yA = yB\n yB = t\n }\n } else if (Math.abs(o[1]) > hh) return null\n const t0 = Math.max(tA, yA)\n const t1 = Math.min(tB, yB)\n if (t0 > t1 || t1 < 0 || !Number.isFinite(t0) || !Number.isFinite(t1)) return null\n const normalAt = (t: number, fromSide: boolean, sign: number): Vec3 => {\n if (fromSide) {\n const p = vec.madd(o, d, t)\n return vec.normalize([p[0], 0, p[2]], [1, 0, 0])\n }\n return [0, sign, 0]\n }\n const n0 = normalAt(t0, tA >= yA, d[1] > 0 ? -1 : 1)\n const n1 = normalAt(t1, tB <= yB, d[1] > 0 ? 1 : -1)\n return { t0, n0, t1, n1 }\n}\n\n/** Distance from a part-space point to the shape (0 inside). */\nexport const distanceToShape = (s: PartShape, p: Vec3): number => {\n if (s.kind === 'box') {\n const dx = Math.max(Math.abs(p[0]) - s.size[0] / 2, 0)\n const dy = Math.max(Math.abs(p[1]) - s.size[1] / 2, 0)\n const dz = Math.max(Math.abs(p[2]) - s.size[2] / 2, 0)\n return Math.hypot(dx, dy, dz)\n }\n if (s.kind === 'sphere') return Math.max(0, vec.length(p) - s.radius)\n const dr = Math.max(0, Math.hypot(p[0], p[2]) - s.radius)\n const dy = Math.max(0, Math.abs(p[1]) - s.height / 2)\n return Math.hypot(dr, dy)\n}\n\n/** Nearest point on the surface of a shape to a part-space point, with the outward normal. */\nexport const surfacePoint = (s: PartShape, p: Vec3): { point: Vec3; normal: Vec3 } => {\n if (s.kind === 'box') {\n const h: Vec3 = [s.size[0] / 2, s.size[1] / 2, s.size[2] / 2]\n const inside = Math.abs(p[0]) <= h[0] && Math.abs(p[1]) <= h[1] && Math.abs(p[2]) <= h[2]\n if (!inside) {\n const c: Vec3 = [Math.max(-h[0], Math.min(h[0], p[0])), Math.max(-h[1], Math.min(h[1], p[1])), Math.max(-h[2], Math.min(h[2], p[2]))]\n return { point: c, normal: vec.normalize(vec.sub(p, c)) }\n }\n let axis = 0\n let best = Infinity\n for (let i = 0; i < 3; i++) {\n const g = h[i] - Math.abs(p[i])\n if (g < best) {\n best = g\n axis = i\n }\n }\n const sign = p[axis] >= 0 ? 1 : -1\n const point: Vec3 = [p[0], p[1], p[2]]\n point[axis] = sign * h[axis]\n const normal: Vec3 = [0, 0, 0]\n normal[axis] = sign\n return { point, normal }\n }\n if (s.kind === 'sphere') {\n const n = vec.normalize(p)\n return { point: vec.scale(n, s.radius), normal: n }\n }\n const rho = Math.hypot(p[0], p[2])\n const hh = s.height / 2\n const inside = rho <= s.radius && Math.abs(p[1]) <= hh\n if (!inside) {\n const k = rho > s.radius ? s.radius / rho : 1\n const c: Vec3 = [p[0] * k, Math.max(-hh, Math.min(hh, p[1])), p[2] * k]\n return { point: c, normal: vec.normalize(vec.sub(p, c)) }\n }\n if (s.radius - rho < hh - Math.abs(p[1])) {\n const k = rho < EPS ? 0 : s.radius / rho\n const point: Vec3 = rho < EPS ? [s.radius, p[1], 0] : [p[0] * k, p[1], p[2] * k]\n return { point, normal: vec.normalize([point[0], 0, point[2]], [1, 0, 0]) }\n }\n const sign = p[1] >= 0 ? 1 : -1\n return { point: [p[0], sign * hh, p[2]], normal: [0, sign, 0] }\n}\n\n/** Axis-aligned bounds of a shape with a given centre and orientation. */\nexport const aabbOf = (s: PartShape, center: Vec3, q: Quat): { min: Vec3; max: Vec3 } => {\n let hx: number, hy: number, hz: number\n if (s.kind === 'sphere') {\n hx = hy = hz = s.radius\n } else {\n const m = quat.toMatrix(q)\n if (s.kind === 'box') {\n const a = s.size[0] / 2, b = s.size[1] / 2, c = s.size[2] / 2\n hx = Math.abs(m[0]) * a + Math.abs(m[1]) * b + Math.abs(m[2]) * c\n hy = Math.abs(m[3]) * a + Math.abs(m[4]) * b + Math.abs(m[5]) * c\n hz = Math.abs(m[6]) * a + Math.abs(m[7]) * b + Math.abs(m[8]) * c\n } else {\n const ax = [m[1], m[4], m[7]]\n const hh = s.height / 2\n const e = (i: number) => s.radius * Math.sqrt(Math.max(0, 1 - ax[i] * ax[i])) + hh * Math.abs(ax[i])\n hx = e(0)\n hy = e(1)\n hz = e(2)\n }\n }\n return { min: [center[0] - hx, center[1] - hy, center[2] - hz], max: [center[0] + hx, center[1] + hy, center[2] + hz] }\n}\n\n/** Seeded generator (mulberry32). The state is a single int32, so it round-trips through JSON. */\nexport interface Rng {\n next(): number\n state(): number\n set(state: number): void\n}\n\nexport const createRng = (seed: number): Rng => {\n let s = seed | 0\n return {\n next() {\n s = (s + 0x6d2b79f5) | 0\n let t = Math.imul(s ^ (s >>> 15), 1 | s)\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n },\n state: () => s,\n set(v) {\n s = v | 0\n },\n }\n}\n","import { quat } from './math'\nimport type { Fragment, FractureStyle, Quat, Vec3 } from './types'\n\n/** A fragment in the part's local space (centre, size in the fragment's own axes, orientation relative to the part). */\nexport interface PlannedFragment {\n center: Vec3\n size: Vec3\n q: Quat\n shape: Fragment['shape']\n /** Share of the part's mass (unnormalised). */\n weight: number\n}\n\nexport interface PlanInput {\n style: FractureStyle\n /** Bounding box dimensions in part axes. */\n dims: Vec3\n thickness: number\n /** Index 0..2 of the grain axis, if any. */\n grain?: number\n /** Impact point in part space. */\n hit: Vec3\n fragmentSize: [number, number]\n maxFragments: number\n rnd: () => number\n}\n\ninterface Box {\n c: Vec3\n s: Vec3\n}\n\n/** Split a box into `count` pieces by cutting the largest piece along its longest allowed axis. */\nconst bsp = (root: Box, count: number, axes: number[], rnd: () => number): Box[] => {\n const pieces: Box[] = [root]\n const vol = (b: Box) => axes.reduce((v, a) => v * b.s[a], 1)\n while (pieces.length < count) {\n let bi = 0\n for (let i = 1; i < pieces.length; i++) if (vol(pieces[i]) > vol(pieces[bi])) bi = i\n const b = pieces[bi]\n let ax = axes[0]\n for (const a of axes) if (b.s[a] > b.s[ax]) ax = a\n if (b.s[ax] < 1e-4) break\n const r = 0.3 + 0.4 * rnd()\n const l1 = b.s[ax] * r\n const l2 = b.s[ax] - l1\n const c1: Vec3 = [b.c[0], b.c[1], b.c[2]]\n const c2: Vec3 = [b.c[0], b.c[1], b.c[2]]\n c1[ax] = b.c[ax] - b.s[ax] / 2 + l1 / 2\n c2[ax] = b.c[ax] + b.s[ax] / 2 - l2 / 2\n const s1: Vec3 = [b.s[0], b.s[1], b.s[2]]\n const s2: Vec3 = [b.s[0], b.s[1], b.s[2]]\n s1[ax] = l1\n s2[ax] = l2\n pieces[bi] = { c: c1, s: s1 }\n pieces.push({ c: c2, s: s2 })\n }\n return pieces\n}\n\nconst parity = (p: [number, number, number]): number => {\n let inv = 0\n for (let i = 0; i < 3; i++) for (let j = i + 1; j < 3; j++) if (p[i] > p[j]) inv++\n return inv % 2 === 0 ? 1 : -1\n}\n\n/** Orientation whose x, y, z axes are the part axes `ax`, `ay`, `az`, then rotated by `angle` around its own z. */\nconst frame = (ax: number, ay: number, az: number, angle = 0): Quat => {\n const e = (i: number): Vec3 => [i === 0 ? 1 : 0, i === 1 ? 1 : 0, i === 2 ? 1 : 0]\n const z = e(az)\n const sg = parity([ax, ay, az])\n const q = quat.fromColumns(e(ax), e(ay), [z[0] * sg, z[1] * sg, z[2] * sg])\n return angle === 0 ? q : quat.mul(q, quat.fromAxisAngle([0, 0, 1], angle))\n}\n\nconst clamp = (v: number, a: number, b: number) => Math.max(a, Math.min(b, v))\n\n/** Deterministic fragment layout for a failed part, in part space. */\nexport const planFragments = (inp: PlanInput): PlannedFragment[] => {\n const { style, dims, rnd, maxFragments } = inp\n const [fmin, fmax] = inp.fragmentSize\n const mean = (fmin + fmax) / 2\n const root: Box = { c: [0, 0, 0], s: [dims[0], dims[1], dims[2]] }\n const idq = quat.identity()\n const out: PlannedFragment[] = []\n const sorted = [0, 1, 2].sort((a, b) => dims[a] - dims[b])\n const t = sorted[0]\n const [u, v] = [sorted[1], sorted[2]].sort((a, b) => a - b)\n\n if (style === 'snap') {\n const n = Math.min(maxFragments, 2 + Math.floor(rnd() * 3))\n for (const b of bsp(root, n, [0, 1, 2], rnd)) out.push({ center: b.c, size: b.s, q: idq, shape: 'slab', weight: b.s[0] * b.s[1] * b.s[2] })\n return out\n }\n if (style === 'crumble' || style === 'none') {\n const n = clamp(Math.ceil((dims[0] * dims[1] * dims[2]) / (mean * mean * mean)), 4, maxFragments)\n for (const b of bsp(root, n, [0, 1, 2], rnd)) out.push({ center: b.c, size: b.s, q: idq, shape: 'chunk', weight: b.s[0] * b.s[1] * b.s[2] })\n return out\n }\n if (style === 'splinter') {\n const g = inp.grain ?? [0, 1, 2].sort((a, b) => dims[b] - dims[a])[0]\n const [a, b] = [0, 1, 2].filter((i) => i !== g)\n const w = Math.max(fmin * 1.5, 0.01)\n const c = clamp(Math.round((dims[a] * dims[b]) / (w * w)), 3, Math.max(3, Math.floor(maxFragments / 2)))\n const maxLen = fmax * 4\n const cells = bsp(root, c, [a, b], rnd)\n const pieces: Box[] = []\n for (const cell of cells) {\n let list = [cell]\n const extra = rnd() < 0.4 ? 1 : 0\n const k = Math.max(1, Math.ceil(dims[g] / maxLen)) + extra\n list = bsp(cell, k, [g], rnd)\n for (const p of list) pieces.push(p)\n }\n for (const p of pieces.slice(0, maxFragments)) {\n out.push({ center: p.c, size: [p.s[g], p.s[a], p.s[b]], q: frame(g, a, b), shape: 'splinter', weight: p.s[0] * p.s[1] * p.s[2] })\n }\n return out\n }\n if (style === 'tear') {\n const n = clamp(Math.round((dims[u] * dims[v]) / (mean * mean)), 3, maxFragments)\n const th = Math.min(inp.thickness, dims[t])\n for (const b of bsp(root, n, [u, v], rnd)) {\n out.push({ center: [b.c[0], b.c[1], b.c[2]], size: [b.s[u], b.s[v], th], q: frame(u, v, t), shape: 'scrap', weight: b.s[u] * b.s[v] })\n }\n return out\n }\n // shatter: thin shards radiating from the impact\n const th = Math.min(inp.thickness, dims[t])\n const Hu = dims[u] / 2, Hv = dims[v] / 2\n const hu = clamp(inp.hit[u], -Hu * 0.95, Hu * 0.95)\n const hv = clamp(inp.hit[v], -Hv * 0.95, Hv * 0.95)\n const R = Math.max(Math.hypot(Hu + Math.abs(hu), Hv + Math.abs(hv)), 0.02)\n const n = clamp(Math.round((dims[u] * dims[v]) / (mean * mean)), 6, maxFragments)\n const sectors = clamp(Math.round(Math.sqrt(n * 1.6)), 5, 10)\n const rings = Math.max(1, Math.ceil(n / sectors))\n const radii: number[] = []\n for (let k = 0; k <= rings; k++) radii.push(R * Math.pow(k / rings, 1.3))\n const cap = fmax * 1.5\n for (let j = 0; j < sectors && out.length < maxFragments; j++) {\n const theta = (j + (rnd() - 0.5) * 0.4) * ((Math.PI * 2) / sectors)\n for (let k = 0; k < rings && out.length < maxFragments; k++) {\n const rm = (radii[k] + radii[k + 1]) / 2\n const cu = hu + rm * Math.cos(theta)\n const cv = hv + rm * Math.sin(theta)\n if (Math.abs(cu) > Hu + 0.01 || Math.abs(cv) > Hv + 0.01) continue\n const radial = clamp(radii[k + 1] - radii[k], 0.01, cap)\n const tang = clamp(radii[k + 1] * ((Math.PI * 2) / sectors) * 0.9, 0.01, cap)\n const c: Vec3 = [0, 0, 0]\n c[u] = clamp(cu, -Hu * 0.98, Hu * 0.98)\n c[v] = clamp(cv, -Hv * 0.98, Hv * 0.98)\n c[t] = 0\n out.push({ center: c, size: [radial, tang, th], q: frame(u, v, t, theta), shape: 'shard', weight: radial * tang })\n }\n }\n if (out.length === 0) out.push({ center: [0, 0, 0], size: [dims[u], dims[v], th], q: frame(u, v, t), shape: 'shard', weight: 1 })\n return out\n}\n","import { quat, rotateVec } from './math'\nimport type { FragmentMark, PartUnits, Quat, Vec3 } from './types'\n\n/** One masonry unit (or panel) cut out of a wall, in the part's own axes. */\nexport interface UnitCell {\n center: Vec3\n size: Vec3\n}\n\n/** The two axes a wall spreads along: height is local y unless the part is thin along y (a slab), then x and z. */\nexport const planeAxes = (thin: number): [number, number] => (thin === 1 ? [0, 2] : [thin === 0 ? 2 : 0, 1])\n\n/**\n * Every unit of the wall laid in `bond`: rows along the plane's second axis, running bond shifts odd rows by half a unit, edge units are cut to\n * the wall. More than `cap` units are merged into bigger ones (the same bond) so a whole wall stays a drawable number of fragments.\n */\nexport const unitGrid = (dims: Vec3, thin: number, units: Pick<PartUnits, 'size' | 'bond'>, cap: number): UnitCell[] => {\n const [u, v] = planeAxes(thin)\n let unitU = Math.min(units.size[0], dims[u]), unitV = Math.min(units.size[1], dims[v])\n const rowsFor = (h: number): number => Math.ceil(dims[v] / h - 1e-9)\n const colsFor = (w: number): number => Math.ceil(dims[u] / w - 1e-9) + (units.bond === 'running' ? 1 : 0)\n const merge = Math.ceil(Math.sqrt((rowsFor(unitV) * colsFor(unitU)) / cap))\n if (merge > 1) {\n unitU = Math.min(unitU * merge, dims[u])\n unitV = Math.min(unitV * merge, dims[v])\n }\n const cells: UnitCell[] = []\n for (let row = 0; row < rowsFor(unitV); row++) {\n const v0 = -dims[v] / 2 + row * unitV, v1 = Math.min(v0 + unitV, dims[v] / 2)\n const shift = units.bond === 'running' && row % 2 === 1 ? unitU / 2 : 0\n for (let col = 0; col < colsFor(unitU); col++) {\n const u0 = Math.max(-dims[u] / 2 + col * unitU - shift, -dims[u] / 2), u1 = Math.min(-dims[u] / 2 + (col + 1) * unitU - shift, dims[u] / 2)\n if (u1 - u0 < 0.01) continue\n const center: Vec3 = [0, 0, 0], size: Vec3 = [0, 0, 0]\n center[u] = (u0 + u1) / 2\n center[v] = (v0 + v1) / 2\n size[u] = u1 - u0\n size[v] = v1 - v0\n size[thin] = dims[thin]\n cells.push({ center, size })\n }\n }\n return cells\n}\n\nconst planeDistance = (cell: UnitCell, thin: number, point: Vec3): number => {\n const [u, v] = planeAxes(thin)\n const du = cell.center[u] - point[u], dv = cell.center[v] - point[v]\n return Math.sqrt(du * du + dv * dv)\n}\n\n/** Units whose centre is within `radius` of `point` (part-local) in the wall plane; at least the nearest one. */\nexport const cellsWithin = (cells: readonly UnitCell[], thin: number, point: Vec3, radius: number): UnitCell[] => {\n const inside = cells.filter((c) => planeDistance(c, thin, point) <= radius)\n if (inside.length > 0 || cells.length === 0) return inside\n return [cells.reduce((best, c) => (planeDistance(c, thin, point) < planeDistance(best, thin, point) ? c : best))]\n}\n\nexport const cellsOutside = (cells: readonly UnitCell[], thin: number, point: Vec3, radius: number): UnitCell[] => cells.filter((c) => planeDistance(c, thin, point) > radius)\n\n/** A hole in the part's own axes. */\nexport interface LocalHole {\n point: Vec3\n normal: Vec3\n diameter: number\n}\n\nexport const MAX_MARKS_PER_FRAGMENT = 12\n\n/** The holes that fall inside a fragment box (`rotation` is the fragment's orientation in the part), in the fragment's own axes. */\nexport const marksInBox = (center: Vec3, size: Vec3, rotation: Quat | undefined, holes: readonly LocalHole[]): FragmentMark[] => {\n const inverse = rotation ? quat.conjugate(rotation) : undefined\n const marks: FragmentMark[] = []\n for (const hole of holes) {\n const offset: Vec3 = [hole.point[0] - center[0], hole.point[1] - center[1], hole.point[2] - center[2]]\n const point = inverse ? rotateVec(inverse, offset) : offset\n const inside = point.every((value, k) => Math.abs(value) <= size[k]! / 2 + hole.diameter / 2)\n if (!inside) continue\n marks.push({ point, normal: inverse ? rotateVec(inverse, hole.normal) : hole.normal, diameter: hole.diameter })\n if (marks.length >= MAX_MARKS_PER_FRAGMENT) break\n }\n return marks\n}\n","import type { MaterialDef, SurfaceLayer, Vec3 } from './types'\n\n/** A surface layer with its material resolved; `energy` is what a bullet spends crossing one face's worth of it, in joules. */\nexport interface LayerRT {\n index: number\n def: SurfaceLayer\n mat: MaterialDef\n energy: number\n}\n\n/** `[layer, face (+1 or -1), x, y, z, radius]`: a patch of a layer that came off, in object-local space. Saved with the part. */\nexport type Spall = readonly [number, number, number, number, number, number]\n\nexport const MAX_SPALLS = 64\n\n/** Index of the smallest dimension (the first one on a tie): the axis a wall is thin along. */\nexport const thinAxisOf = (dims: Vec3): number => (dims[0] <= dims[1] && dims[0] <= dims[2] ? 0 : dims[1] <= dims[2] ? 1 : 2)\n\nexport const resolveLayer = (def: SurfaceLayer, index: number, mat: MaterialDef): LayerRT => ({ index, def, mat, energy: mat.penetration * def.thickness * 1000 })\n\nconst onFace = (layer: LayerRT, face: number): boolean => layer.def.faces === 'both' || layer.def.faces === (face > 0 ? '+' : '-')\n\nconst isSpalled = (spalls: readonly Spall[] | undefined, layer: number, face: number, point: Vec3): boolean => {\n for (const s of spalls ?? []) {\n if (s[0] !== layer || s[1] !== face) continue\n const dx = s[2] - point[0], dy = s[3] - point[1], dz = s[4] - point[2]\n if (dx * dx + dy * dy + dz * dz <= s[5] * s[5]) return true\n }\n return false\n}\n\n/** The outermost layer still on `face` at `point` (layers are listed outermost first). */\nexport const outerLayer = (layers: readonly LayerRT[], spalls: readonly Spall[] | undefined, face: number, point: Vec3): LayerRT | undefined =>\n layers.find((l) => onFace(l, face) && !isSpalled(spalls, l.index, face, point))\n\n/** Joules a bullet spends crossing every layer still on `face` at `point`. */\nexport const layersEnergy = (layers: readonly LayerRT[], spalls: readonly Spall[] | undefined, face: number, point: Vec3): number => {\n let sum = 0\n for (const l of layers) if (onFace(l, face) && !isSpalled(spalls, l.index, face, point)) sum += l.energy\n return sum\n}\n\n/** Metres of layer a ray crosses on one face (full thickness, before obliquity). */\nexport const layersThickness = (layers: readonly LayerRT[], face: number): number => {\n let sum = 0\n for (const l of layers) if (onFace(l, face)) sum += l.def.thickness\n return sum\n}\n","import type { Vec3 } from './types'\n\n/** A bar as two end points. */\nexport type Bar = [Vec3, Vec3]\n\nconst COVER = 0.03\nconst MAX_BARS_PER_DIRECTION = 24\nconst MAX_MEMBER_BARS_PER_SIDE = 6\nconst STEEL_DENSITY = 7850\n\n/** Positions centred on 0 with exact `spacing`, as many as fit inside `length - 2 * cover` (at least two, at most `cap`). */\nconst spread = (length: number, cover: number, spacing: number, cap: number): number[] => {\n const room = Math.max(0, length - 2 * cover)\n const count = Math.min(cap, Math.max(2, Math.floor(room / spacing) + 1))\n const step = count > 1 && room / (count - 1) < spacing ? room / (count - 1) : spacing\n return Array.from({ length: count }, (_, i) => (i - (count - 1) / 2) * step)\n}\n\nconst bar = (axis: number, along: number, fixed: Array<[number, number]>): Bar => {\n const a: Vec3 = [0, 0, 0], b: Vec3 = [0, 0, 0]\n for (const [index, value] of fixed) {\n a[index] = value\n b[index] = value\n }\n a[axis] = -along\n b[axis] = along\n return [a, b]\n}\n\n/** Long members (columns, beams): two smaller dimensions close to each other and a much longer third one. */\nconst isMember = (dims: Vec3): boolean => {\n const [a = 0, b = 0, c = 0] = [...dims].sort((x, y) => x - y)\n return b / a < 3 && c / b >= 3\n}\n\n/**\n * Rebar of a box in the part's own axes. Plates (walls, slabs) get a grid along each of the two large axes at mid thickness; long members get\n * bars along their length at the perimeter of the section. `thin` is the axis the part is thinnest along.\n */\nexport const rebarBars = (dims: Vec3, thin: number, spacing: number): Bar[] => {\n const out: Bar[] = []\n if (isMember(dims)) {\n const long = dims.indexOf(Math.max(...dims))\n const [u = 0, v = 0] = [0, 1, 2].filter((i) => i !== long)\n const us = spread(dims[u], COVER, spacing, MAX_MEMBER_BARS_PER_SIDE)\n const vs = spread(dims[v], COVER, spacing, MAX_MEMBER_BARS_PER_SIDE)\n us.forEach((x, i) => vs.forEach((y, j) => {\n if (i === 0 || j === 0 || i === us.length - 1 || j === vs.length - 1) out.push(bar(long, dims[long] / 2 - 0.02, [[u, x], [v, y]]))\n }))\n return out\n }\n const [u = 0, v = 0] = [0, 1, 2].filter((i) => i !== thin)\n for (const y of spread(dims[v], COVER, spacing, MAX_BARS_PER_DIRECTION)) out.push(bar(u, dims[u] / 2 - 0.02, [[v, y], [thin, 0]]))\n for (const x of spread(dims[u], COVER, spacing, MAX_BARS_PER_DIRECTION)) out.push(bar(v, dims[v] / 2 - 0.02, [[u, x], [thin, 0]]))\n return out\n}\n\n/** The part of each bar that lies within `radius` of `center` in the plane of axes `u` and `v` (bars that miss the disc are dropped). */\nexport const clipBarsToDisc = (bars: readonly Bar[], u: number, v: number, center: [number, number], radius: number): Bar[] => {\n const out: Bar[] = []\n for (const [a, b] of bars) {\n const axis = a[u] !== b[u] ? u : v\n const other = axis === u ? v : u\n const off = a[other] - center[other === u ? 0 : 1]\n if (Math.abs(off) >= radius) continue\n const half = Math.sqrt(radius * radius - off * off)\n const mid = center[axis === u ? 0 : 1]\n const lo = Math.max(Math.min(a[axis], b[axis]), mid - half), hi = Math.min(Math.max(a[axis], b[axis]), mid + half)\n if (hi - lo < 1e-6) continue\n const p: Vec3 = [a[0], a[1], a[2]], q: Vec3 = [b[0], b[1], b[2]]\n p[axis] = lo\n q[axis] = hi\n out.push([p, q])\n }\n return out\n}\n\n/** Steel mass in kg of bars of `diameter` metres. */\nexport const rebarMass = (bars: readonly Bar[], diameter: number, density = STEEL_DENSITY): number => {\n let length = 0\n for (const [a, b] of bars) length += Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]) + Math.abs(a[2] - b[2])\n return Math.PI * (diameter / 2) * (diameter / 2) * length * density\n}\n","[\n {\n \"id\": \"steel\",\n \"density\": 7850,\n \"hpPerKg\": 400,\n \"penetration\": 110,\n \"ductility\": 0.9,\n \"fracture\": \"none\",\n \"damageScale\": {\n \"slash\": 0.1,\n \"blunt\": 0.8\n },\n \"hitDebris\": \"sparks\",\n \"breakDebris\": \"sparks\",\n \"ricochetDeg\": 20,\n \"thermal\": {\n \"meltC\": 1450,\n \"meltRate\": 0.05,\n \"conductivity\": 0.5,\n \"heatCapacity\": 3\n },\n \"visual\": {\n \"glows\": true\n },\n \"tags\": [\n \"metal\",\n \"conductive\"\n ],\n \"compressive\": 2000000\n },\n {\n \"id\": \"cast_iron\",\n \"density\": 7200,\n \"hpPerKg\": 150,\n \"penetration\": 160,\n \"ductility\": 0.2,\n \"fracture\": \"snap\",\n \"fragmentSize\": [\n 0.08,\n 0.3\n ],\n \"damageScale\": {\n \"slash\": 0.1,\n \"blunt\": 1.2\n },\n \"hitDebris\": \"sparks\",\n \"breakDebris\": \"chips\",\n \"ricochetDeg\": 15,\n \"thermal\": {\n \"meltC\": 1200,\n \"meltRate\": 0.05,\n \"conductivity\": 0.45,\n \"heatCapacity\": 3\n },\n \"visual\": {\n \"glows\": true\n },\n \"tags\": [\n \"metal\",\n \"conductive\"\n ],\n \"compressive\": 1500000\n },\n {\n \"id\": \"aluminium\",\n \"density\": 2700,\n \"hpPerKg\": 250,\n \"penetration\": 60,\n \"ductility\": 0.85,\n \"fracture\": \"none\",\n \"damageScale\": {\n \"slash\": 0.2\n },\n \"hitDebris\": \"sparks\",\n \"breakDebris\": \"sparks\",\n \"ricochetDeg\": 15,\n \"thermal\": {\n \"meltC\": 660,\n \"meltRate\": 0.06,\n \"conductivity\": 0.8,\n \"heatCapacity\": 1.5\n },\n \"visual\": {\n \"glows\": true\n },\n \"tags\": [\n \"metal\",\n \"conductive\"\n ],\n \"compressive\": 800000\n },\n {\n \"id\": \"copper\",\n \"density\": 8960,\n \"hpPerKg\": 300,\n \"penetration\": 70,\n \"ductility\": 0.95,\n \"fracture\": \"none\",\n \"damageScale\": {\n \"slash\": 0.2\n },\n \"hitDebris\": \"sparks\",\n \"breakDebris\": \"sparks\",\n \"ricochetDeg\": 15,\n \"thermal\": {\n \"meltC\": 1085,\n \"meltRate\": 0.05,\n \"conductivity\": 1,\n \"heatCapacity\": 2.5\n },\n \"visual\": {\n \"glows\": true\n },\n \"tags\": [\n \"metal\",\n \"conductive\"\n ],\n \"compressive\": 1000000\n },\n {\n \"id\": \"wood_soft\",\n \"density\": 500,\n \"hpPerKg\": 90,\n \"penetration\": 9,\n \"ductility\": 0.35,\n \"fracture\": \"splinter\",\n \"fragmentSize\": [\n 0.03,\n 0.15\n ],\n \"damageScale\": {\n \"blunt\": 1.2,\n \"slash\": 1.5\n },\n \"hitDebris\": \"splinters\",\n \"breakDebris\": \"splinters\",\n \"thermal\": {\n \"ignitionC\": 300,\n \"flameC\": 800,\n \"fuelFraction\": 0.9,\n \"burnRate\": 0.012,\n \"conductivity\": 0.05,\n \"heatCapacity\": 1.2,\n \"smoke\": \"grey\"\n },\n \"visual\": {\n \"charColor\": 1709072\n },\n \"tags\": [\n \"wood\",\n \"organic\",\n \"flammable\"\n ],\n \"compressive\": 100000\n },\n {\n \"id\": \"wood_hard\",\n \"density\": 750,\n \"hpPerKg\": 140,\n \"penetration\": 14,\n \"ductility\": 0.3,\n \"fracture\": \"splinter\",\n \"fragmentSize\": [\n 0.03,\n 0.2\n ],\n \"damageScale\": {\n \"slash\": 1.2\n },\n \"hitDebris\": \"splinters\",\n \"breakDebris\": \"splinters\",\n \"thermal\": {\n \"ignitionC\": 330,\n \"flameC\": 800,\n \"fuelFraction\": 0.9,\n \"burnRate\": 0.01,\n \"conductivity\": 0.06,\n \"heatCapacity\": 1.4,\n \"smoke\": \"grey\"\n },\n \"visual\": {\n \"charColor\": 1709072\n },\n \"tags\": [\n \"wood\",\n \"organic\",\n \"flammable\"\n ],\n \"compressive\": 150000\n },\n {\n \"id\": \"plywood\",\n \"density\": 600,\n \"hpPerKg\": 70,\n \"penetration\": 7,\n \"ductility\": 0.3,\n \"fracture\": \"snap\",\n \"fragmentSize\": [\n 0.1,\n 0.4\n ],\n \"damageScale\": {\n \"slash\": 1.3\n },\n \"hitDebris\": \"splinters\",\n \"breakDebris\": \"splinters\",\n \"thermal\": {\n \"ignitionC\": 300,\n \"flameC\": 800,\n \"fuelFraction\": 0.85,\n \"burnRate\": 0.013,\n \"conductivity\": 0.05,\n \"heatCapacity\": 1.2,\n \"smoke\": \"grey\"\n },\n \"visual\": {\n \"charColor\": 1709072\n },\n \"tags\": [\n \"wood\",\n \"organic\",\n \"flammable\"\n ],\n \"compressive\": 60000\n },\n {\n \"id\": \"mdf\",\n \"density\": 750,\n \"hpPerKg\": 45,\n \"penetration\": 6,\n \"ductility\": 0.15,\n \"fracture\": \"snap\",\n \"fragmentSize\": [\n 0.08,\n 0.35\n ],\n \"hitDebris\": \"chips\",\n \"breakDebris\": \"dust\",\n \"thermal\": {\n \"ignitionC\": 290,\n \"flameC\": 750,\n \"fuelFraction\": 0.85,\n \"burnRate\": 0.014,\n \"conductivity\": 0.05,\n \"heatCapacity\": 1.2,\n \"smoke\": \"grey\"\n },\n \"visual\": {\n \"charColor\": 1709072\n },\n \"tags\": [\n \"wood\",\n \"organic\",\n \"flammable\"\n ],\n \"compressive\": 30000\n },\n {\n \"id\": \"glass\",\n \"density\": 2500,\n \"hpPerKg\": 12,\n \"penetration\": 6,\n \"ductility\": 0.02,\n \"fracture\": \"shatter\",\n \"fragmentSize\": [\n 0.05,\n 0.25\n ],\n \"damageScale\": {\n \"blunt\": 1.5\n },\n \"hitDebris\": \"shards\",\n \"breakDebris\": \"shards\",\n \"ricochetDeg\": 8,\n \"thermal\": {\n \"meltC\": 1400,\n \"meltRate\": 0.03,\n \"conductivity\": 0.1,\n \"heatCapacity\": 1.5,\n \"thermalShockC\": 150\n },\n \"visual\": {\n \"glows\": true,\n \"transparent\": true\n },\n \"tags\": [\n \"glass\",\n \"brittle\"\n ],\n \"compressive\": 100000\n },\n {\n \"id\": \"tempered_glass\",\n \"density\": 2500,\n \"hpPerKg\": 30,\n \"penetration\": 9,\n \"ductility\": 0.02,\n \"fracture\": \"crumble\",\n \"fragmentSize\": [\n 0.006,\n 0.02\n ],\n \"hitDebris\": \"shards\",\n \"breakDebris\": \"shards\",\n \"ricochetDeg\": 8,\n \"thermal\": {\n \"meltC\": 1400,\n \"meltRate\": 0.03,\n \"conductivity\": 0.1,\n \"heatCapacity\": 1.5,\n \"thermalShockC\": 250\n },\n \"visual\": {\n \"glows\": true,\n \"transparent\": true\n },\n \"tags\": [\n \"glass\",\n \"brittle\"\n ],\n \"compressive\": 200000\n },\n {\n \"id\": \"ceramic\",\n \"density\": 2400,\n \"hpPerKg\": 25,\n \"penetration\": 12,\n \"ductility\": 0.02,\n \"fracture\": \"shatter\",\n \"fragmentSize\": [\n 0.03,\n 0.12\n ],\n \"damageScale\": {\n \"blunt\": 1.3\n },\n \"hitDebris\": \"chips\",\n \"breakDebris\": \"shards\",\n \"thermal\": {\n \"conductivity\": 0.1,\n \"heatCapacity\": 1.5,\n \"thermalShockC\": 200\n },\n \"tags\": [\n \"ceramic\",\n \"brittle\"\n ],\n \"compressive\": 150000\n },\n {\n \"id\": \"concrete\",\n \"density\": 2300,\n \"hpPerKg\": 14,\n \"penetration\": 18,\n \"ductility\": 0.03,\n \"fracture\": \"crumble\",\n \"fragmentSize\": [\n 0.05,\n 0.25\n ],\n \"damageScale\": {\n \"explosive\": 1.2\n },\n \"hitDebris\": \"chips\",\n \"breakDebris\": \"dust\",\n \"thermal\": {\n \"conductivity\": 0.15,\n \"heatCapacity\": 2.5\n },\n \"tags\": [\n \"masonry\",\n \"brittle\"\n ],\n \"compressive\": 444000\n },\n {\n \"id\": \"brick\",\n \"density\": 1900,\n \"hpPerKg\": 12,\n \"penetration\": 14,\n \"ductility\": 0.05,\n \"fracture\": \"crumble\",\n \"fragmentSize\": [\n 0.04,\n 0.12\n ],\n \"hitDebris\": \"chips\",\n \"breakDebris\": \"dust\",\n \"thermal\": {\n \"conductivity\": 0.15,\n \"heatCapacity\": 2.5\n },\n \"tags\": [\n \"masonry\",\n \"brittle\"\n ],\n \"compressive\": 40000\n },\n {\n \"id\": \"plaster\",\n \"density\": 850,\n \"hpPerKg\": 18,\n \"penetration\": 3,\n \"ductility\": 0.05,\n \"fracture\": \"crumble\",\n \"fragmentSize\": [\n 0.05,\n 0.3\n ],\n \"hitDebris\": \"dust\",\n \"breakDebris\": \"dust\",\n \"thermal\": {\n \"conductivity\": 0.1,\n \"heatCapacity\": 1.5\n },\n \"tags\": [\n \"masonry\",\n \"brittle\"\n ],\n \"compressive\": 8000\n },\n {\n \"id\": \"stone\",\n \"density\": 2700,\n \"hpPerKg\": 25,\n \"penetration\": 25,\n \"ductility\": 0.03,\n \"fracture\": \"crumble\",\n \"fragmentSize\": [\n 0.06,\n 0.3\n ],\n \"hitDebris\": \"chips\",\n \"breakDebris\": \"dust\",\n \"thermal\": {\n \"conductivity\": 0.2,\n \"heatCapacity\": 2.5\n },\n \"tags\": [\n \"masonry\",\n \"brittle\"\n ],\n \"compressive\": 300000\n },\n {\n \"id\": \"plastic\",\n \"density\": 1100,\n \"hpPerKg\": 60,\n \"penetration\": 8,\n \"ductility\": 0.5,\n \"fracture\": \"snap\",\n \"fragmentSize\": [\n 0.05,\n 0.3\n ],\n \"hitDebris\": \"chips\",\n \"breakDebris\": \"chips\",\n \"thermal\": {\n \"ignitionC\": 400,\n \"flameC\": 700,\n \"fuelFraction\": 0.8,\n \"burnRate\": 0.02,\n \"meltC\": 200,\n \"meltRate\": 0.06,\n \"conductivity\": 0.05,\n \"heatCapacity\": 1,\n \"smoke\": \"black\"\n },\n \"visual\": {\n \"charColor\": 855309\n },\n \"tags\": [\n \"plastic\",\n \"flammable\"\n ],\n \"compressive\": 40000\n },\n {\n \"id\": \"rubber\",\n \"density\": 1100,\n \"hpPerKg\": 80,\n \"penetration\": 12,\n \"ductility\": 0.9,\n \"fracture\": \"tear\",\n \"fragmentSize\": [\n 0.05,\n 0.2\n ],\n \"hitDebris\": \"chips\",\n \"breakDebris\": \"fibers\",\n \"thermal\": {\n \"ignitionC\": 350,\n \"flameC\": 750,\n \"fuelFraction\": 0.6,\n \"burnRate\": 0.015,\n \"conductivity\": 0.05,\n \"heatCapacity\": 1.2,\n \"smoke\": \"black\"\n },\n \"visual\": {\n \"charColor\": 855309\n },\n \"tags\": [\n \"rubber\",\n \"flammable\"\n ],\n \"compressive\": 20000\n },\n {\n \"id\": \"fabric\",\n \"density\": 400,\n \"hpPerKg\": 20,\n \"penetration\": 0.8,\n \"ductility\": 0.8,\n \"fracture\": \"tear\",\n \"fragmentSize\": [\n 0.05,\n 0.25\n ],\n \"damageScale\": {\n \"slash\": 4,\n \"ballistic\": 0.5\n },\n \"hitDebris\": \"fibers\",\n \"breakDebris\": \"fibers\",\n \"thermal\": {\n \"ignitionC\": 230,\n \"flameC\": 600,\n \"fuelFraction\": 1,\n \"burnRate\": 0.05,\n \"conductivity\": 0.03,\n \"heatCapacity\": 0.6,\n \"smoke\": \"grey\"\n },\n \"visual\": {\n \"charColor\": 1709072\n },\n \"tags\": [\n \"fabric\",\n \"organic\",\n \"flammable\"\n ],\n \"compressive\": 500\n },\n {\n \"id\": \"foam\",\n \"density\": 30,\n \"hpPerKg\": 15,\n \"penetration\": 0.5,\n \"ductility\": 0.7,\n \"fracture\": \"tear\",\n \"fragmentSize\": [\n 0.03,\n 0.15\n ],\n \"damageScale\": {\n \"slash\": 2,\n \"ballistic\": 0.4\n },\n \"hitDebris\": \"fibers\",\n \"breakDebris\": \"fibers\",\n \"thermal\": {\n \"ignitionC\": 250,\n \"flameC\": 900,\n \"fuelFraction\": 0.95,\n \"burnRate\": 0.09,\n \"conductivity\": 0.02,\n \"heatCapacity\": 0.5,\n \"smoke\": \"black\"\n },\n \"visual\": {\n \"charColor\": 855309\n },\n \"tags\": [\n \"fabric\",\n \"flammable\"\n ],\n \"compressive\": 100\n },\n {\n \"id\": \"leather\",\n \"density\": 900,\n \"hpPerKg\": 50,\n \"penetration\": 4,\n \"ductility\": 0.8,\n \"fracture\": \"tear\",\n \"fragmentSize\": [\n 0.05,\n 0.25\n ],\n \"damageScale\": {\n \"slash\": 2\n },\n \"hitDebris\": \"fibers\",\n \"breakDebris\": \"fibers\",\n \"thermal\": {\n \"ignitionC\": 320,\n \"flameC\": 650,\n \"fuelFraction\": 0.7,\n \"burnRate\": 0.01,\n \"conductivity\": 0.05,\n \"heatCapacity\": 1,\n \"smoke\": \"grey\"\n },\n \"visual\": {\n \"charColor\": 1709072\n },\n \"tags\": [\n \"fabric\",\n \"organic\",\n \"flammable\"\n ],\n \"compressive\": 2000\n },\n {\n \"id\": \"paper\",\n \"density\": 700,\n \"hpPerKg\": 8,\n \"penetration\": 0.3,\n \"ductility\": 0.5,\n \"fracture\": \"tear\",\n \"fragmentSize\": [\n 0.03,\n 0.15\n ],\n \"damageScale\": {\n \"slash\": 3\n },\n \"hitDebris\": \"fibers\",\n \"breakDebris\": \"fibers\",\n \"thermal\": {\n \"ignitionC\": 230,\n \"flameC\": 600,\n \"fuelFraction\": 1,\n \"burnRate\": 0.06,\n \"conductivity\": 0.03,\n \"heatCapacity\": 0.5,\n \"smoke\": \"grey\"\n },\n \"visual\": {\n \"charColor\": 1709072\n },\n \"tags\": [\n \"fabric\",\n \"organic\",\n \"flammable\"\n ],\n \"compressive\": 500\n },\n {\n \"id\": \"foliage\",\n \"density\": 150,\n \"hpPerKg\": 20,\n \"penetration\": 0.5,\n \"ductility\": 0.6,\n \"fracture\": \"tear\",\n \"fragmentSize\": [\n 0.03,\n 0.1\n ],\n \"damageScale\": {\n \"slash\": 4\n },\n \"hitDebris\": \"leaves\",\n \"breakDebris\": \"leaves\",\n \"thermal\": {\n \"ignitionC\": 300,\n \"flameC\": 700,\n \"fuelFraction\": 0.8,\n \"burnRate\": 0.08,\n \"conductivity\": 0.03,\n \"heatCapacity\": 0.8,\n \"smoke\": \"white\"\n },\n \"visual\": {\n \"charColor\": 1709072\n },\n \"tags\": [\n \"plant\",\n \"organic\",\n \"flammable\"\n ],\n \"compressive\": 500\n },\n {\n \"id\": \"green_wood\",\n \"density\": 650,\n \"hpPerKg\": 5,\n \"penetration\": 10,\n \"ductility\": 0.5,\n \"fracture\": \"splinter\",\n \"fragmentSize\": [\n 0.03,\n 0.2\n ],\n \"damageScale\": {\n \"slash\": 1.3,\n \"ballistic\": 0.1\n },\n \"hitDebris\": \"splinters\",\n \"breakDebris\": \"leaves\",\n \"thermal\": {\n \"ignitionC\": 400,\n \"flameC\": 700,\n \"fuelFraction\": 0.8,\n \"burnRate\": 0.006,\n \"conductivity\": 0.06,\n \"heatCapacity\": 2,\n \"smoke\": \"white\"\n },\n \"visual\": {\n \"charColor\": 1709072\n },\n \"tags\": [\n \"plant\",\n \"wood\",\n \"organic\",\n \"flammable\"\n ],\n \"compressive\": 60000\n },\n {\n \"id\": \"cactus\",\n \"density\": 900,\n \"hpPerKg\": 30,\n \"penetration\": 2,\n \"ductility\": 0.6,\n \"fracture\": \"tear\",\n \"fragmentSize\": [\n 0.04,\n 0.15\n ],\n \"damageScale\": {\n \"slash\": 3\n },\n \"hitDebris\": \"fibers\",\n \"breakDebris\": \"fibers\",\n \"thermal\": {\n \"ignitionC\": 450,\n \"flameC\": 650,\n \"fuelFraction\": 0.3,\n \"burnRate\": 0.01,\n \"conductivity\": 0.05,\n \"heatCapacity\": 3,\n \"smoke\": \"white\"\n },\n \"visual\": {\n \"charColor\": 1709072\n },\n \"tags\": [\n \"plant\",\n \"organic\",\n \"flammable\"\n ],\n \"compressive\": 5000\n },\n {\n \"id\": \"flesh_fruit\",\n \"density\": 950,\n \"hpPerKg\": 15,\n \"penetration\": 1.5,\n \"ductility\": 0.7,\n \"fracture\": \"tear\",\n \"fragmentSize\": [\n 0.02,\n 0.08\n ],\n \"damageScale\": {\n \"slash\": 2\n },\n \"hitDebris\": \"drips\",\n \"breakDebris\": \"drips\",\n \"thermal\": {\n \"conductivity\": 0.05,\n \"heatCapacity\": 3\n },\n \"tags\": [\n \"plant\",\n \"organic\"\n ],\n \"compressive\": 1000\n },\n {\n \"id\": \"wax\",\n \"density\": 900,\n \"hpPerKg\": 30,\n \"penetration\": 3,\n \"ductility\": 0.5,\n \"fracture\": \"snap\",\n \"fragmentSize\": [\n 0.05,\n 0.2\n ],\n \"hitDebris\": \"chips\",\n \"breakDebris\": \"chips\",\n \"thermal\": {\n \"ignitionC\": 230,\n \"flameC\": 700,\n \"fuelFraction\": 0.9,\n \"burnRate\": 0.02,\n \"meltC\": 60,\n \"meltRate\": 0.2,\n \"conductivity\": 0.05,\n \"heatCapacity\": 0.8,\n \"smoke\": \"grey\"\n },\n \"tags\": [\n \"wax\",\n \"flammable\"\n ],\n \"compressive\": 5000\n },\n {\n \"id\": \"soil\",\n \"density\": 1300,\n \"hpPerKg\": 3,\n \"penetration\": 5,\n \"ductility\": 0.3,\n \"fracture\": \"crumble\",\n \"fragmentSize\": [\n 0.03,\n 0.12\n ],\n \"hitDebris\": \"dust\",\n \"breakDebris\": \"dust\",\n \"thermal\": {\n \"conductivity\": 0.1,\n \"heatCapacity\": 2.5\n },\n \"tags\": [\n \"soil\",\n \"masonry\"\n ],\n \"compressive\": 20000\n }\n]","{\n \"cast iron\": \"cast_iron\",\n \"cast_iron\": \"cast_iron\",\n \"castiron\": \"cast_iron\",\n \"metal\": \"steel\",\n \"steel\": \"steel\",\n \"iron\": \"steel\",\n \"chrome\": \"steel\",\n \"alumin\": \"aluminium\",\n \"alu_\": \"aluminium\",\n \"alu-\": \"aluminium\",\n \"alu \": \"aluminium\",\n \"copper\": \"copper\",\n \"brass\": \"copper\",\n \"bronze\": \"copper\",\n \"wood\": \"wood_soft\",\n \"timber\": \"wood_soft\",\n \"plank\": \"wood_soft\",\n \"lumber\": \"wood_soft\",\n \"pine\": \"wood_soft\",\n \"hardwood\": \"wood_hard\",\n \"oak\": \"wood_hard\",\n \"plywood\": \"plywood\",\n \"mdf\": \"mdf\",\n \"chipboard\": \"mdf\",\n \"glass\": \"glass\",\n \"window\": \"glass\",\n \"mirror\": \"glass\",\n \"tempered\": \"tempered_glass\",\n \"windshield\": \"tempered_glass\",\n \"fabric\": \"fabric\",\n \"cloth\": \"fabric\",\n \"cushion\": \"fabric\",\n \"sofa\": \"fabric\",\n \"curtain\": \"fabric\",\n \"carpet\": \"fabric\",\n \"textile\": \"fabric\",\n \"canvas\": \"fabric\",\n \"foam\": \"foam\",\n \"sponge\": \"foam\",\n \"mattress\": \"foam\",\n \"leather\": \"leather\",\n \"paper\": \"paper\",\n \"cardboard\": \"paper\",\n \"leaf\": \"foliage\",\n \"leaves\": \"foliage\",\n \"foliage\": \"foliage\",\n \"bush\": \"foliage\",\n \"grass\": \"foliage\",\n \"trunk\": \"green_wood\",\n \"branch\": \"green_wood\",\n \"twig\": \"green_wood\",\n \"cactus\": \"cactus\",\n \"fruit\": \"flesh_fruit\",\n \"apple\": \"flesh_fruit\",\n \"melon\": \"flesh_fruit\",\n \"wax\": \"wax\",\n \"candle\": \"wax\",\n \"concrete\": \"concrete\",\n \"cement\": \"concrete\",\n \"brick\": \"brick\",\n \"tile\": \"ceramic\",\n \"ceramic\": \"ceramic\",\n \"porcelain\": \"ceramic\",\n \"stone\": \"stone\",\n \"rock\": \"stone\",\n \"marble\": \"stone\",\n \"plaster\": \"plaster\",\n \"drywall\": \"plaster\",\n \"gypsum\": \"plaster\",\n \"plastic\": \"plastic\",\n \"pvc\": \"plastic\",\n \"acrylic\": \"plastic\",\n \"rubber\": \"rubber\",\n \"tire\": \"rubber\",\n \"tyre\": \"rubber\",\n \"soil\": \"soil\",\n \"dirt\": \"soil\",\n \"potting\": \"soil\",\n \"mud\": \"soil\"\n}","import materialsJson from './data/materials.json'\nimport hintsJson from './data/material-hints.json'\nimport { aabbOf, quatFromEuler, shapeDims } from './math'\nimport type { JointKind, JointSpec, MaterialDef, MaterialId, PartShape, PartSpec, ToolKind } from './types'\n\n/** Built-in materials (data in `src/data/materials.json`). Override or extend with the `materials` option of `createDestruction`. */\nexport const MATERIALS: MaterialDef[] = materialsJson as unknown as MaterialDef[]\n\n/** Default joint strength (joint hit points), tools that undo it and seconds of tool work. */\nexport const JOINT_DEFAULTS: Record<JointKind, { strength: number; tools: ToolKind[]; seconds: number }> = {\n screw: { strength: 80, tools: ['screwdriver'], seconds: 2.5 },\n bolt: { strength: 200, tools: ['wrench'], seconds: 4 },\n nail: { strength: 60, tools: ['pry_bar', 'hammer'], seconds: 2 },\n weld: { strength: 600, tools: ['cutting_torch', 'saw'], seconds: 8 },\n glue: { strength: 50, tools: ['pry_bar', 'knife'], seconds: 3 },\n hinge: { strength: 120, tools: ['screwdriver'], seconds: 3 },\n clip: { strength: 20, tools: ['hand'], seconds: 0.6 },\n tie: { strength: 15, tools: ['knife', 'hand'], seconds: 1 },\n mortar: { strength: 400, tools: ['hammer'], seconds: 6 },\n fused: { strength: 1000, tools: [], seconds: 0 },\n stem: { strength: 40, tools: ['knife', 'saw', 'hand'], seconds: 1.5 },\n rebar: { strength: 1500, tools: ['cutting_torch', 'saw'], seconds: 20 },\n resting: { strength: 30, tools: ['hand'], seconds: 1 },\n}\n\nconst has = (m: MaterialDef, tag: string) => !!m.tags && m.tags.includes(tag)\n\n/**\n * The joint kind that fits two materials: glass is glued (clipped to plastic), soft things are tied, plants share a stem, masonry gets mortar,\n * metal is welded, wood is screwed, plastic clips. `inferJoints` refines weld to bolt for thick metal and screw to nail for thin wood.\n */\nexport const JOINT_BY_MATERIALS = (a: MaterialDef, b: MaterialDef): JointKind => {\n const any = (tag: string) => has(a, tag) || has(b, tag)\n const both = (tag: string) => has(a, tag) && has(b, tag)\n if (any('glass')) return any('plastic') ? 'clip' : 'glue'\n if (any('fabric')) return 'tie'\n if (both('plant')) return 'stem'\n if (any('plant')) return 'tie'\n if (both('masonry')) return 'mortar'\n if (any('masonry') && any('metal')) return 'bolt'\n if (both('metal')) return 'weld'\n if (any('plastic')) return 'clip'\n if (any('rubber') || any('wax')) return 'glue'\n return 'screw'\n}\n\nconst MATERIAL_MAP: ReadonlyMap<MaterialId, MaterialDef> = new Map(MATERIALS.map((m) => [m.id, m]))\n\nconst HINTS = Object.entries(hintsJson as Record<string, string>).sort((x, y) => y[0].length - x[0].length)\n\n/** Guess a material id from a mesh or node name (case-insensitive substring; the longest keyword wins). */\nexport const guessMaterial = (name: string): MaterialId | undefined => {\n const n = name.toLowerCase()\n for (const [key, id] of HINTS) if (n.includes(key)) return id\n return undefined\n}\n\n/** Volume of a shape in m³. */\nexport const partVolume = (shape: PartShape): number => {\n if (shape.kind === 'box') return shape.size[0] * shape.size[1] * shape.size[2]\n if (shape.kind === 'cylinder') return Math.PI * shape.radius * shape.radius * shape.height\n return (4 / 3) * Math.PI * shape.radius ** 3\n}\n\n/** Mass of a part in kg: its `mass`, or density × volume × fill. */\nexport const partMass = (part: PartSpec, material: MaterialDef): number => part.mass ?? material.density * partVolume(part.shape) * (part.fill ?? 1)\n\n/** Wall thickness of a part in metres (see `PartSpec.thickness`). */\nexport const partThickness = (part: PartSpec): number => {\n const dims = shapeDims(part.shape)\n const min = Math.min(dims[0], dims[1], dims[2])\n return Math.max(1e-4, Math.min(part.thickness ?? min * (part.fill ?? 1), min))\n}\n\n/**\n * Joints for touching parts. Two parts touch when their axis-aligned bounds (after rotation), grown by `tolerance` metres, overlap. The kind comes\n * from `JOINT_BY_MATERIALS`; thick metal pairs (smallest dimension of both >= 2 cm) get a `bolt` instead of a `weld`, and thin wood pairs (either\n * under 2 cm) a `nail` instead of a `screw`.\n */\nexport const inferJoints = (parts: PartSpec[], tolerance = 0.01, materials: ReadonlyMap<string, MaterialDef> = MATERIAL_MAP): JointSpec[] => {\n const boxes = parts.map((p) => aabbOf(p.shape, p.position, quatFromEuler(...(p.rotation ?? [0, 0, 0]))))\n const out: JointSpec[] = []\n for (let i = 0; i < parts.length; i++) {\n for (let j = i + 1; j < parts.length; j++) {\n const a = boxes[i], b = boxes[j]\n let touch = true\n for (let k = 0; k < 3 && touch; k++) if (a.min[k] - tolerance > b.max[k] || b.min[k] - tolerance > a.max[k]) touch = false\n if (!touch) continue\n const ma = materials.get(parts[i].material)\n const mb = materials.get(parts[j].material)\n let kind: JointKind = ma && mb ? JOINT_BY_MATERIALS(ma, mb) : 'screw'\n const thin = Math.min(partThickness(parts[i]), partThickness(parts[j]))\n if (kind === 'weld' && thin >= 0.02) kind = 'bolt'\n if (kind === 'screw' && ma && mb && has(ma, 'wood') && has(mb, 'wood') && thin < 0.02) kind = 'nail'\n out.push({ id: `${parts[i].id}~${parts[j].id}`, a: parts[i].id, b: parts[j].id, kind })\n }\n }\n return out\n}\n\n/**\n * Load in kg a structural part carries before it fails: `structure.capacity`, else `material.compressive` (default 20 000 kg/m²) times the\n * section. The section is the product of the two smallest dimensions (thickness times longest dimension for slabs; thickness times horizontal length for walls); foundations get x10.\n */\nexport const partCapacity = (part: PartSpec, material: MaterialDef): number => {\n if (part.structure?.capacity !== undefined) return part.structure.capacity\n const d = shapeDims(part.shape).sort((a, b) => a - b)\n const role = part.structure?.role\n const sh = shapeDims(part.shape)\n const section = role === 'wall' || role === 'partition' ? Math.min(sh[0], sh[2]) * Math.max(sh[0], sh[2]) : role === 'slab' ? d[0] * d[2] : d[0] * d[1]\n return Math.max(1, section * (material.compressive ?? 20000) * (role === 'foundation' ? 10 : 1))\n}\n\n\n/**\n * Multiplier of blunt damage on brittle parts (ductility < 0.3): up to x4.7 for fully brittle materials (glass, ceramic, stone), times a thinness\n * term that follows bending stress (1 / thickness squared, x1 at 2 cm or more, at most x25). A 3 mm glass bottle breaks from a 1.5 m drop; a\n * concrete block (thick) is only ever x4.4.\n */\nexport const fragility = (ductility: number, thickness: number): number => {\n if (ductility >= 0.3) return 1\n return (1 + (4 * (0.3 - ductility)) / 0.3) * Math.min(25, Math.max(1, (0.02 / Math.max(thickness, 1e-4)) ** 2))\n}\n","import { chainDelayOf, drawChainDelay, FIRE_PRIME_C, shotDamageFractionOf } from './chain'\nimport type { ChainTrigger } from './chain'\nimport { planFragments } from './fracture'\nimport type { PlannedFragment } from './fracture'\nimport { cellsOutside, cellsWithin, marksInBox, planeAxes, unitGrid } from './breach'\nimport type { LocalHole, UnitCell } from './breach'\nimport { layersEnergy, layersThickness, MAX_SPALLS, outerLayer, resolveLayer, thinAxisOf } from './layers'\nimport type { LayerRT } from './layers'\nimport { clipBarsToDisc, rebarBars, rebarMass } from './rebar'\nimport { JOINT_DEFAULTS, inferJoints, MATERIALS, partCapacity, partMass, partThickness, partVolume, fragility } from './materials'\nimport { aabbOf, createRng, distanceToShape, quat, quatFromEuler, rayShape, rotateVec, shapeArea, shapeBound, shapeDims, surfacePoint, toLocal, toWorld, vec } from './math'\nimport type { DestructibleImpl } from './contracts'\nimport type {\n AddOptions, Crack, DamageType, DebrisKind, DestructibleSpec, Dent, DestructionEvent, DestructionEventType, DestructionOptions, DestructionSnapshot,\n DamageStage, DestructionWorld, Fragment, Hit, HitResult, Hole, JointSpec, JointState, MaterialDef, MaterialId, ObjectRuntime, ObjectState, PartRuntime, PartSpec,\n PartState, Quat, RayHit, ToolKind, Vec3,\n} from './types'\n\n/** Hit points removed per joule (before the material's `damageScale`). */\nconst DMG_PER_J = 0.02\n/** Fraction of a blast's energy that reaches a part at distance 0. */\nconst BLAST_COUPLING = 0.1\nconst FLAMMABLE_FLUIDS = ['gas', 'fuel']\n/** Staged parts: default breach radius (m), blast multiplier on the breach area, area a part must lose to open (m²), and the share of capacity the bare cage keeps. */\nconst BREACH_RADIUS = 0.55\nconst BREACH_BLAST_FACTOR = 6\nconst BREACH_AREA = 0.25\nconst RESIDUAL_CAPACITY = 0.15\n/** Unit-sized fragments of a whole wall: at most this many times `maxFragments`. A breach picks its units from a grid of up to `BREACH_GRID_CAP`. */\nconst UNIT_FRAGMENT_FACTOR = 4\nconst BREACH_GRID_CAP = 4096\n\n/** A cut only goes through a slice of the part, so a part longer than `CUT_SLICE` costs no more to cut than a 1 m piece of the same section. */\nconst CUT_SLICE = 1\nconst cutFactorOf = (shape: PartSpec['shape']): number => clamp(Math.max(...shapeDims(shape)) / CUT_SLICE, 1, 50)\n\ninterface PartRT {\n spec: PartSpec\n mat: MaterialDef\n st: PartState\n q: Quat\n /** Current object-local position (the spec's, unless moved by `setPartPose`). */\n pos: Vec3\n mass0: number\n fuel0: number\n area: number\n thickness: number\n /** Slash damage multiplier: longest dimension / 1 m (1..50). */\n cutFactor: number\n dims: Vec3\n bound: number\n rt: PartRuntime\n /** Structural role other than `none`. */\n structural: boolean\n anchored: boolean\n cap: number\n /** The part has layers, units, reinforcement or a breach: it goes through damage stages. */\n staged: boolean\n /** Axis the part is thinnest along (the wall's depth). */\n thin: number\n layers: LayerRT[]\n}\n\ninterface JointRT {\n spec: Required<JointSpec>\n st: JointState\n ia: number\n ib: number\n bears: boolean | 'a_on_b' | 'b_on_a'\n /** Object-local position. */\n pos: Vec3\n step: number\n}\n\ninterface ObjRT {\n id: string\n spec: DestructibleSpec\n st: ObjectState\n parts: PartRT[]\n byId: Map<string, PartRT>\n idx: Map<string, number>\n joints: JointRT[]\n jointMap: Map<string, JointRT>\n byPart: Map<string, JointRT[]>\n /** Local bounding sphere. */\n bc: Vec3\n br: number\n active: boolean\n tmp: number[]\n hasStructure: boolean\n dirty: boolean\n maxStress: number\n collapsed: Set<string>\n /** Structural parts with no support path to an anchored part (they fall). */\n unsup: boolean[]\n anyAnchor: boolean\n /** Creation order of the object in this world: breaks ties between parts that go off at the same time. */\n order: number\n}\n\ninterface Carry {\n parts: Map<string, { st: PartState; rt: PartRuntime }>\n joints: Map<string, { st: JointState; step: number }>\n collapsed?: string[]\n}\n\ninterface Loc {\n p: PartRT\n point: Vec3\n normal: Vec3\n dir: Vec3\n pathLen: number\n}\n\ninterface ImplRT {\n impl: DestructibleImpl\n position: Vec3\n rotation: Quat\n /** Part pose overrides set by `setPartPose` (object-local). */\n poses: Map<string, { pos: Vec3; q: Quat }>\n}\n\ninterface Blast {\n point: Vec3\n energy: number\n radius: number\n source?: string\n}\n\nconst clamp = (v: number, a: number, b: number) => Math.max(a, Math.min(b, v))\n/** Share of its capacity a structural part still has: a bare rebar cage keeps the reinforcement's residual, a breached part loses what left it. */\nconst capacityScale = (p: PartRT): number => {\n if (p.st.stripped) return p.spec.reinforcement?.residualCapacity ?? RESIDUAL_CAPACITY\n return p.rt.removed ? Math.max(0.05, 1 - p.rt.removed / p.mass0) : 1\n}\nconst isLost = (p: PartRT) => p.st.status === 'broken' || p.st.status === 'melted' || p.st.status === 'ashes'\nconst clone = <T>(v: T): T => structuredClone(v)\n/**\n * Fraction of a structural part's hit points lost per second while its stress is above 1. A floor of 0.12 makes even a barely overloaded part\n * give way in about 8 s (a rate proportional to the excess alone never finishes: stress 1.02 would take two minutes), then it grows with the\n * excess and tops out at 0.6: stress 1.1 fails in ~4.5 s, 1.5 in ~1.9 s and anything above 1.7 in ~1.7 s. Deterministic: depends only on stress.\n */\nconst overloadRate = (stress: number) => Math.min(0.6, 0.12 + 0.8 * (stress - 1))\nconst updateBound = (o: ObjRT) => {\n if (!o.parts.length) return\n const c: Vec3 = [0, 0, 0]\n for (const p of o.parts) for (let k = 0; k < 3; k++) c[k] += p.pos[k] / o.parts.length\n let r = 0\n for (const p of o.parts) r = Math.max(r, vec.distance(c, p.pos) + p.bound)\n o.bc = c\n o.br = r\n}\nconst AXIS = { x: 0, y: 1, z: 2 } as const\n\nexport const createDestruction = (options: DestructionOptions = {}): DestructionWorld => {\n const materials = new Map<MaterialId, MaterialDef>()\n for (const m of MATERIALS) materials.set(m.id, m)\n for (const m of options.materials ?? []) materials.set(m.id, m)\n const ambient = options.ambientC ?? 20\n const maxFragments = options.maxFragments ?? 24\n const maxDents = options.maxDents ?? 24\n const maxHoles = options.maxHoles ?? 32\n const fireSpread = options.fireSpread ?? 0.6\n const breachRadius = options.breach?.radius ?? BREACH_RADIUS\n const breachBlastFactor = options.breach?.blastFactor ?? BREACH_BLAST_FACTOR\n const rng = createRng(options.seed ?? 1)\n const rnd = () => rng.next()\n\n let time = 0\n let counter = 0\n const objects = new Map<string, ObjRT>()\n const listeners = new Map<string, Set<(e: DestructionEvent) => void>>()\n let cur: DestructionEvent[] = []\n const blasts: Blast[] = []\n /** Explosive parts that were primed and wait for their delay. */\n const primed = new Map<PartRT, ObjRT>()\n let orderCounter = 0\n const impls = new Map<string, ImplRT>()\n const taken = (id: string) => objects.has(id) || impls.has(id)\n\n // -------------------------------------------------------------------------------------------------------------------------------------------\n // Events\n // -------------------------------------------------------------------------------------------------------------------------------------------\n\n const emit = (e: DestructionEvent) => {\n cur.push(e)\n options.onEvent?.(e)\n const all = listeners.get('*')\n if (all) for (const fn of [...all]) fn(e)\n const typed = listeners.get(e.type)\n if (typed) for (const fn of [...typed]) fn(e)\n }\n const base = (o: ObjRT, source?: string): { object: string; time: number; source?: string } =>\n source === undefined ? { object: o.id, time } : { object: o.id, time, source }\n\n const pendingCollapse = new Map<ObjRT, string | undefined>()\n let runDepth = 0\n\n /** Blasts queued by parts that exploded; each can prime or set off more parts. It ends: a part goes off once and is primed once, so the queue only grows by parts not yet lost. */\n const drainBlasts = () => {\n for (let blast = blasts.shift(); blast; blast = blasts.shift()) blastWorld(blast.point, blast.energy, blast.radius, blast.source)\n }\n\n const run = <T>(fn: () => T): { value: T; events: DestructionEvent[] } => {\n const prev = cur\n const mine: DestructionEvent[] = []\n cur = mine\n runDepth++\n try {\n const value = fn()\n drainBlasts()\n if (runDepth === 1) flushCollapse()\n return { value, events: mine }\n } finally {\n runDepth--\n cur = prev\n }\n }\n\n // -------------------------------------------------------------------------------------------------------------------------------------------\n // Building objects\n // -------------------------------------------------------------------------------------------------------------------------------------------\n\n const nextId = () => {\n let id: string\n do id = `obj_${++counter}`\n while (taken(id))\n return id\n }\n\n const freshRuntime = (): PartRuntime => ({ meltEmitted: 0, dripT: 0, prevTemp: ambient, shockT: 0, jet: false })\n\n const resolveSpec = (spec: DestructibleSpec): DestructibleSpec => {\n const out = clone(spec)\n const joints = out.joints ?? inferJoints(out.parts, 0.01, materials)\n const structural = (id: string) => {\n const role = out.parts.find((p) => p.id === id)?.structure?.role\n return role !== undefined && role !== 'none'\n }\n out.joints = joints.map((j) => {\n const def = JOINT_DEFAULTS[j.kind]\n return {\n id: j.id ?? `${j.a}~${j.b}`, a: j.a, b: j.b, kind: j.kind, strength: j.strength ?? def.strength, tools: j.tools ?? [...def.tools], seconds: j.seconds ?? def.seconds,\n bears: j.bears ?? (structural(j.a) && structural(j.b)),\n }\n })\n return out\n }\n\n const build = (spec: DestructibleSpec, id: string, pos: Vec3, rot: Quat, carry?: Carry): ObjRT => {\n const st: ObjectState = { id, position: [pos[0], pos[1], pos[2]], rotation: [rot[0], rot[1], rot[2], rot[3]], parts: [], joints: [], groups: [], destroyed: false }\n if (spec.name !== undefined) st.name = spec.name\n const o: ObjRT = {\n id, spec, st, parts: [], byId: new Map(), idx: new Map(), joints: [], jointMap: new Map(), byPart: new Map(), bc: [0, 0, 0], br: 0, active: false, tmp: [], hasStructure: false, dirty: false, maxStress: 0, collapsed: new Set(carry?.collapsed ?? []), unsup: [], anyAnchor: false, order: ++orderCounter,\n }\n for (const ps of spec.parts) {\n if (o.byId.has(ps.id)) throw new Error(`duplicate part id \"${ps.id}\"`)\n const mat = materials.get(ps.material)\n if (!mat) throw new Error(`unknown material \"${ps.material}\" on part \"${ps.id}\"`)\n const mass0 = partMass(ps, mat)\n const maxHp = Math.max(1, ps.hp ?? mass0 * mat.hpPerKg)\n const fuel0 = mat.thermal.ignitionC !== undefined ? mass0 * (mat.thermal.fuelFraction ?? 0) : 0\n const c = carry?.parts.get(ps.id)\n const staged = !!(ps.layers?.length || ps.reinforcement || ps.units || ps.breach)\n const layers = (ps.layers ?? []).map((l, i) => {\n const lm = materials.get(l.material)\n if (!lm) throw new Error(`unknown material \"${l.material}\" on layer ${i} of part \"${ps.id}\"`)\n return resolveLayer(l, i, lm)\n })\n if (ps.reinforcement && !materials.has(ps.reinforcement.material)) throw new Error(`unknown material \"${ps.reinforcement.material}\" on the reinforcement of part \"${ps.id}\"`)\n const pst: PartState = c?.st ?? {\n id: ps.id, material: ps.material, status: 'intact', hp: maxHp, maxHp, mass: mass0, temperature: ambient, burning: false, fuel: fuel0, char: 0, melt: 0,\n dents: [], holes: [], cracks: [], group: 0, ...(staged ? { stage: 0 as DamageStage } : {}),\n }\n if (!c && ps.contains) pst.liters = ps.contains.liters\n const p: PartRT = {\n spec: ps, mat, st: pst, q: quatFromEuler(...(ps.rotation ?? [0, 0, 0])), pos: [ps.position[0], ps.position[1], ps.position[2]], mass0, fuel0, area: shapeArea(ps.shape), thickness: partThickness(ps), cutFactor: cutFactorOf(ps.shape),\n dims: shapeDims(ps.shape), bound: shapeBound(ps.shape), rt: c?.rt ?? { ...freshRuntime(), prevTemp: pst.temperature },\n structural: !!ps.structure && ps.structure.role !== 'none', anchored: !!ps.anchored || ps.structure?.role === 'foundation', cap: ps.structure ? partCapacity(ps, mat) : 0,\n staged, thin: thinAxisOf(shapeDims(ps.shape)), layers,\n }\n if (p.structural) o.hasStructure = true\n if (p.rt.chainDue !== undefined && !isLost(p)) primed.set(p, o)\n o.idx.set(ps.id, o.parts.length)\n o.parts.push(p)\n o.byId.set(ps.id, p)\n o.st.parts.push(pst)\n o.byPart.set(ps.id, [])\n }\n for (const js of spec.joints ?? []) {\n const r = js as Required<JointSpec>\n const ia = o.idx.get(r.a), ib = o.idx.get(r.b)\n if (ia === undefined || ib === undefined) throw new Error(`joint \"${r.id}\" references an unknown part`)\n if (o.jointMap.has(r.id)) throw new Error(`duplicate joint id \"${r.id}\"`)\n const pa = o.parts[ia], pb = o.parts[ib]\n const A = aabbOf(pa.spec.shape, pa.spec.position, pa.q)\n const B = aabbOf(pb.spec.shape, pb.spec.position, pb.q)\n const pos: Vec3 = [0, 0, 0]\n for (let k = 0; k < 3; k++) pos[k] = (Math.max(A.min[k], B.min[k]) + Math.min(A.max[k], B.max[k])) / 2\n const bears: JointRT['bears'] = r.bears ?? (pa.structural && pb.structural)\n const c = carry?.joints.get(r.id)\n const jst: JointState = c?.st ?? { id: r.id, a: r.a, b: r.b, kind: r.kind, hp: r.strength, maxHp: r.strength, progress: 0, open: false }\n const j: JointRT = { spec: r, st: jst, ia, ib, bears, pos, step: c?.step ?? 0 }\n o.joints.push(j)\n o.jointMap.set(r.id, j)\n o.byPart.get(r.a)!.push(j)\n o.byPart.get(r.b)!.push(j)\n o.st.joints.push(jst)\n }\n // open joints whose parts are no longer both here (left behind by `splitGroup`) stay listed, inert, so callers still see them open\n for (const [jid, c] of carry?.joints ?? []) if (c.st.open && !o.jointMap.has(jid)) o.st.joints.push(c.st)\n updateBound(o)\n o.anyAnchor = o.parts.some((p) => p.anchored)\n o.unsup = o.parts.map(() => false)\n solveStructure(o)\n recomputeGroups(o)\n o.st.destroyed = o.parts.length > 0 && o.parts.every(isLost)\n o.active = o.maxStress > 0.8 || o.parts.some((p) => p.st.burning || p.st.temperature > ambient + 0.5 || (p.st.liters ?? 0) > 0)\n return o\n }\n\n const recomputeGroups = (o: ObjRT) => {\n const n = o.parts.length\n const parent = Array.from({ length: n }, (_, i) => i)\n const find = (i: number): number => {\n while (parent[i] !== i) {\n parent[i] = parent[parent[i]]\n i = parent[i]\n }\n return i\n }\n const union = (a: number, b: number) => {\n parent[find(a)] = find(b)\n }\n const live = (j: JointRT) => !j.st.open && !isLost(o.parts[j.ia]) && !isLost(o.parts[j.ib])\n if (o.unsup.some(Boolean)) {\n // parts that lost every support fall: cut them from the supported pieces; loose non-structural parts follow the part they hang on\n for (const j of o.joints) if (live(j) && !o.unsup[j.ia] && !o.unsup[j.ib]) union(j.ia, j.ib)\n const supported = new Set<number>()\n for (let i = 0; i < n; i++) if (!isLost(o.parts[i]) && !o.unsup[i] && (o.parts[i].structural || o.parts[i].anchored)) supported.add(find(i))\n for (const j of o.joints) {\n if (!live(j) || !(o.unsup[j.ia] || o.unsup[j.ib])) continue\n if (o.unsup[j.ia] && o.unsup[j.ib]) union(j.ia, j.ib)\n else {\n const u = o.unsup[j.ia] ? j.ia : j.ib\n const other = u === j.ia ? j.ib : j.ia\n if (!o.parts[other].structural && !supported.has(find(other))) union(u, other)\n }\n }\n } else for (const j of o.joints) if (live(j)) union(j.ia, j.ib)\n const comps = new Map<number, number[]>()\n for (let i = 0; i < n; i++) {\n if (isLost(o.parts[i])) continue\n const r = find(i)\n const l = comps.get(r)\n if (l) l.push(i)\n else comps.set(r, [i])\n }\n const list = [...comps.values()].map((ix) => ({\n ix,\n anchored: ix.some((i) => o.parts[i].anchored),\n mass: ix.reduce((s, i) => s + o.parts[i].st.mass, 0),\n }))\n list.sort((a, b) => (a.anchored === b.anchored ? (b.mass - a.mass) || (a.ix[0] - b.ix[0]) : a.anchored ? -1 : 1))\n o.st.groups = list.map((g) => g.ix.map((i) => o.parts[i].spec.id))\n for (const p of o.parts) if (isLost(p)) p.st.group = -1\n list.forEach((g, gi) => g.ix.forEach((i) => (o.parts[i].st.group = gi)))\n }\n\n /** Which part `r` rests on over joint `j` (index), or -1 when the joint does not let `r` rest on its other end. */\n const restsOn = (j: JointRT, r: number): number => {\n const b = j.bears\n if (!b) return -1\n if (b === true) return j.ia === r ? j.ib : j.ia\n if (b === 'a_on_b') return j.ia === r ? j.ib : -1\n return j.ib === r ? j.ia : -1\n }\n\n /** Distribute own mass plus carried load down the bearing graph to the anchored parts; mark parts without any support path. */\n const solveStructure = (o: ObjRT) => {\n o.maxStress = 0\n if (!o.hasStructure) return\n const parts = o.parts\n const n = parts.length\n const dist = new Array<number>(n).fill(-1)\n const queue: number[] = []\n const ok = (i: number) => parts[i].structural && !isLost(parts[i])\n const isPartition = (i: number) => parts[i].spec.structure?.role === 'partition'\n for (let i = 0; i < n; i++) if (ok(i) && parts[i].anchored) {\n dist[i] = 0\n queue.push(i)\n }\n for (let h = 0; h < queue.length; h++) {\n const s = queue[h]\n if (isPartition(s)) continue\n for (const j of o.byPart.get(parts[s].spec.id)!) {\n if (j.st.open || !j.bears) continue\n const r = j.ia === s ? j.ib : j.ia\n if (dist[r] >= 0 || !ok(r) || restsOn(j, r) !== s) continue\n dist[r] = dist[s] + 1\n queue.push(r)\n }\n }\n const incoming = new Array<number>(n).fill(0)\n for (let h = queue.length - 1; h >= 0; h--) {\n const i = queue[h]\n const total = parts[i].st.mass + incoming[i]\n parts[i].st.load = total\n const lower: number[] = []\n for (const j of o.byPart.get(parts[i].spec.id)!) {\n if (j.st.open || !j.bears) continue\n const k = restsOn(j, i)\n if (k >= 0 && dist[k] >= 0 && dist[k] < dist[i] && !isPartition(k)) lower.push(k)\n }\n for (const k of lower) incoming[k] += total / lower.length\n }\n for (let i = 0; i < n; i++) {\n const p = parts[i]\n o.unsup[i] = false\n if (!p.structural) continue\n if (dist[i] < 0 || isLost(p)) {\n p.st.load = p.st.mass\n p.st.stress = 0\n o.unsup[i] = o.anyAnchor && !isLost(p)\n continue\n }\n p.st.stress = p.st.load! / (p.cap * capacityScale(p))\n if (p.st.stress > o.maxStress) o.maxStress = p.st.stress\n }\n if (o.maxStress > 0.8) o.active = true\n }\n\n /**\n * Ask for a collapse report. It is not computed right away: a blow can break several parts in one go (a column and the roof's supports, or a\n * column whose joint opens just before the column itself fractures), so the groups are examined once, after every loss of the operation.\n */\n const collapseCheck = (o: ObjRT, src?: string) => {\n if (!o.hasStructure || !o.parts.some((p) => p.anchored)) return\n if (!pendingCollapse.has(o)) pendingCollapse.set(o, src)\n }\n\n /** Report the groups of remaining structural parts that lost every anchor (each part is reported once). */\n const flushCollapse = () => {\n for (const [o, src] of [...pendingCollapse]) {\n pendingCollapse.delete(o)\n if (!objects.has(o.id) || objects.get(o.id) !== o) continue\n for (const g of o.st.groups) {\n const ps = g.map((id) => o.byId.get(id)!).filter((p) => !isLost(p) && !o.collapsed.has(p.spec.id))\n if (ps.length === 0 || g.some((id) => o.byId.get(id)!.anchored) || !ps.some((p) => p.structural)) continue\n for (const p of ps) {\n o.collapsed.add(p.spec.id)\n p.st.status = 'collapsed'\n setStage(o, p, 3, {}, src)\n }\n emit({ ...base(o, src), type: 'collapse', parts: ps.map((p) => p.spec.id), mass: ps.reduce((sum, p) => sum + p.st.mass, 0) })\n }\n }\n }\n\n const getObj = (id: string): ObjRT => {\n const o = objects.get(id)\n if (!o) throw new Error(`unknown object \"${id}\"`)\n return o\n }\n const getPart = (o: ObjRT, id: string): PartRT => {\n const p = o.byId.get(id)\n if (!p) throw new Error(`unknown part \"${id}\" in object \"${o.id}\"`)\n return p\n }\n\n // -------------------------------------------------------------------------------------------------------------------------------------------\n // Geometry in world space\n // -------------------------------------------------------------------------------------------------------------------------------------------\n\n const partXf = (o: ObjRT, p: PartRT): { c: Vec3; q: Quat } => ({ c: toWorld(o.st.position, o.st.rotation, p.pos), q: quat.mul(o.st.rotation, p.q) })\n const objLocal = (o: ObjRT, w: Vec3) => toLocal(o.st.position, o.st.rotation, w)\n const objLocalDir = (o: ObjRT, w: Vec3) => rotateVec(quat.conjugate(o.st.rotation), w)\n const jointWorld = (o: ObjRT, j: JointRT) => toWorld(o.st.position, o.st.rotation, j.pos)\n const distToPart = (o: ObjRT, p: PartRT, w: Vec3) => {\n const { c, q } = partXf(o, p)\n return distanceToShape(p.spec.shape, toLocal(c, q, w))\n }\n const partWorldAabb = (o: ObjRT, p: PartRT) => {\n const { c, q } = partXf(o, p)\n return aabbOf(p.spec.shape, c, q)\n }\n\n interface PartRay { t0: number; t1: number; n: Vec3 }\n const rayPartRaw = (pos: Vec3, rot: Quat, spec: PartSpec, pq: Quat, origin: Vec3, d: Vec3, lp: Vec3 = spec.position): PartRay | null => {\n const c = toWorld(pos, rot, lp)\n const q = quat.mul(rot, pq)\n const qi = quat.conjugate(q)\n const r = rayShape(spec.shape, rotateVec(qi, vec.sub(origin, c)), rotateVec(qi, d))\n return r ? { t0: r.t0, t1: r.t1, n: rotateVec(q, r.n0) } : null\n }\n const rayPart = (o: ObjRT, p: PartRT, origin: Vec3, d: Vec3): PartRay | null => rayPartRaw(o.st.position, o.st.rotation, p.spec, p.q, origin, d, p.pos)\n\n const raySphereMiss = (origin: Vec3, d: Vec3, c: Vec3, r: number, maxDist: number): boolean => {\n const oc = vec.sub(origin, c)\n const b = vec.dot(oc, d)\n const cc = vec.dot(oc, oc) - r * r\n if (cc > 0 && b > 0) return true\n const disc = b * b - cc\n if (disc < 0) return true\n return -b - Math.sqrt(disc) > maxDist\n }\n\n const raycastInternal = (origin: Vec3, dir: Vec3, maxDist: number, ignore?: Set<string>): (RayHit & { pathLen: number }) | null => {\n const d = vec.normalize(dir)\n let best: (RayHit & { pathLen: number }) | null = null\n for (const o of objects.values()) {\n if (raySphereMiss(origin, d, toWorld(o.st.position, o.st.rotation, o.bc), o.br, best ? Math.min(maxDist, best.distance) : maxDist)) continue\n for (const p of o.parts) {\n if (isLost(p) || ignore?.has(`${o.id}\\0${p.spec.id}`)) continue\n const r = rayPart(o, p, origin, d)\n if (!r || r.t0 < 0 || r.t0 > maxDist) continue\n if (p.st.opening && insideOpening(o, p, vec.madd(origin, d, r.t0))) continue\n if (!best || r.t0 < best.distance) best = { object: o.id, part: p.spec.id, point: vec.madd(origin, d, r.t0), normal: r.n, distance: r.t0, pathLen: r.t1 - r.t0 }\n }\n }\n for (const im of impls.values()) {\n for (const ps of im.impl.describe().parts) {\n if (ignore?.has(`${im.impl.id}\\0${ps.id}`)) continue\n const ov = im.poses.get(ps.id)\n const r = rayPartRaw(im.position, im.rotation, ps, ov?.q ?? quatFromEuler(...(ps.rotation ?? [0, 0, 0])), origin, d, ov?.pos)\n if (!r || r.t0 < 0 || r.t0 > maxDist) continue\n if (!best || r.t0 < best.distance) best = { object: im.impl.id, part: ps.id, point: vec.madd(origin, d, r.t0), normal: r.n, distance: r.t0, pathLen: r.t1 - r.t0 }\n }\n }\n return best\n }\n\n // impl hosting\n const implHit = (im: ImplRT, hit: Hit): HitResult => {\n let h = hit\n if (hit.space === 'local') {\n h = { ...hit, space: 'world', point: toWorld(im.position, im.rotation, hit.point) }\n if (hit.direction) h.direction = rotateVec(im.rotation, hit.direction)\n }\n const start = cur.length\n for (const e of im.impl.hit(h) ?? []) emit(e.time === undefined ? { ...e, time } : e)\n const mine = cur.slice(start)\n const res: HitResult = { object: im.impl.id, damage: 0, penetrated: false, exitEnergy: 0, events: mine, point: hit.point }\n for (const e of mine) {\n if (e.type === 'damage') res.damage += e.amount\n if (e.type === 'hole' && e.hole.through) res.penetrated = true\n if (res.part === undefined && 'part' in e) res.part = (e as { part: string }).part\n }\n return res\n }\n\n const implJointPos = (im: ImplRT, a: string, b: string): Vec3 | null => {\n const parts = im.impl.describe().parts\n const pa = parts.find((p) => p.id === a), pb = parts.find((p) => p.id === b)\n if (!pa || !pb) return null\n const A = aabbOf(pa.shape, pa.position, quatFromEuler(...(pa.rotation ?? [0, 0, 0])))\n const B = aabbOf(pb.shape, pb.position, quatFromEuler(...(pb.rotation ?? [0, 0, 0])))\n const pos: Vec3 = [0, 0, 0]\n for (let k = 0; k < 3; k++) pos[k] = (Math.max(A.min[k], B.min[k]) + Math.min(A.max[k], B.max[k])) / 2\n return toWorld(im.position, im.rotation, pos)\n }\n\n /** Find the part a hit lands on: a short ray along `dir`, else the nearest part within `tol`. */\n const locate = (o: ObjRT, point: Vec3, dir: Vec3 | undefined, tol: number, only?: PartRT): Loc | null => {\n const cands = only ? [only] : o.parts\n if (dir && vec.length(dir) > 1e-9) {\n const d = vec.normalize(dir)\n const origin = vec.madd(point, d, -0.05)\n let best: Loc | null = null\n let bestT = Infinity\n let inside: Loc | null = null\n for (const p of cands) {\n if (isLost(p)) continue\n const r = rayPart(o, p, origin, d)\n if (!r) continue\n if (r.t0 >= 0 && r.t0 <= 0.15) {\n if (r.t0 < bestT) {\n bestT = r.t0\n best = { p, point: vec.madd(origin, d, r.t0), normal: r.n, dir: d, pathLen: Math.max(r.t1 - r.t0, 1e-4) }\n }\n } else if (r.t0 < 0 && r.t1 > 0 && !inside) {\n inside = { p, point, normal: vec.scale(d, -1), dir: d, pathLen: Math.max(r.t1 - 0.05, p.thickness) }\n }\n }\n if (best) return best\n if (inside) return inside\n }\n let np: PartRT | null = null\n let nd = Infinity\n for (const p of cands) {\n if (isLost(p)) continue\n const dd = distToPart(o, p, point)\n if (dd < nd) {\n nd = dd\n np = p\n }\n }\n if (!np || nd > tol) return null\n const { c, q } = partXf(o, np)\n const sp = surfacePoint(np.spec.shape, toLocal(c, q, point))\n const normal = rotateVec(q, sp.normal)\n return { p: np, point: toWorld(c, q, sp.point), normal, dir: dir && vec.length(dir) > 1e-9 ? vec.normalize(dir) : vec.scale(normal, -1), pathLen: np.thickness }\n }\n\n // -------------------------------------------------------------------------------------------------------------------------------------------\n // Marks on parts\n // -------------------------------------------------------------------------------------------------------------------------------------------\n\n const markDamaged = (p: PartRT) => {\n if (p.st.status === 'intact') p.st.status = 'damaged'\n }\n\n const addDent = (o: ObjRT, p: PartRT, wp: Vec3, wn: Vec3, radius: number, depth: number, src?: string) => {\n const dent: Dent = { point: objLocal(o, wp), normal: objLocalDir(o, wn), radius, depth }\n const arr = p.st.dents\n let ni = -1, nd = Infinity\n for (let i = 0; i < arr.length; i++) {\n const dd = vec.distance(arr[i].point, dent.point)\n if (dd < nd) {\n nd = dd\n ni = i\n }\n }\n if (ni >= 0 && (arr.length >= maxDents || nd < arr[ni].radius * 0.6)) {\n arr[ni].depth = Math.min(0.1, Math.max(arr[ni].depth, depth) + depth * 0.3)\n arr[ni].radius = Math.max(arr[ni].radius, radius)\n } else arr.push(dent)\n markDamaged(p)\n emit({ ...base(o, src), type: 'dent', part: p.spec.id, dent, worldPoint: wp })\n }\n\n const addHole = (o: ObjRT, p: PartRT, wp: Vec3, wn: Vec3, diameter: number, through: boolean, exit?: Vec3, src?: string) => {\n const hole: Hole = { point: objLocal(o, wp), normal: objLocalDir(o, wn), diameter, through }\n p.st.holes.push(hole)\n if (p.st.holes.length > maxHoles) p.st.holes.shift()\n markDamaged(p)\n emit({ ...base(o, src), type: 'hole', part: p.spec.id, hole, worldPoint: wp, ...(exit ? { exitPoint: exit } : {}) })\n setStage(o, p, 1, {}, src)\n return hole\n }\n\n const addCrack = (o: ObjRT, p: PartRT, wp: Vec3, wn: Vec3, length: number, src?: string) => {\n const crack: Crack = { point: objLocal(o, wp), normal: objLocalDir(o, wn), length: Math.min(length, Math.max(p.bound, 0.05)), rays: 5 + Math.floor(rnd() * 5) }\n p.st.cracks.push(crack)\n if (p.st.cracks.length > 16) p.st.cracks.shift()\n markDamaged(p)\n emit({ ...base(o, src), type: 'crack', part: p.spec.id, crack, worldPoint: wp })\n setStage(o, p, 1, {}, src)\n }\n\n const debris = (o: ObjRT, p: PartRT, kind: DebrisKind, point: Vec3, normal: Vec3, count: number, speed: number, src?: string) =>\n emit({ ...base(o, src), type: 'debris', part: p.spec.id, kind, point, normal, count, speed })\n\n const holeRate = (hole: Hole, pressurized: boolean) => (pressurized ? 0.5 : 0.1) * (hole.diameter / 0.009)\n\n // -------------------------------------------------------------------------------------------------------------------------------------------\n // Failure, joints\n // -------------------------------------------------------------------------------------------------------------------------------------------\n\n const detachEvents = (o: ObjRT, opened: JointRT[], by: 'break' | 'tool' | 'part_lost', src?: string) => {\n for (const j of opened) emit({ ...base(o, src), type: 'detach', joint: j.spec.id, parts: [j.spec.a, j.spec.b], by, groups: o.st.groups.map((g) => [...g]) })\n }\n\n const checkDestroyed = (o: ObjRT, src?: string) => {\n if (!o.st.destroyed && o.parts.length > 0 && o.parts.every(isLost)) {\n o.st.destroyed = true\n emit({ ...base(o, src), type: 'destroyed' })\n }\n }\n\n const partLost = (o: ObjRT, p: PartRT, src?: string) => {\n const opened: JointRT[] = []\n for (const j of o.byPart.get(p.spec.id) ?? []) {\n if (j.st.open) continue\n j.st.open = true\n j.st.openedBy = 'part_lost'\n opened.push(j)\n }\n solveStructure(o)\n recomputeGroups(o)\n detachEvents(o, opened, 'part_lost', src)\n collapseCheck(o, src)\n checkDestroyed(o, src)\n }\n\n /**\n * Distance from a world point to the joint's contact region: the overlap box of the two parts' bounds (or, when they only nearly touch, the box\n * of the gap between them). Measuring to the joint centre would make a thick part untouchable: a blow on a trunk's surface is half the trunk's\n * width away from a joint that sits on its axis.\n */\n const jointReach = (o: ObjRT, j: JointRT, point: Vec3): number => {\n const A = partWorldAabb(o, o.parts[j.ia]), B = partWorldAabb(o, o.parts[j.ib])\n let d2 = 0\n for (let k = 0; k < 3; k++) {\n const lo = Math.min(Math.max(A.min[k], B.min[k]), Math.min(A.max[k], B.max[k]))\n const hi = Math.max(Math.max(A.min[k], B.min[k]), Math.min(A.max[k], B.max[k]))\n const d = point[k] < lo ? lo - point[k] : point[k] > hi ? point[k] - hi : 0\n d2 += d * d\n }\n return Math.sqrt(d2)\n }\n /** How far from the contact region a blow still counts: half the smallest dimension of the smaller part, at least 6 cm. */\n const jointReachLimit = (o: ObjRT, j: JointRT): number => {\n const pa = o.parts[j.ia], pb = o.parts[j.ib]\n const small = pa.dims[0] * pa.dims[1] * pa.dims[2] <= pb.dims[0] * pb.dims[1] * pb.dims[2] ? pa : pb\n return Math.max(0.06, 0.5 * Math.min(small.dims[0], small.dims[1], small.dims[2]))\n }\n\n const wearJoints = (o: ObjRT, p: PartRT, amount: number, near?: Vec3, radius = 0.06, src?: string, split = false) => {\n if (amount <= 0) return\n const mine = (o.byPart.get(p.spec.id) ?? []).filter((j) => !j.st.open)\n if (split && mine.length) amount /= mine.length\n for (const j of mine) {\n if (j.st.open) continue\n // the rebar of a reinforced part is its cage: blows do not wear it, only a torch or a saw cuts it (or the cage itself giving way)\n if (j.spec.kind === 'rebar' && (o.parts[j.ia].spec.reinforcement || o.parts[j.ib].spec.reinforcement)) continue\n if (near && jointReach(o, j, near) > Math.max(radius, jointReachLimit(o, j))) continue\n j.st.hp -= amount\n if (j.st.hp <= 0) {\n j.st.hp = 0\n j.st.open = true\n j.st.openedBy = 'break'\n solveStructure(o)\n recomputeGroups(o)\n detachEvents(o, [j], 'break', src)\n collapseCheck(o, src)\n }\n }\n }\n\n // -------------------------------------------------------------------------------------------------------------------------------------------\n // Damage stages: spall, breach, reinforcement cage\n // -------------------------------------------------------------------------------------------------------------------------------------------\n\n const setStage = (o: ObjRT, p: PartRT, stage: DamageStage, extra: { opening?: { center: Vec3; radius: number }; fragments?: Fragment[] } = {}, src?: string) => {\n if (!p.staged || (p.st.stage ?? 0) >= stage) return\n p.st.stage = stage\n emit({ ...base(o, src), type: 'stage', part: p.spec.id, stage, ...extra })\n }\n\n /** `1` when the outward normal points along the part's local +thin axis, else `-1`. */\n const faceOf = (o: ObjRT, p: PartRT, worldNormal: Vec3): number => (rotateVec(quat.conjugate(partXf(o, p).q), worldNormal)[p.thin] >= 0 ? 1 : -1)\n\n const spallOuter = (o: ObjRT, p: PartRT, wp: Vec3, face: number, normal: Vec3, radius: number, src?: string) => {\n if (p.layers.length === 0) return\n const lp = objLocal(o, wp)\n const layer = outerLayer(p.layers, p.rt.spalls, face, lp)\n if (!layer) return\n const spalls = (p.rt.spalls ??= [])\n spalls.push([layer.index, face, lp[0], lp[1], lp[2], radius])\n if (spalls.length > MAX_SPALLS) spalls.shift()\n markDamaged(p)\n emit({ ...base(o, src), type: 'spall', part: p.spec.id, layer: layer.index, point: wp, area: Math.PI * radius * radius })\n debris(o, p, layer.mat.hitDebris, wp, normal, 5, 2, src)\n setStage(o, p, 1, {}, src)\n }\n\n const insideOpening = (o: ObjRT, p: PartRT, objectPoint: Vec3): boolean => {\n const op = p.st.opening\n if (!op) return false\n const [u, v] = planeAxes(p.thin)\n const lp = toLocal(p.pos, p.q, objectPoint)\n const lc = toLocal(p.pos, p.q, op.center)\n return Math.hypot(lp[u] - lc[u], lp[v] - lc[v]) <= op.radius\n }\n\n /** Square metres of wall a blow removes: the volume its damage takes out, over the thickness it crosses. */\n const breachAreaOf = (p: PartRT, damage: number, blast: boolean): number =>\n (damage / (p.mat.hpPerKg * p.mat.density) / Math.max(p.thickness, 0.005)) * (blast ? breachBlastFactor : 1)\n\n const localHolesOf = (p: PartRT): LocalHole[] =>\n p.st.holes.map((h) => ({ point: toLocal(p.pos, p.q, h.point), normal: rotateVec(quat.conjugate(p.q), h.normal), diameter: h.diameter }))\n\n const unitsOf = (p: PartRT) => p.spec.units ?? { size: [p.mat.fragmentSize?.[1] ?? 0.2, p.mat.fragmentSize?.[1] ?? 0.2, p.thickness] as Vec3, bond: 'stack' as const }\n\n const FRAGMENT_SHAPE = { shatter: 'shard', splinter: 'splinter', tear: 'scrap' } as const\n\n /** Unit-sized fragments of `cells` (part-local), thrown from `hitW`; the holes that fell on a unit stay on it as `marks`. */\n const cellFragments = (o: ObjRT, p: PartRT, cells: readonly UnitCell[], hitW: Vec3, dir: Vec3 | null, speed: number, mass: number, tag: string): Fragment[] => {\n const { c, q } = partXf(o, p)\n const holes = p.st.holes.length > 0 ? localHolesOf(p) : []\n const [u, v] = planeAxes(p.thin)\n const faceArea = (cell: UnitCell) => cell.size[u] * cell.size[v]\n const total = cells.reduce((sum, cell) => sum + faceArea(cell), 0) || 1\n const shape = p.spec.units ? 'chunk' : FRAGMENT_SHAPE[p.mat.fracture as keyof typeof FRAGMENT_SHAPE] ?? 'chunk'\n return cells.map((cell, i) => {\n const cw = toWorld(c, q, cell.center)\n const out = vec.normalize(vec.sub(cw, hitW), [0, 1, 0])\n const dv = dir ? vec.normalize(vec.madd(out, dir, 0.6)) : out\n const k = speed * (0.6 + 0.8 * rnd())\n const marks = marksInBox(cell.center, cell.size, undefined, holes)\n return {\n id: `${p.spec.id}#${tag}${i}`, part: p.spec.id, material: p.spec.material, shape, center: cw, size: [cell.size[0], cell.size[1], cell.size[2]], rotation: q,\n velocity: [dv[0] * k, dv[1] * k + 0.5 * rnd(), dv[2] * k], angularVelocity: [(rnd() - 0.5) * 8, (rnd() - 0.5) * 8, (rnd() - 0.5) * 8],\n mass: (mass * faceArea(cell)) / total, ...(marks.length > 0 ? { marks } : {}),\n }\n })\n }\n\n const worldBars = (o: ObjRT, p: PartRT, bars: ReadonlyArray<readonly [Vec3, Vec3]>): Array<[Vec3, Vec3]> => {\n const { c, q } = partXf(o, p)\n return bars.map(([a, b]) => [toWorld(c, q, a), toWorld(c, q, b)])\n }\n\n /** A blow that made through damage of `area` m² at `wp` (world): adds up with the earlier ones within the breach radius, and opens the part past its threshold. */\n const addBreach = (o: ObjRT, p: PartRT, wp: Vec3, area: number, energy: number, dir: Vec3 | null, src?: string) => {\n if (!p.staged || area <= 0 || (p.st.stage ?? 0) >= 2 || p.st.stripped || isLost(p)) return\n const lp = objLocal(o, wp)\n const list = (p.rt.breach ??= [])\n list.push([lp[0], lp[1], lp[2], area])\n if (list.length > MAX_SPALLS) list.shift()\n let total = 0\n const sum: Vec3 = [0, 0, 0]\n for (const [x, y, z, a] of list) {\n if (vec.distance([x, y, z], lp) > breachRadius) continue\n total += a\n sum[0] += x * a\n sum[1] += y * a\n sum[2] += z * a\n }\n if (total < (p.spec.breach?.area ?? BREACH_AREA)) return\n openBreach(o, p, [sum[0] / total, sum[1] / total, sum[2] / total], total, energy, dir, src)\n }\n\n /**\n * Stage 2: the units around `center` (object-local) come out as fragments the size of one unit, the part keeps an opening and its mass drops. An\n * opening as wide as the part cuts it in two (a column, a lintel): that is a fracture instead.\n */\n const openBreach = (o: ObjRT, p: PartRT, center: Vec3, total: number, energy: number, dir: Vec3 | null, src?: string) => {\n const [u, v] = planeAxes(p.thin)\n const radius = clamp(Math.sqrt(total / Math.PI), Math.sqrt((p.spec.breach?.area ?? BREACH_AREA) / Math.PI), breachRadius)\n const lc = toLocal(p.pos, p.q, center)\n lc[p.thin] = 0\n const { c, q } = partXf(o, p)\n const worldCenter = toWorld(c, q, lc)\n if (2 * radius >= Math.min(p.dims[u], p.dims[v])) {\n failPart(o, p, worldCenter, dir, energy, 12, src)\n return\n }\n const cells = cellsWithin(unitGrid(p.dims, p.thin, unitsOf(p), BREACH_GRID_CAP), p.thin, lc, radius)\n const removed = (p.st.mass * cells.reduce((sum, cell) => sum + cell.size[u] * cell.size[v], 0)) / (p.dims[u] * p.dims[v])\n const speed = clamp(Math.sqrt((2 * energy * 0.1) / Math.max(removed, 0.05)), 0.5, 8)\n const fragments = cellFragments(o, p, cells, worldCenter, dir, speed, removed, 'b')\n const holes = localHolesOf(p)\n p.st.holes = p.st.holes.filter((_, i) => !cells.some((cell) => marksInBox(cell.center, cell.size, undefined, [holes[i]!]).length > 0))\n p.st.mass = Math.max(0, p.st.mass - removed)\n p.rt.removed = (p.rt.removed ?? 0) + removed\n p.st.opening = { center: objLocal(o, worldCenter), radius }\n markDamaged(p)\n setStage(o, p, 1, {}, src)\n setStage(o, p, 2, { opening: { center: worldCenter, radius }, fragments }, src)\n debris(o, p, p.mat.breakDebris, worldCenter, vec.scale(dir ?? [0, 1, 0], -1), 14, 3, src)\n const reinforcement = p.spec.reinforcement\n if (reinforcement) {\n const bars = worldBars(o, p, clipBarsToDisc(rebarBars(p.dims, p.thin, reinforcement.spacing), u, v, [lc[u], lc[v]], radius + 0.05))\n if (bars.length > 0) emit({ ...base(o, src), type: 'expose', part: p.spec.id, bars })\n }\n if (p.structural) solveStructure(o)\n }\n\n /** The concrete of a reinforced part is gone: the part stays as its rebar cage, with the capacity the reinforcement leaves it. */\n const stripPart = (o: ObjRT, p: PartRT, reinforcement: NonNullable<PartSpec['reinforcement']>, src?: string) => {\n const bars = rebarBars(p.dims, p.thin, reinforcement.spacing)\n p.st.stripped = true\n p.st.hp = p.st.maxHp\n p.st.mass = rebarMass(bars, reinforcement.diameter, materials.get(reinforcement.material)?.density)\n p.st.holes = []\n p.st.burning = false\n p.rt.jet = false\n markDamaged(p)\n emit({ ...base(o, src), type: 'expose', part: p.spec.id, bars: worldBars(o, p, bars) })\n solveStructure(o)\n collapseCheck(o, src)\n }\n\n /** The units of the part that are still there (the opening of a breach is already gone), as a fragment plan. */\n const unitFragmentPlan = (p: PartRT, cap: number): PlannedFragment[] => {\n const grid = unitGrid(p.dims, p.thin, unitsOf(p), cap)\n const op = p.st.opening\n const cells = op ? cellsOutside(grid, p.thin, toLocal(p.pos, p.q, op.center), op.radius) : grid\n const [u, v] = planeAxes(p.thin)\n return cells.map((cell) => ({ center: cell.center, size: cell.size, q: quat.identity(), shape: 'chunk' as const, weight: cell.size[u] * cell.size[v] }))\n }\n\n /** The bare cage gives way (overload, a blast, a cut that finishes): the part is lost for good. */\n const loseCage = (o: ObjRT, p: PartRT, src?: string) => {\n p.st.status = 'broken'\n p.st.hp = 0\n p.st.mass = 0\n emit({ ...base(o, src), type: 'expose', part: p.spec.id, bars: [] })\n debris(o, p, 'sparks', partXf(o, p).c, [0, 1, 0], 6, 3, src)\n partLost(o, p, src)\n }\n\n /** Part hit points reached 0 (or it was forced to explode): fragments, debris, joints open. */\n const failPart = (o: ObjRT, p: PartRT, origin: Vec3 | null, dir: Vec3 | null, fragEnergy: number, cap: number, src?: string) => {\n if (isLost(p)) return\n if (p.st.stripped) {\n loseCage(o, p, src)\n return\n }\n const ex = p.spec.explodes\n const style = p.mat.fracture === 'none' ? 'snap' : p.mat.fracture\n const { c, q } = partXf(o, p)\n const hitW = origin ?? c\n const grain = p.spec.grain ? AXIS[p.spec.grain] : undefined\n const hitLocal = toLocal(c, q, hitW)\n const unitPlan = p.spec.units ? unitFragmentPlan(p, maxFragments * UNIT_FRAGMENT_FACTOR) : []\n const plan = unitPlan.length > 0 ? unitPlan : planFragments({\n style, dims: p.dims, thickness: p.thickness, grain, hit: hitLocal, fragmentSize: p.mat.fragmentSize ?? [0.04, 0.2], maxFragments, rnd,\n })\n const holes = p.st.holes.length > 0 ? localHolesOf(p) : []\n const mass = p.st.mass\n const totW = plan.reduce((s, f) => s + f.weight, 0) || 1\n const energy = ex ? ex.energy * 0.2 : fragEnergy\n const speed = clamp(Math.sqrt((2 * energy) / Math.max(mass, 0.05)), 0.3, ex ? 40 : cap)\n const fragments: Fragment[] = plan.map((f, i) => {\n const cw = toWorld(c, q, f.center)\n const out = vec.normalize(vec.sub(cw, hitW), [0, 1, 0])\n const dv = dir ? vec.normalize(vec.madd(out, dir, 0.6)) : out\n const k = speed * (0.6 + 0.8 * rnd())\n const marks = marksInBox(f.center, f.size, f.q, holes)\n return {\n id: `${p.spec.id}#${i}`, part: p.spec.id, material: p.spec.material, shape: f.shape, center: cw, size: f.size, rotation: quat.mul(q, f.q),\n velocity: [dv[0] * k, dv[1] * k + 0.5 * rnd(), dv[2] * k],\n angularVelocity: [(rnd() - 0.5) * 12, (rnd() - 0.5) * 12, (rnd() - 0.5) * 12],\n mass: (mass * f.weight) / totW, ...(marks.length > 0 ? { marks } : {}),\n }\n })\n const reinforcement = p.spec.reinforcement\n if (!reinforcement) {\n p.st.status = 'broken'\n p.st.hp = 0\n p.st.mass = 0\n p.st.burning = false\n p.rt.jet = false\n }\n emit({ ...base(o, src), type: 'fracture', part: p.spec.id, style, fragments, point: hitW })\n debris(o, p, p.mat.breakDebris, c, [0, 1, 0], clamp(Math.round(Math.cbrt(partVolume(p.spec.shape)) * 30), 3, 20), 2, src)\n setStage(o, p, 3, {}, src)\n if (reinforcement) {\n stripPart(o, p, reinforcement, src)\n return\n }\n if (ex) {\n emit({ ...base(o, src), type: 'explode', part: p.spec.id, point: c, energy: ex.energy, radius: ex.radius })\n blasts.push({ point: c, energy: ex.energy, radius: ex.radius, source: src })\n }\n partLost(o, p, src)\n }\n\n /**\n * Sets an explosive part off from outside (`explodes.chain`): it will explode after the delay of `trigger`, once. The delay is one draw\n * from the world seed, so the same inputs give the same order of blasts.\n */\n const prime = (o: ObjRT, p: PartRT, trigger: ChainTrigger, src?: string) => {\n const spec = chainDelayOf(p.spec, trigger)\n if (spec === undefined || isLost(p) || p.rt.chainDue !== undefined) return\n const delay = drawChainDelay(spec, rnd)\n p.rt.chainDue = time + delay\n primed.set(p, o)\n o.active = true\n emit({ ...base(o, src), type: 'primed', part: p.spec.id, point: partXf(o, p).c, trigger, delay })\n }\n\n const CHAIN_TRIGGER_OF: Partial<Record<DamageType, ChainTrigger>> = { ballistic: 'shot', explosive: 'explosion' }\n\n /** Remove hit points. Returns the amount actually removed. */\n const applyDamage = (o: ObjRT, p: PartRT, amount: number, type: DamageType, origin: Vec3 | null, dir: Vec3 | null, fragEnergy: number, cap: number, src?: string): number => {\n if (isLost(p) || amount <= 0) return 0\n const prev = p.st.hp\n p.st.hp -= amount\n markDamaged(p)\n const trigger = CHAIN_TRIGGER_OF[type]\n const chained = trigger !== undefined && chainDelayOf(p.spec, trigger) !== undefined\n // a bullet or a blast sets a chained part off after its delay instead of tearing it apart on the spot\n if (chained && p.st.hp <= 0 && p.rt.chainDue === undefined) p.st.hp = Math.min(prev, 1)\n if (p.st.hp <= 0 && p.mat.fracture === 'none' && !p.spec.explodes) p.st.hp = Math.min(prev, 1)\n const done = prev - p.st.hp\n if (done > 0) emit({ ...base(o, src), type: 'damage', part: p.spec.id, amount: done, hp: Math.max(0, p.st.hp), damageType: type })\n if (p.st.hp <= 0) failPart(o, p, origin, dir, fragEnergy, cap, src)\n else if (chained && (trigger === 'explosion' || 1 - p.st.hp / p.st.maxHp >= shotDamageFractionOf(p.spec))) prime(o, p, trigger, src)\n return done\n }\n\n // -------------------------------------------------------------------------------------------------------------------------------------------\n // Hits\n // -------------------------------------------------------------------------------------------------------------------------------------------\n\n interface BallisticOut { penetrated: boolean; exitEnergy: number; exitPoint?: Vec3; damage: number }\n\n const ballistic = (o: ObjRT, p: PartRT, entry: Vec3, n: Vec3, d: Vec3, E: number, caliber: number, pathLen: number, src?: string): BallisticOut => {\n const mat = p.mat\n // a bare cage and an opening do not stop a bullet\n if (p.st.stripped || (p.st.opening && insideOpening(o, p, objLocal(o, entry)))) {\n return { penetrated: true, exitEnergy: E, exitPoint: vec.madd(entry, d, Math.min(pathLen, p.thickness)), damage: 0 }\n }\n const sin = Math.min(1, Math.abs(vec.dot(d, n)))\n const angle = (Math.asin(sin) * 180) / Math.PI\n const slant = Math.max(sin, 0.3)\n const effM = p.thickness / slant\n const face = p.layers.length > 0 ? faceOf(o, p, n) : 1\n const exitLocal = objLocal(o, vec.madd(entry, d, Math.min(pathLen, effM)))\n const coats = p.layers.length > 0 ? layersEnergy(p.layers, p.rt.spalls, face, objLocal(o, entry)) + layersEnergy(p.layers, p.rt.spalls, -face, exitLocal) : 0\n // each coat adds penetration x thickness to the core's; a part without layers keeps the plain formula\n const thr = coats > 0 ? (mat.penetration * p.thickness * 1000 + coats) / slant : mat.penetration * effM * 1000\n const penetrated = E > thr\n // a thin brittle shell that shatters (a pane, a bottle) is lost to one bullet that a thick block of the same glass shrugs off: the same\n // fragility factor that melee uses for blunt hits (1 for ductile materials and for shells 2 cm or thicker, up to x118 for 3 mm glass)\n const scale = (mat.damageScale?.ballistic ?? 1) * (mat.fracture === 'shatter' ? fragility(mat.ductility, p.thickness) : 1)\n const id = p.spec.id\n if (!penetrated && mat.ricochetDeg && angle < mat.ricochetDeg) {\n const r = vec.sub(d, vec.scale(n, 2 * vec.dot(d, n)))\n emit({ ...base(o, src), type: 'ricochet', part: id, point: entry, direction: vec.normalize(r), energy: E * 0.4 })\n debris(o, p, mat.hitDebris, entry, n, 3, 3, src)\n const dmg = applyDamage(o, p, E * DMG_PER_J * scale * 0.2, 'ballistic', entry, d, E * 0.1, 12, src)\n return { penetrated: false, exitEnergy: 0, damage: dmg }\n }\n if (p.layers.length > 0) spallOuter(o, p, entry, face, n, Math.max(0.03, (caliber / 1000) * 4), src)\n const brittle = mat.ductility < 0.3\n const ratio = E / Math.max(thr, 1e-6)\n const crackLen = clamp(0.03 + ratio * 0.2, 0.03, 0.8)\n let exitPoint: Vec3 | undefined\n if (penetrated) {\n exitPoint = vec.madd(entry, d, Math.min(pathLen, effM + layersThickness(p.layers, face) / slant + layersThickness(p.layers, -face) / slant))\n const hole = addHole(o, p, entry, n, (caliber / 1000) * (mat.ductility >= 0.3 ? 1 : 1.5), true, exitPoint, src)\n if (p.layers.length > 0) spallOuter(o, p, exitPoint, -face, vec.scale(n, -1), Math.max(0.03, (caliber / 1000) * 4), src)\n addBreach(o, p, entry, Math.PI * (hole.diameter / 2) * (hole.diameter / 2), E, d, src)\n if (brittle && mat.fracture === 'shatter') addCrack(o, p, entry, n, crackLen, src)\n if (p.spec.contains && (p.st.liters ?? 0) > 0) {\n emit({\n ...base(o, src), type: 'leak', part: id, fluid: p.spec.contains.fluid, point: entry, direction: n, rate: holeRate(hole, !!p.spec.contains.pressurized),\n pressurized: !!p.spec.contains.pressurized,\n })\n }\n } else if (mat.ductility >= 0.5) {\n addDent(o, p, entry, n, Math.max((caliber * 3) / 1000, 0.012), clamp(Math.min(Math.max(p.thickness * 3, 0.003), ratio * 0.01), 0.001, 0.05), src)\n } else if (brittle) {\n addCrack(o, p, entry, n, crackLen, src)\n if (mat.fracture !== 'shatter') addHole(o, p, entry, n, caliber / 1000, false, undefined, src)\n } else addHole(o, p, entry, n, caliber / 1000, false, undefined, src)\n debris(o, p, mat.hitDebris, entry, n, clamp(Math.round(E / 60) + 2, 2, 14), clamp(Math.sqrt(E) / 6, 1, 8), src)\n // a bullet only wears the joints of the part it hits, by the energy the part absorbed (a through-and-through shot transfers little)\n wearJoints(o, p, (penetrated ? thr : E) * 0.02, undefined, 0, src, true)\n const dmg = applyDamage(o, p, E * DMG_PER_J * scale, 'ballistic', entry, d, E * 0.1, 12, src)\n return { penetrated, exitEnergy: penetrated ? E - thr : 0, exitPoint, damage: dmg }\n }\n\n const melee = (o: ObjRT, p: PartRT, kind: 'blunt' | 'slash', E: number, point: Vec3, n: Vec3, d: Vec3, contactR: number, src?: string): number => {\n const mat = p.mat\n const thrMm = mat.penetration * p.thickness * 1000\n // brittle thin shells (a bottle, a mug, a pane) break from a knock that a thick block shrugs off\n const fragile = kind === 'blunt' ? fragility(mat.ductility, p.thickness) : 1\n const Ec = E * fragile\n if (E > 0) {\n if (kind === 'blunt') {\n if (mat.ductility >= 0.5) addDent(o, p, point, n, Math.max(contactR, 0.015), clamp(E * 0.0001, 0.001, 0.06), src)\n else if (mat.ductility < 0.3) {\n if (Ec >= 5) addCrack(o, p, point, n, clamp(0.04 + Math.min(Ec, E * 6) * 0.0008, 0.04, 0.6), src)\n } else if (E >= thrMm * 0.2) addDent(o, p, point, n, Math.max(contactR, 0.015), clamp(E * 0.00006, 0.001, 0.04), src)\n } else if (mat.fracture === 'tear') {\n addHole(o, p, point, n, clamp(0.02 + E * 0.0005, 0.02, 0.3), true, undefined, src)\n } else if (mat.ductility >= 0.5) {\n addDent(o, p, point, n, Math.max(contactR, 0.01), clamp(E * 0.00004, 0.0005, 0.02), src)\n }\n debris(o, p, mat.hitDebris, point, n, clamp(Math.round(E / 25) + 1, 1, 10), clamp(Math.sqrt(E) / 8, 1, 6), src)\n }\n if (kind === 'blunt') wearJoints(o, p, E * 0.3, undefined, 0, src)\n else wearJoints(o, p, E * 0.3, point, 0.06, src)\n if (kind === 'blunt' && E > 0 && p.layers.length > 0) spallOuter(o, p, point, faceOf(o, p, n), n, Math.max(contactR, 0.05), src)\n const scale = mat.damageScale?.[kind] ?? 1\n const done = applyDamage(o, p, Ec * DMG_PER_J * scale * (kind === 'slash' ? p.cutFactor : 1), kind, point, d, E * 0.1, 12, src)\n addBreach(o, p, point, breachAreaOf(p, done, false), E, d, src)\n return done\n }\n\n const blastObject = (o: ObjRT, point: Vec3, energy: number, radius: number, src?: string): HitResult => {\n const start = cur.length\n const res: HitResult = { object: o.id, damage: 0, penetrated: false, exitEnergy: 0, events: [] }\n for (const p of o.parts) {\n if (isLost(p)) continue\n const { c, q } = partXf(o, p)\n const lp = toLocal(c, q, point)\n const dist = distanceToShape(p.spec.shape, lp)\n if (dist >= radius) continue\n const f = (1 - dist / radius) ** 2\n const Ein = energy * f * BLAST_COUPLING\n const sp = surfacePoint(p.spec.shape, lp)\n const wp = toWorld(c, q, sp.point)\n const wn = rotateVec(q, sp.normal)\n if (!res.part) {\n res.part = p.spec.id\n res.point = wp\n }\n const mat = p.mat\n if (Ein > 20) {\n if (mat.ductility >= 0.5) addDent(o, p, wp, wn, clamp(0.05 + Math.sqrt(Ein) * 0.002, 0.05, 0.4), clamp(0.004 + Ein * 0.00002, 0.004, 0.08), src)\n else if (mat.ductility < 0.3 && Ein > 60) addCrack(o, p, wp, wn, clamp(0.05 + Ein * 0.0005, 0.05, 1), src)\n debris(o, p, mat.hitDebris, wp, wn, clamp(Math.round(Ein / 80) + 1, 1, 12), clamp(Math.sqrt(Ein) / 4, 2, 15), src)\n }\n const th = mat.thermal\n if (th.ignitionC !== undefined && p.st.fuel > 0) {\n p.st.temperature += 300 * f\n o.active = true\n if (f >= 0.25 && !p.st.burning) {\n p.st.temperature = Math.max(p.st.temperature, th.ignitionC + 1)\n checkIgnite(o, p, src)\n }\n }\n wearJoints(o, p, Ein * 0.5, undefined, 0, src)\n if (Ein > 20 && p.layers.length > 0) spallOuter(o, p, wp, faceOf(o, p, wn), wn, clamp(0.05 + Math.sqrt(Ein) * 0.002, 0.05, 0.4), src)\n const dealt = applyDamage(o, p, Ein * DMG_PER_J * (mat.damageScale?.explosive ?? 1), 'explosive', point, null, Ein * 0.3, 40, src)\n res.damage += dealt\n addBreach(o, p, wp, breachAreaOf(p, dealt, true), Ein, null, src)\n }\n res.events = cur.slice(start)\n return res\n }\n\n const blastWorld = (point: Vec3, energy: number, radius: number, src?: string): HitResult[] => {\n const out: HitResult[] = []\n for (const o of [...objects.values()]) {\n if (vec.distance(toWorld(o.st.position, o.st.rotation, o.bc), point) - o.br >= radius) continue\n const r = blastObject(o, point, energy, radius, src)\n if (r.part) out.push(r)\n }\n for (const im of [...impls.values()]) {\n const inRange = im.impl.describe().parts.some((ps) => {\n const ov = im.poses.get(ps.id)\n const c = toWorld(im.position, im.rotation, ov?.pos ?? ps.position)\n const q = quat.mul(im.rotation, ov?.q ?? quatFromEuler(...(ps.rotation ?? [0, 0, 0])))\n return distanceToShape(ps.shape, toLocal(c, q, point)) < radius\n })\n if (inRange) out.push(implHit(im, { type: 'explosive', point, energy, radius, ...(src !== undefined ? { source: src } : {}) }))\n }\n return out\n }\n\n const heatObject = (o: ObjRT, point: Vec3, T: number, radius: number, duration: number, src?: string): HitResult => {\n const start = cur.length\n const res: HitResult = { object: o.id, damage: 0, penetrated: false, exitEnergy: 0, events: [] }\n for (const p of o.parts) {\n if (isLost(p)) continue\n const dist = distToPart(o, p, point)\n if (dist >= radius) continue\n const f = clamp(1 - dist / radius, 0.25, 1)\n if (!res.part) {\n res.part = p.spec.id\n res.point = point\n }\n if (T > p.st.temperature) {\n const k = (0.8 * f) / (p.mat.thermal.heatCapacity ?? 1)\n p.st.temperature += (T - p.st.temperature) * (1 - Math.exp(-k * duration))\n }\n o.active = true\n checkIgnite(o, p, src)\n }\n res.events = cur.slice(start)\n return res\n }\n\n const doHit = (o: ObjRT, hit: Hit, only?: PartRT): HitResult => {\n let point = hit.point\n let dir = hit.direction\n if (hit.space === 'local') {\n point = toWorld(o.st.position, o.st.rotation, point)\n if (dir) dir = rotateVec(o.st.rotation, dir)\n }\n const src = hit.source\n const start = cur.length\n let res: HitResult = { object: o.id, damage: 0, penetrated: false, exitEnergy: 0, events: [] }\n const E = hit.energy ?? 0\n if (hit.type === 'ballistic') {\n const loc = locate(o, point, dir, 0.05, only)\n if (loc) {\n const out = ballistic(o, loc.p, loc.point, loc.normal, loc.dir, E, hit.caliber ?? 9, loc.pathLen, src)\n res = { ...res, part: loc.p.spec.id, point: loc.point, damage: out.damage, penetrated: out.penetrated, exitEnergy: out.exitEnergy }\n }\n } else if (hit.type === 'blunt' || hit.type === 'slash') {\n const radius = hit.radius ?? 0\n const loc = locate(o, point, dir, Math.max(0.05, radius), only)\n if (loc) {\n res.part = loc.p.spec.id\n res.point = loc.point\n res.damage += melee(o, loc.p, hit.type, E, loc.point, loc.normal, loc.dir, radius || 0.03, src)\n if (radius > 0.1 && !only) {\n for (const p of o.parts) {\n if (p === loc.p || isLost(p)) continue\n const dd = distToPart(o, p, point)\n if (dd >= radius) continue\n const { c, q } = partXf(o, p)\n const sp = surfacePoint(p.spec.shape, toLocal(c, q, point))\n res.damage += melee(o, p, hit.type, E * (1 - dd / radius) ** 2, toWorld(c, q, sp.point), rotateVec(q, sp.normal), loc.dir, radius, src)\n }\n }\n }\n } else if (hit.type === 'explosive') {\n res = blastObject(o, point, E, hit.radius ?? 2, src)\n } else {\n res = heatObject(o, point, hit.temperature ?? 800, hit.radius ?? 0.25, hit.duration ?? 1, src)\n }\n res.events = cur.slice(start)\n return res\n }\n\n // -------------------------------------------------------------------------------------------------------------------------------------------\n // Fire, heat, melting, leaks\n // -------------------------------------------------------------------------------------------------------------------------------------------\n\n const checkIgnite = (o: ObjRT, p: PartRT, src?: string) => {\n const th = p.mat.thermal\n if (isLost(p) || p.st.burning || th.ignitionC === undefined || p.st.fuel <= 0 || p.st.temperature < th.ignitionC) return\n p.st.burning = true\n p.st.temperature = Math.max(p.st.temperature, th.flameC ?? 800)\n o.active = true\n markDamaged(p)\n emit({ ...base(o, src), type: 'ignite', part: p.spec.id, point: partXf(o, p).c })\n }\n\n const syncMass = (p: PartRT) => {\n p.st.mass = Math.max(0, p.mass0 * (1 - p.st.melt) - (p.fuel0 - p.st.fuel))\n }\n\n const burnStep = (o: ObjRT, p: PartRT, dt: number) => {\n const th = p.mat.thermal\n const use = Math.min((th.burnRate ?? 0.01) * p.area * dt, p.st.fuel)\n p.st.fuel -= use\n syncMass(p)\n if (p.structural) o.dirty = true\n p.st.temperature = th.flameC ?? 800\n markDamaged(p)\n if (p.fuel0 > 0) {\n p.st.char = clamp(1 - p.st.fuel / p.fuel0, 0, 1)\n p.st.hp = Math.min(p.st.hp, Math.max(1, p.st.maxHp * (p.st.fuel / p.fuel0)))\n }\n if (p.st.fuel <= 1e-9) {\n p.st.fuel = 0\n p.st.burning = false\n p.st.char = 1\n const c = partXf(o, p).c\n if ((th.fuelFraction ?? 0) >= 0.8) {\n p.st.status = 'ashes'\n p.st.hp = 0\n p.st.mass = p.mass0 * (1 - (th.fuelFraction ?? 0))\n emit({ ...base(o), type: 'burnout', part: p.spec.id, point: c })\n debris(o, p, 'ash', c, [0, 1, 0], clamp(Math.round(Math.cbrt(partVolume(p.spec.shape)) * 30), 3, 20), 1)\n partLost(o, p)\n } else {\n emit({ ...base(o), type: 'burnout', part: p.spec.id, point: c })\n }\n }\n }\n\n const meltStep = (o: ObjRT, p: PartRT, dt: number) => {\n const th = p.mat.thermal\n if (th.meltC === undefined || p.st.temperature <= th.meltC) return\n const rate = (th.meltRate ?? 0.05) * ((p.st.temperature - th.meltC) / 100)\n p.st.melt = Math.min(1, p.st.melt + rate * dt)\n syncMass(p)\n if (p.structural) o.dirty = true\n markDamaged(p)\n p.rt.dripT += dt\n if (p.rt.dripT >= 0.25) {\n p.rt.dripT -= 0.25\n const b = partWorldAabb(o, p)\n const pt: Vec3 = [b.min[0] + (b.max[0] - b.min[0]) * (0.2 + 0.6 * rnd()), b.min[1], b.min[2] + (b.max[2] - b.min[2]) * (0.2 + 0.6 * rnd())]\n emit({ ...base(o), type: 'drip', part: p.spec.id, point: pt, material: p.mat.id })\n }\n if (p.st.melt - p.rt.meltEmitted >= 0.05 || p.st.melt >= 1) {\n p.rt.meltEmitted = p.st.melt\n emit({ ...base(o), type: 'melt', part: p.spec.id, melt: p.st.melt })\n }\n if (p.st.melt >= 1) {\n p.st.status = 'melted'\n p.st.hp = 0\n p.st.mass = 0\n p.st.burning = false\n p.rt.jet = false\n partLost(o, p)\n }\n }\n\n const stepObject = (o: ObjRT, dt: number, sources: Array<{ o: ObjRT; p: PartRT; flame: number }>) => {\n const parts = o.parts\n const T0 = o.tmp\n T0.length = parts.length\n for (let i = 0; i < parts.length; i++) T0[i] = parts[i].st.temperature\n let hot = false\n for (let i = 0; i < parts.length; i++) {\n const p = parts[i]\n if (isLost(p)) continue\n const th = p.mat.thermal\n const hc = th.heatCapacity ?? 1\n const s = p.st\n if (p.rt.jet) {\n s.temperature = Math.max(s.temperature, 900)\n } else if (s.burning) {\n burnStep(o, p, dt)\n if (isLost(p)) continue\n }\n if (!s.burning && !p.rt.jet) {\n // conduction from hotter neighbours through closed joints, then cooling\n let dT = 0\n let maxN = s.temperature\n for (const j of o.byPart.get(p.spec.id)!) {\n if (j.st.open) continue\n const k = j.ia === i ? j.ib : j.ia\n if (isLost(parts[k]) || T0[k] <= T0[i]) continue\n const c = (th.conductivity + parts[k].mat.thermal.conductivity) / 2\n dT += (T0[k] - T0[i]) * (1 - Math.exp((-1.2 * c * dt) / hc))\n if (T0[k] > maxN) maxN = T0[k]\n }\n if (dT > 0) s.temperature = Math.min(s.temperature + dT, maxN)\n s.temperature += (ambient - s.temperature) * (1 - Math.exp(-dt / (20 * hc)))\n if (Math.abs(s.temperature - ambient) < 0.05) s.temperature = ambient\n }\n meltStep(o, p, dt)\n if (isLost(p)) continue\n checkIgnite(o, p)\n const ex = p.spec.explodes\n if (ex && chainDelayOf(p.spec, 'fire') !== undefined) {\n if (s.temperature >= (ex.atC ?? FIRE_PRIME_C)) prime(o, p, 'fire')\n } else if (ex && ex.atC !== undefined && s.temperature >= ex.atC) {\n failPart(o, p, null, null, 0, 40)\n continue\n }\n // leaks\n const cont = p.spec.contains\n if (cont && (s.liters ?? 0) > 0) {\n let rate = 0\n for (const h of s.holes) if (h.through) rate += holeRate(h, !!cont.pressurized)\n if (rate > 0) {\n s.liters = Math.max(0, (s.liters ?? 0) - rate * dt)\n hot = true\n if (FLAMMABLE_FLUIDS.includes(cont.fluid) && s.temperature >= 350 && !p.rt.jet) {\n if (ex && chainDelayOf(p.spec, 'fire') !== undefined) {\n prime(o, p, 'fire')\n continue\n }\n if (ex) {\n failPart(o, p, null, null, 0, 40)\n continue\n }\n p.rt.jet = true\n s.burning = true\n emit({ ...base(o), type: 'ignite', part: p.spec.id, point: partXf(o, p).c })\n }\n }\n }\n if (p.rt.jet && (s.liters ?? 0) <= 0) {\n p.rt.jet = false\n s.burning = false\n emit({ ...base(o), type: 'extinguish', part: p.spec.id })\n }\n // thermal shock\n const sc = th.thermalShockC\n if (sc !== undefined) {\n p.rt.shockT = Math.max(0, p.rt.shockT - dt)\n const rate = Math.abs(s.temperature - p.rt.prevTemp) / dt\n p.rt.prevTemp = s.temperature\n if (rate > sc && p.rt.shockT <= 0) {\n p.rt.shockT = 1\n const { c, q } = partXf(o, p)\n const lp: Vec3 = [(rnd() - 0.5) * p.dims[0], (rnd() - 0.5) * p.dims[1], (rnd() - 0.5) * p.dims[2]]\n const sp = surfacePoint(p.spec.shape, lp)\n addCrack(o, p, toWorld(c, q, sp.point), rotateVec(q, sp.normal), 0.1 + (rate / sc) * 0.1)\n applyDamage(o, p, p.st.maxHp * 0.25, 'heat', null, null, 5, 3)\n if (isLost(p)) continue\n }\n }\n if (s.burning || p.rt.jet) sources.push({ o, p, flame: p.rt.jet ? 900 : th.flameC ?? 800 })\n if (s.burning || p.rt.jet || s.temperature > ambient + 0.5) hot = true\n }\n if (o.hasStructure) {\n if (o.dirty) {\n o.dirty = false\n solveStructure(o)\n }\n for (const p of parts) {\n if (!p.structural || isLost(p)) continue\n const stress = p.st.stress ?? 0\n p.rt.stressT = Math.max(0, (p.rt.stressT ?? 0) - dt)\n if (stress > 1) {\n if (p.rt.stressT <= 0) {\n p.rt.stressT = 0.5\n emit({ ...base(o), type: 'stress', part: p.spec.id, stress, load: p.st.load ?? 0 })\n }\n applyDamage(o, p, overloadRate(stress) * p.st.maxHp * dt, 'blunt', null, null, 5, 3)\n } else if (stress > 0.8 && p.mat.ductility < 0.3 && p.rt.stressT <= 0 && p.st.cracks.length < 6) {\n p.rt.stressT = 0.5\n const { c, q } = partXf(o, p)\n const sp = surfacePoint(p.spec.shape, [(rnd() - 0.5) * p.dims[0], (rnd() - 0.5) * p.dims[1], (rnd() - 0.5) * p.dims[2]])\n addCrack(o, p, toWorld(c, q, sp.point), rotateVec(q, sp.normal), 0.1 + (stress - 0.8) * 0.5)\n }\n }\n if (o.maxStress > 0.8) hot = true\n }\n o.active = hot\n }\n\n const spread = (sources: Array<{ o: ObjRT; p: PartRT; flame: number }>, dt: number) => {\n for (const src of sources) {\n if (!src.p.st.burning && !src.p.rt.jet) continue\n const sc = toWorld(src.o.st.position, src.o.st.rotation, src.p.pos)\n const A = partWorldAabb(src.o, src.p)\n for (const o of objects.values()) {\n if (o === src.o) continue\n if (vec.distance(toWorld(o.st.position, o.st.rotation, o.bc), sc) > o.br + src.p.bound + fireSpread) continue\n for (const q of o.parts) {\n if (isLost(q) || q.st.burning) continue\n const B = partWorldAabb(o, q)\n const gap = Math.hypot(\n Math.max(0, A.min[0] - B.max[0], B.min[0] - A.max[0]),\n Math.max(0, A.min[1] - B.max[1], B.min[1] - A.max[1]),\n Math.max(0, A.min[2] - B.max[2], B.min[2] - A.max[2]),\n )\n if (gap >= fireSpread || src.flame <= q.st.temperature) continue\n const f = 1 - gap / fireSpread\n q.st.temperature += (src.flame - q.st.temperature) * (1 - Math.exp((-0.6 * f * dt) / (q.mat.thermal.heatCapacity ?? 1)))\n o.active = true\n }\n }\n }\n }\n\n // -------------------------------------------------------------------------------------------------------------------------------------------\n // World API\n // -------------------------------------------------------------------------------------------------------------------------------------------\n\n /** The primed part that goes off first: earliest due time, then the older object, then the part listed first. */\n const nextPrimed = (until: number): { o: ObjRT; p: PartRT } | null => {\n let best: { o: ObjRT; p: PartRT } | null = null\n for (const [p, o] of primed) {\n if (objects.get(o.id) !== o || isLost(p)) {\n primed.delete(p)\n continue\n }\n const due = p.rt.chainDue as number\n if (due > until) continue\n if (!best) best = { o, p }\n else {\n const bestDue = best.p.rt.chainDue as number\n if (due < bestDue || (due === bestDue && (o.order < best.o.order || (o.order === best.o.order && (o.idx.get(p.spec.id) ?? 0) < (best.o.idx.get(best.p.spec.id) ?? 0))))) best = { o, p }\n }\n }\n return best\n }\n\n /**\n * Explodes the primed parts whose delay ran out by `until`, one at a time in order of time; each blast is resolved before the next part goes off,\n * so a part it primes counts its delay from that moment, not from the end of the frame.\n */\n const detonatePrimed = (until: number) => {\n const end = time\n for (let next = nextPrimed(until); next; next = nextPrimed(until)) {\n primed.delete(next.p)\n time = Math.max(0, Math.min(end, next.p.rt.chainDue as number))\n next.p.rt.chainDue = undefined\n failPart(next.o, next.p, null, null, 0, 40)\n drainBlasts()\n }\n time = end\n }\n\n /** Collapse events are produced after the whole operation: make sure the result of the operation carries them. */\n const withCollapses = (r: { value: HitResult[]; events: DestructionEvent[] }): HitResult[] => {\n const last = r.value[r.value.length - 1]\n if (!last) return r.value\n for (const e of r.events) if (e.type === 'collapse' && !r.value.some((h) => h.events.includes(e))) last.events.push(e)\n return r.value\n }\n\n const whole = (fn: () => HitResult): HitResult => {\n const r = run(fn)\n r.value.events = r.events\n return r.value\n }\n\n const world: DestructionWorld = {\n materials,\n get time() {\n return time\n },\n add(spec, opts: AddOptions = {}) {\n const id = opts.id ?? nextId()\n if (taken(id)) throw new Error(`object \"${id}\" already exists`)\n objects.set(id, build(resolveSpec(spec), id, opts.position ?? [0, 0, 0], opts.rotation ?? [0, 0, 0, 1]))\n return id\n },\n register(impl, opts: AddOptions = {}) {\n const id = opts.id ?? impl.id\n if (taken(id)) throw new Error(`object \"${id}\" already exists`)\n impls.set(id, { impl, position: opts.position ?? [0, 0, 0], rotation: opts.rotation ?? [0, 0, 0, 1], poses: new Map() })\n return id\n },\n setPartPose(objectId, partId, position, rotation) {\n const q = quatFromEuler(...(rotation ?? [0, 0, 0]))\n const im = impls.get(objectId)\n if (im) {\n im.impl.setPartPose?.(partId, position, rotation)\n im.poses.set(partId, { pos: [position[0], position[1], position[2]], q })\n return\n }\n const o = getObj(objectId)\n const p = getPart(o, partId)\n p.pos = [position[0], position[1], position[2]]\n p.q = q\n updateBound(o)\n },\n remove(id) {\n objects.delete(id)\n impls.delete(id)\n },\n has: (id) => taken(id),\n ids: () => [...objects.keys(), ...impls.keys()],\n setTransform(id, position, rotation) {\n const im = impls.get(id)\n if (im) {\n im.position = [position[0], position[1], position[2]]\n im.rotation = [rotation[0], rotation[1], rotation[2], rotation[3]]\n return\n }\n const o = getObj(id)\n o.st.position = [position[0], position[1], position[2]]\n o.st.rotation = [rotation[0], rotation[1], rotation[2], rotation[3]]\n },\n splitGroup(id, group, newId) {\n if (impls.has(id)) throw new Error(`object \"${id}\" is a registered DestructibleImpl and cannot be split; its module owns its pieces`)\n const o = getObj(id)\n if (o.st.groups.length < 2) return id\n const names = o.st.groups[group]\n if (!names) throw new Error(`object \"${id}\" has no group ${group}`)\n const moved = new Set(names)\n const nid = newId ?? nextId()\n if (objects.has(nid)) throw new Error(`object \"${nid}\" already exists`)\n // an open joint between the two objects stays with the original\n const carryFor = (keep: (pid: string) => boolean, keepOpen: (a: string, b: string) => boolean = () => false): Carry => ({\n parts: new Map(o.parts.filter((p) => keep(p.spec.id)).map((p) => [p.spec.id, { st: p.st, rt: p.rt }])),\n joints: new Map([\n ...o.joints.filter((j) => (keep(j.spec.a) && keep(j.spec.b)) || (j.st.open && keepOpen(j.spec.a, j.spec.b))).map((j): [string, { st: JointState; step: number }] => [j.spec.id, { st: j.st, step: j.step }]),\n ...o.st.joints.filter((st) => st.open && !o.jointMap.has(st.id) && keepOpen(st.a, st.b)).map((st): [string, { st: JointState; step: number }] => [st.id, { st, step: 0 }]),\n ]),\n collapsed: [...o.collapsed].filter(keep),\n })\n const sub = (keep: (pid: string) => boolean): DestructibleSpec => {\n const s: DestructibleSpec = { parts: o.spec.parts.filter((p) => keep(p.id)), joints: (o.spec.joints ?? []).filter((j) => keep(j.a) && keep(j.b)) }\n if (o.spec.name !== undefined) s.name = o.spec.name\n if (o.spec.tags) s.tags = [...o.spec.tags]\n return clone(s)\n }\n const inNew = (pid: string) => moved.has(pid)\n const inOld = (pid: string) => !moved.has(pid)\n const pos = o.st.position, rot = o.st.rotation\n const fresh = build(sub(inNew), nid, pos, rot, carryFor(inNew, (a, b) => inNew(a) && inNew(b)))\n const rest = build(sub(inOld), id, pos, rot, carryFor(inOld, (a, b) => !(inNew(a) && inNew(b))))\n objects.set(id, rest)\n objects.set(nid, fresh)\n return nid\n },\n hit(objectId, h) {\n const im = impls.get(objectId)\n if (im) return whole(() => implHit(im, h))\n const o = getObj(objectId)\n return whole(() => doHit(o, h))\n },\n hitPart(objectId, partId, h) {\n const im = impls.get(objectId)\n if (im) return whole(() => implHit(im, h))\n const o = getObj(objectId)\n const p = getPart(o, partId)\n return whole(() => doHit(o, h, p))\n },\n explode(point, energy, radius, source) {\n return withCollapses(run(() => blastWorld(point, energy, radius, source)))\n },\n raycast(origin, direction, maxDistance = Infinity) {\n const r = raycastInternal(origin, direction, maxDistance)\n return r ? { object: r.object, part: r.part, point: r.point, normal: r.normal, distance: r.distance } : null\n },\n shoot(origin, direction, energy, caliber, source) {\n return withCollapses(run(() => {\n const results: HitResult[] = []\n const d = vec.normalize(direction)\n const ignore = new Set<string>()\n let org = origin\n let E = energy\n for (let i = 0; i < 4 && E > 0; i++) {\n const rh = raycastInternal(org, d, Infinity, ignore)\n if (!rh) break\n const im = impls.get(rh.object)\n if (im) {\n const r = implHit(im, { type: 'ballistic', point: rh.point, direction: d, energy: E, caliber, ...(source !== undefined ? { source } : {}) })\n r.part = rh.part\n r.point = rh.point\n r.exitEnergy = r.penetrated ? E * 0.5 : 0\n results.push(r)\n ignore.add(`${im.impl.id}\\0${rh.part}`)\n if (!r.penetrated) break\n org = vec.madd(rh.point, d, Math.min(rh.pathLen, 0.05) + 0.001)\n E = r.exitEnergy\n continue\n }\n const o = getObj(rh.object)\n const p = getPart(o, rh.part)\n const start = cur.length\n const out = ballistic(o, p, rh.point, rh.normal, d, E, caliber, rh.pathLen, source)\n results.push({ object: o.id, part: p.spec.id, point: rh.point, damage: out.damage, penetrated: out.penetrated, exitEnergy: out.exitEnergy, events: cur.slice(start) })\n ignore.add(`${o.id}\\0${p.spec.id}`)\n if (!out.penetrated || !out.exitPoint) break\n org = vec.madd(out.exitPoint, d, 0.001)\n E = out.exitEnergy\n }\n return results\n }))\n },\n disassemble(objectId, jointId, tool: ToolKind, dt) {\n const im = impls.get(objectId)\n if (im) return im.impl.disassemble ? im.impl.disassemble(jointId, tool, dt) : -1\n const o = getObj(objectId)\n const j = o.jointMap.get(jointId)\n if (!j || !j.spec.tools.includes(tool)) return -1\n if (j.st.open) return 1\n return run(() => {\n j.st.progress = Math.min(1, j.st.progress + (j.spec.seconds > 0 ? dt / j.spec.seconds : 1))\n if (j.st.progress >= 1 - 1e-9) j.st.progress = 1\n const step = Math.floor(j.st.progress * 10 + 1e-9)\n if (step > j.step || j.st.progress >= 1) {\n j.step = step\n emit({ ...base(o), type: 'disassemble_progress', joint: j.spec.id, tool, progress: j.st.progress })\n }\n if (j.st.progress >= 1) {\n j.st.open = true\n j.st.openedBy = 'tool'\n solveStructure(o)\n recomputeGroups(o)\n detachEvents(o, [j], 'tool')\n collapseCheck(o)\n }\n return j.st.progress\n }).value\n },\n workableJoints(objectId, tool) {\n const im = impls.get(objectId)\n if (im) {\n const spec = im.impl.describe()\n return im.impl.state().joints.filter((js) => {\n const j = (spec.joints ?? []).find((x) => (x.id ?? `${x.a}~${x.b}`) === js.id)\n return !js.open && !!j && (j.tools ?? JOINT_DEFAULTS[j.kind].tools).includes(tool)\n })\n }\n return getObj(objectId).joints.filter((j) => !j.st.open && j.spec.tools.includes(tool)).map((j) => j.st)\n },\n nearestJoint(objectId, point, maxDistance = 0.3, tool) {\n const im = impls.get(objectId)\n // Candidates: closed joints with their world position and whether `tool` can undo them.\n const cands: { st: JointState; d: number; ok: boolean }[] = []\n if (im) {\n const spec = im.impl.describe()\n for (const js of im.impl.state().joints) {\n if (js.open) continue\n const pos = implJointPos(im, js.a, js.b)\n const j = (spec.joints ?? []).find((x) => (x.id ?? `${x.a}~${x.b}`) === js.id)\n cands.push({ st: js, d: pos ? vec.distance(pos, point) : Infinity, ok: !!j && (j.tools ?? JOINT_DEFAULTS[j.kind].tools).includes(tool as ToolKind) })\n }\n } else {\n const o = getObj(objectId)\n for (const j of o.joints) {\n if (j.st.open) continue\n cands.push({ st: j.st, d: vec.distance(jointWorld(o, j), point), ok: tool ? j.spec.tools.includes(tool) : true })\n }\n }\n const pick = (only: boolean): JointState | null => {\n let best: JointState | null = null\n let bd = maxDistance\n for (const c of cands) {\n if (only && !c.ok) continue\n if (c.d <= bd) {\n bd = c.d\n best = c.st\n }\n }\n return best\n }\n return (tool ? pick(true) : null) ?? pick(false)\n },\n extinguish(objectId, partId, coolC = 200) {\n const im = impls.get(objectId)\n if (im) {\n run(() => im.impl.extinguish?.(partId))\n return\n }\n const o = getObj(objectId)\n run(() => {\n for (const p of partId ? [getPart(o, partId)] : o.parts) {\n if (isLost(p)) continue\n if (p.st.burning) {\n p.st.burning = false\n p.rt.jet = false\n emit({ ...base(o), type: 'extinguish', part: p.spec.id })\n }\n p.st.temperature = Math.max(ambient, p.st.temperature - coolC)\n }\n o.active = true\n })\n },\n setLiters(objectId, partId, liters) {\n if (impls.has(objectId)) return\n const p = getPart(getObj(objectId), partId)\n if (!p.spec.contains) return\n p.st.liters = clamp(liters, 0, p.spec.contains.liters)\n getObj(objectId).active = true\n },\n update(dt) {\n if (!(dt > 0)) return []\n return run(() => {\n time += dt\n const sources: Array<{ o: ObjRT; p: PartRT; flame: number }> = []\n for (const o of [...objects.values()]) if (o.active) stepObject(o, dt, sources)\n if (sources.length) spread(sources, dt)\n detonatePrimed(time)\n for (const im of [...impls.values()]) {\n if (!im.impl.update) continue\n for (const e of im.impl.update(dt) ?? []) emit(e.time === undefined ? { ...e, time } : e)\n }\n }).events\n },\n state: (id) => objects.get(id)?.st ?? impls.get(id)?.impl.state() ?? null,\n snapshot: (id) => {\n const st = objects.get(id)?.st ?? impls.get(id)?.impl.state()\n return st ? clone(st) : null\n },\n part: (id, partId) => objects.get(id)?.byId.get(partId)?.st ?? impls.get(id)?.impl.state().parts.find((p) => p.id === partId) ?? null,\n reset(id) {\n const im = impls.get(id)\n if (im) {\n im.impl.reset?.()\n return\n }\n const o = getObj(id)\n objects.set(id, build(o.spec, id, o.st.position, o.st.rotation))\n },\n on(type: DestructionEventType | '*', fn) {\n let set = listeners.get(type)\n if (!set) listeners.set(type, (set = new Set()))\n set.add(fn)\n return () => {\n set!.delete(fn)\n }\n },\n serialize(): DestructionSnapshot {\n return {\n version: 1,\n time,\n rng: rng.state(),\n counter,\n objects: [...objects.values()].map((o) => {\n const runtime: ObjectRuntime = { parts: {}, joints: {}, collapsed: [...o.collapsed] }\n for (const p of o.parts) runtime.parts[p.spec.id] = clone(p.rt)\n for (const j of o.joints) runtime.joints[j.spec.id] = j.step\n return { id: o.id, spec: clone(o.spec), state: clone(o.st), runtime }\n }),\n ...(impls.size\n ? { impls: [...impls.values()].map((im) => ({ id: im.impl.id, position: [...im.position] as Vec3, rotation: [...im.rotation] as Quat, data: im.impl.serialize?.() })) }\n : {}),\n }\n },\n load(snap) {\n if (snap.version !== 1) throw new Error(`unsupported snapshot version ${String(snap.version)}`)\n objects.clear()\n time = snap.time\n rng.set(snap.rng)\n counter = snap.counter ?? 0\n for (const e of snap.objects) {\n const state = clone(e.state)\n const carry: Carry = {\n parts: new Map(\n state.parts.map((st) => [st.id, { st, rt: e.runtime?.parts[st.id] ? clone(e.runtime.parts[st.id]) : { ...freshRuntime(), prevTemp: st.temperature } }]),\n ),\n joints: new Map(state.joints.map((st) => [st.id, { st, step: e.runtime?.joints[st.id] ?? 0 }])),\n collapsed: e.runtime?.collapsed,\n }\n objects.set(e.id, build(clone(e.spec), e.id, state.position, state.rotation, carry))\n }\n for (const e of snap.impls ?? []) {\n const im = impls.get(e.id)\n if (!im) continue\n im.position = [e.position[0], e.position[1], e.position[2]]\n im.rotation = [e.rotation[0], e.rotation[1], e.rotation[2], e.rotation[3]]\n if (e.data !== undefined) im.impl.load?.(e.data)\n }\n },\n }\n return world\n}\n","[\n {\n \"id\": \"brick_wall_plastered\",\n \"name\": \"Plastered brick wall\",\n \"core\": { \"material\": \"brick\", \"thickness\": 0.09 },\n \"layers\": [{ \"material\": \"plaster\", \"thickness\": 0.02, \"faces\": \"both\" }],\n \"units\": { \"size\": [0.23, 0.075, 0.11], \"bond\": \"running\", \"mortar\": \"plaster\" },\n \"breach\": { \"area\": 0.25 }\n },\n {\n \"id\": \"concrete_block_wall\",\n \"name\": \"Concrete block wall\",\n \"core\": { \"material\": \"concrete\", \"thickness\": 0.14 },\n \"fill\": 0.55,\n \"units\": { \"size\": [0.39, 0.19, 0.14], \"bond\": \"running\", \"mortar\": \"plaster\" },\n \"breach\": { \"area\": 0.25 }\n },\n {\n \"id\": \"reinforced_concrete\",\n \"name\": \"Reinforced concrete wall\",\n \"core\": { \"material\": \"concrete\", \"thickness\": 0.2 },\n \"reinforcement\": { \"material\": \"steel\", \"spacing\": 0.18, \"diameter\": 0.008, \"residualCapacity\": 0.15 },\n \"units\": { \"size\": [0.6, 0.42, 0.2], \"bond\": \"stack\", \"mortar\": \"concrete\" },\n \"breach\": { \"area\": 0.25 }\n },\n {\n \"id\": \"drywall\",\n \"name\": \"Drywall partition on steel studs\",\n \"core\": { \"material\": \"plaster\", \"thickness\": 0.0125 },\n \"layers\": [{ \"material\": \"plaster\", \"thickness\": 0.0125, \"faces\": \"+\" }],\n \"depth\": 0.095,\n \"breach\": { \"area\": 0.25 }\n },\n {\n \"id\": \"wood_frame_wall\",\n \"name\": \"Wood frame wall\",\n \"core\": { \"material\": \"plywood\", \"thickness\": 0.012 },\n \"layers\": [{ \"material\": \"plaster\", \"thickness\": 0.0125, \"faces\": \"-\" }],\n \"depth\": 0.1135,\n \"breach\": { \"area\": 0.25 }\n },\n {\n \"id\": \"log_wall\",\n \"name\": \"Log wall\",\n \"core\": { \"material\": \"wood_soft\", \"thickness\": 0.2 },\n \"fill\": 0.785,\n \"breach\": { \"area\": 0.25 }\n },\n {\n \"id\": \"sheet_metal_shack\",\n \"name\": \"Corrugated sheet metal wall\",\n \"core\": { \"material\": \"steel\", \"thickness\": 0.0006 },\n \"depth\": 0.02,\n \"breach\": { \"area\": 0.25 }\n },\n {\n \"id\": \"glass_pane\",\n \"name\": \"Glass pane\",\n \"core\": { \"material\": \"glass\", \"thickness\": 0.006 },\n \"breach\": { \"area\": 0.1 }\n }\n]\n","import assembliesJson from './data/assemblies.json'\nimport { MATERIALS } from './materials'\nimport type { MaterialDef, MaterialId, PartBreach, PartSpec, PartUnits, Reinforcement, SurfaceLayer, Vec3 } from './types'\n\n/**\n * A wall as a builder builds it: a core with coats, the masonry unit it is laid in, its rebar and when it breaches. Dimensions are metres (data in\n * `src/data/assemblies.json`); `assemblyPart` turns one into a `PartSpec`. Extend or override with `registerAssembly`.\n */\nexport interface AssemblyDef {\n id: string\n name: string\n /** `thickness` is the core's, in metres: what a bullet has to get through besides the coats. */\n core: { material: MaterialId; thickness: number }\n /** Coats, outermost first. */\n layers?: readonly SurfaceLayer[]\n /** Physical depth of the wall when it is not core plus coats (a drywall partition is mostly air between the boards). */\n depth?: number\n /** Solid fraction of the core (hollow blocks, round logs): scales its mass and the thickness a bullet crosses. Default 1. */\n fill?: number\n units?: PartUnits\n reinforcement?: Reinforcement\n breach?: PartBreach\n}\n\nexport interface AssemblyPartOptions {\n id: string\n /** Along the part's x axis. */\n width: number\n /** Along the part's y axis. */\n height: number\n position: Vec3\n rotation?: Vec3\n structure?: PartSpec['structure']\n /** Other `PartSpec` fields (tags, anchored, hp...). */\n extra?: Partial<PartSpec>\n /** Materials to read densities from (default the built-in `MATERIALS`). */\n materials?: ReadonlyMap<MaterialId, MaterialDef>\n}\n\n/** Built-in assemblies; `registerAssembly` adds to this list. */\nexport const ASSEMBLIES: AssemblyDef[] = assembliesJson as unknown as AssemblyDef[]\n\nexport const registerAssembly = (def: AssemblyDef): void => {\n const at = ASSEMBLIES.findIndex((a) => a.id === def.id)\n if (at >= 0) ASSEMBLIES[at] = def\n else ASSEMBLIES.push(def)\n}\n\nexport const getAssembly = (id: string): AssemblyDef | undefined => ASSEMBLIES.find((a) => a.id === id)\n\nconst faceCount = (layer: SurfaceLayer): number => (layer.faces === 'both' ? 2 : 1)\n\n/** Physical depth of the wall in metres. */\nexport const assemblyDepth = (def: AssemblyDef): number => def.depth ?? def.core.thickness + (def.layers ?? []).reduce((sum, l) => sum + l.thickness * faceCount(l), 0)\n\n/**\n * The wall as a box `[width, height, depth]` (thin along local z) with the assembly's layers, units, rebar and breach. Mass is the core (times `fill`)\n * plus the coats; `thickness` is the core's, so each coat adds its own `penetration x thickness` to what a bullet must cross.\n */\nexport const assemblyPart = (assemblyId: string, options: AssemblyPartOptions): PartSpec => {\n const def = getAssembly(assemblyId)\n if (!def) throw new Error(`unknown assembly \"${assemblyId}\"`)\n const densityOf = (id: MaterialId): number => {\n const m = options.materials?.get(id) ?? MATERIALS.find((x) => x.id === id)\n if (!m) throw new Error(`unknown material \"${id}\" in assembly \"${assemblyId}\"`)\n return m.density\n }\n const fill = def.fill ?? 1\n const area = options.width * options.height\n const coreMass = area * def.core.thickness * fill * densityOf(def.core.material)\n const layerMass = (def.layers ?? []).reduce((sum, l) => sum + area * l.thickness * faceCount(l) * densityOf(l.material), 0)\n return {\n id: options.id,\n material: def.core.material,\n shape: { kind: 'box', size: [options.width, options.height, assemblyDepth(def)] },\n position: options.position,\n ...(options.rotation ? { rotation: options.rotation } : {}),\n mass: coreMass + layerMass,\n thickness: def.core.thickness * fill,\n ...(def.layers ? { layers: def.layers.map((l) => ({ ...l })) } : {}),\n ...(def.units ? { units: { ...def.units, size: [...def.units.size] as Vec3 } } : {}),\n ...(def.reinforcement ? { reinforcement: { ...def.reinforcement } } : {}),\n ...(def.breach ? { breach: { ...def.breach } } : {}),\n ...(options.structure ? { structure: options.structure } : {}),\n ...options.extra,\n }\n}\n","import type { DestructibleSpec, JointSpec, MaterialId, PartSpec } from './types'\n\nexport interface FrameOptions {\n /** Total length along x between the outer column centres, metres (default 8). */\n spanX?: number\n /** Total length along z (default 8). */\n spanZ?: number\n /** Columns along x (at least 2, default 3). */\n columnsX?: number\n /** Columns along z (at least 2, default 3). */\n columnsZ?: number\n /** Height of one floor from slab top to the underside of the next slab, metres (default 3). */\n height?: number\n /** Number of floors (default 1). */\n floors?: number\n /** Brick walls on every perimeter bay of every floor; the first bay of the ground floor on the -z side gets a door opening (default false). */\n walls?: boolean\n /** A thin roof slab resting on the top beams (default true); without it the top floor is open. */\n roof?: boolean\n columnSize?: number\n beamHeight?: number\n slabThickness?: number\n wallThickness?: number\n doorWidth?: number\n doorHeight?: number\n /** Material of foundations, columns, beams, slabs and roof (default `concrete`). */\n material?: MaterialId\n wallMaterial?: MaterialId\n /** Override the load capacity of every column, kg (see `PartState.load`). */\n columnCapacity?: number\n}\n\n/**\n * A parametric test structure: a grid of columns on foundations, beams between the column tops, one slab per floor (the last one a roof), and\n * optional brick walls with a door. Joints are explicit and directional: columns rest on foundations (or on the slab below) with `rebar`, beams on\n * columns, slabs on beams, the roof rests on the top beams, walls hang on their columns with `mortar`. Part ids: `foundation_i_j`, `column_f_i_j`,\n * `beam_x_f_i_j`, `beam_z_f_i_j`, `slab_f`, `roof`, `wall_*`, `door`. Ground is y = 0 (the top of the foundations).\n */\nexport const buildFrame = (o: FrameOptions = {}): DestructibleSpec => {\n const spanX = o.spanX ?? 8, spanZ = o.spanZ ?? 8\n const nx = Math.max(2, o.columnsX ?? 3), nz = Math.max(2, o.columnsZ ?? 3)\n const H = o.height ?? 3, floors = Math.max(1, o.floors ?? 1)\n const cs = o.columnSize ?? 0.3, bh = o.beamHeight ?? 0.3, bw = 0.2, T = o.slabThickness ?? 0.2, wt = o.wallThickness ?? 0.2\n const dw = o.doorWidth ?? 1, dh = o.doorHeight ?? 2.1\n const mat = o.material ?? 'concrete', wmat = o.wallMaterial ?? 'brick'\n const roof = o.roof ?? true\n const xs = Array.from({ length: nx }, (_, i) => -spanX / 2 + (i * spanX) / (nx - 1))\n const zs = Array.from({ length: nz }, (_, j) => -spanZ / 2 + (j * spanZ) / (nz - 1))\n const parts: PartSpec[] = []\n const joints: JointSpec[] = []\n const on = (a: string, b: string, kind: JointSpec['kind']) => joints.push({ id: `${a}~${b}`, a, b, kind, bears: 'a_on_b' })\n\n for (let i = 0; i < nx; i++) {\n for (let j = 0; j < nz; j++) {\n parts.push({\n id: `foundation_${i}_${j}`, material: mat, shape: { kind: 'box', size: [cs * 2.2, 0.3, cs * 2.2] }, position: [xs[i], -0.15, zs[j]],\n structure: { role: 'foundation' }, anchored: true,\n })\n }\n }\n for (let f = 0; f < floors; f++) {\n const yb = f * (H + T)\n const top = yb + H\n const last = f === floors - 1\n const slabId = last && roof ? 'roof' : `slab_${f}`\n for (let i = 0; i < nx; i++) {\n for (let j = 0; j < nz; j++) {\n const id = `column_${f}_${i}_${j}`\n parts.push({\n id, material: mat, shape: { kind: 'box', size: [cs, H, cs] }, position: [xs[i], yb + H / 2, zs[j]],\n structure: o.columnCapacity === undefined ? { role: 'column' } : { role: 'column', capacity: o.columnCapacity },\n })\n on(id, f === 0 ? `foundation_${i}_${j}` : `slab_${f - 1}`, 'rebar')\n }\n }\n const beams: string[] = []\n const beam = (id: string, size: [number, number, number], pos: [number, number, number], c1: string, c2: string) => {\n parts.push({ id, material: mat, shape: { kind: 'box', size }, position: pos, structure: { role: 'beam' } })\n on(id, c1, 'rebar')\n on(id, c2, 'rebar')\n beams.push(id)\n }\n for (let j = 0; j < nz; j++) {\n for (let i = 0; i < nx - 1; i++) {\n beam(`beam_x_${f}_${i}_${j}`, [xs[i + 1] - xs[i] - cs, bh, bw], [(xs[i] + xs[i + 1]) / 2, top - bh / 2, zs[j]], `column_${f}_${i}_${j}`, `column_${f}_${i + 1}_${j}`)\n }\n }\n for (let i = 0; i < nx; i++) {\n for (let j = 0; j < nz - 1; j++) {\n beam(`beam_z_${f}_${i}_${j}`, [bw, bh, zs[j + 1] - zs[j] - cs], [xs[i], top - bh / 2, (zs[j] + zs[j + 1]) / 2], `column_${f}_${i}_${j}`, `column_${f}_${i}_${j + 1}`)\n }\n }\n const thick = last && roof ? T * 0.75 : T\n parts.push({\n id: slabId, material: mat, shape: { kind: 'box', size: [spanX + cs + 0.2, thick, spanZ + cs + 0.2] }, position: [0, top + thick / 2, 0],\n structure: { role: last && roof ? 'roof' : 'slab' },\n })\n for (const b of beams) on(slabId, b, last && roof ? 'resting' : 'rebar')\n\n if (o.walls) {\n const wh = H - bh\n const wy = yb + wh / 2\n const wall = (id: string, size: [number, number, number], pos: [number, number, number], supports: string[]) => {\n parts.push({ id, material: wmat, shape: { kind: 'box', size }, position: pos, structure: { role: 'wall' } })\n for (const s of supports) on(id, s, 'mortar')\n }\n for (const j of [0, nz - 1]) {\n for (let i = 0; i < nx - 1; i++) {\n const c1 = `column_${f}_${i}_${j}`, c2 = `column_${f}_${i + 1}_${j}`\n const avail = xs[i + 1] - xs[i] - cs\n if (f === 0 && j === 0 && i === 0 && avail > dw + 0.4) {\n const side = (avail - dw) / 2\n const lx = xs[i] + cs / 2 + side / 2, rx = xs[i + 1] - cs / 2 - side / 2\n wall(`wall_door_left`, [side, wh, wt], [lx, wy, zs[j]], [c1])\n wall(`wall_door_right`, [side, wh, wt], [rx, wy, zs[j]], [c2])\n const lh = wh - dh\n wall(`wall_door_lintel`, [dw, lh, wt], [xs[i] + cs / 2 + side + dw / 2, yb + dh + lh / 2, zs[j]], ['wall_door_left', 'wall_door_right'])\n parts.push({ id: 'door', material: 'wood_hard', shape: { kind: 'box', size: [dw - 0.04, dh, 0.05] }, position: [xs[i] + cs / 2 + side + dw / 2, yb + dh / 2, zs[j]], tags: ['door'] })\n joints.push({ id: 'door~wall_door_left', a: 'door', b: 'wall_door_left', kind: 'hinge', bears: false })\n } else wall(`wall_x_${f}_${i}_${j}`, [avail, wh, wt], [(xs[i] + xs[i + 1]) / 2, wy, zs[j]], [c1, c2])\n }\n }\n for (const i of [0, nx - 1]) {\n for (let j = 0; j < nz - 1; j++) {\n wall(`wall_z_${f}_${i}_${j}`, [wt, wh, zs[j + 1] - zs[j] - cs], [xs[i], wy, (zs[j] + zs[j + 1]) / 2], [`column_${f}_${i}_${j}`, `column_${f}_${i}_${j + 1}`])\n }\n }\n }\n }\n return { name: 'frame', parts, joints, tags: ['structure'] }\n}\n","import { createDestruction } from './world'\nimport type { DestructibleSpec, SizeStructureOptions, StructureRole } from './types'\n\n/**\n * Sizes the load capacity of a structure the way an engineer would, from the loads the world itself computes. The intact spec goes through the\n * same load solver `createDestruction` uses, and each structural part (`structure.role` other than `none`) gets `structure.capacity = load / safety`,\n * so its at-rest stress is exactly `safety` (`safetyByRole` overrides it per role). With `redundancy` set, every part whose role is in\n * `redundancyRoles` (default `column`) is also removed in turn and the capacity of the parts that would carry more is raised so they stay at or below\n * `redundancy`. Parts without `structure`, with role `none`, or with no support path to an\n * anchored part are left as they are. The spec is not modified; a copy is returned.\n */\nexport const sizeStructure = (spec: DestructibleSpec, options: SizeStructureOptions = {}): DestructibleSpec => {\n const safety = options.safety ?? 0.65\n const redundancy = options.redundancy\n const redundancyRoles: readonly StructureRole[] = options.redundancyRoles ?? ['column']\n const safetyOf = (role: StructureRole): number => options.safetyByRole?.[role] ?? safety\n const loads = (s: DestructibleSpec): Map<string, { load: number; stress: number }> => {\n const w = createDestruction(options.materials ? { materials: options.materials } : {})\n const id = w.add(s)\n return new Map(w.state(id)!.parts.map((p) => [p.id, { load: p.load ?? 0, stress: p.stress ?? 0 }]))\n }\n const out = structuredClone(spec)\n const base = loads(out)\n const need = new Map<string, number>()\n for (const p of out.parts) {\n if (!p.structure || p.structure.role === 'none') continue\n const b = base.get(p.id)\n if (!b || b.stress <= 0) continue\n need.set(p.id, b.load / safetyOf(p.structure.role))\n }\n if (redundancy !== undefined) {\n for (const col of out.parts) {\n if (!col.structure || !redundancyRoles.includes(col.structure.role)) continue\n const reduced: DestructibleSpec = {\n ...out,\n parts: out.parts.filter((p) => p.id !== col.id),\n joints: (out.joints ?? []).filter((j) => j.a !== col.id && j.b !== col.id),\n }\n // joints are inferred when the spec has none; removing a part then removes its joints with it\n if (!out.joints) delete reduced.joints\n const l = loads(reduced)\n for (const [id, n] of need) {\n const r = l.get(id)\n if (r && r.stress > 0) need.set(id, Math.max(n, r.load / redundancy))\n }\n }\n }\n for (const p of out.parts) {\n const n = need.get(p.id)\n if (n !== undefined) p.structure = { ...p.structure!, capacity: n }\n }\n return out\n}\n","import type { DamageType, DestructionEventType, FractureStyle, JointKind, PartStatus, StructureRole, ToolKind } from './types'\n\n/** Locales shipped with the package. Unknown locales fall back to `en`. */\nexport type DestructionLocale = 'en' | 'pt-BR'\n\nexport interface DestructionStrings {\n /** Display name per material id (see `MATERIALS`). Unknown ids are not listed. */\n materialNames: Record<string, string>\n partStatus: Record<PartStatus, string>\n jointKinds: Record<JointKind, string>\n toolKinds: Record<ToolKind, string>\n damageTypes: Record<DamageType, string>\n /** Short label per event type, for logs and kill-feed style text. */\n eventLabels: Record<DestructionEventType, string>\n fractureStyles: Record<FractureStyle, string>\n structureRoles: Record<StructureRole, string>\n}\n\nexport const locales: Record<DestructionLocale, DestructionStrings> = {\n en: {\n materialNames: {\n steel: 'steel', cast_iron: 'cast iron', aluminium: 'aluminium', copper: 'copper', wood_soft: 'softwood', wood_hard: 'hardwood', plywood: 'plywood',\n mdf: 'MDF', glass: 'glass', tempered_glass: 'tempered glass', ceramic: 'ceramic', concrete: 'concrete', brick: 'brick', plaster: 'plaster',\n stone: 'stone', plastic: 'plastic', rubber: 'rubber', fabric: 'fabric', foam: 'foam', leather: 'leather', paper: 'paper', foliage: 'foliage',\n green_wood: 'green wood', cactus: 'cactus', flesh_fruit: 'fruit', wax: 'wax', soil: 'soil',\n },\n partStatus: { intact: 'intact', damaged: 'damaged', collapsed: 'collapsed', broken: 'broken', melted: 'melted', ashes: 'ashes' },\n jointKinds: {\n screw: 'screw', bolt: 'nut and bolt', nail: 'nail', weld: 'weld', glue: 'glue', hinge: 'hinge', clip: 'clip', tie: 'tie', mortar: 'mortar',\n fused: 'fused', stem: 'stem', rebar: 'rebar', resting: 'resting',\n },\n toolKinds: {\n hand: 'hand', screwdriver: 'screwdriver', wrench: 'wrench', pry_bar: 'pry bar', saw: 'saw', cutting_torch: 'cutting torch', knife: 'knife', hammer: 'hammer',\n },\n damageTypes: { ballistic: 'ballistic', blunt: 'blunt', slash: 'slash', explosive: 'explosive', fire: 'fire', heat: 'heat' },\n eventLabels: {\n damage: 'damage', dent: 'dent', hole: 'hole', crack: 'crack', ricochet: 'ricochet', debris: 'debris', fracture: 'broke', detach: 'came loose',\n disassemble_progress: 'taking apart', ignite: 'caught fire', extinguish: 'put out', burnout: 'burned to ash', melt: 'melting', drip: 'dripping',\n leak: 'leak', explode: 'exploded', primed: 'about to explode', stress: 'overload', collapse: 'collapsed', spall: 'plaster came off', stage: 'damage stage', expose: 'rebar bare', body: 'body', destroyed: 'destroyed',\n },\n fractureStyles: { shatter: 'shatter', crumble: 'crumble', splinter: 'splinter', tear: 'tear', snap: 'snap', none: 'none' },\n structureRoles: { foundation: 'foundation', column: 'column', beam: 'beam', slab: 'slab', wall: 'wall', partition: 'partition', roof: 'roof', stair: 'stairs', none: 'none' },\n },\n 'pt-BR': {\n materialNames: {\n steel: 'aço', cast_iron: 'ferro fundido', aluminium: 'alumínio', copper: 'cobre', wood_soft: 'madeira macia', wood_hard: 'madeira de lei',\n plywood: 'compensado', mdf: 'MDF', glass: 'vidro', tempered_glass: 'vidro temperado', ceramic: 'cerâmica', concrete: 'concreto', brick: 'tijolo',\n plaster: 'gesso', stone: 'pedra', plastic: 'plástico', rubber: 'borracha', fabric: 'tecido', foam: 'espuma', leather: 'couro', paper: 'papel',\n foliage: 'folhagem', green_wood: 'madeira verde', cactus: 'cacto', flesh_fruit: 'fruta', wax: 'cera', soil: 'terra',\n },\n partStatus: { intact: 'intacto', damaged: 'danificado', collapsed: 'desabado', broken: 'quebrado', melted: 'derretido', ashes: 'cinzas' },\n jointKinds: {\n screw: 'parafuso', bolt: 'porca e parafuso', nail: 'prego', weld: 'solda', glue: 'cola', hinge: 'dobradiça', clip: 'encaixe', tie: 'amarração',\n mortar: 'argamassa', fused: 'fundido', stem: 'caule', rebar: 'vergalhão', resting: 'apoiado',\n },\n toolKinds: {\n hand: 'mão', screwdriver: 'chave de fenda', wrench: 'chave inglesa', pry_bar: 'pé de cabra', saw: 'serra', cutting_torch: 'maçarico', knife: 'faca', hammer: 'martelo',\n },\n damageTypes: { ballistic: 'tiro', blunt: 'impacto', slash: 'corte', explosive: 'explosão', fire: 'fogo', heat: 'calor' },\n eventLabels: {\n damage: 'dano', dent: 'amassado', hole: 'furo', crack: 'trinca', ricochet: 'ricochete', debris: 'estilhaços', fracture: 'quebrou', detach: 'soltou',\n disassemble_progress: 'desmontando', ignite: 'pegou fogo', extinguish: 'apagou', burnout: 'virou cinza', melt: 'derretendo', drip: 'pingando',\n leak: 'vazamento', explode: 'explodiu', primed: 'prestes a explodir', stress: 'sobrecarga', collapse: 'desabou', spall: 'reboco soltou', stage: 'estágio de dano', expose: 'vergalhão à mostra', body: 'corpo', destroyed: 'destruído',\n },\n fractureStyles: { shatter: 'estilhaçar', crumble: 'esfarelar', splinter: 'lascar', tear: 'rasgar', snap: 'partir', none: 'nenhuma' },\n structureRoles: { foundation: 'fundação', column: 'pilar', beam: 'viga', slab: 'laje', wall: 'parede', partition: 'divisória', roof: 'telhado', stair: 'escada', none: 'nenhum' },\n },\n}\n\nexport const resolveStrings = (locale: string | undefined): DestructionStrings => locales[(locale as DestructionLocale) ?? 'en'] ?? locales.en\n","import { checkDestructible as check } from '@adatechnology/game-contracts'\nimport type { CheckOptions as ContractCheckOptions, DestructibleImpl } from '@adatechnology/game-contracts'\nimport { MATERIALS } from './materials'\n\n// The contract itself lives in @adatechnology/game-contracts (a module depends only on that); re-exported here so that no import breaks.\nexport { IMPACT_CONTRACT, checkHit } from '@adatechnology/game-contracts'\nexport type { DestructibleImpl, ImpactContract } from '@adatechnology/game-contracts'\n\nexport interface CheckOptions {\n /** Ids of custom materials the impl uses besides the built-in `MATERIALS`. */\n materials?: string[]\n}\n\n/**\n * `checkDestructible` of `@adatechnology/game-contracts`, with the built-in `MATERIALS` (plus `options.materials`) as the known material ids.\n * It hits the impl (and calls `reset()` afterwards when there is one).\n */\nexport const checkDestructible = (impl: DestructibleImpl, options: CheckOptions = {}): { ok: boolean; problems: string[] } => {\n const contractOptions: ContractCheckOptions = { materials: [...MATERIALS.map((m) => m.id), ...(options.materials ?? [])] }\n return check(impl, contractOptions)\n}\n","import { GROUND } from './types'\nimport type { StructurePart, Support } from './types'\n\n/**\n * Load each part carries at rest, by the rules of the Visor de casas 3D (which the destruction world shares): load only goes down to supports closer to\n * the ground, shared equally, and a partition wall carries nothing, so what rests only on partitions has no load. `without` leaves one part out (as if it\n * had failed). Parts that are not structural (the tank) are not loaded.\n */\nexport function loadsAtRest(parts: readonly StructurePart[], supports: readonly Support[], without?: string): Map<string, number> {\n const byId = new Map(parts.filter((part) => part.id !== without).map((part) => [part.id, part]))\n const resting = new Map<string, string[]>()\n const carrying = new Map<string, string[]>()\n const push = (map: Map<string, string[]>, key: string, value: string): void => {\n const list = map.get(key)\n if (list) list.push(value)\n else map.set(key, [value])\n }\n for (const support of supports) {\n if (support.bears === false) continue\n if (!byId.has(support.part) || (support.on !== GROUND && !byId.has(support.on))) continue\n push(resting, support.part, support.on)\n push(carrying, support.on, support.part)\n }\n const partition = (id: string): boolean => byId.get(id)?.role === 'partition'\n const structural = (id: string): boolean => byId.has(id) && byId.get(id)!.role !== 'none'\n const distance = new Map<string, number>([[GROUND, 0]])\n const queue = [GROUND]\n for (let head = 0; head < queue.length; head++) {\n const current = queue[head]!\n if (current !== GROUND && partition(current)) continue\n for (const above of carrying.get(current) ?? []) {\n if (distance.has(above) || !structural(above)) continue\n distance.set(above, distance.get(current)! + 1)\n queue.push(above)\n }\n }\n const incoming = new Map<string, number>()\n const loads = new Map<string, number>()\n for (let head = queue.length - 1; head >= 1; head--) {\n const id = queue[head]!\n const total = (byId.get(id)!.mass || 1) + (incoming.get(id) ?? 0)\n loads.set(id, total)\n const below = (resting.get(id) ?? []).filter((other) => distance.has(other) && distance.get(other)! < distance.get(id)! && !(other !== GROUND && partition(other)))\n for (const other of below) incoming.set(other, (incoming.get(other) ?? 0) + total / below.length)\n }\n return loads\n}\n\nexport interface SizingOptions {\n /** Fraction of its capacity a pillar or bearing wall uses at rest. */\n safety: number\n /** The most of its capacity a pillar or bearing wall uses after any other pillar or bearing wall is lost. */\n redundancy: number\n /** Fraction of capacity every other structural part uses at rest. */\n safetyOthers: number\n}\n\nconst isBearing = (part: StructurePart): boolean => part.role === 'column' || part.role === 'wall'\n\n/**\n * Capacity of each loaded part, as a designer would size it: a pillar or bearing wall uses `safety` of it at rest and stays under `redundancy` when\n * any other pillar or bearing wall is lost (the house holds one loss and falls with two); every other part uses `safetyOthers`.\n * `sizeStructure` of game-destruction gives the same numbers except for beams of a framed building (it holds them under `redundancy` too).\n */\nexport function sizeCapacities(parts: readonly StructurePart[], supports: readonly Support[], options: SizingOptions): Map<string, number> {\n const loads = loadsAtRest(parts, supports)\n const worst = new Map<string, number>()\n for (const part of parts.filter(isBearing)) {\n for (const [id, load] of loadsAtRest(parts, supports, part.id)) {\n const before = loads.get(id)\n if (before && load / before > (worst.get(id) ?? 1)) worst.set(id, load / before)\n }\n }\n const capacities = new Map<string, number>()\n for (const part of parts) {\n const load = loads.get(part.id)\n if (load === undefined || part.role === 'none') continue\n const factor = isBearing(part) ? Math.max(1 / options.safety, (worst.get(part.id) ?? 1) / options.redundancy) : 1 / options.safetyOthers\n capacities.set(part.id, Math.max(1, load * factor))\n }\n return capacities\n}\n","import { touches } from '../geometry'\nimport type { Rect, StructurePart, Support } from '../types'\nimport type { WallSplit } from './panels'\n\nexport interface PartsAndSupports {\n parts: StructurePart[]\n supports: Support[]\n}\n\n/** Replaces each part that has a split by its pieces, and re-points what rested on it or what it rested on (the pieces touching the part resting on it get the load). */\nexport function applySplits(input: PartsAndSupports, splits: ReadonlyMap<string, WallSplit>): PartsAndSupports {\n if (!splits.size) return input\n const boxes = new Map<string, Rect>(input.parts.map((part) => [part.id, part.aabb]))\n const pieceBox = new Map<string, Rect>()\n for (const split of splits.values()) for (const piece of split.pieces) pieceBox.set(piece.id, piece.aabb)\n const parts = input.parts.flatMap((part) => splits.get(part.id)?.pieces ?? [part])\n const supports: Support[] = []\n for (const support of input.supports) {\n const own = splits.get(support.part)\n const host = splits.get(support.on)\n const resting = boxes.get(support.part)\n const targets = host ? host.top.filter((id) => resting && touches(pieceBox.get(id)!, resting, 0.05)) : [support.on]\n const carriers = host ? (targets.length ? targets : host.top) : targets\n for (const part of own ? own.base : [support.part]) for (const on of carriers) supports.push({ ...support, part, on })\n }\n for (const split of splits.values()) supports.push(...split.internal)\n return { parts, supports }\n}\n","import type { JointKind } from '@adatechnology/game-contracts'\n\nimport { round2 } from '../geometry'\nimport type { Opening, Rect, StructurePart, Support } from '../types'\nimport type { WallSplit } from './panels'\n\nexport interface CourseSpec {\n rowHeight: number\n /** Length of a unit along the wall; without it a course is one piece per stretch (a log). */\n unitLength?: number\n bond: 'running' | 'stack'\n /** Joint of a unit on the units under it. */\n joint: JointKind\n assembly: string\n}\n\nconst MIN_UNIT = 0.02\n\ninterface Cell {\n from: number\n to: number\n row: number\n y0: number\n y1: number\n}\n\nfunction cutAt(from: number, to: number, openings: readonly Opening[], y0: number, y1: number): [number, number][] {\n let stretches: [number, number][] = [[from, to]]\n for (const opening of openings.filter((o) => o.y0 < y1 - MIN_UNIT && o.y1 > y0 + MIN_UNIT)) {\n stretches = stretches.flatMap(([a, b]): [number, number][] => {\n if (opening.to <= a || opening.from >= b) return [[a, b]]\n return [[a, Math.min(b, opening.from)], [Math.max(a, opening.to), b]].filter(([x, y]) => (y as number) - (x as number) > MIN_UNIT) as [number, number][]\n })\n }\n return stretches\n}\n\nfunction unitsOf(from: number, to: number, row: number, spec: CourseSpec): [number, number][] {\n const length = spec.unitLength\n if (!length) return [[from, to]]\n const offset = spec.bond === 'running' && row % 2 === 1 ? length / 2 : 0\n const cuts: number[] = [from]\n for (let at = from + (offset || length); at < to - MIN_UNIT; at += length) cuts.push(at)\n cuts.push(to)\n return cuts.slice(0, -1).map((start, k): [number, number] => [start, cuts[k + 1]!]).filter(([a, b]) => b - a > MIN_UNIT)\n}\n\n/**\n * Cuts a wall into courses of units (bricks laid in bond, or logs): each course is cut at the openings it meets, and each unit rests on the units of the course\n * below that it overlaps. A wall whose lowest course goes loses every course above it. The mass of the wall is shared among the units by volume.\n */\nexport function splitIntoCourses(wall: StructurePart, openings: readonly Opening[], spec: CourseSpec): WallSplit {\n const alongU = wall.aabb[2] - wall.aabb[0] >= wall.aabb[3] - wall.aabb[1]\n const from = alongU ? wall.aabb[0] : wall.aabb[1]\n const to = alongU ? wall.aabb[2] : wall.aabb[3]\n const cross: [number, number] = alongU ? [wall.aabb[1], wall.aabb[3]] : [wall.aabb[0], wall.aabb[2]]\n const rows = Math.max(1, Math.round((wall.y1 - wall.y0) / spec.rowHeight))\n const rowHeight = (wall.y1 - wall.y0) / rows\n const cells: Cell[] = []\n for (let row = 0; row < rows; row++) {\n const y0 = wall.y0 + row * rowHeight\n const y1 = wall.y0 + (row + 1) * rowHeight\n for (const [a, b] of cutAt(from, to, openings.filter((o) => o.wall === wall.id), y0, y1)) for (const [x0, x1] of unitsOf(a, b, row, spec)) cells.push({ from: x0, to: x1, row, y0, y1 })\n }\n const total = cells.reduce((sum, cell) => sum + (cell.to - cell.from) * (cell.y1 - cell.y0), 0)\n const box = (cell: Cell): Rect => (alongU ? [cell.from, cross[0], cell.to, cross[1]] : [cross[0], cell.from, cross[1], cell.to])\n const pieces = cells.map((cell, index): StructurePart => ({\n id: `${wall.id}_${spec.unitLength ? 'u' : 'log'}${cell.row}_${index}`, role: wall.role, material: wall.material, aabb: box(cell), y0: cell.y0, y1: cell.y1, floor: wall.floor,\n mass: round2(Math.max(0.1, (wall.mass * (cell.to - cell.from) * (cell.y1 - cell.y0)) / total)), host: wall.id, assembly: spec.assembly, unit: true,\n }))\n const internal: Support[] = []\n cells.forEach((cell, index) => {\n if (cell.row === 0) return\n const below = cells.map((other, k) => ({ other, k })).filter(({ other }) => other.row === cell.row - 1 && Math.min(other.to, cell.to) - Math.max(other.from, cell.from) > MIN_UNIT)\n for (const { k } of below) internal.push({ part: pieces[index]!.id, on: pieces[k]!.id, joint: spec.joint })\n })\n return { pieces, internal, base: pieces.filter((_, i) => cells[i]!.row === 0).map((p) => p.id), top: pieces.filter((_, i) => cells[i]!.row === rows - 1).map((p) => p.id) }\n}\n","import type { JointKind } from '@adatechnology/game-contracts'\n\nimport { round2 } from '../geometry'\nimport type { Opening, Rect, StructurePart, Support } from '../types'\n\nexport interface PanelStyle {\n lintelMaterial: string\n lintelAssembly?: string\n /** Joint of a lintel on its piers and of the wall above it on the lintel. */\n lintelJoint: JointKind\n wallJoint: JointKind\n}\n\nexport interface WallSplit {\n pieces: StructurePart[]\n /** What the pieces rest on among themselves (lintel on piers, spandrel on lintel). */\n internal: Support[]\n /** Pieces that rest on what the wall rests on. */\n base: string[]\n /** Pieces that carry what rests on the wall. */\n top: string[]\n}\n\nexport const LINTEL_DEPTH = 0.2\nexport const LINTEL_BEARING = 0.2\nconst MIN_PIECE = 0.05\n\ninterface Frame {\n alongU: boolean\n from: number\n to: number\n cross: [number, number]\n}\n\nconst frameOf = (wall: StructurePart): Frame => {\n const alongU = wall.aabb[2] - wall.aabb[0] >= wall.aabb[3] - wall.aabb[1]\n return alongU ? { alongU, from: wall.aabb[0], to: wall.aabb[2], cross: [wall.aabb[1], wall.aabb[3]] } : { alongU, from: wall.aabb[1], to: wall.aabb[3], cross: [wall.aabb[0], wall.aabb[2]] }\n}\n\nconst boxOf = (frame: Frame, from: number, to: number): Rect => (frame.alongU ? [from, frame.cross[0], to, frame.cross[1]] : [frame.cross[0], from, frame.cross[1], to])\n\ninterface Draft {\n id: string\n role: StructurePart['role']\n material: string\n assembly?: string\n from: number\n to: number\n y0: number\n y1: number\n /** Volume that counts for the mass share (pieces tile the wall: a lintel keeps the bearing it shares with the piers). */\n volume: number\n}\n\n/**\n * Cuts a wall at its windows: piers between them at full height, a sill wall under each window, a lintel over it that bears 0.2 m on the piers and the wall\n * above the lintel up to the top. The mass of the wall is shared among the pieces by volume, so the total is the wall's.\n */\nexport function splitIntoPanels(wall: StructurePart, openings: readonly Opening[], style: PanelStyle): WallSplit {\n const frame = frameOf(wall)\n const own = openings.filter((o) => o.wall === wall.id && o.to > frame.from + MIN_PIECE && o.from < frame.to - MIN_PIECE).sort((a, b) => a.from - b.from)\n if (!own.length) return { pieces: [wall], internal: [], base: [wall.id], top: [wall.id] }\n const drafts: Draft[] = []\n const piers: Draft[] = []\n const lintels: Draft[] = []\n const spandrels: (Draft | undefined)[] = []\n const height = wall.y1 - wall.y0\n let cursor = frame.from\n const roleOf = wall.role\n const addPier = (to: number): void => {\n if (to - cursor < MIN_PIECE) return\n piers.push({ id: `${wall.id}_pier_${piers.length}`, role: roleOf, material: wall.material, from: cursor, to, y0: wall.y0, y1: wall.y1, volume: (to - cursor) * height })\n }\n own.forEach((opening, k) => {\n addPier(Math.max(cursor, opening.from))\n const lintelTop = Math.min(wall.y1, opening.y1 + LINTEL_DEPTH)\n const lintelFrom = Math.max(frame.from, opening.from - LINTEL_BEARING)\n const lintelTo = Math.min(frame.to, opening.to + LINTEL_BEARING)\n const lintelHeight = lintelTop - opening.y1\n if (opening.y0 - wall.y0 > MIN_PIECE) drafts.push({ id: `${wall.id}_sill_${k}`, role: 'partition', material: wall.material, from: opening.from, to: opening.to, y0: wall.y0, y1: opening.y0, volume: (opening.to - opening.from) * (opening.y0 - wall.y0) })\n lintels.push({ id: `${wall.id}_lintel_${k}`, role: 'beam', material: style.lintelMaterial, from: lintelFrom, to: lintelTo, y0: opening.y1, y1: lintelTop, volume: (lintelTo - lintelFrom) * lintelHeight })\n spandrels.push(wall.y1 - lintelTop > MIN_PIECE ? { id: `${wall.id}_spandrel_${k}`, role: roleOf, material: wall.material, from: opening.from, to: opening.to, y0: lintelTop, y1: wall.y1, volume: (opening.to - opening.from) * (wall.y1 - lintelTop) } : undefined)\n cursor = opening.to\n })\n addPier(frame.to)\n // the piers give the bearing zone of each lintel to it\n for (const pier of piers) {\n for (const lintel of lintels) {\n const overlap = Math.max(0, Math.min(pier.to, lintel.to) - Math.max(pier.from, lintel.from))\n pier.volume -= overlap * (lintel.y1 - lintel.y0)\n }\n }\n const all = [...piers, ...drafts, ...lintels, ...spandrels.filter((d): d is Draft => d !== undefined)]\n const total = all.reduce((sum, d) => sum + d.volume, 0)\n const pieces = all.map((d): StructurePart => ({\n id: d.id, role: d.role, material: d.material, aabb: boxOf(frame, d.from, d.to), y0: d.y0, y1: d.y1, floor: wall.floor, mass: round2(Math.max(0.1, (wall.mass * d.volume) / total)), host: wall.id,\n ...(d.role === 'beam' ? (style.lintelAssembly ? { assembly: style.lintelAssembly } : {}) : wall.assembly ? { assembly: wall.assembly } : {}),\n }))\n const internal: Support[] = []\n lintels.forEach((lintel, k) => {\n for (const pier of piers) if (Math.min(pier.to, lintel.to) - Math.max(pier.from, lintel.from) > 0) internal.push({ part: lintel.id, on: pier.id, joint: style.lintelJoint })\n const spandrel = spandrels[k]\n if (spandrel) internal.push({ part: spandrel.id, on: lintel.id, joint: style.wallJoint })\n })\n const base = [...piers, ...drafts.filter((d) => d.id.includes('_sill_'))].map((d) => d.id)\n const top = [...piers.map((p) => p.id), ...lintels.map((l, k) => spandrels[k]?.id ?? l.id)]\n return { pieces, internal, base, top }\n}\n","import { getAssembly } from '@adatechnology/game-destruction'\n\nimport type { Construction, Rect, Structure, StructurePart, WallDetail } from '../types'\nimport { applySplits } from './apply'\nimport type { PartsAndSupports } from './apply'\nimport { splitIntoCourses } from './courses'\nimport type { CourseSpec } from './courses'\nimport { splitIntoPanels } from './panels'\nimport type { WallSplit } from './panels'\nimport { CONSTRUCTION_SYSTEMS } from '../registry'\n\nconst LOG_DIAMETER = 0.26\nconst isWall = (part: StructurePart): boolean => part.id.startsWith('wall_') && part.assembly !== undefined && (part.role === 'wall' || part.role === 'partition')\n\nfunction logSpec(construction: Construction, part: StructurePart): CourseSpec {\n const diameter = (construction.walls.logDiameter as number | undefined) ?? LOG_DIAMETER\n return { rowHeight: diameter, bond: 'stack', joint: CONSTRUCTION_SYSTEMS.get(construction.system)!.joints.wall, assembly: part.assembly! }\n}\n\n/** Walls cut at their windows (piers, sills, lintels, spandrels); the walls of logs as courses of logs. */\nfunction panelSplits(input: PartsAndSupports, structure: Structure): Map<string, WallSplit> {\n const { construction } = structure\n const system = CONSTRUCTION_SYSTEMS.get(construction.system)!\n const splits = new Map<string, WallSplit>()\n for (const part of input.parts.filter(isWall)) {\n if (construction.system === 'log') {\n splits.set(part.id, splitIntoCourses(part, structure.openings, logSpec(construction, part)))\n continue\n }\n const split = splitIntoPanels(part, structure.openings, {\n lintelMaterial: system.timber ? construction.frame.timber : 'concrete', ...(system.timber ? {} : { lintelAssembly: 'reinforced_concrete' }), lintelJoint: system.joints.beam, wallJoint: system.joints.wall,\n })\n if (split.pieces.length > 1) splits.set(part.id, split)\n }\n return splits\n}\n\n/** Splits the walls the way `detail` says: `coarse` keeps one part per wall, `panels` cuts them at the windows, `units` goes on to bricks and blocks. */\nexport function applyPanels(input: PartsAndSupports, structure: Structure, detail: WallDetail): PartsAndSupports {\n if (detail === 'coarse') return input\n return applySplits(input, panelSplits(input, structure))\n}\n\nexport interface Sized extends PartsAndSupports {\n capacities: Map<string, number>\n}\n\n/** Cuts each wall piece that its assembly lays in units (bricks, blocks, concrete panels) into those units; a unit takes the share of the piece's capacity its width has (it carries its column of the wall). */\nexport function applyUnits(input: Sized, structure: Structure): Sized {\n const splits = new Map<string, WallSplit>()\n for (const part of input.parts) {\n if (part.unit || !part.assembly || part.role === 'beam' || part.role === 'none') continue\n const units = getAssembly(part.assembly)?.units\n if (!units) continue\n const joint = CONSTRUCTION_SYSTEMS.get(structure.construction.system)!.joints.wall\n splits.set(part.id, splitIntoCourses(part, [], { rowHeight: units.size[1], unitLength: units.size[0], bond: units.bond, joint: units.mortar === 'concrete' ? 'mortar' : joint, assembly: part.assembly }))\n }\n const next = applySplits(input, splits)\n const capacities = new Map(input.capacities)\n for (const [id, split] of splits) {\n const capacity = input.capacities.get(id)\n capacities.delete(id)\n if (capacity === undefined) continue\n const along = (box: Rect): number => Math.max(box[2] - box[0], box[3] - box[1])\n const length = along(input.parts.find((part) => part.id === id)!.aabb)\n for (const piece of split.pieces) capacities.set(piece.id, Math.max(1, (capacity * along(piece.aabb)) / length))\n }\n return { ...next, capacities }\n}\n","import type { DestructibleSpec, JointSpec, PartSpec, StructureRole } from '@adatechnology/game-contracts'\nimport { assemblyPart } from '@adatechnology/game-destruction'\nimport { sizeCapacities } from './loads'\nimport { GROUND } from './types'\nimport { applyPanels, applyUnits } from './wall-detail'\nimport type { PartRole, Structure, StructurePart, WallDetail } from './types'\n\nexport interface DestructibleSpecOptions {\n /** Fraction of its capacity a pillar or bearing wall uses at rest (default 0.65). */\n safety?: number\n /** After losing any other pillar or bearing wall, the most of its capacity one of them uses (default 0.97: the house holds one loss and falls with two). */\n redundancy?: number\n /** Fraction of capacity beams, slabs, roofs, stairs and partitions use at rest (default 0.45). */\n safetyOthers?: number\n /** Bearing walls close but do not carry: a frame of pillars and beams carries the building. Default: for a framed building unless the detail is `coarse`. */\n portico?: boolean\n /** How finely the walls are split (default `panels`; `coarse` is one part per wall as the Visor de casas 3D builds it). */\n wallDetail?: WallDetail\n /** Name of the spec (default `house`). */\n name?: string\n /** Leaves parts out (and what rests on them is dropped from the joints). */\n filter?: (part: StructurePart) => boolean\n /** `false` keeps the capacity of the material instead of sizing it from the load. */\n sized?: boolean\n /** Metres the anchored terrain slab reaches beyond the parts (default 6). */\n terrainMargin?: number\n}\n\nconst CONTRACT_ROLE: Record<PartRole, StructureRole> = { column: 'column', beam: 'beam', slab: 'slab', wall: 'wall', partition: 'partition', roof: 'roof', stair: 'stair', none: 'none' }\n\nconst TERRAIN_MARGIN = 6\nconst TERRAIN_THICKNESS = 0.5\n\nconst boxSpec = (part: StructurePart, capacity: number | undefined): PartSpec => {\n const [u0, v0, u1, v1] = part.aabb\n return {\n id: part.id, material: part.material, shape: { kind: 'box', size: [Math.max(0.01, u1 - u0), Math.max(0.01, part.y1 - part.y0), Math.max(0.01, v1 - v0)] },\n position: [(u0 + u1) / 2, (part.y0 + part.y1) / 2, (v0 + v1) / 2], mass: Math.max(0.1, part.mass || 1),\n structure: capacity === undefined ? { role: CONTRACT_ROLE[part.role] } : { role: CONTRACT_ROLE[part.role], capacity },\n }\n}\n\n/** A wall piece as its assembly builds it (layers, rebar, units, breach), with the mass the structure gave it. A brick or log is the unit itself, so it keeps no units or breach. */\nconst assemblySpec = (part: StructurePart, capacity: number | undefined): PartSpec => {\n const [u0, v0, u1, v1] = part.aabb\n const alongU = u1 - u0 >= v1 - v0\n const spec = assemblyPart(part.assembly!, {\n id: part.id, width: alongU ? u1 - u0 : v1 - v0, height: part.y1 - part.y0, position: [(u0 + u1) / 2, (part.y0 + part.y1) / 2, (v0 + v1) / 2], ...(alongU ? {} : { rotation: [0, Math.PI / 2, 0] }),\n structure: capacity === undefined ? { role: CONTRACT_ROLE[part.role] } : { role: CONTRACT_ROLE[part.role], capacity }, extra: { mass: Math.max(0.1, part.mass || 1) },\n })\n if (part.unit) {\n delete spec.units\n delete spec.breach\n }\n return spec\n}\n\nconst partSpecOf = (part: StructurePart, capacity: number | undefined, detailed: boolean): PartSpec => (detailed && part.assembly ? assemblySpec(part, capacity) : boxSpec(part, capacity))\n\n/**\n * The structure as a `DestructibleSpec` in the space of the house (x = u, y = height, z = v; the ground is y = 0), one box per part and a terrain slab\n * that anchors it. Capacities are sized from the loads at rest, as a designer would: a house stands whole, holds the loss of one pillar or bearing wall\n * and falls with two.\n */\nexport function toDestructibleSpec(structure: Structure, options: DestructibleSpecOptions = {}): DestructibleSpec {\n const { safety = 0.65, redundancy = 0.97, safetyOthers = 0.45 } = options\n const kept = structure.parts.filter((part) => !options.filter || options.filter(part))\n const portico = options.portico ?? (options.wallDetail !== 'coarse' && structure.framed)\n const roled = portico ? kept.map((part): StructurePart => (part.role === 'wall' ? { ...part, role: 'partition' } : part)) : kept\n const ids = new Set(roled.map((part) => part.id))\n const filtered = structure.supports.filter((support) => !options.filter || (ids.has(support.part) && (support.on === GROUND || ids.has(support.on))))\n const detail = options.wallDetail ?? 'panels'\n const panels = applyPanels({ parts: roled, supports: filtered }, structure, detail)\n const sizing = { safety, redundancy, safetyOthers }\n const sized = { ...panels, capacities: options.sized === false ? new Map<string, number>() : sizeCapacities(panels.parts, panels.supports, sizing) }\n const { parts, supports, capacities } = detail === 'units' ? applyUnits(sized, structure) : sized\n const specs = parts.map((part) => partSpecOf(part, capacities.get(part.id), detail !== 'coarse'))\n const margin = options.terrainMargin ?? TERRAIN_MARGIN\n const x0 = Math.min(...parts.map((part) => part.aabb[0]))\n const z0 = Math.min(...parts.map((part) => part.aabb[1]))\n const x1 = Math.max(...parts.map((part) => part.aabb[2]))\n const z1 = Math.max(...parts.map((part) => part.aabb[3]))\n if (parts.length) specs.push({ id: GROUND, material: 'concrete', shape: { kind: 'box', size: [x1 - x0 + margin, TERRAIN_THICKNESS, z1 - z0 + margin] }, position: [(x0 + x1) / 2, -TERRAIN_THICKNESS / 2, (z0 + z1) / 2], hp: 1e12, structure: { role: 'foundation' }, anchored: true, tags: ['terrain'] })\n const present = new Set([...parts.map((part) => part.id), GROUND])\n const joints: JointSpec[] = supports.filter((s) => present.has(s.part) && present.has(s.on)).map((s) => ({ id: `${s.part}~${s.on}`, a: s.part, b: s.on, kind: s.joint, bears: s.bears === false ? false : 'a_on_b' }))\n return { name: options.name ?? 'house', parts: specs, joints, tags: ['structure', 'house'] }\n}\n","import type { DestructibleSpec } from '@adatechnology/game-contracts'\nimport { assemblyDepth, assemblyPart, getAssembly } from '@adatechnology/game-destruction'\n\nimport { GROUND } from './types'\nimport { constructionOfSystem } from './presets'\nimport { CONSTRUCTION_SYSTEMS } from './registry'\nimport { toDestructibleSpec } from './to-destructible-spec'\nimport type { Opening, StructureSource, WallDetail } from './types'\n\nexport interface WallSpecimenOptions {\n /** Wall assembly of `game-destruction` (`brick_wall_plastered`, `concrete_block_wall`, `reinforced_concrete`, `drywall`, `wood_frame_wall`, `log_wall`, `sheet_metal_shack`...). */\n assembly: string\n /** Width and height in metres (the test area uses 2.4 x 2.1). */\n w: number\n h: number\n opening?: 'door' | 'window' | null\n /** Default `panels`: piers, lintel with its 0.2 m bearing, sill, plaster and rebar; `units` also lays the bricks, blocks or concrete panels one by one. */\n detail?: WallDetail\n}\n\nconst SYSTEM_OF_ASSEMBLY: Record<string, string> = { log_wall: 'log', wood_frame_wall: 'wood_frame', sheet_metal_shack: 'improvised' }\nconst DOOR_WIDTH = 0.9\nconst WINDOW_WIDTH = 1.0\n\nfunction openingOf(kind: 'door' | 'window', height: number): Opening {\n return kind === 'door'\n ? { id: 'door', kind, wall: 'wall_specimen', from: -DOOR_WIDTH / 2, to: DOOR_WIDTH / 2, y0: 0, y1: height * 0.8 }\n : { id: 'window', kind, wall: 'wall_specimen', from: -WINDOW_WIDTH / 2, to: WINDOW_WIDTH / 2, y0: height * 0.33, y1: height * 0.8 }\n}\n\n/**\n * A test wall as its assembly builds it, standing on a plinth: in `panels` the piers beside the opening, the lintel over it (reinforced concrete bearing 0.2 m on\n * the piers; a header in timber walls), the sill under a window and the wall above; with the plaster coat and the rebar of the assembly. The mass is the\n * assembly's for the whole w x h, whatever the detail.\n */\nexport function buildWallSpecimen(options: WallSpecimenOptions): DestructibleSpec {\n const { assembly, w, h, opening = null, detail = 'panels' } = options\n const def = getAssembly(assembly)\n if (!def) throw new Error(`unknown assembly \"${assembly}\"`)\n const system = SYSTEM_OF_ASSEMBLY[assembly] ?? 'masonry'\n const depth = assemblyDepth(def)\n const mass = assemblyPart(assembly, { id: 'wall_specimen', width: w, height: h, position: [0, h / 2, 0] }).mass ?? 1\n const construction = constructionOfSystem(system, { facade: {}, floors: [], rooms: [], walls: [], doors: [], items: [], w, d: depth } as StructureSource)!\n const joint = CONSTRUCTION_SYSTEMS.get(system)!.joints.wall\n const structure = {\n parts: [{ id: 'wall_specimen', role: 'wall' as const, material: def.core.material, aabb: [-w / 2, -depth / 2, w / 2, depth / 2] as [number, number, number, number], y0: 0, y1: h, floor: 0, mass, assembly }],\n supports: [{ part: 'wall_specimen', on: GROUND, joint }],\n openings: opening ? [openingOf(opening, h)] : [],\n levels: [0], elevation: 0, construction, framed: false,\n roof: { shape: 'slab' as const, covering: '', material: '', pitch: 0, bearingFloor: 0, panes: [], trusses: 0 },\n }\n return toDestructibleSpec(structure, { wallDetail: detail, sized: false, terrainMargin: 0.6, name: `wall_${assembly}` })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqBA,MAAM,UAAU,CAAC,WAAuD,EAAE,MAAM,OAAO,MAAM,OAAO,MAAM,OAAO,QAAQ,OAAO,OAAO,MAAM;AAEtI,MA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;MACf,SAAW;QACV,OAAS;QACT,UAAY;QACZ,cAAgB;QAChB,cAAgB;MACjB;MACA,QAAU;QACT,OAAS;MACV;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,aAAe;QACd,OAAS;MACV;MACA,WAAa;MACb,aAAe;MACf,aAAe;MACf,SAAW;QACV,OAAS;QACT,UAAY;QACZ,cAAgB;QAChB,cAAgB;MACjB;MACA,QAAU;QACT,OAAS;MACV;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,OAAS;QACT,OAAS;MACV;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,QAAU;QACT,WAAa;MACd;MACA,MAAQ;QACP;QACA;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,OAAS;MACV;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,QAAU;QACT,WAAa;MACd;MACA,MAAQ;QACP;QACA;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,OAAS;MACV;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,QAAU;QACT,WAAa;MACd;MACA,MAAQ;QACP;QACA;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,QAAU;QACT,WAAa;MACd;MACA,MAAQ;QACP;QACA;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,OAAS;MACV;MACA,WAAa;MACb,aAAe;MACf,aAAe;MACf,SAAW;QACV,OAAS;QACT,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,eAAiB;MAClB;MACA,QAAU;QACT,OAAS;QACT,aAAe;MAChB;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,WAAa;MACb,aAAe;MACf,aAAe;MACf,SAAW;QACV,OAAS;QACT,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,eAAiB;MAClB;MACA,QAAU;QACT,OAAS;QACT,aAAe;MAChB;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,OAAS;MACV;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,cAAgB;QAChB,cAAgB;QAChB,eAAiB;MAClB;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,WAAa;MACd;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,cAAgB;QAChB,cAAgB;MACjB;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,cAAgB;QAChB,cAAgB;MACjB;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,cAAgB;QAChB,cAAgB;MACjB;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,cAAgB;QAChB,cAAgB;MACjB;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,OAAS;QACT,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,QAAU;QACT,WAAa;MACd;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,QAAU;QACT,WAAa;MACd;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,OAAS;QACT,WAAa;MACd;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,QAAU;QACT,WAAa;MACd;MACA,MAAQ;QACP;QACA;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,OAAS;QACT,WAAa;MACd;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,QAAU;QACT,WAAa;MACd;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,OAAS;MACV;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,QAAU;QACT,WAAa;MACd;MACA,MAAQ;QACP;QACA;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,OAAS;MACV;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,QAAU;QACT,WAAa;MACd;MACA,MAAQ;QACP;QACA;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,OAAS;MACV;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,QAAU;QACT,WAAa;MACd;MACA,MAAQ;QACP;QACA;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,OAAS;QACT,WAAa;MACd;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,QAAU;QACT,WAAa;MACd;MACA,MAAQ;QACP;QACA;QACA;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,OAAS;MACV;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,QAAU;QACT,WAAa;MACd;MACA,MAAQ;QACP;QACA;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,aAAe;QACd,OAAS;MACV;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,cAAgB;QAChB,cAAgB;MACjB;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,WAAa;QACb,QAAU;QACV,cAAgB;QAChB,UAAY;QACZ,OAAS;QACT,UAAY;QACZ,cAAgB;QAChB,cAAgB;QAChB,OAAS;MACV;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;IACA;MACC,IAAM;MACN,SAAW;MACX,SAAW;MACX,aAAe;MACf,WAAa;MACb,UAAY;MACZ,cAAgB;QACf;QACA;MACD;MACA,WAAa;MACb,aAAe;MACf,SAAW;QACV,cAAgB;QAChB,cAAgB;MACjB;MACA,MAAQ;QACP;QACA;MACD;MACA,aAAe;IAChB;EACD;ACn0BA,MAAA,yBAAA;IACC,aAAa;IACb,WAAa;IACb,UAAY;IACZ,OAAS;IACT,OAAS;IACT,MAAQ;IACR,QAAU;IACV,QAAU;IACV,MAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAU;IACV,OAAS;IACT,QAAU;IACV,MAAQ;IACR,QAAU;IACV,OAAS;IACT,QAAU;IACV,MAAQ;IACR,UAAY;IACZ,KAAO;IACP,SAAW;IACX,KAAO;IACP,WAAa;IACb,OAAS;IACT,QAAU;IACV,QAAU;IACV,UAAY;IACZ,YAAc;IACd,QAAU;IACV,OAAS;IACT,SAAW;IACX,MAAQ;IACR,SAAW;IACX,QAAU;IACV,SAAW;IACX,QAAU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AAC,GAAG,SAAS,EAAE;AAAA,IAC/G;AACA,WAAO,mBAAmB,WAAW,EAAE,YAAY,QAAQ,OAAO,OAAO,eAAe,KAAK,MAAM,QAAQ,QAAQ,GAAG,CAAC;AAAA,EACzH;;;AlEpDO,MAAM,UAAU;","names":["at","at","item","flight","part","entry","entry","round2","round2","round2","round2","round2","absolute","round2","round2","DOOR_HEIGHT","round2","clamp","densityOf","opening","at","LINTEL_DEPTH","LINTEL_BEARING","roleOf","opening","DOOR_WIDTH","opening"]}
|