feat: a living village: workers walk out with their tools, work, and bring the load home; talkers, builders, a gate guard, sheep, chickens and birds

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-29 15:50:07 +01:00
parent 7f431dafe5
commit bcd98dba5a
11 changed files with 456 additions and 44 deletions

View File

@ -8,7 +8,7 @@ This is the Nuxt client for a browser strategy game in the style of Tribal Wars.
- **`ssr: false` for every target**, so one static build serves both the web and Steam. Code must not rely on Nuxt server routes or SSR-only APIs. - **`ssr: false` for every target**, so one static build serves both the web and Steam. Code must not rely on Nuxt server routes or SSR-only APIs.
- **Transport** is WS-first through the `ws` singleton from `@blax-software/networking`, the same as learn-atc. HTTP is only for login and register, which return the bearer token. Load the `blax-websockets` skill before you write `ws.send` or `ws.listen` code. - **Transport** is WS-first through the `ws` singleton from `@blax-software/networking`, the same as learn-atc. HTTP is only for login and register, which return the bearer token. Load the `blax-websockets` skill before you write `ws.send` or `ws.listen` code.
- **Dense and plain, like the old browser strategy games** (the reference is Die Stämme; notes and screenshots in the sibling repo `game-village-politics-research` (`../game-village-politics-research/die-staemme/`), kept out of this repo). A 16 px root (17 px from 1800 px wide; rem sizes only, `text-sm` for body text, no fixed `text-[13px]`), square frames with thin lines, tan header bands, tight table rows (`.grid-table`), small squared buttons (`.btn-primary` dark wood, `.btn-attack` red for attacks only), thin notice bars. Actions are buttons, not text links: `.btn` for screen links and commands, `.btn-fill` for the "(20)" that fills an amount field; names inside lists and tables stay links. Bigger text must not add line wraps: keep rows `whitespace-nowrap` where they were one line. No rounded cards, pills, big padding or decorative icons: an icon only where it carries meaning. Theme and component classes live in `app/assets/css/main.css`; hand-written inline SVG graphics in `app/components/icon/`, colours in `app/utils/palette.ts`. No paid, hosted or licensed assets: no icon packs, web fonts or images from outside the repo, and nothing copied from Die Stämme. - **Dense and plain, like the old browser strategy games** (the reference is Die Stämme; notes and screenshots in the sibling repo `game-village-politics-research` (`../game-village-politics-research/die-staemme/`), kept out of this repo). A 16 px root (17 px from 1800 px wide; rem sizes only, `text-sm` for body text, no fixed `text-[13px]`), square frames with thin lines, tan header bands, tight table rows (`.grid-table`), small squared buttons (`.btn-primary` dark wood, `.btn-attack` red for attacks only), thin notice bars. Actions are buttons, not text links: `.btn` for screen links and commands, `.btn-fill` for the "(20)" that fills an amount field; names inside lists and tables stay links. Bigger text must not add line wraps: keep rows `whitespace-nowrap` where they were one line. No rounded cards, pills, big padding or decorative icons: an icon only where it carries meaning. Theme and component classes live in `app/assets/css/main.css`; hand-written inline SVG graphics in `app/components/icon/`, colours in `app/utils/palette.ts`. No paid, hosted or licensed assets: no icon packs, web fonts or images from outside the repo, and nothing copied from Die Stämme.
- **The village is a ground-level land view** (`app/components/village/Diorama.vue`, geometry in `app/diorama/`): isometric low-poly, drawn as inline SVG, no WebGL. The land fills the frame edge to edge (no island, no sky), cut to the container's shape; narrow screens scroll sideways. There are no tiles or positions: the server only sends each building's `space` and the village's `space.used/max`, and the client lays everything out deterministically in id order. The village core sits in the middle (headquarters on the plaza, storage, hiding places and rally point around it, inside the wall ring when there is one, a dirt edge without). Resource sites stand outside in their zones: iron mines at the rocky hill (upper left), clay pits on clay ground (lower left), timber camps at the forest edge (lower right), farms with fields (right); dirt roads lead from the gates to each zone and forest fills the rest. Levels start at 1. Each type has a model per level tier (1–4, 5–14, 15+); the wall goes stakes → timber → stone with towers. Buildings are focusable buttons that enter the building (`buildingRoute`): the headquarters opens construction, the rally point its commands, a military building its recruiting, every other building its own screen (`/village/<id>/building/<bid>`); each of these screens starts with `VillageBuildingHeader`: a close-up (`VillageCloseup`, `app/diorama/closeup.ts`: the building large on its ground, its props and forest, its assigned workers walking to where they work and back carrying what they make), what it does now and one level up (`effects`/`next_effects` from the server), workers, priority, upgrade and demolish. The open building stays outlined in the village, and clicking it again returns to the overview. Buildings are clickable anywhere on their outline (`hit`, a convex hull round their polygons and ground ring), the thin wall also along a wide band on its ring, and their level badges and countdowns as well; a type that doesn't stand yet keeps an invisible empty plot that opens its build card. Buildings never move or light up on hover: only a click outlines the ground under them. Ambient life is welcome and stays out of the way: flat ground shadows, smoke from chimneys, forges and kilns, villagers walking the roads to the zones they work in; all motion stops under `prefers-reduced-motion`. The same models draw the building portraits on screen headers, the HQ list and the building cards (`VillageBuildingPortrait`). The world map groups forests, lakes and rocky hills by smooth noise of the coordinates, and village markers grow in five sizes with points. Map coordinates run around 0|0, negative included (−500 to 499 on a 1000-field map, lowest value from `map.view`'s `min`); continents are named from the top-left like Die Stämme, so 0|0 is the corner of K44, K45, K54 and K55. Use `app/utils/map.ts` for bounds and continents, never `0` or `500` literals. - **The village is a ground-level land view** (`app/components/village/Diorama.vue`, geometry in `app/diorama/`): isometric low-poly, drawn as inline SVG, no WebGL. The land fills the frame edge to edge (no island, no sky), cut to the container's shape; narrow screens scroll sideways. There are no tiles or positions: the server only sends each building's `space` and the village's `space.used/max`, and the client lays everything out deterministically in id order. The village core sits in the middle (headquarters on the plaza, storage, hiding places and rally point around it, inside the wall ring when there is one, a dirt edge without). Resource sites stand outside in their zones: iron mines at the rocky hill (upper left), clay pits on clay ground (lower left), timber camps at the forest edge (lower right), farms with fields (right); dirt roads lead from the gates to each zone and forest fills the rest. Levels start at 1. Each type has a model per level tier (1–4, 5–14, 15+); the wall goes stakes → timber → stone with towers. Buildings are focusable buttons that enter the building (`buildingRoute`): the headquarters opens construction, the rally point its commands, a military building its recruiting, every other building its own screen (`/village/<id>/building/<bid>`); each of these screens starts with `VillageBuildingHeader`: a close-up (`VillageCloseup`, `app/diorama/closeup.ts`: the building large on its ground, its props and forest, its assigned workers walking to where they work and back carrying what they make), what it does now and one level up (`effects`/`next_effects` from the server), workers, priority, upgrade and demolish. The open building stays outlined in the village, and clicking it again returns to the overview. Buildings are clickable anywhere on their outline (`hit`, a convex hull round their polygons and ground ring), the thin wall also along a wide band on its ring, and their level badges and countdowns as well; a type that doesn't stand yet keeps an invisible empty plot that opens its build card. Buildings never move or light up on hover: only a click outlines the ground under them. The village feels alive, and life stays out of the way: flat ground shadows, smoke from chimneys, forges and kilns; workers go out to their zone with their tool (`VillageWorker`, timing in `app/diorama/life.ts`: one SMIL clock per figure for the walk, stepping legs, the tool swing at work, the load on the way home and turning round), two villagers talk on the plaza, a builder hammers at every order in the works, a guard paces inside the gate, sheep graze past the farms and chickens peck round the plaza (`VillageAnimal`), birds cross now and then (`VillageBird`); the close-up does the same for its building. All motion stops under `prefers-reduced-motion`; people who stay put then stand still. The same models draw the building portraits on screen headers, the HQ list and the building cards (`VillageBuildingPortrait`). The world map groups forests, lakes and rocky hills by smooth noise of the coordinates, and village markers grow in five sizes with points. Map coordinates run around 0|0, negative included (−500 to 499 on a 1000-field map, lowest value from `map.view`'s `min`); continents are named from the top-left like Die Stämme, so 0|0 is the corner of K44, K45, K54 and K55. Use `app/utils/map.ts` for bounds and continents, never `0` or `500` literals.
- **Flat medieval colours only**, in the diorama and everywhere else: no gradients (CSS or SVG), no blur or backdrop-blur, no SVG filters or glows, no translucent overlays. Depth comes from the three flat shades per face in `app/diorama/iso.ts`, solid borders and hard shadows. In the diorama there are no outlines: a polygon strokes in its own fill only to close seams, detail comes from a few large shaded panels (a stone plinth, a door and windows from `house()`/`openings()`, two-tier firs, people as shaded shapes in `VillageWalker`), not from many small nodes. A face that must draw over its wall (doors, windows) sets `depth`; offsets and `shift()` carry it along. In the close-up, workers are sorted in among the objects by depth. Surfaces carry small repeating patterns generated in code at startup (`app/utils/patterns.ts` → `--pat-*` custom properties, set by `plugins/patterns.client.ts`, painted per `bg-parchment-*`/`bg-wood-*` class and on `.panel`, `.frame`, `.btn-primary` in `main.css`): parchment flecks, woven header bands with a stitched hem, wood grain; flat opaque shades a step off the surface, never images or opacity. Keep them minimal. One look for every part: each header band is `.panel-head` with a `.panel-title`, everything that floats over the village has the `.float` hard shadow and sits in a bordered frame, and every vertical scroll area is `.scroll-y`, whose bar always shows so content never shifts sideways; the one scrollbar style (wood handle with notches in a parchment track) lives in `main.css`. Every page keeps the page scrollbar, the fullscreen village included (an empty track there), so the usable width never changes when hopping between the village, the map and the reports. Keep components small and typed, with state in composables (`useVillage`, `useWorld`). - **Flat medieval colours only**, in the diorama and everywhere else: no gradients (CSS or SVG), no blur or backdrop-blur, no SVG filters or glows, no translucent overlays. Depth comes from the three flat shades per face in `app/diorama/iso.ts`, solid borders and hard shadows. In the diorama there are no outlines: a polygon strokes in its own fill only to close seams, detail comes from a few large shaded panels (a stone plinth, a door and windows from `house()`/`openings()`, two-tier firs, people as shaded shapes in `VillageWalker`), not from many small nodes. A face that must draw over its wall (doors, windows) sets `depth`; offsets and `shift()` carry it along. In the close-up, workers are sorted in among the objects by depth. Surfaces carry small repeating patterns generated in code at startup (`app/utils/patterns.ts` → `--pat-*` custom properties, set by `plugins/patterns.client.ts`, painted per `bg-parchment-*`/`bg-wood-*` class and on `.panel`, `.frame`, `.btn-primary` in `main.css`): parchment flecks, woven header bands with a stitched hem, wood grain; flat opaque shades a step off the surface, never images or opacity. Keep them minimal. One look for every part: each header band is `.panel-head` with a `.panel-title`, everything that floats over the village has the `.float` hard shadow and sits in a bordered frame, and every vertical scroll area is `.scroll-y`, whose bar always shows so content never shifts sideways; the one scrollbar style (wood handle with notches in a parchment track) lives in `main.css`. Every page keeps the page scrollbar, the fullscreen village included (an empty track there), so the usable width never changes when hopping between the village, the map and the reports. Keep components small and typed, with state in composables (`useVillage`, `useWorld`).
- **The village fills the screen.** On the village's own screens (`/village/<id>/…`) `GameVillageFrame` draws the diorama fixed across the whole browser window and docks everything over it, solid and opaque: the menu and the village bar along the top, the overview boxes in a right column (on phones a bottom sheet on the overview), and the open screen (headquarters, recruit, rally point, workforce) in a `UiWindow` on the left that folds and closes back to the overview; on the overview the left slot holds the build card of an empty plot picked in the village (`useVillageSelection`). Screen grids inside a window use container queries (`@4xl:`), not viewport breakpoints. The village scales to fit, no pan: the frame measures what the bars, the right column, the phone tab bar and the bottom sheet cover (`inset`), `buildScene` fits the whole village into the rest, and ground and forest are generated for the whole stage, so nothing of the village is ever cut off. Windows are docked now and meant to become draggable later, so `UiWindow` holds no position logic. This is where the game deliberately leaves Die Stämme's look behind. - **The village fills the screen.** On the village's own screens (`/village/<id>/…`) `GameVillageFrame` draws the diorama fixed across the whole browser window and docks everything over it, solid and opaque: the menu and the village bar along the top, the overview boxes in a right column (on phones a bottom sheet on the overview), and the open screen (headquarters, recruit, rally point, workforce) in a `UiWindow` on the left that folds and closes back to the overview; on the overview the left slot holds the build card of an empty plot picked in the village (`useVillageSelection`). Screen grids inside a window use container queries (`@4xl:`), not viewport breakpoints. The village scales to fit, no pan: the frame measures what the bars, the right column, the phone tab bar and the bottom sheet cover (`inset`), `buildScene` fits the whole village into the rest, and ground and forest are generated for the whole stage, so nothing of the village is ever cut off. Windows are docked now and meant to become draggable later, so `UiWindow` holds no position logic. This is where the game deliberately leaves Die Stämme's look behind.
- **One game shell for the rest.** The map and reports sit in one centred column (1100 px). All world pages use `layouts/game.vue` (on village screens `GameVillageFrame` draws the same parts over the village): the dark main menu (`GameMenuBar`: village, map, reports with its count inline, each with a hover dropdown of its sub-pages; server clock; account dropdown), then the village header (`GameVillageBar`, in two pieces with the village showing between them: on the left the quick bar with the village's screens over the village row, on the right the stock in thin cells and incoming troops; the space between lets clicks through), thin notices, and the content in a `.frame`. On phones the screens move to a bottom tab bar (`GameTabBar`). The header's village is the URL's on village screens and the last opened one elsewhere; `GameVillageFrame` holds its one `useVillage()` and shares it through `useVillageContext()`. Pages outside a world use `layouts/default.vue` (menu only). A page has one of two shapes: a title with box tabs (`UiSubTabs`: buildings like the rally point) or a title with a sub-menu on the left (`UiSideMenu`: lists like reports). One key per screen (`useShortcuts`): V overview, H headquarters, T recruit, P rally point, W workforce, M map, R reports. The overview stays clean: the village and a narrow column of boxes (incoming attacks, production, units, population, construction); tables live on the building screens. The map shows a popup over a hovered village and actions under a clicked one. The village row starts with the quest book (`QuestBook`, a native `<dialog>` without a veil): it opens by itself when `quests.claimable` goes up, and a goal's "show me" opens its screen, a building goal the headquarters with `?hint=<type>` marking that row. - **One game shell for the rest.** The map and reports sit in one centred column (1100 px). All world pages use `layouts/game.vue` (on village screens `GameVillageFrame` draws the same parts over the village): the dark main menu (`GameMenuBar`: village, map, reports with its count inline, each with a hover dropdown of its sub-pages; server clock; account dropdown), then the village header (`GameVillageBar`, in two pieces with the village showing between them: on the left the quick bar with the village's screens over the village row, on the right the stock in thin cells and incoming troops; the space between lets clicks through), thin notices, and the content in a `.frame`. On phones the screens move to a bottom tab bar (`GameTabBar`). The header's village is the URL's on village screens and the last opened one elsewhere; `GameVillageFrame` holds its one `useVillage()` and shares it through `useVillageContext()`. Pages outside a world use `layouts/default.vue` (menu only). A page has one of two shapes: a title with box tabs (`UiSubTabs`: buildings like the rally point) or a title with a sub-menu on the left (`UiSideMenu`: lists like reports). One key per screen (`useShortcuts`): V overview, H headquarters, T recruit, P rally point, W workforce, M map, R reports. The overview stays clean: the village and a narrow column of boxes (incoming attacks, production, units, population, construction); tables live on the building screens. The map shows a popup over a hovered village and actions under a clicked one. The village row starts with the quest book (`QuestBook`, a native `<dialog>` without a veil): it opens by itself when `quests.claimable` goes up, and a goal's "show me" opens its screen, a building goal the headquarters with `?hint=<type>` marking that row.

View File

@ -0,0 +1,42 @@
<script setup lang="ts">
const props = defineProps<{
kind: 'sheep' | 'chicken'
/** A small closed loop on screen it wanders along, stopping to graze or peck. */
d: string
dur: number
begin: number
size: number
}>()
// Four stretches of the loop, each followed by a stop.
const keyPoints = '0;0.25;0.25;0.5;0.5;0.75;0.75;1;1'
const keyTimes = '0;0.12;0.3;0.42;0.55;0.67;0.8;0.92;1'
const peck = computed(() => (props.kind === 'chicken' ? 0.7 : 2.2))
</script>
<!-- A sheep or a chicken: a few flat panels, head going down to graze or peck. -->
<template>
<g>
<g :transform="`scale(${size})`">
<template v-if="kind === 'sheep'">
<path d="M-1 -0.9h0.6V0h-0.6zM1.2 -0.9h0.6V0h-0.6z" fill="#3a2a1c" />
<path d="M-2.2 -3.4Q-2.4 -1 -0.6 -0.7H2Q3 -1.6 2.4 -3.4Q0.2 -4.6 -2.2 -3.4z" fill="#e8e1cf" />
<path d="M0.2 -0.7H2Q3 -1.6 2.4 -3.4Q1.4 -3.9 0.2 -3.9z" fill="#c9c1ad" />
<g>
<animateTransform attributeName="transform" type="rotate" :values="`0 2.2 -2.6;28 2.2 -2.6;28 2.2 -2.6;0 2.2 -2.6;0 2.2 -2.6`" keyTimes="0;0.15;0.6;0.75;1" :dur="`${peck}s`" :begin="`${begin}s`" repeatCount="indefinite" />
<path d="M2.1 -3.3L3.7 -3.1L3.6 -1.9L2.3 -2.1z" fill="#3a2a1c" />
</g>
</template>
<template v-else>
<path d="M-0.3 -0.8h0.3V0h-0.3zM0.4 -0.8h0.3V0h-0.3z" fill="#c49a2c" />
<path d="M-1.4 -2.6Q-1.2 -0.7 0.4 -0.8Q1.4 -1.2 1.2 -2.2Q0 -3.2 -1.4 -2.6z" fill="#f0e8d6" />
<g>
<animateTransform attributeName="transform" type="rotate" values="0 1 -2.2;40 1 -2.2;0 1 -2.2;0 1 -2.2" keyTimes="0;0.2;0.4;1" :dur="`${peck}s`" :begin="`${begin}s`" repeatCount="indefinite" />
<path d="M0.8 -3.4L1.7 -3.2L1.6 -2.2L0.9 -2.3z" fill="#f0e8d6" />
<path d="M1.7 -3L2.3 -2.7L1.7 -2.5z" fill="#c49a2c" />
<path d="M0.9 -3.6L1.4 -3.9L1.4 -3.3z" fill="#9b2a1c" />
</g>
</template>
</g>
<animateMotion :dur="`${dur}s`" :begin="`${begin}s`" repeatCount="indefinite" calcMode="linear" :keyPoints="keyPoints" :keyTimes="keyTimes" :path="d" />
</g>
</template>

View File

@ -0,0 +1,16 @@
<script setup lang="ts">
defineProps<{ d: string; dur: number; begin: number; size: number }>()
</script>
<!-- A bird crossing the land, two flat wings beating. -->
<template>
<g>
<g :transform="`scale(${size})`">
<g>
<animateTransform attributeName="transform" type="scale" values="1 1;1 -0.6;1 1" keyTimes="0;0.5;1" dur="0.45s" :begin="`${begin}s`" repeatCount="indefinite" />
<path d="M0 0L-3.2 -1.4L-1.4 0.2zM0 0L3.2 -1.4L1.4 0.2z" fill="#2f2620" />
</g>
</g>
<animateMotion :dur="`${dur}s`" :begin="`${begin}s`" repeatCount="indefinite" :path="d" />
</g>
</template>

View File

@ -15,6 +15,9 @@ const emit = defineEmits<{
priority: [buildingId: number, priority: number] priority: [buildingId: number, priority: number]
}>() }>()
const { t } = useI18n() const { t } = useI18n()
const v = useVillageContext()
/** A builder is at work on it right now. */
const upgrading = computed(() => !!v.village.value?.queue.some((o) => o.building_id === props.building.id && o.builder !== null))
/** Effects side by side: now and one level up (null at max level). */ /** Effects side by side: now and one level up (null at max level). */
const rows = computed(() => const rows = computed(() =>
@ -46,7 +49,7 @@ function value(e: BuildingEffect) {
<template> <template>
<section class="grid gap-3 @3xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]"> <section class="grid gap-3 @3xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<div class="h-52 border border-wood-700 @3xl:h-auto @3xl:min-h-60"> <div class="h-52 border border-wood-700 @3xl:h-auto @3xl:min-h-60">
<VillageCloseup :type="building.type" :level="building.level" :workers="building.workers.assigned" /> <VillageCloseup :type="building.type" :level="building.level" :workers="building.workers.assigned" :upgrading="upgrading" />
</div> </div>
<div class="space-y-2.5 text-sm"> <div class="space-y-2.5 text-sm">

View File

@ -1,8 +1,15 @@
<script setup lang="ts"> <script setup lang="ts">
import type { BuildingType } from '~/types/game' import type { BuildingType } from '~/types/game'
import { buildCloseup } from '~/diorama/closeup' import { buildCloseup } from '~/diorama/closeup'
import { workInPlace } from '~/diorama/life'
const props = defineProps<{ type: BuildingType; level: number; workers: number }>() const props = defineProps<{
type: BuildingType
level: number
workers: number
/** A builder hammers at it while an upgrade is running. */
upgrading?: boolean
}>()
// Drawn for the stage's own shape, so land and forest fill it edge to edge. // Drawn for the stage's own shape, so land and forest fill it edge to edge.
const stage = ref<HTMLElement | null>(null) const stage = ref<HTMLElement | null>(null)
@ -19,7 +26,8 @@ onMounted(() => {
}) })
onBeforeUnmount(() => observer?.disconnect()) onBeforeUnmount(() => observer?.disconnect())
const scene = computed(() => buildCloseup(props.type, props.level, props.workers, aspect.value)) const scene = computed(() => buildCloseup(props.type, props.level, props.workers, aspect.value, props.upgrading))
const hammering = workInPlace()
// Workers only walk for players who don't ask for reduced motion. // Workers only walk for players who don't ask for reduced motion.
const motion = ref(false) const motion = ref(false)
@ -35,17 +43,33 @@ const SHIRTS = ['#6b4f3a', '#7b1e16', '#3d5a26', '#57391f', '#5a5f63']
<polygon v-for="(p, i) in scene.terrain" :key="`t${i}`" :points="p.points" :fill="p.fill" :stroke="p.stroke" /> <polygon v-for="(p, i) in scene.terrain" :key="`t${i}`" :points="p.points" :fill="p.fill" :stroke="p.stroke" />
<polygon v-for="(p, i) in scene.decals" :key="`d${i}`" :points="p.points" :fill="p.fill" :stroke="p.stroke" /> <polygon v-for="(p, i) in scene.decals" :key="`d${i}`" :points="p.points" :fill="p.fill" :stroke="p.stroke" />
</g> </g>
<g v-if="motion">
<VillageAnimal v-for="(a, i) in scene.herds" :key="`herd-${i}`" :kind="a.kind" :d="a.d" :dur="a.dur" :begin="a.begin" :size="a.kind === 'sheep' ? 3 : 2.6" />
</g>
<template v-for="(l, i) in scene.layers" :key="l.key"> <template v-for="(l, i) in scene.layers" :key="l.key">
<g v-if="l.walk"> <template v-if="l.walk">
<template v-if="motion"> <VillageWorker
<VillageWalker transform="scale(2.6)" :shirt="SHIRTS[i % SHIRTS.length]!" :carry="l.walk.carry" /> v-if="motion"
<animateMotion :dur="`${l.walk.seconds}s`" :begin="`${l.walk.delay}s`" repeatCount="indefinite" keyPoints="0;1;0" keyTimes="0;0.5;1" calcMode="linear" :path="l.walk.d" /> :d="l.walk.d"
:walk="l.walk.walk"
:work="l.walk.work"
:tool="l.walk.tool"
:carry="l.walk.carry"
:shirt="SHIRTS[i % SHIRTS.length]!"
:size="2.6"
:begin="l.walk.begin"
/>
</template> </template>
<g v-else-if="l.life" :transform="`translate(${l.life.at[0]} ${l.life.at[1]}) scale(2.6)`">
<VillageWalker :shirt="SHIRTS[i % SHIRTS.length]!" :facing="l.life.facing" :tool="l.life.tool" :swing="motion ? hammering : null" />
</g> </g>
<g v-else v-memo="[l]" stroke-width="0.6" stroke-linejoin="round"> <g v-else v-memo="[l]" stroke-width="0.6" stroke-linejoin="round">
<polygon v-for="(p, j) in l.polys" :key="j" :points="p.points" :fill="p.fill" :stroke="p.stroke" /> <polygon v-for="(p, j) in l.polys" :key="j" :points="p.points" :fill="p.fill" :stroke="p.stroke" />
</g> </g>
</template> </template>
<g v-if="motion">
<VillageBird v-for="(b, i) in scene.birds" :key="`bird-${i}`" :d="b.d" :dur="b.dur" :begin="b.begin" :size="2.4" />
</g>
</svg> </svg>
</div> </div>
</template> </template>

View File

@ -1,5 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import type { BuildingType, VillageState } from '~/types/game' import type { BuildingType, VillageState } from '~/types/game'
import { workInPlace } from '~/diorama/life'
import { buildScene, type SceneBuilding, type SceneInset, type ScenePlot } from '~/diorama/scene' import { buildScene, type SceneBuilding, type SceneInset, type ScenePlot } from '~/diorama/scene'
const props = defineProps<{ const props = defineProps<{
@ -125,22 +126,24 @@ const timers = computed(() => {
<polygon v-for="(p, i) in scene.decals" :key="`d${i}`" :points="p.points" :fill="p.fill" :stroke="p.stroke" /> <polygon v-for="(p, i) in scene.decals" :key="`d${i}`" :points="p.points" :fill="p.fill" :stroke="p.stroke" />
</g> </g>
<!-- Villagers on their way to work and back, under the buildings they walk into. --> <!-- Villagers going out to work and bringing the load home, under the buildings they
walk into; sheep and chickens wandering. -->
<g v-if="motion" class="pointer-events-none"> <g v-if="motion" class="pointer-events-none">
<template v-for="(w, i) in scene.walks" :key="`walk-${i}-${w.d.length}`"> <template v-for="(w, i) in scene.walks" :key="`walk-${i}-${w.d.length}`">
<g v-for="n in w.count" :key="n"> <VillageWorker
<VillageWalker transform="scale(1.35)" :shirt="SHIRTS[(i * 3 + n) % SHIRTS.length]!" /> v-for="n in w.count"
<animateMotion :key="n"
:dur="`${w.seconds}s`" :d="w.d"
:begin="`${-((n - 1) * w.seconds) / w.count - i * 3}s`" :walk="w.walk"
repeatCount="indefinite" :work="w.work"
keyPoints="0;1;0" :tool="w.tool"
keyTimes="0;0.5;1" :carry="w.carry"
calcMode="linear" :shirt="SHIRTS[(i * 3 + n) % SHIRTS.length]!"
:path="w.d" :size="1.6"
:begin="-((n - 1) * (w.walk * 2 + w.work)) / w.count - i * 3"
/> />
</g>
</template> </template>
<VillageAnimal v-for="(a, i) in scene.herds" :key="`herd-${i}`" :kind="a.kind" :d="a.d" :dur="a.dur" :begin="a.begin" :size="a.kind === 'sheep' ? 1.7 : 1.4" />
</g> </g>
<!-- Empty plots: nothing to see, but each opens its building type's build card. --> <!-- Empty plots: nothing to see, but each opens its building type's build card. -->
@ -193,6 +196,27 @@ const timers = computed(() => {
<polygon v-for="(p, i) in obj.polys" :key="i" :points="p.points" :fill="p.fill" :stroke="p.stroke" /> <polygon v-for="(p, i) in obj.polys" :key="i" :points="p.points" :fill="p.fill" :stroke="p.stroke" />
<title>{{ label(obj.building) }}</title> <title>{{ label(obj.building) }}</title>
</g> </g>
<!-- Villagers who stay put: talking, or hammering at a building in the works. -->
<g v-else-if="obj.life" class="pointer-events-none" :transform="`translate(${obj.life.at[0]} ${obj.life.at[1]})`">
<g transform="scale(1.6)">
<animateTransform
v-if="motion && !obj.life.tool"
attributeName="transform"
type="translate"
values="0 0;0 -0.5;0 0;0 0"
keyTimes="0;0.15;0.3;1"
:dur="`${2.2 + (obj.life.shirt % 3) * 0.4}s`"
additive="sum"
repeatCount="indefinite"
/>
<VillageWalker
:shirt="SHIRTS[obj.life.shirt % SHIRTS.length]!"
:facing="obj.life.facing"
:tool="obj.life.tool"
:swing="motion && obj.life.tool ? workInPlace() : null"
/>
</g>
</g>
<g v-else v-memo="[obj]" stroke-width="0.6" stroke-linejoin="round"> <g v-else v-memo="[obj]" stroke-width="0.6" stroke-linejoin="round">
<polygon v-for="(p, i) in obj.polys" :key="i" :points="p.points" :fill="p.fill" :stroke="p.stroke" /> <polygon v-for="(p, i) in obj.polys" :key="i" :points="p.points" :fill="p.fill" :stroke="p.stroke" />
<title v-if="obj.planned">{{ $t('village.diorama.planned') }}</title> <title v-if="obj.planned">{{ $t('village.diorama.planned') }}</title>
@ -206,6 +230,11 @@ const timers = computed(() => {
</g> </g>
</g> </g>
<!-- Birds crossing now and then. -->
<g v-if="motion" class="pointer-events-none">
<VillageBird v-for="(b, i) in scene.birds" :key="`bird-${i}`" :d="b.d" :dur="b.dur" :begin="b.begin" :size="1.6" />
</g>
<!-- Level badges and countdowns. Flat colours only. --> <!-- Level badges and countdowns. Flat colours only. -->
<g class="pointer-events-none" font-family="ui-sans-serif, system-ui, sans-serif" text-anchor="middle"> <g class="pointer-events-none" font-family="ui-sans-serif, system-ui, sans-serif" text-anchor="middle">
<g <g

View File

@ -1,28 +1,92 @@
<script setup lang="ts"> <script setup lang="ts">
import { scale } from '~/diorama/iso' import { scale } from '~/diorama/iso'
import type { Cycle, Tool } from '~/diorama/life'
const props = defineProps<{ const props = defineProps<{
shirt: string shirt: string
/** What the villager carries on the shoulder, as a colour; none when empty-handed. */ /** What the villager brings home on the shoulder, as a colour. */
carry?: string | null carry?: string | null
tool?: Tool | null
/** A work cycle to run (steps, swing, load, turning); without one the figure stands. */
cycle?: Cycle | null
/** Swinging the tool on the spot for good, e.g. a builder. */
swing?: { dur: number; values: string; keyTimes: string } | null
/** Seconds offset shared with the figure's motion. */
begin?: number
/** Which way it faces while standing: 1 right, -1 left. */
facing?: 1 | -1
}>() }>()
const shirtShade = computed(() => scale(props.shirt, 0.72)) const shirtShade = computed(() => scale(props.shirt, 0.72))
const carryTop = computed(() => (props.carry ? scale(props.carry, 1.15) : '')) const carryTop = computed(() => (props.carry ? scale(props.carry, 1.15) : ''))
const carryShade = computed(() => (props.carry ? scale(props.carry, 0.7) : '')) const carryShade = computed(() => (props.carry ? scale(props.carry, 0.7) : ''))
const begin = computed(() => `${props.begin ?? 0}s`)
const toolSwing = computed(() => props.cycle?.swing ?? props.swing ?? null)
const toolDur = computed(() => `${props.cycle?.dur ?? props.swing?.dur ?? 1}s`)
/** Rotation values about the shoulder, where the hand holds the tool. */
const swingValues = computed(() => toolSwing.value?.values.split(';').map((a) => `${a} 1.1 -6.4`).join(';') ?? '')
const METAL = '#8b9094'
const HANDLE = '#6a4526'
const HEADS: Record<Tool, string> = {
axe: 'M3.3 -11.4L5.5 -10.5L5 -9.3L3.6 -10.1z',
pick: 'M2.1 -11.7L5.7 -10.1L5.4 -9.7L3.8 -10.5L2.3 -11.1z',
shovel: 'M3.3 -10.5L4.8 -12L5.7 -11.1L4.2 -9.7z',
sickle: 'M3.6 -10.9Q6.6 -12.3 5.7 -9.1Q5.3 -10.8 3.9 -10.4z',
hammer: 'M2.9 -11.2L4.6 -10.3L4.1 -9.3L2.4 -10.1z',
spear: 'M1.2 -15.6L1.8 -13.6L0.6 -13.6z',
}
</script> </script>
<!-- A villager in a few flat, shaded panels: legs, a two-tone shirt, head and hair, a load. --> <!--
A villager in a few flat, shaded panels: legs that step while walking, a two-tone
shirt, head and hair, a tool that swings while working, and the load on the way home.
-->
<template> <template>
<g> <g :transform="`scale(${facing ?? 1} 1)`">
<path d="M-1.5 -2.4h1.2V0h-1.2zM0.3 -2.4h1.2V0h-1.2z" fill="#3a2a1c" /> <animateTransform
v-if="cycle"
attributeName="transform"
type="scale"
calcMode="discrete"
:values="cycle.face.values"
:keyTimes="cycle.face.keyTimes"
:dur="`${cycle.dur}s`"
:begin="begin"
repeatCount="indefinite"
/>
<rect x="-1.5" y="-2.4" width="1.2" height="2.4" fill="#3a2a1c">
<animateTransform v-if="cycle" attributeName="transform" type="translate" :values="cycle.step.values" :keyTimes="cycle.step.keyTimes" :dur="`${cycle.dur}s`" :begin="begin" repeatCount="indefinite" />
</rect>
<rect x="0.3" y="-2.4" width="1.2" height="2.4" fill="#2f2219">
<animateTransform v-if="cycle" attributeName="transform" type="translate" :values="cycle.step.mirrored" :keyTimes="cycle.step.keyTimes" :dur="`${cycle.dur}s`" :begin="begin" repeatCount="indefinite" />
</rect>
<path d="M-1.9 -6.9L0 -7.3V-2.2H-1.7z" :fill="shirt" /> <path d="M-1.9 -6.9L0 -7.3V-2.2H-1.7z" :fill="shirt" />
<path d="M0 -7.3L1.9 -6.9L1.7 -2.2H0z" :fill="shirtShade" /> <path d="M0 -7.3L1.9 -6.9L1.7 -2.2H0z" :fill="shirtShade" />
<circle cy="-8.9" r="1.65" fill="#d8a982" /> <circle cy="-8.9" r="1.65" fill="#d8a982" />
<path d="M-1.7 -9.1Q0 -11.5 1.7 -9.1Q0 -9.9 -1.7 -9.1z" fill="#4a3220" /> <path d="M-1.7 -9.1Q0 -11.5 1.7 -9.1Q0 -9.9 -1.7 -9.1z" fill="#4a3220" />
<template v-if="carry">
<path d="M0.3 -9.3L3.1 -9.8L4.7 -9L1.9 -8.5z" :fill="carryTop" /> <g v-if="tool">
<path d="M0.3 -9.3L1.9 -8.5V-6.9L0.3 -7.7z" :fill="carry" /> <animateTransform
<path d="M1.9 -8.5L4.7 -9V-7.4L1.9 -6.9z" :fill="carryShade" /> v-if="toolSwing && tool !== 'spear'"
</template> attributeName="transform"
type="rotate"
:values="swingValues"
:keyTimes="toolSwing.keyTimes"
:dur="toolDur"
:begin="begin"
repeatCount="indefinite"
/>
<path v-if="tool === 'spear'" d="M0.95 -0.6H1.45V-13.8H0.95z" :fill="HANDLE" />
<path v-else d="M0.85 -6.6L1.35 -6.2L4.15 -10.7L3.65 -11.1z" :fill="HANDLE" />
<path :d="HEADS[tool]" :fill="METAL" />
</g>
<g v-if="carry" :visibility="cycle ? 'hidden' : 'visible'">
<animate v-if="cycle" attributeName="visibility" calcMode="discrete" :values="cycle.load.values" :keyTimes="cycle.load.keyTimes" :dur="`${cycle.dur}s`" :begin="begin" repeatCount="indefinite" />
<path d="M-0.6 -9.3L2.2 -9.8L3.8 -9L1 -8.5z" :fill="carryTop" />
<path d="M-0.6 -9.3L1 -8.5V-6.9L-0.6 -7.7z" :fill="carry" />
<path d="M1 -8.5L3.8 -9V-7.4L1 -6.9z" :fill="carryShade" />
</g>
</g> </g>
</template> </template>

View File

@ -0,0 +1,42 @@
<script setup lang="ts">
import { type Tool, workCycle } from '~/diorama/life'
const props = defineProps<{
/** Screen path from home to where the work is. */
d: string
/** Seconds one way, and seconds of work at the far end (0: just turns round). */
walk: number
work: number
shirt: string
carry?: string | null
tool?: Tool | null
size: number
/** Seconds into its cycle, so workers on one road don't move in lockstep. */
begin: number
}>()
/** Faces right when the way out leads right on screen. */
const facing = computed<1 | -1>(() => {
const nums = props.d.match(/-?\d+(\.\d+)?/g)?.map(Number) ?? []
return nums.length >= 4 && nums[nums.length - 2]! < nums[0]! ? -1 : 1
})
const cycle = computed(() => workCycle(props.walk, props.work, 1.2, facing.value))
</script>
<!-- A villager going out to work, working, and bringing the load home, round and round. -->
<template>
<g>
<g :transform="`scale(${size})`">
<VillageWalker :shirt="shirt" :carry="carry" :tool="tool" :cycle="cycle" :begin="begin" />
</g>
<animateMotion
:dur="`${cycle.dur}s`"
:begin="`${begin}s`"
repeatCount="indefinite"
calcMode="linear"
:keyPoints="cycle.motion.keyPoints"
:keyTimes="cycle.motion.keyTimes"
:path="d"
/>
</g>
</template>

View File

@ -5,6 +5,7 @@
import type { BuildingType } from '~/types/game' import type { BuildingType } from '~/types/game'
import { type Face, hash, plane, type Poly, project, rect, scale, toPolys, type V2, type V3 } from './iso' import { type Face, hash, plane, type Poly, project, rect, scale, toPolys, type V2, type V3 } from './iso'
import type { Tool } from './life'
import { broadleaf, buildingModel, bush, C, conifer, rock } from './models' import { broadleaf, buildingModel, bush, C, conifer, rock } from './models'
import { disc, ground, shadow, U, wallSegments } from './scene' import { disc, ground, shadow, U, wallSegments } from './scene'
@ -18,13 +19,23 @@ export interface Closeup {
* Back to front: objects, and one entry per worker shown (a screen path walked there * Back to front: objects, and one entry per worker shown (a screen path walked there
* and back, with what they carry), sorted in among the objects by depth. * and back, with what they carry), sorted in among the objects by depth.
*/ */
layers: ({ key: string; polys: Poly[]; walk?: undefined } | { key: string; walk: Walk; polys?: undefined })[] layers: (
| { key: string; polys: Poly[]; walk?: undefined; life?: undefined }
| { key: string; walk: Walk; polys?: undefined; life?: undefined }
| { key: string; life: { at: V2; facing: 1 | -1; tool: Tool | null }; polys?: undefined; walk?: undefined }
)[]
/** Sheep at a farm, chickens round the core buildings. */
herds: { kind: 'sheep' | 'chicken'; d: string; dur: number; begin: number }[]
birds: { d: string; dur: number; begin: number }[]
} }
export interface Walk { export interface Walk {
d: string d: string
seconds: number /** Seconds one way and seconds of work at the spot. */
delay: number walk: number
work: number
begin: number
tool: Tool | null
carry: string | null carry: string | null
} }
@ -40,6 +51,8 @@ const GROUND: Record<Kind, string> = {
} }
/** What a worker carries home: logs, clay, ore, sheaves; core buildings move crates. */ /** What a worker carries home: logs, clay, ore, sheaves; core buildings move crates. */
const CARRY: Record<Kind, string | null> = { timber: C.wood, clay: C.clay, iron: C.ore, farm: C.wheat, wall: null, core: C.plank } const CARRY: Record<Kind, string | null> = { timber: C.wood, clay: C.clay, iron: C.ore, farm: C.wheat, wall: null, core: C.plank }
/** What workers work with at the spot; core buildings' workers carry crates. */
const TOOL: Record<Kind, Tool | null> = { timber: 'axe', clay: 'shovel', iron: 'pick', farm: 'sickle', wall: 'spear', core: null }
/** Workers drawn at most; more would crowd the scene. */ /** Workers drawn at most; more would crowd the scene. */
const MAX_WALKERS = 8 const MAX_WALKERS = 8
@ -49,7 +62,7 @@ const at = (a: number, r: number): V2 => [Math.cos(a) * r, Math.sin(a) * r]
const screen = ([x, y]: V2, z = 1.2) => project([x, y, z]) const screen = ([x, y]: V2, z = 1.2) => project([x, y, z])
const line = (pts: V2[]) => pts.map((p, i) => `${i ? 'L' : 'M'}${screen(p).map((v) => v.toFixed(1)).join(' ')}`).join(' ') const line = (pts: V2[]) => pts.map((p, i) => `${i ? 'L' : 'M'}${screen(p).map((v) => v.toFixed(1)).join(' ')}`).join(' ')
export function buildCloseup(type: BuildingType, level: number, workers: number, aspect = 2): Closeup { export function buildCloseup(type: BuildingType, level: number, workers: number, aspect = 2, upgrading = false): Closeup {
const kind = KIND[type] ?? 'core' const kind = KIND[type] ?? 'core'
const objects: { key: string; depth: number; polys: Poly[] }[] = [] const objects: { key: string; depth: number; polys: Poly[] }[] = []
const decals: Face[] = [plane(disc(0, 0, S * 2.3, 16, 7, 0.5), GROUND[kind])] const decals: Face[] = [plane(disc(0, 0, S * 2.3, 16, 7, 0.5), GROUND[kind])]
@ -149,6 +162,7 @@ export function buildCloseup(type: BuildingType, level: number, workers: number,
// hides those who work behind it and those in front walk over it. // hides those who work behind it and those in front walk over it.
const shown = Math.min(MAX_WALKERS, Math.max(0, workers)) const shown = Math.min(MAX_WALKERS, Math.max(0, workers))
const walkers: { key: string; depth: number; walk: Walk }[] = [] const walkers: { key: string; depth: number; walk: Walk }[] = []
const work = kind === 'core' ? 1.5 : kind === 'wall' ? 2.5 : 4.5
for (let i = 0; i < shown && spots.length; i++) { for (let i = 0; i < shown && spots.length; i++) {
const spot = spots[i % spots.length]! const spot = spots[i % spots.length]!
const path: V2[] = const path: V2[] =
@ -156,21 +170,51 @@ export function buildCloseup(type: BuildingType, level: number, workers: number,
? [0, 15, 30, 45, 60, 75, 90].map((d) => at(deg(i * 90 + d), S * 2.0)) ? [0, 15, 30, 45, 60, 75, 90].map((d) => at(deg(i * 90 + d), S * 2.0))
: [at(Math.atan2(spot[1], spot[0]), S * 1.5), spot] : [at(Math.atan2(spot[1], spot[0]), S * 1.5), spot]
const length = path.slice(1).reduce((n, p, k) => n + Math.hypot(p[0] - path[k]![0], p[1] - path[k]![1]), 0) const length = path.slice(1).reduce((n, p, k) => n + Math.hypot(p[0] - path[k]![0], p[1] - path[k]![1]), 0)
const seconds = Math.max(7, (length / U) * 2.4) const walk = Math.max(3.5, (length / U) * 1.2)
walkers.push({ walkers.push({
key: `walker${i}`, key: `walker${i}`,
depth: Math.min(...path.map(([x, y]) => x + y)), depth: Math.min(...path.map(([x, y]) => x + y)),
walk: { d: line(path), seconds, delay: -(i * seconds) / Math.max(1, shown), carry: CARRY[kind] }, walk: { d: line(path), walk, work, begin: -(i * (walk * 2 + work)) / Math.max(1, shown), tool: TOOL[kind], carry: CARRY[kind] },
}) })
} }
// A builder hammers at the building while it is being upgraded.
const life: { key: string; depth: number; life: { at: V2; facing: 1 | -1; tool: Tool | null } }[] = []
if (upgrading && kind !== 'wall') {
const [x, y] = at(deg(15), S * 1.35)
life.push({ key: 'builder', depth: x + y, life: { at: screen([x, y]), facing: -1, tool: 'hammer' } })
}
const layers = [...objects, ...walkers].sort((a, b) => a.depth - b.depth) // Animals and birds.
const loop = (cx: number, cy: number, r: number, seed: number) =>
line([0, 1, 2, 3, 0].map((i): V2 => {
const a = (i / 4) * Math.PI * 2 + hash(seed, 1) * 6
return [cx + Math.cos(a) * r * (0.7 + 0.5 * hash(seed, i + 2)), cy + Math.sin(a) * r]
}))
const herds: Closeup['herds'] = []
if (kind === 'farm') {
for (let k = 0; k < 3; k++) {
const [x, y] = at(deg(200 + k * 30), S * 2.1)
herds.push({ kind: 'sheep', d: loop(x, y, U * 0.8, 400 + k), dur: 22 + k * 5, begin: -k * 6 })
}
} else if (kind === 'core') {
for (let k = 0; k < 2; k++) {
const [x, y] = at(deg(100 + k * 40), S * 1.8)
herds.push({ kind: 'chicken', d: loop(x, y, U * 0.5, 420 + k), dur: 12 + k * 4, begin: -k * 5 })
}
}
const layers = [...objects, ...walkers, ...life].sort((a, b) => a.depth - b.depth)
return { return {
viewBox: `${view.x.toFixed(1)} ${view.y.toFixed(1)} ${w.toFixed(1)} ${h.toFixed(1)}`, viewBox: `${view.x.toFixed(1)} ${view.y.toFixed(1)} ${w.toFixed(1)} ${h.toFixed(1)}`,
width: w, width: w,
height: h, height: h,
terrain: ground(view), terrain: ground(view),
decals: [...decals, ...shadows].flatMap((face) => toPolys([face])), decals: [...decals, ...shadows].flatMap((face) => toPolys([face])),
layers: layers.map((l) => ('walk' in l ? { key: l.key, walk: l.walk } : { key: l.key, polys: l.polys })), layers: layers.map((l) => ('walk' in l ? { key: l.key, walk: l.walk } : 'life' in l ? { key: l.key, life: l.life } : { key: l.key, polys: l.polys })),
herds,
birds: [0, 1].map((k) => {
const y0 = view.y + h * (0.1 + 0.12 * k)
return { d: `M${(view.x - U).toFixed(1)} ${y0.toFixed(1)} L${(view.x + w + U).toFixed(1)} ${(y0 - h * 0.1).toFixed(1)}`, dur: 16 + k * 7, begin: -k * 9 }
}),
} }
} }

75
app/diorama/life.ts Normal file
View File

@ -0,0 +1,75 @@
// Timing for the people and animals in the dioramas, as SMIL value lists. Everything a
// figure does runs on one clock of `dur` seconds, so its walk, steps, tool, load and the
// way it faces stay in step without any script.
export type Tool = 'axe' | 'pick' | 'shovel' | 'sickle' | 'hammer' | 'spear'
export interface Cycle {
dur: number
/** animateMotion: out along the path, work, back, a short stop at home. */
motion: { keyPoints: string; keyTimes: string }
/** Legs: a translate on one leg (the other mirrors it), only while walking. */
step: { values: string; mirrored: string; keyTimes: string }
/** The tool: rests on the shoulder, swings only while working. */
swing: { values: string; keyTimes: string }
/** The load shows on the way home. */
load: { values: string; keyTimes: string }
/** Turns round to walk home. */
face: { values: string; keyTimes: string }
}
const STEP = 0.32
const SWING = 0.55
/** Alternating values every `period` seconds across [from, to] of a cycle of `dur` seconds. */
function alternate(from: number, to: number, dur: number, period: number, a: string, b: string): [number, string][] {
const out: [number, string][] = []
const n = Math.max(1, Math.floor((to - from) / period))
for (let i = 0; i < n; i++) out.push([(from + i * period) / dur, i % 2 ? b : a])
return out
}
/** Builds key lists, making sure they start at 0, end at 1 and only grow. */
function keys(points: [number, string][]): { values: string; keyTimes: string } {
const list = [...points].sort((p, q) => p[0] - q[0])
if (list[0]![0] > 0) list.unshift([0, list[0]![1]])
if (list[list.length - 1]![0] < 1) list.push([1, list[list.length - 1]![1]])
const clean: [number, string][] = []
for (const [t, v] of list) {
const time = Math.min(1, Math.max(0, t))
if (clean.length && time <= clean[clean.length - 1]![0]) clean[clean.length - 1] = [clean[clean.length - 1]![0], v]
else clean.push([time, v])
}
clean[clean.length - 1]![0] = 1
return { values: clean.map((p) => p[1]).join(';'), keyTimes: clean.map((p) => p[0].toFixed(4)).join(';') }
}
/**
* A work cycle: walk out for `walk` seconds, work for `work`, walk home for `walk`, stand
* for `rest`. `facing` is 1 when walking out goes to the right on screen, else -1.
*/
export function workCycle(walk: number, work: number, rest = 1.2, facing: 1 | -1 = 1): Cycle {
const dur = walk * 2 + work + rest
const a = walk / dur
const b = (walk + work) / dur
const c = (walk * 2 + work) / dur
const stepping = [...alternate(0, walk, dur, STEP, '0.7 0', '-0.7 0'), [a, '0 0'] as [number, string], ...alternate(walk + work, walk * 2 + work, dur, STEP, '0.7 0', '-0.7 0'), [c, '0 0'] as [number, string]]
const step = keys(stepping)
const mirrored = step.values
.split(';')
.map((v) => (v.startsWith('-') ? v.slice(1) : v === '0 0' ? v : `-${v}`))
.join(';')
return {
dur,
motion: { keyPoints: '0;1;1;0;0', keyTimes: `0;${a.toFixed(4)};${b.toFixed(4)};${c.toFixed(4)};1` },
step: { ...step, mirrored },
swing: keys([[0, '0'], [a, '0'], ...alternate(walk, walk + work, dur, SWING, '-70', '35'), [b, '0'], [1, '0']]),
load: { values: 'hidden;visible;hidden', keyTimes: `0;${b.toFixed(4)};${c.toFixed(4)}` },
face: { values: `${facing} 1;${-facing} 1;${facing} 1`, keyTimes: `0;${b.toFixed(4)};${c.toFixed(4)}` },
}
}
/** Working on the spot for good: a builder hammering, a farmer cutting. */
export function workInPlace(): { dur: number; values: string; keyTimes: string } {
return { dur: SWING * 2, values: '-70;35;-70', keyTimes: '0;0.5;1' }
}

View File

@ -11,6 +11,7 @@
import type { BuildingType, VillageState } from '~/types/game' import type { BuildingType, VillageState } from '~/types/game'
import { type Face, hash, ngon, plane, type Poly, prism, project, pyramid, scale, toPolys, type V2, type V3 } from './iso' import { type Face, hash, ngon, plane, type Poly, prism, project, pyramid, scale, toPolys, type V2, type V3 } from './iso'
import type { Tool } from './life'
import { broadleaf, buildingModel, bush, C, conifer, crane, rock, scaffold, well } from './models' import { broadleaf, buildingModel, bush, C, conifer, crane, rock, scaffold, well } from './models'
/** World units per unit of building space, roughly. */ /** World units per unit of building space, roughly. */
@ -62,6 +63,24 @@ export interface SceneObject {
polys: Poly[] polys: Poly[]
building?: SceneBuilding building?: SceneBuilding
planned?: boolean planned?: boolean
/** A villager who stays put, sorted in among the buildings: chatting, or building with a hammer. */
life?: SceneLife
}
export interface SceneLife {
/** Screen point at their feet. */
at: V2
facing: 1 | -1
tool: Tool | null
shirt: number
}
/** What each zone's workers work with and bring home. */
const WORK: Record<Zone, { tool: Tool; carry: string }> = {
timber: { tool: 'axe', carry: C.wood },
clay: { tool: 'shovel', carry: C.clay },
iron: { tool: 'pick', carry: C.ore },
farm: { tool: 'sickle', carry: C.wheat },
} }
/** /**
@ -100,7 +119,11 @@ export interface Scene {
/** Chimneys, forges and kilns that smoke, as screen points. */ /** Chimneys, forges and kilns that smoke, as screen points. */
smoke: V2[] smoke: V2[]
/** Roads villagers walk to work and back: a screen path, how many walk it, seconds per round trip. */ /** Roads villagers walk to work and back: a screen path, how many walk it, seconds per round trip. */
walks: { d: string; count: number; seconds: number }[] walks: { d: string; count: number; walk: number; work: number; tool: Tool | null; carry: string | null }[]
/** Sheep by the farms and chickens on the plaza, wandering small loops. */
herds: { kind: 'sheep' | 'chicken'; d: string; dur: number; begin: number }[]
/** Birds crossing the land now and then. */
birds: { d: string; dur: number; begin: number }[]
/** A wide click band along the wall ring, so the thin wall is easy to hit. */ /** A wide click band along the wall ring, so the thin wall is easy to hit. */
wallBand: { id: number; ring: { cx: number; cy: number; rx: number; ry: number }; width: number } | null wallBand: { id: number; ring: { cx: number; cy: number; rx: number; ry: number }; width: number } | null
} }
@ -565,6 +588,27 @@ export function buildScene(village: VillageState, frame: number | { width: numbe
// Landscape: a rocky hill behind the iron zone, then forest everywhere else. // Landscape: a rocky hill behind the iron zone, then forest everywhere else.
const taken: { x: number; y: number; r: number }[] = allSlots.map((s) => ({ x: s.x, y: s.y, r: s.r + U * 0.45 })) const taken: { x: number; y: number; r: number }[] = allSlots.map((s) => ({ x: s.x, y: s.y, r: s.r + U * 0.45 }))
// Sheep graze past the farms, chickens peck round the plaza: small loops kept free of trees.
const herds: Scene['herds'] = []
const loop = (cx: number, cy: number, r: number, seed: number) => {
const pts = [0, 1, 2, 3, 0].map((i): V2 => {
const a = (i / 4) * Math.PI * 2 + hash(seed, 1) * 6
return project([cx + Math.cos(a) * r * (0.7 + 0.5 * hash(seed, i + 2)), cy + Math.sin(a) * r, 1.2])
})
return pts.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ')
}
if (activeZones.includes('farm')) {
const [fx, fy] = dir(ZONES.farm.angle + deg(14))
const r = zoneEnd('farm') + U * 1.6
taken.push({ x: fx * r, y: fy * r, r: U * 1.8 })
for (let k = 0; k < 3; k++) herds.push({ kind: 'sheep', d: loop(fx * r + (k - 1) * U * 0.9, fy * r + (k % 2) * U * 0.7, U * 0.9, 300 + k), dur: 26 + k * 5, begin: -k * 7 })
}
{
const [cx, cy] = dir(FRONT + deg(75))
const r = hqRadius * 1.5
for (let k = 0; k < 2; k++) herds.push({ kind: 'chicken', d: loop(cx * r + k * U * 0.5, cy * r - k * U * 0.4, U * 0.5, 320 + k), dur: 14 + k * 4, begin: -k * 5 })
}
// A pond in the meadow between the clay pits and the hill, with reeds on its bank. // A pond in the meadow between the clay pits and the hill, with reeds on its bank.
const pondR = U * 1.5 const pondR = U * 1.5
const pondOut = Math.max(Rv + U * 2.6, zoneEnd('clay') * 0.85) const pondOut = Math.max(Rv + U * 2.6, zoneEnd('clay') * 0.85)
@ -656,16 +700,42 @@ export function buildScene(village: VillageState, frame: number | { width: numbe
if (at) timers.push({ orderId: o.id, finishesAt: o.finishes_at, at, buildingId: onBuilding ? o.building_id : null }) if (at) timers.push({ orderId: o.id, finishesAt: o.finishes_at, at, buildingId: onBuilding ? o.building_id : null })
} }
// Villagers walk from the plaza out to the zones they work in and back, more where more work. // Villagers go out to the zones they work in, work there with their tool and bring the
// load home, more where more work. One walks out of the gate and back.
const walks: Scene['walks'] = [] const walks: Scene['walks'] = []
for (const zone of activeZones) { for (const zone of activeZones) {
const workers = village.buildings.filter((b) => ZONE_OF[b.type] === zone).reduce((n, b) => n + b.workers.assigned, 0) const workers = village.buildings.filter((b) => ZONE_OF[b.type] === zone).reduce((n, b) => n + b.workers.assigned, 0)
if (!workers) continue if (!workers) continue
const end = zoneEnd(zone) const end = zoneEnd(zone)
const d = walkPath(ZONES[zone].angle, hqRadius * 0.9, end + U * 0.5, ZONE_NAMES.indexOf(zone) + 2, hqRadius * 1.4, end - U * 1.2) const d = walkPath(ZONES[zone].angle, hqRadius * 0.9, end + U * 0.5, ZONE_NAMES.indexOf(zone) + 2, hqRadius * 1.4, end - U * 1.2)
walks.push({ d, count: Math.min(3, Math.max(1, Math.round(workers / 6))), seconds: Math.max(16, ((end - hqRadius) / U) * 4.5) }) walks.push({ d, count: Math.min(3, Math.max(1, Math.round(workers / 6))), walk: Math.max(8, ((end - hqRadius) / U) * 2.2), work: 4.5, ...WORK[zone] })
} }
walks.push({ d: walkPath(FRONT, hqRadius * 0.9, Rz * 3, 1, hqRadius * 1.4, Rv + U * 5), count: 1, seconds: 40 }) walks.push({ d: walkPath(FRONT, hqRadius * 0.9, Rz * 3, 1, hqRadius * 1.4, Rv + U * 5), count: 1, walk: 20, work: 0, tool: null, carry: null })
// A guard paces inside the gate.
if (wall) {
const arc = [10, 22, 34, 46].map((a) => project([Math.cos(FRONT + deg(a)) * (Rv - U * 0.9), Math.sin(FRONT + deg(a)) * (Rv - U * 0.9), 1.2]))
walks.push({ d: arc.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' '), count: 1, walk: 6, work: 2.5, tool: 'spear', carry: null })
}
// People who stay put: two talking on the plaza in front of the headquarters, a builder
// at every order in the works.
const people = (key: string, x: number, y: number, facing: 1 | -1, tool: Tool | null, shirt: number) =>
objects.push({ key, depth: x + y, polys: [], life: { at: project([x, y, 1.2]), facing, tool, shirt } })
const [chatX, chatY] = dir(FRONT + deg(32)).map((v) => v * hqRadius * 1.3)
people('chat-a', chatX! - U * 0.45, chatY! + U * 0.45, 1, null, 1)
people('chat-b', chatX! + U * 0.45, chatY! - U * 0.45, -1, null, 3)
for (const o of village.queue.filter((q) => q.builder !== null)) {
const b = o.building_id !== null ? village.buildings.find((x) => x.id === o.building_id) : null
if (b?.type === 'wall') continue
const slot = b ? (b.type === 'headquarters' ? core[0]! : slotOf(`b${b.id}`)) : slotOf(`o${o.id}`)
people(`builder-${o.id}`, slot.x + slot.r * 0.95, slot.y + slot.r * 0.35, -1, 'hammer', o.id)
}
// Birds cross the upper part of the view now and then.
const birds: Scene['birds'] = [0, 1].map((k) => {
const y0 = view.y + h * (0.12 + 0.1 * k)
return { d: `M${(view.x - U * 2).toFixed(1)} ${y0.toFixed(1)} L${(view.x + w + U * 2).toFixed(1)} ${(y0 - h * 0.08).toFixed(1)}`, dur: 30 + k * 11, begin: -k * 17 }
})
objects.sort((a, b) => a.depth - b.depth) objects.sort((a, b) => a.depth - b.depth)
return { return {
@ -676,11 +746,12 @@ export function buildScene(village: VillageState, frame: number | { width: numbe
// One at a time, so the layers keep the order they were added in. // One at a time, so the layers keep the order they were added in.
decals: [...decalFaces, ...shadows].flatMap((face) => toPolys([face])), decals: [...decalFaces, ...shadows].flatMap((face) => toPolys([face])),
// Wall segments keep their own outlines; the band below covers the stretches between. // Wall segments keep their own outlines; the band below covers the stretches between.
objects: objects.map(({ key, polys, building, planned }) => ({ objects: objects.map(({ key, polys, building, planned, life }) => ({
key, key,
polys, polys,
building: building ? { ...building, hit: hitOutline(polys, building.ring) } : undefined, building: building ? { ...building, hit: hitOutline(polys, building.ring) } : undefined,
planned, planned,
life,
})), })),
// Centred halfway up the palisade, so the band covers the wall itself, not only its foot. // Centred halfway up the palisade, so the band covers the wall itself, not only its foot.
wallBand: wall ? { id: wall.id, ring: { ...screenRing(0, 0, Rv), cy: -wallTop / 2 }, width: U * 1.6 + wallTop } : null, wallBand: wall ? { id: wall.id, ring: { ...screenRing(0, 0, Rv), cy: -wallTop / 2 }, width: U * 1.6 + wallTop } : null,
@ -688,5 +759,7 @@ export function buildScene(village: VillageState, frame: number | { width: numbe
timers, timers,
smoke, smoke,
walks, walks,
herds,
birds,
} }
} }