oda-engine 0.0.0-stage → 0.1.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.
Files changed (204) hide show
  1. package/README.md +151 -2
  2. package/bin/nowhere.mjs +352 -0
  3. package/lib/account.mjs +57 -0
  4. package/lib/agentModules.mjs +57 -0
  5. package/lib/devServer.mjs +351 -0
  6. package/lib/headless.mjs +231 -0
  7. package/lib/headlessPreview.mjs +212 -0
  8. package/lib/keys.mjs +517 -0
  9. package/lib/make.mjs +855 -0
  10. package/lib/mcp.mjs +537 -0
  11. package/lib/open.mjs +22 -0
  12. package/lib/preview.mjs +87 -0
  13. package/lib/previewRpc.mjs +134 -0
  14. package/lib/project.mjs +359 -0
  15. package/lib/publishFlow.mjs +90 -0
  16. package/lib/resources.mjs +50 -0
  17. package/lib/rules.mjs +60 -0
  18. package/lib/scaffold.mjs +42 -0
  19. package/lib/setup.mjs +59 -0
  20. package/lib/tools.mjs +668 -0
  21. package/package.json +51 -4
  22. package/template/game.config.json +9 -0
  23. package/template/scene.json +4 -0
  24. package/template/src/main.ts +11 -0
  25. package/vendor/DOCS.md +447 -0
  26. package/vendor/agent/appRun.mjs +520 -0
  27. package/vendor/agent/assets/brief.mjs +242 -0
  28. package/vendor/agent/assets/collider.mjs +531 -0
  29. package/vendor/agent/assets/environments/index.mjs +12 -0
  30. package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
  31. package/vendor/agent/assets/fetch.mjs +168 -0
  32. package/vendor/agent/assets/footprint.mjs +13 -0
  33. package/vendor/agent/assets/gltf.mjs +547 -0
  34. package/vendor/agent/assets/hdr.mjs +269 -0
  35. package/vendor/agent/assets/imageOps.mjs +171 -0
  36. package/vendor/agent/assets/images/codex.mjs +307 -0
  37. package/vendor/agent/assets/images/fal.mjs +75 -0
  38. package/vendor/agent/assets/images/gemini.mjs +84 -0
  39. package/vendor/agent/assets/images/index.mjs +25 -0
  40. package/vendor/agent/assets/images/openai.mjs +75 -0
  41. package/vendor/agent/assets/images/stability.mjs +71 -0
  42. package/vendor/agent/assets/images/views.mjs +31 -0
  43. package/vendor/agent/assets/import.mjs +1352 -0
  44. package/vendor/agent/assets/inspect.mjs +465 -0
  45. package/vendor/agent/assets/jobs.mjs +196 -0
  46. package/vendor/agent/assets/ktx2.mjs +290 -0
  47. package/vendor/agent/assets/ledger.mjs +466 -0
  48. package/vendor/agent/assets/net.mjs +254 -0
  49. package/vendor/agent/assets/prices.json +39 -0
  50. package/vendor/agent/assets/providers/fal.mjs +115 -0
  51. package/vendor/agent/assets/providers/index.mjs +22 -0
  52. package/vendor/agent/assets/providers/meshy.mjs +119 -0
  53. package/vendor/agent/assets/providers/tripo.mjs +188 -0
  54. package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
  55. package/vendor/agent/assets/sources/index.mjs +23 -0
  56. package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
  57. package/vendor/agent/assets/sources/polypizza.mjs +121 -0
  58. package/vendor/agent/assets/splat.mjs +631 -0
  59. package/vendor/agent/assets/targets.mjs +122 -0
  60. package/vendor/agent/assets/tile.mjs +261 -0
  61. package/vendor/agent/assets/unzip.mjs +180 -0
  62. package/vendor/agent/blender/cleanup.py +360 -0
  63. package/vendor/agent/blender/convert.py +167 -0
  64. package/vendor/agent/blender/find.mjs +192 -0
  65. package/vendor/agent/blender/nw_export.py +104 -0
  66. package/vendor/agent/blender/nw_rubric.py +426 -0
  67. package/vendor/agent/blender/run.mjs +193 -0
  68. package/vendor/agent/blender/runner.py +252 -0
  69. package/vendor/agent/blender/sheet.py +743 -0
  70. package/vendor/agent/depth.mjs +134 -0
  71. package/vendor/agent/director/board.mjs +451 -0
  72. package/vendor/agent/director/contracts.mjs +663 -0
  73. package/vendor/agent/director/director.mjs +2365 -0
  74. package/vendor/agent/director/estimate.mjs +200 -0
  75. package/vendor/agent/director/gate.mjs +802 -0
  76. package/vendor/agent/director/limits.json +16 -0
  77. package/vendor/agent/director/methods.mjs +457 -0
  78. package/vendor/agent/director/policy.json +33 -0
  79. package/vendor/agent/director/prompts.mjs +244 -0
  80. package/vendor/agent/director/reading.mjs +341 -0
  81. package/vendor/agent/director/router.mjs +184 -0
  82. package/vendor/agent/director/seams.mjs +243 -0
  83. package/vendor/agent/director/session.mjs +643 -0
  84. package/vendor/agent/director/store.mjs +119 -0
  85. package/vendor/agent/director/taskGate.mjs +110 -0
  86. package/vendor/agent/director/teamLedger.mjs +118 -0
  87. package/vendor/agent/director/triage.mjs +63 -0
  88. package/vendor/agent/downloads.cjs +363 -0
  89. package/vendor/agent/flow.mjs +78 -0
  90. package/vendor/agent/guard.mjs +613 -0
  91. package/vendor/agent/host.mjs +1736 -0
  92. package/vendor/agent/language.mjs +58 -0
  93. package/vendor/agent/ledger.mjs +360 -0
  94. package/vendor/agent/locale.cjs +186 -0
  95. package/vendor/agent/loop/capacity.mjs +74 -0
  96. package/vendor/agent/loop/compose.mjs +127 -0
  97. package/vendor/agent/loop/gate.mjs +205 -0
  98. package/vendor/agent/loop/judge.mjs +189 -0
  99. package/vendor/agent/loop/levels.mjs +273 -0
  100. package/vendor/agent/loop/state.mjs +358 -0
  101. package/vendor/agent/notes.cjs +278 -0
  102. package/vendor/agent/pace.mjs +258 -0
  103. package/vendor/agent/panels.mjs +431 -0
  104. package/vendor/agent/prompt.mjs +342 -0
  105. package/vendor/agent/reference/board.mjs +410 -0
  106. package/vendor/agent/reference/compose.mjs +364 -0
  107. package/vendor/agent/reference/decode.mjs +56 -0
  108. package/vendor/agent/reference/facts.mjs +1874 -0
  109. package/vendor/agent/reference/png.mjs +107 -0
  110. package/vendor/agent/reference/records.mjs +63 -0
  111. package/vendor/agent/reference/web.mjs +252 -0
  112. package/vendor/agent/roles/artist.mjs +69 -0
  113. package/vendor/agent/roles/builder.mjs +79 -0
  114. package/vendor/agent/roles/checks.mjs +223 -0
  115. package/vendor/agent/roles/common.mjs +188 -0
  116. package/vendor/agent/roles/critic.mjs +171 -0
  117. package/vendor/agent/roles/index.mjs +39 -0
  118. package/vendor/agent/roles/modeller.mjs +142 -0
  119. package/vendor/agent/roles/qa.mjs +58 -0
  120. package/vendor/agent/roles/rubrics.mjs +79 -0
  121. package/vendor/agent/roles/sound.mjs +69 -0
  122. package/vendor/agent/rounds.cjs +333 -0
  123. package/vendor/agent/shared.mjs +284 -0
  124. package/vendor/agent/stopGate.mjs +574 -0
  125. package/vendor/agent/subagents.mjs +129 -0
  126. package/vendor/agent/tools/assets.mjs +499 -0
  127. package/vendor/agent/tools/blender.mjs +754 -0
  128. package/vendor/agent/tools/cards.mjs +479 -0
  129. package/vendor/agent/tools/choices.mjs +479 -0
  130. package/vendor/agent/tools/compose.mjs +74 -0
  131. package/vendor/agent/tools/environment.mjs +488 -0
  132. package/vendor/agent/tools/eyes.mjs +733 -0
  133. package/vendor/agent/tools/generate.mjs +338 -0
  134. package/vendor/agent/tools/guide.mjs +46 -0
  135. package/vendor/agent/tools/harness.mjs +193 -0
  136. package/vendor/agent/tools/image.mjs +643 -0
  137. package/vendor/agent/tools/index.mjs +162 -0
  138. package/vendor/agent/tools/look.mjs +578 -0
  139. package/vendor/agent/tools/loop.mjs +858 -0
  140. package/vendor/agent/tools/others.mjs +123 -0
  141. package/vendor/agent/tools/pictures.mjs +535 -0
  142. package/vendor/agent/tools/reference.mjs +366 -0
  143. package/vendor/agent/transcripts.mjs +118 -0
  144. package/vendor/agent-loop.mjs +602 -0
  145. package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
  146. package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
  147. package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
  148. package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
  149. package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
  150. package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
  151. package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
  152. package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
  153. package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
  154. package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
  155. package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
  156. package/vendor/auth.cjs +570 -0
  157. package/vendor/build.cjs +953 -0
  158. package/vendor/catalog.json +455 -0
  159. package/vendor/connectors.cjs +688 -0
  160. package/vendor/eyes.mjs +733 -0
  161. package/vendor/gameExports.json +1390 -0
  162. package/vendor/git.cjs +222 -0
  163. package/vendor/models.json +57 -0
  164. package/vendor/publish.cjs +1018 -0
  165. package/vendor/refBoard.cjs +301 -0
  166. package/vendor/schema/dist/assets.d.ts +335 -0
  167. package/vendor/schema/dist/assets.js +439 -0
  168. package/vendor/schema/dist/brief.d.ts +357 -0
  169. package/vendor/schema/dist/brief.js +302 -0
  170. package/vendor/schema/dist/common.d.ts +9 -0
  171. package/vendor/schema/dist/common.js +13 -0
  172. package/vendor/schema/dist/config.d.ts +406 -0
  173. package/vendor/schema/dist/config.js +355 -0
  174. package/vendor/schema/dist/contract.d.ts +599 -0
  175. package/vendor/schema/dist/contract.js +1146 -0
  176. package/vendor/schema/dist/index.d.ts +14 -0
  177. package/vendor/schema/dist/index.js +21 -0
  178. package/vendor/schema/dist/look.d.ts +463 -0
  179. package/vendor/schema/dist/look.js +681 -0
  180. package/vendor/schema/dist/lookStats.d.ts +230 -0
  181. package/vendor/schema/dist/lookStats.js +768 -0
  182. package/vendor/schema/dist/pilot.d.ts +32 -0
  183. package/vendor/schema/dist/pilot.js +44 -0
  184. package/vendor/schema/dist/publish.d.ts +214 -0
  185. package/vendor/schema/dist/publish.js +291 -0
  186. package/vendor/schema/dist/scene.d.ts +75 -0
  187. package/vendor/schema/dist/scene.js +120 -0
  188. package/vendor/schema/dist/skyLight.d.ts +141 -0
  189. package/vendor/schema/dist/skyLight.js +436 -0
  190. package/vendor/schema/dist/style.d.ts +131 -0
  191. package/vendor/schema/dist/style.js +155 -0
  192. package/vendor/schema/package.json +1 -0
  193. package/vendor/selectionPrompt.mjs +51 -0
  194. package/vendor/useTools.mjs +195 -0
  195. package/vendor/userMessage.mjs +26 -0
  196. package/web-dist/assets/GaussianSplatUtils-CB77cP9U.js +1 -0
  197. package/web-dist/assets/KTX2Loader-6OIWUF7s.js +2 -0
  198. package/web-dist/assets/SPZLoader-zYj0Alfv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-CJTI1sEh.js +1 -0
  200. package/web-dist/assets/index-CcjyyQco.css +1 -0
  201. package/web-dist/assets/index-DMyJcoZJ.js +693 -0
  202. package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
  203. package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
  204. package/web-dist/index.html +34 -0
@@ -0,0 +1,244 @@
1
+ // What the director's own decision sessions are told. Each system prompt is
2
+ // one static text per phase, so it caches; everything that changes per
3
+ // production goes into the user text the functions below build. The role
4
+ // sessions' prompts are the roles' own (roles/); the only director text a
5
+ // role sees is the next attempt's (ATTEMPT_PROMPT) and the handoff to a
6
+ // fresh session.
7
+ //
8
+ // Every value of the game comes from the request and the reference, never
9
+ // from a default to keep: the prompts say so in each phase, and the board's
10
+ // checks (the palette check above all) hold the roles to the brief.
11
+
12
+ import { advisoryOf, factsSummary } from '../reference/facts.mjs'
13
+
14
+ const PLATFORM = `The game is an Oda planet: a TypeScript project whose src/main.ts exports createGame(ctx), rendered with three r185's WebGPURenderer (node materials, TSL), with the SDK's World for objects, rules and the player. One unit is one metre; the player is 1.75 m tall and sees from about 1.6 m. The map is 100 * sqrt(tiles) metres a side, as large as the brief's map says (code sizes it from the subjects' footprints), so a form is never shrunk to fit a map. It runs on an inexpensive laptop unless the creator asks otherwise.`
15
+
16
+ export const TRIAGE_PROMPT = `You route a request in Oda Studio, a tool where people make 3D web games by asking for them. You never talk to the creator.
17
+
18
+ Answer one thing: does this request need a production (a team of roles that interprets the request and any reference, sets a vision, plans tasks, builds and judges them over several rounds), or the fast path (one agent that makes the change directly)?
19
+ - production: a new game or world, a large rework, matching a reference picture, anything whose quality depends on art direction and several kinds of work (layout, look, models, sound).
20
+ - fast: a question, a tweak, a fix, one feature in a game that exists, anything one agent finishes in a few steps.
21
+ When unsure, choose fast. Give why in one short English sentence.`
22
+
23
+ export const INTERPRET_PROMPT = `You are the director of an Oda game production: you read what the creator asked for and the reference they gave, and you turn it into the art brief every role works from. You never talk to the creator and never write code.
24
+
25
+ ${PLATFORM}
26
+
27
+ You get the creator's request, the measured facts of the reference picture (its lettering, masked out before it was measured; palette with where each colour sits, value key, contrast, saturation, warmth, haze; the masses and focal points with their boxes; the horizon and camera guess with how sure each is; its shape and frame), the picture itself, and what the project already holds.
28
+
29
+ Rules:
30
+ - Read the request two or three ways (readings), choose one and say why.
31
+ - Derive every value from the request and the facts, and cite the fact each palette colour, value, light and haze number comes from (for example "palette[2], share 0.18" or "haze.score 0.71, toward-top"); write "request" when the request set it. There are no defaults to keep: a value neither gives is an assumption, listed with why. A palette colour's role is what lies where the facts say it sits.
32
+ - When the request and the reference disagree, the request wins.
33
+ - Describe the reference: its mood, light, palette, form language and composition.
34
+ - subjects: every clearly visible thing of the picture, each with an id (s1, s2, ...), what it is, its box [x0, y0, x1, y1] in fractions of the picture as the facts measure it, its kind (mass for a body that stands out whole, a rock, a hill, a cliff; ground for the terrain the visitor stands on; landmark; figure; atmosphere for sky, cloud, haze and scenery beyond the map; scale-cue for a person or a door that gives the others their size) and its role: keep (the game has it, in its place and proportion) or transform (a specific character, logo or likeness the game must not copy: an original thing of the same role, frame position and relative size takes its place, named in replacement). Every focal point and every mass of the facts lies in the box of a subject about its size (a sky boxed as the whole picture names none of what stands in it). A subject that stands in the game names the forms.scale element it is sized by (form, its element exactly), and that form's height against its width keeps the box's proportion within a factor of 2 (atmosphere aside, and ground that runs across the frame's width, which the picture shows in depth; a ground the picture shows whole is held to its box as a mass is), unless an assumption that names the subject says why the game departs from it. Lettering is never a subject.
35
+ - Size the subjects against the 1.75 m player and against each other as the picture shows them (a scale cue in it gives the others their metres); never fit them into a map: code sizes the map from their footprints.
36
+ - Never plan to reproduce a specific character, logo, title or typography from the picture: such a subject is transformed, never left out, so what it does in the picture stays. Exclusions name marks only (lettering, logos, a named character's likeness), never a generic form (a building, a rock, a tree, a cloud).
37
+ - A reading of the facts under 0.5 confidence is advisory (the facts say which): its numbers (a horizon's place in the frame, a pitch) may inform an assumption, never a request element, a camera's horizonY or a value you cite from the reference. What the picture clearly shows (a low camera, looking up) you say in words.
38
+ - atmosphere: fog is null when the request and the reference have none (clear air, space, a room); otherwise its colour and distances from what the reference's haze shows. hazeLayers only when the reference stages distinct distances; leave it out otherwise.
39
+ - light: sunElevationDeg is the sun's height above the horizon; sunAzimuthDeg is where the sun stands, in degrees around the vertical from -Z (0) toward +X (90), the convention the look-dev skill turns into a direction.
40
+ - requestElements: every element the creator named, each with an id, plus what the reference shows that the game must carry (from: reference), one element per subject that matters rather than many in one; an element from the reference names its subject (subject) or the fact it reads (fact: palette, value, haze, ...).
41
+ - cameras: at least three, with ids: "player" (the visitor's view), "reference" when there is a picture (the framing that matches it: its height and pitch; code sets its aspect from the picture, and its horizonY only from a horizon read at 0.5 confidence or more), and close-ups or overviews of what matters.
42
+ - performance: tier "low" (150 draw calls, 500000 triangles) unless the creator asks for more.
43
+ - List every assumption with why and how sure you are.
44
+ Answer only with the structured output.`
45
+
46
+ export const READBACK_PROMPT = `You check a game's art brief against the reference picture it was read from. You never talk to the creator and never write code.
47
+
48
+ You get the picture as it is and, when the brief has subjects, again with each subject drawn on it as a box in its own colour (the list below says which colour is which). You get the brief's subjects, its forms with their sizes, and its cameras; nothing else.
49
+
50
+ List what the picture clearly shows that the brief lacks or contradicts:
51
+ - missing: a clearly visible thing that no subject's box covers.
52
+ - contradicts: a subject whose form, size or proportion the picture contradicts (its form wide and low where the picture shows it taller than wide, a kind of thing other than the one there, a box that misses the thing), or a camera that frames the picture otherwise (another shape of frame, or a pitch the other way). Give the subject's id.
53
+ Each with its box [x0, y0, x1, y1] in fractions of the picture from its top left, what it is and why, in a line each. Only what is clearly visible: nothing about style, mood or colour, and never lettering, titles or credits (they are masked out and are not part of the game). When the brief agrees with the picture, answer an empty list.
54
+ Answer only with the structured output.`
55
+
56
+ export const NOTES_PROMPT = `You are the director of an Oda game production, between rounds of its tasks. Notes have come to you: requests the roles made of the director, and the critic's word that the brief contradicts the reference. You never talk to the creator and never write code.
57
+
58
+ You get the reference picture (when there is one), the brief's subjects, forms and cameras, the roles with work still to come, and the notes, numbered. For each note, one action:
59
+ - amend: the brief is wrong against the picture or the request. Give the subject as it should be (subject: the whole subject, its id kept when it is one the brief has) and the form's size (form: the forms.scale element exactly and its sizeM). Code keeps the change only when the brief then holds to the picture's measures no worse, and tells the roles.
60
+ - route: the note is a role's work: owner is the role whose next task does it.
61
+ - report: neither; it goes to the creator's report as it is.
62
+ Amend only what the picture or the request clearly shows; never the request's own elements, the palette or the look. Answer only with the structured output.`
63
+
64
+ export const VISION_PROMPT = `You are the creative director of an Oda game production. From the brief, the request and the reference, you set what the game will be at its best: not only what was asked, but what a skilled game team would add to make it great, within the creator's intent. You never talk to the creator directly; your card does.
65
+
66
+ ${PLATFORM}
67
+
68
+ Answer with:
69
+ - concepts: two or three genuinely different directions for this request (different in play, staging or mood, not in wording), each with a title, a one-line pitch and how it differs; then the chosen one and the reasons.
70
+ - pillars: three to five short lines the whole team decides by.
71
+ - moments: two to four signature moments, each at one of the brief's camera ids, with what the player sees, what they do, and one acceptance line a reviewer can check from a picture or a playtest. Write each acceptance line for this request, from its brief and reference: a line that would fit any game is not one.
72
+ - additions: one to five things beyond the literal request that make the game better, each with why and why it stays within the creator's intent.
73
+ - scope: what is in and what is out of this version.
74
+ - card: a title and a short body for the creator.
75
+ Every text field is in the screen language (named below), the studio's, because the card shows it to them; ids stay in English. Never plan to copy a specific character, logo or text from the reference.
76
+ Answer only with the structured output.`
77
+
78
+ export const PLAN_PROMPT = `You are the producer of an Oda game production: you turn the brief and the vision into a board of small tasks for specialist roles, each one verifiable by tools. You get the reference picture too, when there is one, to see what the brief's subjects are. You never talk to the creator and never write code.
79
+
80
+ ${PLATFORM}
81
+
82
+ Roles (the catalogue below says what each does and which checks it has): builder (layout, generators, gameplay, integration; the only owner of src/main.ts, scene.json and game.config.json), artist (look values through look_apply, materials and shaders), modeller (one asset per task, made the way its method says), sound (Web Audio synthesis), qa (playtests; owns nothing).
83
+
84
+ Rules the board is checked against:
85
+ - 1 to 12 tasks, ids t1, t2, ... in board order; deps name earlier work and never go round in a circle.
86
+ - t1, the first task in the preview lane, is a builder blockout with makesCameras true: the layout at the brief's scales, the spawn, the landmarks, and every brief camera as a shot. Every artist and QA task depends on it.
87
+ - placements: the blockout declares one for each thing a modeller task makes ({ id, what, anchor }): the id its code adds the stand-in under through the placements seam (src/placements/index.ts, the director's), what stands there, and anchor "base" when the model stands where the stand-in stood (the default) or "top" when things stand on it (a platform or an island the player walks). Every modeller task names its placement (placement: "<id>"), one model per placement. When a modeller task ends with its model, the director puts it in the game at its placement itself, so no task places it and nothing waits for it.
88
+ - owns: project-relative globs inside the role's own area. Two tasks with no dependency path between them own disjoint files. Never own the seams (src/look/index.ts, src/audio/index.ts, src/placements/index.ts), brief.md or .nowhere/.
89
+ - The look keys of game.config.json (sky, fog, lighting, bloom, look) change only through look_apply in artist tasks.
90
+ - interfaces: what one task makes for others (materials in a module beside src/look/index.ts, audio in src/audio/sound.ts, the module the sound role writes), with the names (material code names; sound event ids from the brief), one producer (whose interface field names it and who owns the module) and the consumers. The builder imports from the seam from the start, and the seam keeps the game building until the producer's work is in, so a consumer need not wait for it. A dependency on an artist, an interface's producer or a modeller orders the work and never blocks: when one fails, its stand-in stays and the tasks after it go on.
91
+ - Every task but QA has at least one tool check from the check catalogue; camera ids are the brief's. The checks that use the preview (build, runtime, view, compare, cameras, placements, play, perf) go only on builder, artist and QA tasks; a modeller task owns its .glb by its exact path, so it has an asset check.
92
+ - Critic criteria, 1 to 6, each concrete and checkable from a picture (cite the brief's facts and the reference), on every artist and modeller task, the blockout and the last builder task. They are this request's acceptance criteria, written for it from the brief, the vision's moments and the reference: there is no standard list to reuse, and a criterion that would fit any game is not one. With a reference, the blockout, every hero modeller task (an asset check with hero true) and the last builder task each have at least one criterion tied to a brief subject (subject: its id), which the critic judges against that subject's crop of the reference. A criterion never stands on an advisory fact (listed below): no place of the horizon or camera pitch the picture reads under 0.5 confidence; say what the picture clearly shows in words instead. The critic brings no bar of its own; it judges each role's work on the general axes against these criteria: a builder on form and composition, an artist on colour, light and material detail, a modeller on form, detail and colour.
93
+ - Every brief request element and every vision moment is in some task's covers.
94
+ - roundLimit at most the limit per task; all round limits together within the attempt limit.
95
+ - examples: for small tasks, the exact tool inputs to start from (an nw_view shot, an nw_play step with goto, a look_apply call), in the catalogue's shapes with this game's own names and the brief's values in place of its <placeholders>.
96
+ - tier: small for a narrow task that its checks fully verify, mid for most, top only for the hardest.
97
+ - method, on every modeller task: how its asset is made (how: project, library, blender, crop-3d or image-3d; the subject, the image generator, the views and the image-to-3D provider it needs; why, in one line), chosen for this asset from the capability list below: what can run here, what each costs, and how usable the reference's crop of each subject is, weighed against the asset's form, its class and what the brief asks of it. Code checks only that it can run, and prices what it spends on the cost card. A method that needs a card the creator may refuse (a key, Codex's consent, installing Blender) gives fallback: the way to make it when that card is refused (with none, the asset is not made and its stand-in stays). paid stays empty: a method's spending is priced from it.
98
+ - A QA task depends on the last builder (integration) task when the game has anything to play.
99
+ Also answer the cost card's title, body and note, the five role names and the cost words (direction, critique, report, reserve) in the screen language.
100
+ Answer only with the structured output.`
101
+
102
+ export const METHOD_PROMPT = `You are the director of an Oda game production, between two rounds of a modeller task that did not pass. You decide how its asset is made from here: keep its method, or switch to another that the capability list says can run. You never talk to the creator and never write code.
103
+
104
+ You get the task, its method and why it was chosen, the methods it was made by so far, what the last round's gate found (the checks that failed, the critic's scores, criteria and changes), the capability list with the measures of the reference's crops, and the pictures: the reference's crop of its subject when it has one, and the last round's colour sheet when there is one.
105
+
106
+ Switch when the method itself is what held the asset back, so that another round of it would repeat it (a service that failed, a crop that cannot show the form, a form or a budget its way of making cannot reach); keep it when the next round can fix what the gate named. A switch gives the whole method: how, the subject and providers it needs, and why, in one line. Code checks that it can run, and a paid one goes on a new cost card first. Answer only with the structured output.`
107
+
108
+ export const REPORT_PROMPT = `You write the last reply of an Oda game production to the creator who asked for it. You get what was verified (with the camera or playtest that showed it), what was kept below the critic's bar (in the game as the best attempt there was, but not passed), what was assumed or added, what is not done and why, and the cost by model.
109
+
110
+ Write it in the creator's language, short and plain, in this order: what works and how it was seen; what is kept below the bar, said as kept, never as passed or done; what was assumed or added beyond the request; what is not done; the cost; how to continue (they can ask to continue, or ask for a change). Never claim anything the evidence does not show. Answer only with the structured output: text is the reply; verified, assumed and notDone are its points as short lines (a kept task is a notDone line that says it is kept).`
111
+
112
+ // ---------------------------------------------------------------- user texts
113
+
114
+ const json = (v) => JSON.stringify(v, null, 2)
115
+
116
+ export function triageText({ text, images, emptyProject, history }) {
117
+ const earlier = (history ?? []).slice(-4).map((m) => `${m.role === 'user' ? 'Creator' : 'Agent'}: ${String(m.text ?? '').slice(0, 300)}`)
118
+ return [
119
+ `Request: ${text}`,
120
+ `Pictures attached: ${images}. Project: ${emptyProject ? 'the blank template (nothing built yet)' : 'a game exists'}.`,
121
+ earlier.length ? `Earlier in the conversation:\n${earlier.join('\n')}` : '',
122
+ ]
123
+ .filter(Boolean)
124
+ .join('\n\n')
125
+ }
126
+
127
+ export function interpretText({ request, facts, project, blender, web, declinePaid, languageName, errors }) {
128
+ const main = facts ? (facts.art ?? facts.full) : null
129
+ return [
130
+ `The creator's request (they write in ${languageName}):\n${request}`,
131
+ main ? `The reference's measured facts${facts.art ? ', of the art inside its frame' : ''}:\n${factsSummary(main)}\n\nAs JSON:\n${json(main)}` : 'There is no reference picture: every value comes from the request.',
132
+ facts?.art ? `The whole picture's facts, frame included:\n${json(facts.full)}` : '',
133
+ `The project:\n${json(project)}`,
134
+ `Blender: ${blender ? `installed (${blender.version ?? 'version unknown'})` : 'not installed'}. The web: ${web}. Paid generation: ${declinePaid ? 'declined by the creator' : 'possible after a cost card'}.`,
135
+ errors?.length ? `Your last answer did not hold. Fix these and answer again:\n${errors.map((e) => `- ${e}`).join('\n')}` : '',
136
+ ]
137
+ .filter(Boolean)
138
+ .join('\n\n')
139
+ }
140
+
141
+ export function visionText({ brief, request, languageName, develop, edit }) {
142
+ return [
143
+ `The creator's request:\n${request}`,
144
+ `The brief:\n${json(brief)}`,
145
+ `The screen language: ${languageName}. Write every text field in it.`,
146
+ develop ? `The creator picked the concept "${develop.title}" (${develop.pitch}). Develop that one as the chosen concept; keep two others beside it.` : '',
147
+ edit ? `The creator answered your last vision with this change (their own words):\n${edit}\nMake the vision say it, and keep what they did not change.` : '',
148
+ ]
149
+ .filter(Boolean)
150
+ .join('\n\n')
151
+ }
152
+
153
+ export function planText({ brief, vision, facts = null, roleCatalogue, checkCatalogue, routing, project, limits, web, declinePaid, blender, methods = null, languageName, errors }) {
154
+ const advisory = advisoryOf(facts)
155
+ return [
156
+ `The brief:\n${json(brief)}`,
157
+ `The vision:\n${json(vision)}`,
158
+ facts ? `The reference's advisory facts, which no criterion may stand on: ${advisory.length ? advisory.map((a) => a.why).join('; ') : 'none'}.` : '',
159
+ `The roles:\n${roleCatalogue}`,
160
+ `The checks:\n${checkCatalogue}`,
161
+ `The models (the router decides; tier is your proposal):\n${routing}`,
162
+ `The project:\n${json(project)}`,
163
+ `Limits: at most ${limits.maxTasks} tasks, roundLimit at most ${limits.roundsPerTask}, ${limits.attempts} attempts in all, ${limits.criteriaPerTask} critic criteria per task.`,
164
+ `The web: ${web}. Paid generation: ${declinePaid ? 'declined (no paid lines)' : 'allowed after the cost card'}. Blender: ${blender ? 'installed' : 'not installed (CC0 libraries and forms built in code instead)'}.`,
165
+ methods ? `The capability list for the modelled assets:\n${methods}` : '',
166
+ `The screen language for the card, the role names and the cost words: ${languageName}.`,
167
+ errors?.length ? `Your last board did not pass these rules. Fix every one and answer the whole board again:\n${errors.map((e) => `- ${e}`).join('\n')}` : '',
168
+ ]
169
+ .filter(Boolean)
170
+ .join('\n\n')
171
+ }
172
+
173
+ /**
174
+ * The next attempt's prompt: the round, the failed checks, then the
175
+ * critic's changes most important first (only those the task's own role
176
+ * owns; the director hands the rest to their owners), then what to do. Its
177
+ * first line is always "Round <n> of <limit>.".
178
+ */
179
+ export function ATTEMPT_PROMPT({ round, limit, failures = [], changes = [], restored = false, notes = [] }) {
180
+ const out = [`Round ${round} of ${limit}.`]
181
+ if (restored) out.push('Your last change made it worse and was put back. Try the next change in the list.')
182
+ if (failures.length) out.push(`${restored ? 'Before it was put back, these checks failed' : 'These checks failed'}:\n${failures.map((f) => `- ${f.id} (${f.kind}): ${String(f.text).split('\n').slice(0, 4).join(' ')}`).join('\n')}`)
183
+ const ranked = [...changes].sort((a, b) => a.rank - b.rank).slice(0, 5)
184
+ if (ranked.length) out.push(`The critic's changes, most important first:\n${ranked.map((c, i) => `${i + 1}. ${c.what} (where: ${c.where}; why: ${c.why}). Fix: ${c.fix}`).join('\n')}`)
185
+ if (notes.length) out.push(`Also asked of you:\n${notes.map((n) => `- ${n}`).join('\n')}`)
186
+ out.push('Fix these in this order; start nothing new. Run task_check before you finish.')
187
+ return out.join('\n\n')
188
+ }
189
+
190
+ /** What a fresh session on another model is told about the attempts before it. */
191
+ export function handoffText({ reports = [], diffStat = '' }) {
192
+ const lines = reports.map((r, i) => `Attempt ${i + 1}: ${r?.summary ?? 'no report'}${r?.notDone?.length ? ` Not done: ${r.notDone.join('; ')}.` : ''}`)
193
+ return `What was done so far:\n${lines.join('\n') || 'No report came back.'}${diffStat ? `\nYour files now: ${diffStat}` : ''}`
194
+ }
195
+
196
+ /** The read-back's words: the picture's size, then the brief's subjects
197
+ * (each with the colour its box is drawn in), forms and cameras. */
198
+ export function readbackText({ brief, facts, marks }) {
199
+ const subjects = (brief.subjects ?? []).map((s, i) => `- ${s.id} (${marks(i)[0]} box ${JSON.stringify(s.box)}): ${s.what}; ${s.kind}, ${s.role}${s.replacement ? ` (in its place: ${s.replacement})` : ''}${s.form ? `; sized by "${s.form}"` : ''}`)
200
+ const forms = (brief.forms?.scale ?? []).map((f) => `- ${f.element}: ${Object.entries(f.sizeM ?? {}).map(([k, v]) => `${k} ${v} m`).join(', ')}${f.count ? `, ${f.count} of them` : ''}`)
201
+ const cameras = (brief.cameras ?? []).map((c) => `- ${c.id} (${c.purpose})${c.subject ? `: ${c.subject}` : ''}${c.aspect ? `, ${c.aspect}` : ''}${c.heightM !== undefined ? `, ${c.heightM} m up` : ''}${c.pitchDeg !== undefined ? `, pitch ${c.pitchDeg}` : ''}${c.horizonY !== undefined ? `, horizon at ${c.horizonY} of the height` : ''}`)
202
+ return [
203
+ facts ? `The picture is ${facts.size.width} x ${facts.size.height} (${facts.size.shape}).` : '',
204
+ `The brief's subjects:\n${subjects.join('\n') || '- none'}`,
205
+ `Its forms:\n${forms.join('\n') || '- none'}`,
206
+ `Its cameras:\n${cameras.join('\n')}`,
207
+ ]
208
+ .filter(Boolean)
209
+ .join('\n\n')
210
+ }
211
+
212
+ /** The method review's words: the task, its method and the ones before
213
+ * it, what the last gate found, and the capability list. */
214
+ export function methodText({ task, method, tried = [], gate = null, why = [], capabilities }) {
215
+ const failed = (gate?.checks ?? []).filter((c) => !c.ok)
216
+ const critic = gate?.critic
217
+ return [
218
+ `The task ${task.id} (${task.title}): ${task.goal}`,
219
+ `Its method now: ${method}.`,
220
+ tried.length ? `How it was made in its rounds so far:\n${tried.map((t) => `- ${t}`).join('\n')}` : '',
221
+ failed.length ? `The last round's checks that failed:\n${failed.map((c) => `- ${c.id} (${c.kind}): ${String(c.text).split('\n')[0]}`).join('\n')}` : 'Its tool checks passed.',
222
+ gate?.noReport ? `It gave no report: ${gate.reportError ?? 'no reason'}.` : '',
223
+ critic ? `The critic: ${Object.entries(critic.scores ?? {}).map(([k, v]) => `${k} ${v}`).join(', ')}; ${why.join(' ')}\nIts changes:\n${(critic.changes ?? []).slice(0, 5).map((c) => `- ${c.what} (${c.why}). Fix: ${c.fix}`).join('\n') || '- none'}` : gate?.criticError ? `The critic did not judge it: ${gate.criticError}` : '',
224
+ `The capability list:\n${capabilities}`,
225
+ ]
226
+ .filter(Boolean)
227
+ .join('\n\n')
228
+ }
229
+
230
+ /** The notes review's words: the brief's subjects, forms and cameras, the
231
+ * roles with work to come, and the open notes, numbered. */
232
+ export function notesText({ brief, roles, notes }) {
233
+ return [
234
+ `The brief's subjects:\n${json(brief.subjects ?? [])}`,
235
+ `Its forms:\n${json(brief.forms?.scale ?? [])}`,
236
+ `Its cameras:\n${json(brief.cameras ?? [])}`,
237
+ `Roles with work still to come: ${roles.length ? roles.join(', ') : 'none'}.`,
238
+ `The notes:\n${notes.map((n, i) => `${i + 1}. ${n.line}`).join('\n')}`,
239
+ ].join('\n\n')
240
+ }
241
+
242
+ export function reportText(input) {
243
+ return `Everything to report, as checked:\n${json(input)}\n\nThe creator's language: ${input.languageName}.`
244
+ }
@@ -0,0 +1,341 @@
1
+ // The brief held to the picture it was read from (post-mortem gaps 2 and 6).
2
+ // INTERPRET's answer is a reading, and a cheap model's reading can invent a
3
+ // form, take a title's edge for a horizon or drop what the picture is about;
4
+ // nothing after it looks at the picture again unless something here does.
5
+ // So code checks the brief against what the facts measure (readingErrors),
6
+ // and a narrow read-back decision, a fresh model that sees only the picture
7
+ // and the brief's subjects, forms and cameras, lists what the picture
8
+ // clearly shows that the brief lacks or contradicts (readbackErrors). Both
9
+ // come back to INTERPRET as errors for its one repair, and what the repair
10
+ // leaves unanswered (unanswered) goes on, said, as not done.
11
+ //
12
+ // What the picture decides is set by code, never asked of a model
13
+ // (settleBrief): the reference camera's aspect and its horizonY (only from
14
+ // a horizon read at CONFIDENT or more), each subject's proportion in the
15
+ // picture beside its form's, and the map the subjects' footprints need.
16
+ // The same subjects travel on: PLAN ties criteria to them, the critic
17
+ // judges form against their crops of the reference (subjectCrops), and a
18
+ // change of the brief between rounds is kept only when these checks hold
19
+ // no worse with it.
20
+
21
+ import { decodeImage } from '../reference/decode.mjs'
22
+ import { CONFIDENT, advisoryOf, citesAdvisory, cropPicture, fitEdge } from '../reference/facts.mjs'
23
+ import { blit, canvas, encodePng, line } from '../reference/png.mjs'
24
+
25
+ /** How far a kept subject's form may part from its proportion in the
26
+ * picture, either way, before it is an error (a proposal). */
27
+ export const PROPORTION = 2
28
+ /** A focal point the eye gives at least this share of itself to needs a subject. */
29
+ const SALIENT = 0.02
30
+ /** A mass of at least this share of the picture needs a subject over most of it. */
31
+ const MASS_SHARE = 0.05
32
+ /** A subject's box accounts for a thing at most this many times the thing's
33
+ * size: a sky boxed as the whole picture does not name what stands in it. */
34
+ const COVER = 3
35
+ /** A ground whose box spans this share of the frame's width runs out of it
36
+ * on both sides: terrain seen in depth, its box no measure of its shape. A
37
+ * narrower one (a plateau, a hilltop) is seen whole, as a mass is. */
38
+ const ACROSS = 0.8
39
+ /** The facts a request element may cite by name. */
40
+ export const FACT_KEYS = ['size', 'palette', 'accents', 'value', 'contrast', 'saturation', 'temperature', 'haze', 'masses', 'composition', 'horizon', 'camera']
41
+ /** The colours a subject's box is drawn in on the read-back's picture, by its order. */
42
+ const MARKS = [
43
+ ['red', [235, 40, 40]],
44
+ ['blue', [40, 90, 255]],
45
+ ['green', [40, 200, 70]],
46
+ ['yellow', [250, 220, 30]],
47
+ ['magenta', [230, 40, 220]],
48
+ ['cyan', [30, 220, 230]],
49
+ ['orange', [255, 140, 20]],
50
+ ['white', [255, 255, 255]],
51
+ ]
52
+
53
+ const r2 = (n) => Math.round(n * 100) / 100
54
+ const pct = (v) => `${Math.round(v * 100)}%`
55
+ export const isBox = (b) => Array.isArray(b) && b.length === 4 && b.every((v) => Number.isFinite(v)) && b[0] >= 0 && b[1] >= 0 && b[2] <= 1 && b[3] <= 1 && b[2] > b[0] && b[3] > b[1]
56
+ const areaOf = (b) => Math.max(0, b[2] - b[0]) * Math.max(0, b[3] - b[1])
57
+ const within = (b, x, y) => x >= b[0] && x <= b[2] && y >= b[1] && y <= b[3]
58
+ export const boxText = (b) => `[${b.map((v) => Number(v).toFixed(2)).join(', ')}]`
59
+ const escape = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
60
+ const median = (list) => {
61
+ const s = [...list].sort((a, b) => a - b)
62
+ return s.length ? s[Math.floor(s.length / 2)] : null
63
+ }
64
+
65
+ /** How much of box `a` the boxes cover between them, on a 40 x 40 grid. */
66
+ export function covered(a, boxes) {
67
+ if (!boxes.length) return 0
68
+ let k = 0
69
+ for (let i = 0; i < 40; i++) {
70
+ for (let j = 0; j < 40; j++) {
71
+ const x = a[0] + ((i + 0.5) / 40) * (a[2] - a[0])
72
+ const y = a[1] + ((j + 0.5) / 40) * (a[3] - a[1])
73
+ if (boxes.some((b) => within(b, x, y))) k++
74
+ }
75
+ }
76
+ return k / 1600
77
+ }
78
+
79
+ /** A subject's height over its width in the picture, in pixels. */
80
+ export const pictureTall = (subject, facts) => ((subject.box[3] - subject.box[1]) * facts.size.height) / Math.max(1e-9, (subject.box[2] - subject.box[0]) * facts.size.width)
81
+ /** A form's height over its widest side, or null when it gives no both. */
82
+ export function formTall(form) {
83
+ const h = Number(form?.sizeM?.h)
84
+ const wide = Math.max(Number(form?.sizeM?.w) || 0, Number(form?.sizeM?.d) || 0)
85
+ return h > 0 && wide > 0 ? h / wide : null
86
+ }
87
+ /** The forms.scale line a subject is sized by. */
88
+ export const formOf = (brief, subject) => (subject?.form ? ((brief?.forms?.scale ?? []).find((s) => s.element === subject.form) ?? null) : null)
89
+ /** Whether the picture shows a subject in depth (sky and haze, terrain
90
+ * across the frame), so its box says nothing of its form's proportion. */
91
+ export const inDepth = (subject) => subject.kind === 'atmosphere' || (subject.kind === 'ground' && subject.box[2] - subject.box[0] >= ACROSS)
92
+ /** Whether an assumption of the brief names a subject (and so says why it departs). */
93
+ const assumes = (brief, id) => (brief?.assumptions ?? []).some((a) => new RegExp(`(^|[^\\w-])${escape(id)}([^\\w-]|$)`).test(`${a.what} ${a.why}`))
94
+
95
+ /**
96
+ * What code checks in a brief against the facts of its reference, each as
97
+ * { key, text }: the subjects (every focal point and every big mass in the
98
+ * box of a subject of about its size, each box a place in the picture and
99
+ * not its lettering, a
100
+ * transform with its replacement, a form that is one of the brief's), the
101
+ * proportion of every kept subject against its form (within PROPORTION,
102
+ * unless an assumption that names it says why; never for what the picture
103
+ * shows in depth, inDepth), the request elements
104
+ * from the reference (each names its subject or its fact, and none stands
105
+ * on an advisory reading), and the cameras (the reference camera's framing
106
+ * and any camera's horizonY never an advisory reading's). Empty without
107
+ * facts: a brief with no picture is held to its request alone.
108
+ */
109
+ export function readingErrors(brief, facts) {
110
+ if (!facts) return []
111
+ const out = []
112
+ const err = (key, text) => out.push({ key, text })
113
+ const subjects = brief?.subjects ?? []
114
+ const lettering = (facts.text?.boxes ?? []).map((t) => t.box)
115
+ const masses = new Set((facts.masses ?? []).map((m) => m.id))
116
+ const forms = new Set((brief?.forms?.scale ?? []).map((s) => s.element))
117
+ if (!subjects.length) err('subjects', 'The brief names no subjects, but it reads a picture: give every clearly visible thing of it a subject, with its box as the facts measure it, its kind and its role (keep, or transform with a replacement).')
118
+ const ids = new Set()
119
+ for (const s of subjects) {
120
+ if (ids.has(s.id)) err(`subject:${s.id}:id`, `Two subjects are ${s.id}.`)
121
+ ids.add(s.id)
122
+ if (!isBox(s.box) || areaOf(s.box) < 0.001) {
123
+ err(`subject:${s.id}:box`, `The subject ${s.id} (${s.what}) has the box ${Array.isArray(s.box) ? boxText(s.box) : String(s.box)}, which is not a place in the picture: [x0, y0, x1, y1] in fractions, x0 < x1 and y0 < y1, from its top left.`)
124
+ continue
125
+ }
126
+ if (lettering.length && covered(s.box, lettering) > 0.6) err(`subject:${s.id}:lettering`, `The subject ${s.id} (${s.what}) lies in the picture's lettering, which was masked out before it was measured: lettering is never a subject of the game.`)
127
+ if (s.role === 'transform' && !String(s.replacement ?? '').trim()) err(`subject:${s.id}:replacement`, `The subject ${s.id} (${s.what}) is transformed but names no replacement: say the original thing that takes its place, with its role, its place in the frame and its size there.`)
128
+ if (s.form && !forms.has(s.form)) err(`subject:${s.id}:form`, `The subject ${s.id} is sized by the form "${s.form}", which forms.scale does not have: name one of its elements exactly.`)
129
+ for (const m of s.masses ?? []) if (!masses.has(m)) err(`subject:${s.id}:mass`, `The subject ${s.id} names the mass ${m}, which the facts do not have (${[...masses].join(', ') || 'none'}).`)
130
+ const form = formOf(brief, s)
131
+ const want = formTall(form)
132
+ // Sky and terrain across the frame are seen in perspective: their box is depth, not their shape.
133
+ if (s.role === 'keep' && !inDepth(s) && want !== null && !assumes(brief, s.id)) {
134
+ const seen = pictureTall(s, facts)
135
+ const apart = Math.max(seen / want, want / seen)
136
+ if (apart > PROPORTION) {
137
+ err(
138
+ `proportion:${s.id}`,
139
+ `The subject ${s.id} (${s.what}) is ${r2(seen)} times as tall as wide in the picture (its box ${boxText(s.box)}), but its form "${form.element}" is ${form.sizeM.h} m tall and ${Math.max(Number(form.sizeM.w) || 0, Number(form.sizeM.d) || 0)} m wide (${r2(want)}): ${r2(apart)} times apart. Make the form keep the picture's proportion within a factor of ${PROPORTION}, or say in an assumption that names ${s.id} why the game departs from it.`,
140
+ )
141
+ }
142
+ }
143
+ }
144
+ const boxes = subjects.filter((s) => isBox(s.box)).map((s) => s.box)
145
+ const near = (size) => boxes.filter((b) => areaOf(b) <= COVER * Math.max(size, 0.02))
146
+ for (const f of facts.composition?.focal ?? []) {
147
+ if (!(f.share >= SALIENT) || lettering.some((b) => within(b, f.x, f.y))) continue
148
+ if (!near(isBox(f.box) ? areaOf(f.box) : 0).some((b) => within(b, f.x, f.y))) {
149
+ err(`focal:${f.id}`, `The picture's focal point ${f.id} at (${f.x}, ${f.y}), ${f.where}, in ${boxText(f.box)} (${pct(f.share)} of where the eye goes), lies in no subject's box: name what is there as a subject (keep it, or transform it into an original thing of the same role, place and size in the frame), or widen the box of the subject that is there.`)
150
+ }
151
+ }
152
+ for (const m of facts.masses ?? []) {
153
+ if (m.share < MASS_SHARE) continue
154
+ if (covered(m.box, near(areaOf(m.box))) < 0.5) err(`mass:${m.id}`, `The mass ${m.id} (${m.value}, ${boxText(m.box)}, ${pct(m.share)} of the picture) lies mostly outside every subject's box: say what it is as a subject (of kind mass, or atmosphere when it is sky, cloud or haze).`)
155
+ }
156
+ const advisory = advisoryOf(facts)
157
+ for (const e of brief?.requestElements ?? []) {
158
+ if (e.from !== 'reference') continue
159
+ if (!e.subject && !e.fact) err(`element:${e.id}`, `${e.id} ("${e.text}") is from the reference but names neither the subject it shows (subject) nor the fact it reads (fact).`)
160
+ if (e.subject && !ids.has(e.subject)) err(`element:${e.id}:subject`, `${e.id} names the subject ${e.subject}, which the brief does not have.`)
161
+ const named = String(e.fact ?? '').split(/[.[\s]/)[0]
162
+ if (e.fact && !FACT_KEYS.includes(named)) err(`element:${e.id}:fact`, `${e.id} names the fact "${e.fact}", which is not one of the facts (${FACT_KEYS.join(', ')}).`)
163
+ const leans = [...new Set([...citesAdvisory(e.text, facts, { reference: true }), ...advisory.filter((a) => a.fact === named).map((a) => a.fact)])]
164
+ if (leans.length) {
165
+ const why = leans.map((fact) => advisory.find((a) => a.fact === fact)?.why).join('; ')
166
+ err(`element:${e.id}:advisory`, `${e.id} ("${e.text}") stands on the picture's ${leans.join(' and ')}, which ${leans.length === 1 ? 'is' : 'are'} advisory (${why}, under ${CONFIDENT}): a reading that unsure may inform an assumption, never a request element. Leave it out, or make it an assumption.`)
167
+ }
168
+ }
169
+ const horizon = advisory.find((a) => a.fact === 'horizon' && a.value !== null)
170
+ for (const c of brief?.cameras ?? []) {
171
+ // What the reference camera frames is said by what the picture shows, never by an advisory reading.
172
+ const leans = c.purpose === 'reference' ? citesAdvisory(c.subject, facts, { reference: true }) : []
173
+ if (leans.length) err(`camera:${c.id}:subject`, `The ${c.id} camera's framing ("${c.subject}") stands on the picture's ${leans.join(' and ')}, which ${leans.length === 1 ? 'reads' : 'read'} under ${CONFIDENT} confidence (advisory): say what it frames by what the picture clearly shows (its subjects and where they sit).`)
174
+ if (c.purpose === 'reference' || c.horizonY === undefined || !horizon) continue
175
+ if (Math.abs(c.horizonY - horizon.value) <= 0.02) err(`camera:${c.id}`, `The camera ${c.id} puts its horizon at ${c.horizonY}, the picture's advisory horizon (${horizon.why}): a reading under ${CONFIDENT} never sets a camera's horizonY.`)
176
+ }
177
+ return out
178
+ }
179
+
180
+ /**
181
+ * The read-back's answer as errors for INTERPRET's repair: each trait the
182
+ * picture shows that the brief lacks (a subject to add) or contradicts (a
183
+ * subject to fix, by its id, or a form or camera to fix and a subject to
184
+ * give it). A trait with no place in the picture, or one in its masked
185
+ * lettering, is not the game's and is left out.
186
+ */
187
+ export function readbackErrors(answer, brief, facts) {
188
+ const out = []
189
+ const subjects = brief?.subjects ?? []
190
+ const lettering = (facts?.text?.boxes ?? []).map((t) => t.box)
191
+ for (const [i, t] of (answer?.traits ?? []).entries()) {
192
+ if (!isBox(t.box) || areaOf(t.box) < 0.0005) continue
193
+ if (lettering.length && covered(t.box, lettering) > 0.6) continue
194
+ const named = t.kind === 'contradicts' ? subjects.find((s) => s.id === t.subject) : null
195
+ if (named) {
196
+ out.push({ key: `readback:${named.id}:${i + 1}`, text: `Read against the picture, the subject ${named.id} (${named.what}) is contradicted at ${boxText(t.box)}: ${t.what} (${t.why}). Fix its form, size or box to what the picture shows, or say in an assumption that names ${named.id} why the game departs from it.` })
197
+ } else if (t.kind === 'contradicts') {
198
+ out.push({ key: `readback:contradicts:${i + 1}`, text: `Read against the picture, the brief contradicts it at ${boxText(t.box)}: ${t.what} (${t.why}). Give what is there a subject, and fix the form or the camera that says otherwise to what the picture shows.` })
199
+ } else {
200
+ out.push({ key: `readback:missing:${i + 1}`, text: `Read against the picture, the brief lacks ${t.what} at ${boxText(t.box)} (${t.why}): give it a subject (keep it, or transform it into an original thing of the same role, place and size in the frame), with its form when it stands in the game.` })
201
+ }
202
+ }
203
+ return out
204
+ }
205
+
206
+ /**
207
+ * The read-back's traits a repair of the brief still does not answer, as
208
+ * error lines (readbackErrors, against the repair): a thing missing that
209
+ * no subject of the repair boxes at about its size; a named subject's
210
+ * contradiction when the repair left the subject, its form and the
211
+ * assumptions that name it as they were; a contradiction that names no
212
+ * subject (a form, a camera) when the repair changed neither its forms nor
213
+ * its cameras and boxes nothing there that the first answer did not.
214
+ */
215
+ export function unanswered(answer, before, after, facts) {
216
+ const boxesOf = (brief, size) => (brief?.subjects ?? []).filter((s) => isBox(s.box) && areaOf(s.box) <= COVER * Math.max(size, 0.02)).map((s) => s.box)
217
+ const was = (brief, id) => {
218
+ const s = (brief?.subjects ?? []).find((x) => x.id === id)
219
+ return JSON.stringify([s ?? null, formOf(brief, s), (brief?.assumptions ?? []).filter((a) => assumes({ assumptions: [a] }, id))])
220
+ }
221
+ const kept = (key) => JSON.stringify(before?.[key] ?? null) === JSON.stringify(after?.[key] ?? null)
222
+ const left = new Set()
223
+ for (const [i, t] of (answer?.traits ?? []).entries()) {
224
+ if (!isBox(t.box)) continue
225
+ const boxed = (brief) => covered(t.box, boxesOf(brief, areaOf(t.box))) >= 0.5
226
+ const named = t.kind === 'contradicts' && (before?.subjects ?? []).some((x) => x.id === t.subject)
227
+ if (t.kind !== 'contradicts' ? !boxed(after) : named ? was(before, t.subject) === was(after, t.subject) : kept('forms') && kept('cameras') && (boxed(before) || !boxed(after))) left.add(i + 1)
228
+ }
229
+ // Each error's key ends in its trait's place in the answer.
230
+ return readbackErrors(answer, after, facts).filter((e) => left.has(Number(e.key.split(':').at(-1))))
231
+ }
232
+
233
+ /**
234
+ * The map the subjects need, in tiles (100 * sqrt(tiles) metres a side):
235
+ * the largest footprint of a subject that stands in the game, or the width
236
+ * the subjects span across the picture in metres (each sized subject's
237
+ * footprint over its box's width gives the picture's metres there), with a
238
+ * quarter more for room, whichever is larger. null when no subject in the
239
+ * game has a sized form: the builder decides then, and says so.
240
+ */
241
+ export function mapOf(brief) {
242
+ const standing = (brief?.subjects ?? []).filter((s) => s.kind !== 'atmosphere' && isBox(s.box))
243
+ const foot = (f) => Math.max(Number(f?.sizeM?.w) || 0, Number(f?.sizeM?.d) || 0)
244
+ const sized = standing.map((s) => ({ s, f: formOf(brief, s) })).filter(({ f }) => foot(f) > 0)
245
+ if (!sized.length) return null
246
+ const largest = Math.max(...sized.map(({ f }) => foot(f)))
247
+ const perWidth = median(sized.map(({ s, f }) => foot(f) / (s.box[2] - s.box[0])))
248
+ const across = perWidth * (Math.max(...standing.map((s) => s.box[2])) - Math.min(...standing.map((s) => s.box[0])))
249
+ const span = Math.max(largest, across)
250
+ const tiles = Math.min(4096, Math.max(1, Math.ceil(((1.25 * span) / 100) ** 2)))
251
+ return {
252
+ tiles,
253
+ sideM: Math.round(100 * Math.sqrt(tiles)),
254
+ why: `the subjects in the game span about ${Math.round(across)} m across the picture and the largest stands ${Math.round(largest)} m wide (${sized.map(({ s, f }) => `${s.id} ${foot(f)} m`).join(', ')}), with a quarter more for room`,
255
+ }
256
+ }
257
+
258
+ /**
259
+ * What code sets in a brief from its facts, never a model: the reference
260
+ * camera's aspect (the picture's shape) and its horizonY (the horizon's, when
261
+ * it reads at CONFIDENT or more; none otherwise, with an assumption saying
262
+ * so when the brief gave one), each subject's proportion in the picture
263
+ * beside its form's, and the map. Returns a new brief.
264
+ */
265
+ export function settleBrief(brief, facts) {
266
+ const out = structuredClone(brief)
267
+ out.subjects ??= []
268
+ if (facts) {
269
+ const ref = (out.cameras ?? []).find((c) => c.purpose === 'reference')
270
+ if (ref) {
271
+ ref.aspect = facts.size?.shape ?? ref.aspect
272
+ const hz = facts.horizon
273
+ if (hz?.y !== null && hz?.y !== undefined && hz.confidence >= CONFIDENT) ref.horizonY = Math.round(hz.y * 1000) / 1000
274
+ else if (ref.horizonY !== undefined) {
275
+ delete ref.horizonY
276
+ const why = advisoryOf(facts).find((a) => a.fact === 'horizon')?.why ?? 'no horizon was read'
277
+ out.assumptions = [...(out.assumptions ?? []), { what: `the ${ref.id} camera sets no horizon height: its framing follows the picture by eye`, why: `${why}, under ${CONFIDENT}`, confidence: 'high' }].slice(-16)
278
+ }
279
+ }
280
+ for (const s of out.subjects) {
281
+ if (!isBox(s.box)) continue
282
+ const want = formTall(formOf(out, s))
283
+ s.proportion = { picture: r2(pictureTall(s, facts)), form: want === null ? null : r2(want) }
284
+ }
285
+ }
286
+ const map = mapOf(out)
287
+ if (map) out.map = map
288
+ else delete out.map
289
+ return out
290
+ }
291
+
292
+ // ---------------------------------------------------------------- the subjects in pictures
293
+
294
+ /** A box of the art (the picture as the facts read it, after `crop`) as a
295
+ * box of the whole picture. */
296
+ export const toWhole = (box, crop) => (crop ? [crop[0] + box[0] * (crop[2] - crop[0]), crop[1] + box[1] * (crop[3] - crop[1]), crop[0] + box[2] * (crop[2] - crop[0]), crop[1] + box[3] * (crop[3] - crop[1])] : box)
297
+
298
+ /** The colour each subject's box is drawn in, by its order: [name, rgb]. */
299
+ export const markOf = (i) => MARKS[i % MARKS.length]
300
+
301
+ /**
302
+ * The reference with each subject's box drawn on it in its colour (markOf),
303
+ * for the read-back: { mime, data } or null when the picture cannot be
304
+ * decoded. `crop` is the facts' crop of the whole picture, if any.
305
+ */
306
+ export async function subjectsPicture(image, subjects, crop = null) {
307
+ if (!image?.data || !subjects?.length) return null
308
+ const pic = await decodeImage(Buffer.from(image.data, 'base64'), { mime: image.mime, maxEdge: 1024 })
309
+ if (!pic.ok) return null
310
+ const out = blit(canvas(pic.width, pic.height), pic, 0, 0)
311
+ const thick = Math.max(2, Math.round(Math.max(pic.width, pic.height) / 256))
312
+ subjects.forEach((s, i) => {
313
+ if (!isBox(s.box)) return
314
+ const [x0, y0, x1, y1] = toWhole(s.box, crop).map((v, k) => Math.round(v * ((k % 2 ? pic.height : pic.width) - 1)))
315
+ const rgb = markOf(i)[1]
316
+ line(out, x0, y0, x1, y0, rgb, thick)
317
+ line(out, x0, y1, x1, y1, rgb, thick)
318
+ line(out, x0, y0, x0, y1, rgb, thick)
319
+ line(out, x1, y0, x1, y1, rgb, thick)
320
+ })
321
+ return { mime: 'image/png', data: encodePng(out).toString('base64') }
322
+ }
323
+
324
+ /**
325
+ * The reference cut to each named subject's box (with a tenth of it round
326
+ * the edge), at most 512 px on the long edge, for the critic to judge form
327
+ * against: [{ id, what, role, image }], in the order the ids come.
328
+ */
329
+ export async function subjectCrops(image, subjects, ids, crop = null) {
330
+ const wanted = [...new Set(ids)].map((id) => (subjects ?? []).find((s) => s.id === id)).filter((s) => s && isBox(s.box))
331
+ if (!image?.data || !wanted.length) return []
332
+ const pic = await decodeImage(Buffer.from(image.data, 'base64'), { mime: image.mime, maxEdge: 1568 })
333
+ if (!pic.ok) return []
334
+ return wanted.map((s) => {
335
+ const [x0, y0, x1, y1] = toWhole(s.box, crop)
336
+ const mx = 0.1 * (x1 - x0)
337
+ const my = 0.1 * (y1 - y0)
338
+ const cut = fitEdge(cropPicture(pic, [Math.max(0, x0 - mx), Math.max(0, y0 - my), Math.min(1, x1 + mx), Math.min(1, y1 + my)]), 512)
339
+ return { id: s.id, what: s.what, role: s.role, image: { mime: 'image/png', data: encodePng(cut).toString('base64') } }
340
+ })
341
+ }