Skip to content

A town simulation in pale isometric line art, implemented with Ritmo ECS and PixiJs 3D

11.9 KB
Raw Blame
import assert from "node:assert/strict"
import { test } from "node:test"
import { Container3D, Mesh3D } from "@pixi/3d"
import { kindIds, kinds } from "../src/game/content/index.ts"
import { U } from "../src/game/world/iso.ts"
import { dressed } from "../src/render/pixi3d/assets/upgrade-dress.ts"
import { Drawing, type InkAsset } from "../src/render/pixi3d/assets/primitives.ts"
import { buildingAsset, buildingHeight, buildingTop, homeAsset, noDoors, scaffoldAsset, treeVariant } from "../src/render/pixi3d/models.ts"
import { upgradeHeights } from "../src/render/pixi3d/assets/service-upgrades.ts"
import { ModelHandle, ModelPool } from "../src/render/pixi3d/pool.ts"
import { assetById } from "../src/render/pixi3d/assets/assets.ts"
import { surfaceState, hazardStrength } from "../src/render/pixi3d/surface-state.ts"
import { StructureEffects } from "../src/render/pixi3d/structure-effects.ts"
import { vertex3 } from "../src/render/pixi3d/assets/space.ts"
import { fan, segmentHits } from "../src/render/pixi3d/mesh/ray.ts"
import { cross, length, mean, sub, type Vec3 } from "../src/render/pixi3d/mesh/vec3.ts"

function valid(asset: InkAsset) {
  for (const face of asset.faces) {
    assert.ok(face.points.every(p => p.every(Number.isFinite)), asset.id)
    const [a, b, c] = face.points
    assert.ok(a && b && c)
    assert.ok(length(cross(sub(b, a), sub(c, a))) > 1e-10, `${asset.id}: zero-area face`)
  }
  for (const stroke of asset.strokes) assert.ok(stroke.points.every(p => p.every(Number.isFinite)), asset.id)
}

test("live construction and fitting are valid for every building and all three home tiers", () => {
  for (const build of [0, 0.125, 0.3, 0.55, 0.77, 0.78, 0.8, 0.9, 1]) {
    for (const kind of kindIds) for (const side of Object.keys(noDoors)) {
      valid(buildingAsset(kind, build, 0.5, { ...noDoors, [side]: true }, 0.5))
    }
    for (const tier of [1, 2, 3] as const) valid(homeAsset(tier, 0.62, build, 1, { ...noDoors, backLeft: true }))
  }
})

test("live service upgrades retain their taller models and material bounds beside the revised base buildings", () => {
  for (const id of ["market", "chapel"] as const) for (const side of Object.keys(noDoors)) {
    const doors = { ...noDoors, [side]: true }
    const base = buildingAsset(id, 1, null, doors, 1)
    const upgraded = buildingAsset(id, 1, null, doors, 1, { winter: true }, 1)
    valid(upgraded)
    assert.equal(upgraded.reference?.type === "building" && upgraded.reference.tier, 2)
    const top = (asset: InkAsset) => Math.max(...asset.faces.flatMap(face => face.points.map(p => p[2])))
    assert.ok(top(upgraded) > top(base), `${id}/${side}: live upgrade lost its silhouette`)
    assert.equal(buildingHeight(id, 1), upgradeHeights[id].eave)
    assert.equal(upgraded.effects?.height, upgradeHeights[id].eave)
    assert.equal(upgraded.effects?.state.snow, 1)
  }
  for (const [id, height] of [["bakery", 26], ["weaver", 26], ["fishery", 24], ["carpenter", 28]] as const)
    assert.equal(buildingHeight(id), height, `${id}: public height must follow the revised model`)
})

test("workplace and civic upgrades stay inside their plots in every orientation and retain marker clearance", () => {
  for (const id of dressed) for (const level of id === "townhall" ? [1, 2] : [1]) for (const side of Object.keys(noDoors)) {
    const doors = { ...noDoors, [side]: true }
    const base = buildingAsset(id, 1, null, doors, 1), up = buildingAsset(id, 1, null, doors, 1, {}, level)
    valid(up)
    const plot = kinds[id].size * 8 * U + 1e-9
    const reach = (asset: InkAsset) => Math.max(...[...asset.faces.flatMap((f) => f.points), ...asset.strokes.flatMap((s) => s.points)].map((p) => Math.max(Math.abs(p[0]), Math.abs(p[1]))))
    assert.ok(reach(up) <= plot, `${id}/${level}: the upgrade reaches past its plot (${reach(up)} > ${plot})`)
    assert.ok(up.faces.length + up.strokes.length > base.faces.length + base.strokes.length, `${id}/${level}: nothing is added`)
    assert.ok(buildingTop(id, level) >= buildingTop(id, 0), `${id}/${level}: its marker sinks`)
    const actualTop = Math.max(...up.faces.flatMap(f => f.points.map(p => p[2])), ...up.strokes.flatMap(s => s.points.map(p => p[2])))
    assert.ok(buildingTop(id, level) + 0.1 >= actualTop, `${id}/${level}: marker bounds miss geometry (${actualTop})`)
  }
})

test("civic milestones have progressively taller silhouettes, road-facing entrances and correct surface bounds", () => {
  let previous=buildingTop("townhall")
  for(const level of [1,2]) {
    assert.ok(buildingTop("townhall",level)>previous+5,"Each civic milestone must change the skyline")
    previous=buildingTop("townhall",level)
    for(const side of Object.keys(noDoors)) {
      const asset=buildingAsset("townhall",1,null,{...noDoors,[side]:true},1,{winter:true},level)
      const door=asset.faces.find(f=>f.color===0xbda683)!
      assert.ok(door,"A civic milestone needs a visible entrance")
      const u=door.points.reduce((n,p)=>n+p[0],0)/door.points.length,v=door.points.reduce((n,p)=>n+p[1],0)/door.points.length
      assert.equal(Math.abs(u)>Math.abs(v)?u>0?"right":"backRight":v>0?"left":"backLeft",side)
      assert.equal(asset.effects?.height,buildingHeight("townhall",level))
      assert.equal(asset.effects?.state.snow,1)
    }
  }
})

test("guildhall clock faces are circular in world space on every tower wall", () => {
  for (const side of Object.keys(noDoors)) {
    const asset=buildingAsset("townhall",1,null,{...noDoors,[side]:true},1,{},1)
    const clocks=asset.faces.filter(face=>face.color===0xf7f5e9)
    assert.equal(clocks.length,4)
    for (const face of clocks) {
      const points=face.points.slice(0,-1).map(vertex3)
      const center=mean(points)
      const radius=length(sub(points[0]!,center))
      assert.ok(points.every(p=>Math.abs(length(sub(p,center))-radius)<1e-8),`${side}: squashed clock face`)
    }
  }
})

test("the same scaffold fits every building footprint and leaves all four central approaches clear", () => {
  for(const id of kindIds)for(const share of [0,.15,.5,.9,1]) {
    const size=kinds[id].size,asset=scaffoldAsset(size,buildingHeight(id),share),half=size/2
    valid(asset)
    assert.ok([...asset.faces,...asset.strokes].flatMap(p=>p.points).every(p=>Math.abs(p[0])<=half&&Math.abs(p[1])<=half),id)
    for(const [u,v,du,dv]of [[0,half+.1,0,-1],[half+.1,0,-1,0],[0,-half-.1,0,1],[-half-.1,0,1,0]]) {
      const origin:Vec3=[u!,v!,6],reach:Vec3=[u!+du!*.6,v!+dv!*.6,6]
      assert.equal(segmentHits(origin,reach,asset.faces.flatMap(f=>fan(f.points))).length,0,`${id}/${share}: scaffold blocks a central entrance`)
    }
  }
})

test("scaffolding stays inside the plot and rises with the materials in", () => {
  for (const size of [2, 3]) {
    const plot = size * 8 * U + 1e-9
    const top = (asset: InkAsset) => Math.max(...asset.strokes.flatMap((s) => s.points.map((p) => p[2])))
    const some = scaffoldAsset(size, 32, 0.2), most = scaffoldAsset(size, 32, 0.9)
    for (const asset of [some, most]) {
      valid(asset)
      assert.ok(Math.max(...asset.strokes.flatMap((s) => s.points.map((p) => Math.max(Math.abs(p[0]), Math.abs(p[1]))))) <= plot)
    }
    assert.ok(most.strokes.length > some.strokes.length, "more boards as more comes in")
    assert.ok(top(most) >= top(some))
  }
})

test("shared geometry retains independent colours, transforms and entity picking", () => {
  const pool = new ModelPool(), root = new Container3D()
  let built = 0
  const create = () => {
    built++
    const d = new Drawing("box", "Box", "")
    d.box(0, 0, 0.1, 0.1, 0, 5, 0xff0001, 0xff0001, 0xff0001)
    return d.asset
  }
  const a = new ModelHandle(pool, 17), b = new ModelHandle(pool, 29)
  root.addChild(a.root, b.root)
  b.root.position.x = 30
  a.colors = new Map([[0xff0001, 0x89aabb]])
  b.colors = new Map([[0xff0001, 0x663311]])
  a.use("box", create)
  b.use("box", create)
  pool.flush()
  assert.equal(built, 1)
  assert.equal(pool.stats().models, 2)
  // Each copy is meshes of its own under its root, the fill first: they share the box's geometry, and each has its own colour.
  assert.ok(a.root.children[0] instanceof Mesh3D)
  assert.equal(a.pieces[0]!.mesh.geometry, b.pieces[0]!.mesh.geometry)
  const hex = (handle: ModelHandle) => {
    const color = handle.pieces[0]!.opaque.data.color as ArrayLike<number>
    return [0, 1, 2].reduce((n, k) => (n << 8) | Math.round(color[k]! * 255), 0)
  }
  assert.equal(hex(a), 0x89aabb)
  assert.equal(hex(b), 0x663311)
  const hit = pool.pick({ origin: [30, 10, 0], direction: [0, -1, 0] })
  assert.ok(hit)
  assert.equal(hit.handle.entity, 29)
  b.dispose()
  pool.flush()
  assert.equal(pool.pick({ origin: [30, 10, 0], direction: [0, -1, 0] }), null)
  assert.equal(pool.pick({ origin: [0, 10, 0], direction: [0, -1, 0] })?.handle.entity, 17)
  a.dispose()
  for (let i = 0; i < 100; i++) {
    a.use(`state/${i}`, create)
    pool.flush()
  }
  assert.ok(pool.stats().templates <= 65, "Idle animation/construction states must not accumulate")
  pool.dispose()
})

test("a seeded forest uses a bounded set of variants and preserves cell offsets", () => {
  const variants = new Set<string>()
  for (let y = 0; y < 64; y++) for (let x = 0; x < 64; x++) {
    const v = treeVariant(x, y)
    variants.add(v.id)
    assert.ok(v.scale > 0.8 && v.scale < 1.25)
    assert.ok(v.offset.every(Number.isFinite))
  }
  assert.ok(variants.size <= 34)
})

test("surface states preserve the base geometry instead of making variant meshes", () => {
  for (const id of ["granary", "smokehouse", "firewatch", "healer", "hospital", "watchhouse", "builder"] as const) {
    const plain = buildingAsset(id, 1, null, noDoors, 0)
    for (const appearance of ["worn", "winter"] as const) {
      const model = buildingAsset(id, 1, null, noDoors, 0, { worn: appearance === "worn", winter: appearance === "winter" })
      valid(model)
      assert.ok(assetById.has(`${id}-${appearance}`))
      assert.deepEqual(model.faces,plain.faces)
      assert.deepEqual(model.strokes,plain.strokes)
      assert.ok(model.effects)
    }
  }
  for (const tier of [1, 2, 3] as const) {
    const plain = homeAsset(tier, 0.03, 1, null, noDoors)
    for (const look of [{ band: "fine" as const }, { band: "poor" as const }, { worn: true }, { winter: true }]) {
      const model = homeAsset(tier, 0.03, 1, null, noDoors, look)
      valid(model)
      assert.deepEqual(model.faces,plain.faces)
      assert.deepEqual(model.strokes,plain.strokes)
      assert.ok(model.effects)
    }
  }
})

test("different surface states share geometry and remain independent per instance", () => {
  const pool=new ModelPool(),a=new ModelHandle(pool),b=new ModelHandle(pool)
  let built=0
  const create=()=>{built++;return homeAsset(2,0.28,1,null,noDoors)}
  a.use("home",create);b.use("home",create)
  a.effectBounds=[12,30,0.1,1];b.effectBounds=[...a.effectBounds]
  a.effects=surfaceState({snow:1});b.effects=surfaceState({wear:0.9,burning:1})
  pool.flush()
  // Non-pickable effects use the same pool; inspect each copy's face material directly.
  const state=(handle:ModelHandle,k:number)=>(handle.pieces.find(p=>p.part.role==="fill")!.opaque.data.surfaceState as ArrayLike<number>)[k]
  assert.equal(a.pieces[0]!.mesh.geometry,b.pieces[0]!.mesh.geometry)
  assert.equal(state(a,2),1);assert.equal(state(b,0),Math.fround(0.9));assert.equal(state(b,3),1)
  for(let i=0;i<100;i++){a.effects=surfaceState({wear:i/100});pool.flush()}
  assert.equal(built,1);assert.equal(pool.stats().templates,1)
  const particles=new StructureEffects(create(),26)
  particles.set(surfaceState({burning:1}));particles.update(0)
  assert.equal(particles.group.children.length,3)
  particles.update(100);assert.equal(particles.group.children.length,3)
  particles.set(surfaceState());assert.equal(particles.group.visible,false)
  particles.dispose();pool.dispose()
})

test("hazard effects become visible at the warning threshold and remain bounded", () => {
  assert.equal(hazardStrength(6999,7000,10000),0)
  assert.equal(hazardStrength(7000,7000,10000),0.35)
  assert.equal(hazardStrength(10000,7000,10000),1)
  assert.equal(hazardStrength(12000,7000,10000),1)
})