diff --git a/docs/achievements.md b/docs/achievements.md index 4ad5a82c..3ea41eec 100644 --- a/docs/achievements.md +++ b/docs/achievements.md @@ -7,7 +7,7 @@ or a claim that achievements have been enabled on the hosted service. ## Hook contract -- `achievementDefinitions()` returns `{ revision: 2, achievements }`. Each definition +- `achievementDefinitions()` returns `{ revision: 3, achievements }`. Each definition has string `id`, `name`, and `description` fields and an optional strict `icon`: `{ type: "asset", key: string }` or `{ type: "text", text: string }`. Asset keys match `^[a-z0-9][a-z0-9-]{0,63}$`; text matches `^[A-Za-z0-9]{1,4}$`. No URLs, @@ -41,19 +41,21 @@ player order after removing Automa players; they are not raw engine player numbe Automa never receives a result. Dropped humans retain their human seat index and return `{ seat, earned: [] }`, with no outcome, rather than shifting later seats. -## Revision 2 catalog (36 stable IDs) +## Revision 3 catalog (36 stable IDs) IDs follow BGS's `^[a-z0-9][a-z0-9-]{0,63}$` validator: lowercase letters, ASCII digits, and hyphens, at most 64 characters. All 36 IDs are unique. The pre-publication dotted spellings were replaced with hyphens; they are not aliases -and were never published. Revision 2 adds icons without changing revision 1's IDs -or earned predicates: 18 faction asset references, four 150/200 text emblems, -and no icon on the remaining 14 definitions. +and were never published. Revision 2 added 18 faction asset references and four +150/200 text emblems. Revision 3 replaces those text emblems with two shared +raster score assets: `achievement-score-150` and `achievement-score-200`. +All 36 IDs and earned predicates remain unchanged. There are 22 icon-bearing +definitions referencing 20 unique assets; the remaining 14 definitions have no icon. **Deployment order:** the platform icon contract (platform commit `fca050c9509c1dec3afd8d4631cc57245f834f29`, platform PR [578](https://codeberg.org/boardgamers/boardgamers/pulls/578)) must be deployed -before activating this revision-2 manifest. Older strict validators reject `icon`. +before activating this revision-3 manifest. Older strict validators reject `icon`. No production assets or achievement activation are implied by this source change. ### Faction victories (18) @@ -154,8 +156,12 @@ count toward their separate shared-civilization feat. ## Portrait assets and release procedure Faction win icons reference **named game assets**, not viewer-bundle URLs: -`achievement-faction-`. Score badges use platform-rendered text `150` -or `200`, shared across the two rulesets, and require no uploaded image. +`achievement-faction-`. Score badges reference uploaded raster assets +`achievement-score-150` and `achievement-score-200`, shared across the two rulesets. +They include the authentic approved BGS Gaia pictogram and large score numerals, +not a plain text emblem or an invented logo. The approved pictogram is vendored +as a reproducible source with its original URL and SHA-256 recorded alongside it; +generation requires no network access. Source artwork is in `viewer/src/assets/factions/*.jpg`, with provenance in [`viewer/src/assets/factions/README.md`](../viewer/src/assets/factions/README.md). @@ -171,15 +177,24 @@ pnpm run generate:achievement-portraits pnpm run test:achievement-portraits ``` -The generator crops a 167×167 square at x=13, y=0 from each 392×167 header, -matching the existing viewer's left-side portrait framing. Outputs are square -raster PNGs without a baked-in circular mask; the platform controls presentation. +The generator crops a 167×167 square at x=13, y=0 from each 392×167 faction header, +matching the existing viewer's left-side portrait framing. Faction outputs are +square raster PNGs without a baked-in circular mask; the platform controls +presentation. Score artwork uses a dark space background and circular metallic +framing (silver for 150, gold for 200), the approved Gaia pictogram and large +numerals from pinned licensed raster glyphs. No system font, network fetch or +arbitrary SVG/HTML payload is used during generation. Outputs are written to `artifacts/achievement-portraits/`: 18 -`achievement-faction-.png` files, `contact-sheet.png` (all 18 labeled crops), -and `manifest.json` recording source/output hashes, crop coordinates and toolchain. -Review all 18 crops on the generated contact sheet before uploading. Generated -assets are ignored build outputs, not committed artwork copies. The source map, -crop coordinates and dependency lockfile are the reproducible inputs. +`achievement-faction-.png` files, two 512×512 score files +`achievement-score-150.png` / `achievement-score-200.png`, +`contact-sheet.png` (all 18 labeled faction crops), `score-contact-sheet.png` +(including small-size score previews), and `manifest.json` recording source/output +hashes, crop coordinates and toolchain. Score source provenance is documented in +[`scripts/assets/achievement-scores/README.md`](../scripts/assets/achievement-scores/README.md). +Review faction crops and score artwork at full and badge sizes before uploading. +Generated assets are ignored build outputs, not committed artwork copies. The +source map, approved pictogram, crop coordinates and dependency lockfile are the +reproducible inputs. **Release only after separate publication authorization:** @@ -187,17 +202,23 @@ crop coordinates and dependency lockfile are the reproducible inputs. engine's icon manifest against an older strict schema. 2. Generate and visually inspect the portraits locally. Keep the generated input/output hash manifest with the release verification record. -3. For each generated `achievement-faction-.png`, upload its raw bytes to - `PUT /api/admin/gameinfo/gaia-project/assets/achievement-faction-` with +3. Upload the raw bytes of all 20 image files (18 `achievement-faction-.png` + plus `achievement-score-150.png` and `achievement-score-200.png`) to + `PUT /api/admin/gameinfo/gaia-project/assets/` with `Content-Type: image/png` and the authorized admin bearer token. This is the **version-independent named game asset** endpoint, not `/gaia-project/3/viewer`. - Do not upload the contact sheet or hash manifest as achievement images. + Do not upload contact sheets or the hash manifest as achievement images. 4. BGS re-encodes images to WebP and records the content-hashed URL under the - metadata asset key. Verify all 18 keys resolve to the expected portraits and + metadata asset key. Verify all 20 keys resolve to the expected artwork and verify the platform fallback for a missing asset. Do not invent public URLs or embed them in engine definitions; viewer-bundle retention is irrelevant. -5. Only then publish/activate the engine/catalog through the normal authorized - release workflow and verify portraits and 150/200 emblems in the platform UI. +5. For local platform review, its author must upload these real named assets to + the local environment **before capturing UI screenshots**. Do not intercept + image requests or inject replacement images to simulate a successful upload. + Local upload does not authorize production upload or activation. +6. Only after production release authorization publish/activate the engine/catalog + through the normal release workflow and verify portraits and score artwork in + the platform UI. Deploy the platform icon support before catalog activation. This PR generates inputs only: no named asset is claimed to exist in production, and no upload, engine publication, npm publication or BGS activation is performed. diff --git a/engine/README.md b/engine/README.md index a42870e5..94c41301 100644 --- a/engine/README.md +++ b/engine/README.md @@ -4,7 +4,7 @@ Javascript engine for Gaia Project. ## Achievements -See the [achievement hooks and revision 2 catalog](../docs/achievements.md) for the +See the [achievement hooks and revision 3 catalog](../docs/achievements.md) for the optional BGS contract, completion requirements, award semantics, and verification scope. ## Play online at diff --git a/engine/achievements.spec.ts b/engine/achievements.spec.ts index 8b153e9b..96888c6f 100644 --- a/engine/achievements.spec.ts +++ b/engine/achievements.spec.ts @@ -54,10 +54,10 @@ function solo(difficulty = "automa"): Record { } describe("BGS achievement hooks", () => { - it("exports a complete, unique, isolated revision-2 catalog", () => { + it("exports a complete, unique, isolated revision-3 catalog", () => { const manifest = achievementDefinitions(); const ids = manifest.achievements.map((definition) => definition.id); - expect(manifest.revision).to.equal(2); + expect(manifest.revision).to.equal(3); expect(ids).to.have.length(36); expect(new Set(ids).size).to.equal(ids.length); // BGS packages/protocol/achievements.ts: achievementIdSchema. @@ -69,12 +69,14 @@ describe("BGS achievement hooks", () => { expect(achievementDefinitions().achievements[0].name).not.to.equal("mutated"); }); - it("adds only 18 named faction assets and four score text emblems without changing IDs", () => { + it("references 18 faction assets and two shared score assets without changing IDs", () => { const definitions = achievementDefinitions().achievements; const assets = definitions.filter((definition) => definition.icon?.type === "asset"); const texts = definitions.filter((definition) => definition.icon?.type === "text"); - expect(assets).to.have.length(18); - expect(texts).to.have.length(4); + expect(assets).to.have.length(22); + expect(texts).to.have.length(0); + const keys = assets.map((definition) => (definition.icon.type === "asset" ? definition.icon.key : "")); + expect(new Set(keys).size).to.equal(20); for (const faction of Faction.values(Expansion.All)) { expect(definitions.find((definition) => definition.id === `win-faction-${faction}`).icon).to.deep.equal({ type: "asset", @@ -84,8 +86,8 @@ describe("BGS achievement hooks", () => { for (const mode of ["base", "lost-fleet"]) { for (const score of [150, 200]) { expect(definitions.find((definition) => definition.id === `score-${mode}-${score}`).icon).to.deep.equal({ - type: "text", - text: String(score), + type: "asset", + key: `achievement-score-${score}`, }); } } diff --git a/engine/src/achievements.ts b/engine/src/achievements.ts index 99e7d50a..f5bef57d 100644 --- a/engine/src/achievements.ts +++ b/engine/src/achievements.ts @@ -69,7 +69,7 @@ export function achievementDefinitions(): AchievementManifest { for (const threshold of [150, 200]) { definitions.push({ id: `score-${mode}-${threshold}`, - icon: { type: "text", text: String(threshold) }, + icon: { type: "asset", key: `achievement-score-${threshold}` }, name: `${name}: ${threshold} Points`, description: `Finish a ${name} game with at least ${threshold} final victory points, after auction deductions. No win required.`, }); @@ -123,7 +123,7 @@ export function achievementDefinitions(): AchievementManifest { description: "As Bescods, finish at level 3 or higher on all six research tracks. No win required.", } ); - return { revision: 2, achievements: definitions }; + return { revision: 3, achievements: definitions }; } /** Evaluate authoritative completed state only; never advance play or recompute final scoring. */ diff --git a/scripts/achievement-portraits.test.mjs b/scripts/achievement-portraits.test.mjs index 77e58f31..63818f7f 100644 --- a/scripts/achievement-portraits.test.mjs +++ b/scripts/achievement-portraits.test.mjs @@ -7,6 +7,10 @@ import sharp from "sharp"; import { CROP, FACTIONS, + ROOT, + SCORES, + SCORE_RENDER, + SCORE_SOURCE_DIR, SOURCE_DIR, generatePortraits, sha256, @@ -42,6 +46,12 @@ test("generation is byte-deterministic, exact pixel crops, labeled contact sheet const before = new Map( await Promise.all(sourceFiles.map(async (name) => [name, sha256(await readFile(path.join(SOURCE_DIR, name)))])) ); + const scoreSourceFiles = await readdir(SCORE_SOURCE_DIR); + const scoreBefore = new Map( + await Promise.all( + scoreSourceFiles.map(async (name) => [name, sha256(await readFile(path.join(SCORE_SOURCE_DIR, name)))]) + ) + ); try { const first = path.join(temporary, "first"); const second = path.join(temporary, "second"); @@ -49,6 +59,8 @@ test("generation is byte-deterministic, exact pixel crops, labeled contact sheet assert.deepEqual(await generatePortraits(second), manifest); const expectedFiles = [ ...FACTIONS.map((id) => `achievement-faction-${id}.png`), + ...SCORES.map((score) => `achievement-score-${score}.png`), + "score-contact-sheet.png", "contact-sheet.png", "manifest.json", ].sort(); @@ -57,6 +69,57 @@ test("generation is byte-deterministic, exact pixel crops, labeled contact sheet for (const name of expectedFiles) assert.deepEqual(await readFile(path.join(first, name)), await readFile(path.join(second, name))); assert.deepEqual(JSON.parse(await readFile(path.join(first, "manifest.json"), "utf8")), manifest); + assert.deepEqual(SCORES, [150, 200]); + assert.equal(manifest.schemaVersion, 2); + assert.deepEqual(manifest.scoreRender, SCORE_RENDER); + assert.deepEqual( + manifest.scores.map((item) => item.score), + [150, 200] + ); + assert.equal(manifest.generator.sha256, sha256(await readFile(path.join(ROOT, manifest.generator.path)))); + assert.deepEqual(manifest.toolchain.libraries, sharp.versions); + assert.deepEqual( + manifest.scoreInputs.map((item) => path.basename(item.path)), + ["gaia-pictogram.webp", "digit-0.png", "digit-1.png", "digit-2.png", "digit-5.png"] + ); + for (const input of manifest.scoreInputs) { + const bytes = await readFile(path.join(ROOT, input.path)); + assert.equal(input.sha256, sha256(bytes)); + const metadata = await sharp(bytes).metadata(); + assert.equal(input.width, metadata.width); + assert.equal(input.height, metadata.height); + } + assert.equal(manifest.scoreInputs[0].sha256, "09bdce75fb8e0020a1b52e9e4352d62bced93b117e94704549e0662e04093a62"); + assert.notEqual(manifest.scores[0].output.sha256, manifest.scores[1].output.sha256); + for (const item of [...manifest.scores.map((s) => s.output), manifest.scoreContactSheet]) { + const png = await readFile(path.join(first, item.path)); + assert.equal(sha256(png), item.sha256); + const metadata = await sharp(png).metadata(); + assert.equal(metadata.format, "png"); + assert.equal(metadata.width, item.width); + assert.equal(metadata.height, item.height); + const stats = await sharp(png).removeAlpha().stats(); + assert.ok(stats.entropy > 4, "Nontrivial raster detail"); + for (const channel of stats.channels.slice(0, 3)) assert.ok(channel.stdev > 30); + } + const scoreSheet = path.join(first, "score-contact-sheet.png"); + for (const [index, item] of manifest.scores.entries()) { + assert.equal(item.output.width, 512); + assert.equal(item.output.height, 512); + const badge = path.join(first, item.output.path); + const full = await sharp(scoreSheet) + .extract({ left: 16 + index * 544, top: 16, width: 512, height: 512 }) + .raw() + .toBuffer(); + assert.deepEqual(full, await sharp(badge).raw().toBuffer()); + for (const [i, size] of [64, 48, 32].entries()) { + const preview = await sharp(scoreSheet) + .extract({ left: 152 + index * 544 + i * 88, top: 552, width: size, height: size }) + .raw() + .toBuffer(); + assert.deepEqual(preview, await sharp(badge).resize(size, size).raw().toBuffer()); + } + } assert.equal(manifest.portraits.length, 18); for (const item of manifest.portraits) { const original = await readFile(path.join(SOURCE_DIR, sourceName(item.faction))); @@ -105,6 +168,9 @@ test("generation is byte-deterministic, exact pixel crops, labeled contact sheet } } finally { await rm(temporary, { recursive: true, force: true }); + assert.deepEqual(await readdir(SCORE_SOURCE_DIR), scoreSourceFiles); + for (const [name, hash] of scoreBefore) + assert.equal(sha256(await readFile(path.join(SCORE_SOURCE_DIR, name))), hash, `Score source modified: ${name}`); assert.deepEqual(await readdir(SOURCE_DIR), sourceFiles); for (const [name, hash] of before) assert.equal(sha256(await readFile(path.join(SOURCE_DIR, name))), hash, `Source modified: ${name}`); diff --git a/scripts/assets/achievement-scores/FONT-LICENSE.txt b/scripts/assets/achievement-scores/FONT-LICENSE.txt new file mode 100644 index 00000000..32597449 --- /dev/null +++ b/scripts/assets/achievement-scores/FONT-LICENSE.txt @@ -0,0 +1,51 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: DejaVu fonts +Upstream-Author: Stepan Roh (original author), + see /usr/share/doc/fonts-dejavu-core/AUTHORS for full list +Source: https://dejavu-fonts.github.io/ + +Files: * +Copyright: Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. + Bitstream Vera is a trademark of Bitstream, Inc. + DejaVu changes are in public domain. +License: bitstream-vera + Permission is hereby granted, free of charge, to any person obtaining a copy + of the fonts accompanying this license ("Fonts") and associated + documentation files (the "Font Software"), to reproduce and distribute the + Font Software, including without limitation the rights to use, copy, merge, + publish, distribute, and/or sell copies of the Font Software, and to permit + persons to whom the Font Software is furnished to do so, subject to the + following conditions: + . + The above copyright and trademark notices and this permission notice shall + be included in all copies of one or more of the Font Software typefaces. + . + The Font Software may be modified, altered, or added to, and in particular + the designs of glyphs or characters in the Fonts may be modified and + additional glyphs or characters may be added to the Fonts, only if the fonts + are renamed to names not containing either the words "Bitstream" or the word + "Vera". + . + This License becomes null and void to the extent applicable to Fonts or Font + Software that has been modified and is distributed under the "Bitstream + Vera" names. + . + The Font Software may be sold as part of a larger software package but no + copy of one or more of the Font Software typefaces may be sold by itself. + . + THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, + TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME + FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING + ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF + THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE + FONT SOFTWARE. + . + Except as contained in this notice, the names of Gnome, the Gnome + Foundation, and Bitstream Inc., shall not be used in advertising or + otherwise to promote the sale, use or other dealings in this Font Software + without prior written authorization from the Gnome Foundation or Bitstream + Inc., respectively. For further information, contact: fonts at gnome dot + org. diff --git a/scripts/assets/achievement-scores/README.md b/scripts/assets/achievement-scores/README.md new file mode 100644 index 00000000..7dd813d6 --- /dev/null +++ b/scripts/assets/achievement-scores/README.md @@ -0,0 +1,32 @@ +# Achievement score source artwork + +These are version-controlled **source inputs**, not generated badge outputs. Do not replace them with the unrelated icons under `viewer/public`. + +## Gaia Project pictogram + +`gaia-pictogram.webp` is the approved Boardgamers.space (BGS) Gaia Project pictogram, copied byte-for-byte from: + +https://s3.fr-par.scw.cloud/bgs-assets/assets/gaia-project/pictogram/09bdce75fb8e0020/pictogram.webp + +SHA-256: `09bdce75fb8e0020a1b52e9e4352d62bced93b117e94704549e0662e04093a62` + +The generator verifies that digest. This provenance identifies the supplied artwork; it does not assert a new license for game artwork. The entire 256×256 transparent image is used, without cropping. + +## Pinned raster numerals + +`digit-{0,1,2,5}.png` are transparent, tightly bounded raster glyphs from DejaVu Sans Bold (Bitstream copyright; DejaVu changes public domain). See `FONT-LICENSE.txt` and https://dejavu-fonts.github.io/ . They are intentionally pinned so generation needs neither installed fonts nor text/SVG rendering. + +Source font SHA-256: `0d977336a6d5fba34eab8e3199eb218327161b5143749f802982c2bc34df0c96` (`DejaVuSans-Bold.ttf`). One-time rasterization used Sharp's text input with `{ text: digit, font: "DejaVu Sans Bold 800", fontfile: "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", rgba: true, dpi: 72 }`, followed by `.png().toFile(...)`. The badge generator uses only the resulting alpha masks, recolored with a gentle metallic gradient. No font is loaded at runtime. + +Pinned PNG SHA-256 values: + +- 0: `cbdbb951c1de0da3d280249c8197e9b66146ad3f3ca6920717049057117ca3ce` +- 1: `a1c07e26fe5cfa1b58552a7fd18723434d6d46c58fe1ffadbd831f94daac7d1c` +- 2: `f38ce297ccdd1b470e1e4a48210617d90a7a6e410570d303cfdf358be002e525` +- 5: `65975965deb89c3b546218ade0f2af28fecb4921278e1fa961a51568242e9b19` + +## Rendering and review + +Run `node scripts/generate-achievement-portraits.mjs`. The ignored `artifacts/achievement-portraits/` directory contains 512×512 score PNGs and `score-contact-sheet.png`: full-size 150 and 200 badges, followed by 64, 48 and 32 pixel previews from left to right below each. The original faction contact sheet and crops remain unchanged. + +Background, sparse stars and beveled rings are analytic raster graphics, supersampled at 4× and downsampled with Lanczos3. Silver distinguishes 150; gold distinguishes 200. All image input/output hashes, rendering geometry, generator hash and library versions are recorded in the manifest. Reproducibility is byte-for-byte for a fixed input/toolchain; no timestamp, random state, network fetch or system font participates. diff --git a/scripts/assets/achievement-scores/digit-0.png b/scripts/assets/achievement-scores/digit-0.png new file mode 100644 index 00000000..30e60659 Binary files /dev/null and b/scripts/assets/achievement-scores/digit-0.png differ diff --git a/scripts/assets/achievement-scores/digit-1.png b/scripts/assets/achievement-scores/digit-1.png new file mode 100644 index 00000000..81f27eda Binary files /dev/null and b/scripts/assets/achievement-scores/digit-1.png differ diff --git a/scripts/assets/achievement-scores/digit-2.png b/scripts/assets/achievement-scores/digit-2.png new file mode 100644 index 00000000..02f38501 Binary files /dev/null and b/scripts/assets/achievement-scores/digit-2.png differ diff --git a/scripts/assets/achievement-scores/digit-5.png b/scripts/assets/achievement-scores/digit-5.png new file mode 100644 index 00000000..7f8398d8 Binary files /dev/null and b/scripts/assets/achievement-scores/digit-5.png differ diff --git a/scripts/assets/achievement-scores/gaia-pictogram.webp b/scripts/assets/achievement-scores/gaia-pictogram.webp new file mode 100644 index 00000000..981c5763 Binary files /dev/null and b/scripts/assets/achievement-scores/gaia-pictogram.webp differ diff --git a/scripts/generate-achievement-portraits.mjs b/scripts/generate-achievement-portraits.mjs index abc3c0a1..2f6c239a 100644 --- a/scripts/generate-achievement-portraits.mjs +++ b/scripts/generate-achievement-portraits.mjs @@ -80,6 +80,147 @@ export function validateCrop(width, height, crop = CROP) { } } +export const SCORES = Object.freeze([150, 200]); +export const SCORE_SOURCE_DIR = path.join(ROOT, "scripts/assets/achievement-scores"); +export const SCORE_RENDER = Object.freeze({ + width: 512, + height: 512, + supersampling: 4, + pictogram: { left: 151, top: 57, width: 210, height: 210 }, + digitHeight: 132, + digitTop: 282, + digitGap: 12, +}); + +// Analytic raster shading, sampled at 4x. No SVG, fonts, clock, or random state. +async function renderScore(score, sources) { + const scale = SCORE_RENDER.supersampling; + const size = 512 * scale; + const data = Buffer.alloc(size * size * 3); + const gold = score === 200; + for (let y = 0; y < size; y++) + for (let x = 0; x < size; x++) { + const px = (x + 0.5) / scale - 256; + const py = (y + 0.5) / scale - 256; + const r = Math.hypot(px, py); + const angle = Math.atan2(py, px); + const glow = Math.exp(-((px + 65) ** 2 + (py + 100) ** 2) / 28000); + let color = [7 + 9 * glow, 13 + 21 * glow, 24 + 28 * glow]; + if (r < 228) { + const mist = (Math.sin(px / 39 + py / 61) + Math.cos(py / 31 - px / 70) + 2) / 4; + color = [9 + 8 * glow + 3 * mist, 19 + 26 * glow + 5 * mist, 32 + 32 * glow + 8 * mist]; + // Sparse, fixed star field; gentle points rather than visual noise. + for (const [sx, sy, radius] of [ + [-154, -116, 1.2], + [128, -126, 1.3], + [-176, 2, 1], + [159, 38, 1.4], + [-128, 169, 1], + [104, 174, 1.2], + [-69, -193, 0.8], + [173, -60, 0.8], + ]) { + const light = Math.max(0, 1 - Math.hypot(px - sx, py - sy) / (radius * 2)); + color = color.map((c) => c + 110 * light); + } + } + if (r >= 228 && r < 249) { + const bevel = Math.sin(((r - 228) / 21) * Math.PI); + const light = 0.52 + 0.32 * Math.cos(angle + 2.2) + 0.16 * Math.cos(angle * 3 - 1); + const metal = 48 + 170 * light * bevel; + color = gold ? [metal * 1.13, metal * 0.94, metal * 0.59] : [metal * 0.87, metal, metal * 1.08]; + if (r < 230 || r > 247) color = gold ? [150, 126, 74] : [119, 154, 170]; + if (r > 233 && r < 235) color = [24, 38, 46]; + } + if (r >= 249 && r < 252) color = [3, 7, 13]; + const offset = (y * size + x) * 3; + for (let c = 0; c < 3; c++) data[offset + c] = Math.min(255, Math.round(color[c])); + } + const layers = []; + const icon = SCORE_RENDER.pictogram; + layers.push({ + input: await sharp(sources.get("gaia-pictogram.webp")) + .resize(icon.width * scale, icon.height * scale) + .png(PNG) + .toBuffer(), + left: icon.left * scale, + top: icon.top * scale, + }); + const digits = []; + for (const digit of String(score)) { + const mask = await sharp(sources.get(`digit-${digit}.png`)) + .resize({ height: SCORE_RENDER.digitHeight * scale }) + .ensureAlpha() + .raw() + .toBuffer({ resolveWithObject: true }); + const { width, height, channels } = mask.info; + for (let y = 0; y < height; y++) + for (let x = 0; x < width; x++) { + const offset = (y * width + x) * channels; + const t = y / height; + const color = gold ? [255 - 22 * t, 247 - 43 * t, 209 - 65 * t] : [249 - 35 * t, 254 - 26 * t, 255 - 18 * t]; + for (let c = 0; c < 3; c++) mask.data[offset + c] = Math.round(color[c]); + } + digits.push({ input: mask.data, raw: { width, height, channels }, width }); + } + let left = Math.round((size - digits.reduce((sum, d) => sum + d.width, 0) - SCORE_RENDER.digitGap * scale * 2) / 2); + for (const { width, ...digit } of digits) { + layers.push({ ...digit, left, top: SCORE_RENDER.digitTop * scale }); + left += width + SCORE_RENDER.digitGap * scale; + } + const high = await sharp(data, { raw: { width: size, height: size, channels: 3 } }) + .composite(layers) + .png(PNG) + .toBuffer(); + return sharp(high).resize(512, 512, { kernel: "lanczos3" }).png(PNG).toBuffer(); +} + +async function generateScores() { + const sources = new Map(); + const inputs = []; + for (const name of ["gaia-pictogram.webp", "digit-0.png", "digit-1.png", "digit-2.png", "digit-5.png"]) { + const bytes = await readFile(path.join(SCORE_SOURCE_DIR, name)); + sources.set(name, bytes); + const { width, height } = await sharp(bytes).metadata(); + inputs.push({ path: `scripts/assets/achievement-scores/${name}`, sha256: sha256(bytes), width, height }); + } + if (inputs[0].sha256 !== "09bdce75fb8e0020a1b52e9e4352d62bced93b117e94704549e0662e04093a62") + throw new Error("Unapproved Gaia pictogram"); + const outputs = [], + scores = [], + layers = []; + for (const [index, score] of SCORES.entries()) { + const png = await renderScore(score, sources); + const filename = `achievement-score-${score}.png`; + outputs.push([filename, png]); + scores.push({ score, output: { path: filename, sha256: sha256(png), width: 512, height: 512 } }); + layers.push({ input: png, left: 16 + index * 544, top: 16 }); + for (const [i, size] of [64, 48, 32].entries()) + layers.push({ + input: await sharp(png).resize(size, size).png(PNG).toBuffer(), + left: 152 + index * 544 + i * 88, + top: 552, + }); + } + const sheet = await sharp({ create: { width: 1088, height: 640, channels: 3, background: "#181818" } }) + .composite(layers) + .png(PNG) + .toBuffer(); + outputs.push(["score-contact-sheet.png", sheet]); + return { + outputs, + inputs, + scores, + contactSheet: { + path: "score-contact-sheet.png", + sha256: sha256(sheet), + width: 1088, + height: 640, + previews: [64, 48, 32], + }, + }; +} + export async function generatePortraits(outputDir = OUTPUT_DIR) { // Only the destination changes in tests. Source files and crop policy are fixed. const files = (await readdir(SOURCE_DIR)).filter((name) => /\.jpe?g$/i.test(name)).sort(); @@ -124,8 +265,14 @@ export async function generatePortraits(outputDir = OUTPUT_DIR) { .composite(composites) .png(PNG) .toBuffer(); + const scoreAssets = await generateScores(); + outputs.push(...scoreAssets.outputs); const manifest = { - schemaVersion: 1, + schemaVersion: 2, + scoreInputs: scoreAssets.inputs, + scoreRender: SCORE_RENDER, + scores: scoreAssets.scores, + scoreContactSheet: scoreAssets.contactSheet, generator: { path: "scripts/generate-achievement-portraits.mjs", sha256: sha256(await readFile(fileURLToPath(import.meta.url))), @@ -165,6 +312,6 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me process.exitCode = 1; } else { await generatePortraits(); - console.log(`Generated 18 portraits, contact-sheet.png and manifest.json in ${OUTPUT_DIR}`); + console.log(`Generated 18 portraits, 2 score badges, both contact sheets and manifest.json in ${OUTPUT_DIR}`); } }