BlueGit

timfa questward

Add shared magenta material tint for potions, ores, bars, and tools.

One sprite per shape: R==B and G<R pixels recolor with preserved lightness; world and UI share the formula, then apply darkness in lit shaders.

timfa Tim Falken · pushed by timfa

Authored 2026-08-25 · 2 months ago

Hash
0ad31421b50d692511f97a59971e3ad00ea9b4d2
Parent
97347406
24 files changed +344 −90
client/assets/items/axe/axe-equip.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/axe/axe.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bar/bar.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/ore/ore.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/fill-1.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/fill-2.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/fill-3.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/fill-4.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/fill-5.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/potion-1.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/potion-2.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/potion-3.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/potion-4.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/potion-5.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/potion/potion.png Binary file +0 −0

The contents of this binary file are not shown.

client/src/render/potionIcon.js +48 −33
@@ -1,19 +1,29 @@
1 import { ItemId } from "/shared/definitions/items.js";
1 import { ItemId, itemDefinition, itemAssetPathForStack } from "/shared/definitions/items.js";
2 2 import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
3 import {
4 applyMagentaTintToImageData,
5 normalizeRgb,
6 resolveItemTint
7 } from "/shared/render/tint.js";
3 8
4 9 const bottleCache = new Map();
5 10 const fillCache = new Map();
6 11 const urlCache = new Map();
12 const imageCache = new Map();
7 13
8 14 function loadImage (src)
9 15 {
10 return new Promise((resolve, reject) =>
16 if (imageCache.has(src))
17 { return imageCache.get(src); }
18 const promise = new Promise((resolve, reject) =>
11 19 {
12 20 const img = new Image();
13 21 img.onload = () => resolve(img);
14 22 img.onerror = () => reject(new Error(`Failed to load ${src}`));
15 23 img.src = src;
16 24 });
25 imageCache.set(src, promise);
26 return promise;
17 27 }
18 28
19 29 async function getBottle ()
@@ -33,22 +43,19 @@ async function getFill (level)
33 43
34 44 function colorKey (color)
35 45 {
36 if (!color)
37 { return "0,0,0"; }
38 const r = Math.round((color.r ?? 0) * 255);
39 const g = Math.round((color.g ?? 0) * 255);
40 const b = Math.round((color.b ?? 0) * 255);
41 return `${r},${g},${b}`;
46 const c = normalizeRgb(color);
47 return `${Math.round(c.r * 255)},${Math.round(c.g * 255)},${Math.round(c.b * 255)}`;
42 48 }
43 49
44 50 /**
45 * Build a data-URL icon: clear bottle + fill mask tinted to potion color.
46 * UI-only; world ground items use the same bake then lit darkness shader.
51 * Bottle + magenta fill mask → tinted potion icon (UI).
52 * Fill sprites use magenta lightness; bottle stays non-magenta.
47 53 */
48 54 export async function potionIconDataUrl (instance)
49 55 {
50 56 const fillLevel = Math.max(1, Math.min(5, instance?.fillLevel | 0 || 4));
51 const key = `${fillLevel}|${colorKey(instance?.color)}`;
57 const tint = normalizeRgb(instance?.color);
58 const key = `potion|${fillLevel}|${colorKey(tint)}`;
52 59 if (urlCache.has(key))
53 60 { return urlCache.get(key); }
54 61
@@ -58,23 +65,9 @@ export async function potionIconDataUrl (instance)
58 65 canvas.height = SPRITE_SIZE_PX;
59 66 const ctx = canvas.getContext("2d");
60 67 ctx.clearRect(0, 0, canvas.width, canvas.height);
61
62 68 ctx.drawImage(fill, 0, 0);
63 69 const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
64 const data = image.data;
65 const r = Math.round((instance?.color?.r ?? 0.4) * 255);
66 const g = Math.round((instance?.color?.g ?? 0.4) * 255);
67 const b = Math.round((instance?.color?.b ?? 0.7) * 255);
68 for (let i = 0; i < data.length; i += 4)
69 {
70 if (data[i + 3] < 8)
71 { continue; }
72 const a = data[i + 3] / 255;
73 data[i] = r;
74 data[i + 1] = g;
75 data[i + 2] = b;
76 data[i + 3] = Math.round(220 * a);
77 }
70 applyMagentaTintToImageData(image, tint);
78 71 ctx.putImageData(image, 0, 0);
79 72 ctx.drawImage(bottle, 0, 0);
80 73
@@ -83,23 +76,45 @@ export async function potionIconDataUrl (instance)
83 76 return url;
84 77 }
85 78
79 /** Tint magenta pixels in an arbitrary item PNG for UI icons. */
80 export async function tintedItemIconDataUrl (assetPath, tint)
81 {
82 const key = `item|${assetPath}|${colorKey(tint)}`;
83 if (urlCache.has(key))
84 { return urlCache.get(key); }
85 const img = await loadImage(assetPath);
86 const canvas = document.createElement("canvas");
87 canvas.width = img.width || SPRITE_SIZE_PX;
88 canvas.height = img.height || SPRITE_SIZE_PX;
89 const ctx = canvas.getContext("2d");
90 ctx.clearRect(0, 0, canvas.width, canvas.height);
91 ctx.drawImage(img, 0, 0);
92 const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
93 applyMagentaTintToImageData(image, tint);
94 ctx.putImageData(image, 0, 0);
95 const url = canvas.toDataURL("image/png");
96 urlCache.set(key, url);
97 return url;
98 }
99
86 100 export function isPotionStack (stack)
87 101 {
88 102 return stack?.itemId === ItemId.potion && stack.instance?.kind === "potion";
89 103 }
90 104
91 /** Sync helper: set img.src to recolored potion or fall back to asset path. */
105 /** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */
92 106 export function applyItemIcon (img, stack, fallbackPath)
93 107 {
94 108 if (!img)
95 109 { return; }
96 if (!isPotionStack(stack))
97 {
98 img.src = fallbackPath;
99 return;
100 }
101 110 img.src = fallbackPath;
102 potionIconDataUrl(stack.instance).then((url) =>
111 const tint = resolveItemTint(stack, itemDefinition(stack?.itemId));
112 if (!tint)
113 { return; }
114 const work = isPotionStack(stack)
115 ? potionIconDataUrl(stack.instance)
116 : tintedItemIconDataUrl(fallbackPath || itemAssetPathForStack(stack), tint);
117 work.then((url) =>
103 118 {
104 119 img.src = url;
105 120 }).catch(() =>
@@ -1,19 +1,29 @@
1import { ItemId } from "/shared/definitions/items.js";
1import { ItemId, itemDefinition, itemAssetPathForStack } from "/shared/definitions/items.js";
2import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
3import {
4 applyMagentaTintToImageData,
5 normalizeRgb,
6 resolveItemTint
7} from "/shared/render/tint.js";
3
8
4const bottleCache = new Map();
9const bottleCache = new Map();
5const fillCache = new Map();
10const fillCache = new Map();
6const urlCache = new Map();
11const urlCache = new Map();
12const imageCache = new Map();
7
13
8function loadImage (src)
14function loadImage (src)
9{
15{
10 return new Promise((resolve, reject) =>
16 if (imageCache.has(src))
17 { return imageCache.get(src); }
18 const promise = new Promise((resolve, reject) =>
11 {
19 {
12 const img = new Image();
20 const img = new Image();
13 img.onload = () => resolve(img);
21 img.onload = () => resolve(img);
14 img.onerror = () => reject(new Error(`Failed to load ${src}`));
22 img.onerror = () => reject(new Error(`Failed to load ${src}`));
15 img.src = src;
23 img.src = src;
16 });
24 });
25 imageCache.set(src, promise);
26 return promise;
17}
27}
18
28
19async function getBottle ()
29async function getBottle ()
@@ -33,22 +43,19 @@ async function getFill (level)
33
43
34function colorKey (color)
44function colorKey (color)
35{
45{
36 if (!color)
46 const c = normalizeRgb(color);
37 { return "0,0,0"; }
47 return `${Math.round(c.r * 255)},${Math.round(c.g * 255)},${Math.round(c.b * 255)}`;
38 const r = Math.round((color.r ?? 0) * 255);
39 const g = Math.round((color.g ?? 0) * 255);
40 const b = Math.round((color.b ?? 0) * 255);
41 return `${r},${g},${b}`;
42}
48}
43
49
44/**
50/**
45 * Build a data-URL icon: clear bottle + fill mask tinted to potion color.
51 * Bottle + magenta fill mask → tinted potion icon (UI).
46 * UI-only; world ground items use the same bake then lit darkness shader.
52 * Fill sprites use magenta lightness; bottle stays non-magenta.
47 */
53 */
48export async function potionIconDataUrl (instance)
54export async function potionIconDataUrl (instance)
49{
55{
50 const fillLevel = Math.max(1, Math.min(5, instance?.fillLevel | 0 || 4));
56 const fillLevel = Math.max(1, Math.min(5, instance?.fillLevel | 0 || 4));
51 const key = `${fillLevel}|${colorKey(instance?.color)}`;
57 const tint = normalizeRgb(instance?.color);
58 const key = `potion|${fillLevel}|${colorKey(tint)}`;
52 if (urlCache.has(key))
59 if (urlCache.has(key))
53 { return urlCache.get(key); }
60 { return urlCache.get(key); }
54
61
@@ -58,23 +65,9 @@ export async function potionIconDataUrl (instance)
58 canvas.height = SPRITE_SIZE_PX;
65 canvas.height = SPRITE_SIZE_PX;
59 const ctx = canvas.getContext("2d");
66 const ctx = canvas.getContext("2d");
60 ctx.clearRect(0, 0, canvas.width, canvas.height);
67 ctx.clearRect(0, 0, canvas.width, canvas.height);
61
62 ctx.drawImage(fill, 0, 0);
68 ctx.drawImage(fill, 0, 0);
63 const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
69 const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
64 const data = image.data;
70 applyMagentaTintToImageData(image, tint);
65 const r = Math.round((instance?.color?.r ?? 0.4) * 255);
66 const g = Math.round((instance?.color?.g ?? 0.4) * 255);
67 const b = Math.round((instance?.color?.b ?? 0.7) * 255);
68 for (let i = 0; i < data.length; i += 4)
69 {
70 if (data[i + 3] < 8)
71 { continue; }
72 const a = data[i + 3] / 255;
73 data[i] = r;
74 data[i + 1] = g;
75 data[i + 2] = b;
76 data[i + 3] = Math.round(220 * a);
77 }
78 ctx.putImageData(image, 0, 0);
71 ctx.putImageData(image, 0, 0);
79 ctx.drawImage(bottle, 0, 0);
72 ctx.drawImage(bottle, 0, 0);
80
73
@@ -83,23 +76,45 @@ export async function potionIconDataUrl (instance)
83 return url;
76 return url;
84}
77}
85
78
79/** Tint magenta pixels in an arbitrary item PNG for UI icons. */
80export async function tintedItemIconDataUrl (assetPath, tint)
81{
82 const key = `item|${assetPath}|${colorKey(tint)}`;
83 if (urlCache.has(key))
84 { return urlCache.get(key); }
85 const img = await loadImage(assetPath);
86 const canvas = document.createElement("canvas");
87 canvas.width = img.width || SPRITE_SIZE_PX;
88 canvas.height = img.height || SPRITE_SIZE_PX;
89 const ctx = canvas.getContext("2d");
90 ctx.clearRect(0, 0, canvas.width, canvas.height);
91 ctx.drawImage(img, 0, 0);
92 const image = ctx.getImageData(0, 0, canvas.width, canvas.height);
93 applyMagentaTintToImageData(image, tint);
94 ctx.putImageData(image, 0, 0);
95 const url = canvas.toDataURL("image/png");
96 urlCache.set(key, url);
97 return url;
98}
99
86export function isPotionStack (stack)
100export function isPotionStack (stack)
87{
101{
88 return stack?.itemId === ItemId.potion && stack.instance?.kind === "potion";
102 return stack?.itemId === ItemId.potion && stack.instance?.kind === "potion";
89}
103}
90
104
91/** Sync helper: set img.src to recolored potion or fall back to asset path. */
105/** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */
92export function applyItemIcon (img, stack, fallbackPath)
106export function applyItemIcon (img, stack, fallbackPath)
93{
107{
94 if (!img)
108 if (!img)
95 { return; }
109 { return; }
96 if (!isPotionStack(stack))
97 {
98 img.src = fallbackPath;
99 return;
100 }
101 img.src = fallbackPath;
110 img.src = fallbackPath;
102 potionIconDataUrl(stack.instance).then((url) =>
111 const tint = resolveItemTint(stack, itemDefinition(stack?.itemId));
112 if (!tint)
113 { return; }
114 const work = isPotionStack(stack)
115 ? potionIconDataUrl(stack.instance)
116 : tintedItemIconDataUrl(fallbackPath || itemAssetPathForStack(stack), tint);
117 work.then((url) =>
103 {
118 {
104 img.src = url;
119 img.src = url;
105 }).catch(() =>
120 }).catch(() =>
client/src/render/worldView.js +62 −42
@@ -2,7 +2,8 @@ import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BO
2 2 import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3 3 import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
4 4 import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
5 import { itemSpriteName } from "/shared/definitions/items.js";
5 import { itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
6 import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";
6 7 import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";
7 8 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
8 9 import { bakeChunkAtlases } from "./chunkBake.js";
@@ -86,20 +87,36 @@ const WATER_GROUND_FRAG = [
86 87 "}"
87 88 ].join("\n");
88 89
89 /** Potion bottle: recolor near-white liquid, then apply night darkness. */
90 const POTION_SPRITE_FRAG = [
90 /** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */
91 const TINT_LIT_SPRITE_FRAG = [
91 92 "precision mediump float;",
92 93 "varying vec2 v_texCoord;",
93 94 "uniform sampler2D u_texture;",
94 95 "uniform float u_darkness;",
95 "uniform vec3 u_potionColor;",
96 "uniform float u_strength;",
97 "uniform float u_wade;",
98 "uniform float u_spriteHeight;",
99 "uniform float u_useTint;",
100 "uniform vec3 u_tintColor;",
96 101 "void main() {",
97 102 " vec4 color = texture2D(u_texture, v_texCoord);",
98 103 " if (color.a <= 0.0) { discard; }",
104 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
105 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
99 106 " vec3 rgb = color.rgb;",
100 " float liquid = step(0.95, min(min(color.r, color.g), color.b));",
101 " rgb = mix(rgb, u_potionColor, liquid);",
107 " if (u_useTint > 0.5) {",
108 " float eps = 1.0 / 255.0;",
109 " if (abs(color.r - color.b) <= eps && color.g < color.r - eps) {",
110 " float L = color.r;",
111 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
112 " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;",
113 " }",
114 " }",
115 " if (u_wade > 0.5 && fromBottom < 5.0) {",
116 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
117 " }",
102 118 " rgb = mix(rgb, vec3(0.0), u_darkness);",
119 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
103 120 " gl_FragColor = vec4(rgb, color.a);",
104 121 "}"
105 122 ].join("\n");
@@ -128,7 +145,7 @@ const ATLAS_LIGHTING_FRAG = [
128 145 let spriteLightingShader = null;
129 146 let atlasLightingShader = null;
130 147 let waterGroundShader = null;
131 let potionSpriteShader = null;
148 let tintLitSpriteShader = null;
132 149
133 150 function getSpriteLightingShader ()
134 151 {
@@ -151,11 +168,11 @@ function getWaterGroundShader ()
151 168 return waterGroundShader;
152 169 }
153 170
154 function getPotionSpriteShader ()
171 function getTintLitSpriteShader ()
155 172 {
156 if (!potionSpriteShader)
157 { potionSpriteShader = Shader.fragment(POTION_SPRITE_FRAG); }
158 return potionSpriteShader;
173 if (!tintLitSpriteShader)
174 { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); }
175 return tintLitSpriteShader;
159 176 }
160 177
161 178 export class WorldView
@@ -392,7 +409,8 @@ export class WorldView
392 409 item.displayName = payload.displayName;
393 410 item.sprite = spriteName;
394 411 item.instance = payload.instance ?? null;
395 item.potionColor = potion?.color ?? null;
412 const stack = { itemId: payload.itemId, instance: payload.instance ?? null };
413 item.tintColor = resolveItemTint(stack, itemDefinition(payload.itemId));
396 414 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
397 415 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
398 416 }
@@ -930,6 +948,7 @@ export class WorldView
930 948 for (const overlay of entity.bloomOverlays ?? [])
931 949 { overlay.destroy(); }
932 950 entity.overlays = [];
951 entity.overlayTints = [];
933 952 entity.bloomOverlays = [];
934 953 for (const layer of layers.slice(1))
935 954 {
@@ -939,6 +958,11 @@ export class WorldView
939 958 const object = new GameObject(0, 0, image, SORT_ENTITY);
940 959 this.scene.addObject(object);
941 960 entity.overlays.push(object);
961 entity.overlayTints.push(
962 layer.tint
963 ? normalizeRgb(layer.tint)
964 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)
965 );
942 966 const bloomName = bloomCompanionName(layer.sprite);
943 967 const bloomImage = this.game.images[bloomName];
944 968 if (!bloomImage)
@@ -980,7 +1004,7 @@ export class WorldView
980 1004 const overlay = entity.overlays[index];
981 1005 const overlaySortY = entity.visualY + 0.5 * (index + 1);
982 1006 overlay.transform.rotation = walkTilt;
983 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
1007 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null);
984 1008 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
985 1009 }
986 1010 for (const overlay of entity.bloomOverlays ?? [])
@@ -1002,7 +1026,7 @@ export class WorldView
1002 1026 object.renderer.secondaryMap = null;
1003 1027 }
1004 1028
1005 #syncLitSprite (object, darkness, flashStrength = 0, wade = false)
1029 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null)
1006 1030 {
1007 1031 if (!object?.renderer || object._lit === false)
1008 1032 { return; }
@@ -1010,39 +1034,35 @@ export class WorldView
1010 1034 const dark = Math.min(1, Math.max(0, darkness ?? 0));
1011 1035 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
1012 1036 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
1013 object.renderer.shader = getSpriteLightingShader();
1014 object.renderer.shaderUniforms = {
1015 u_darkness: dark,
1016 u_strength: flash,
1017 u_wade: wade ? 1 : 0,
1018 u_spriteHeight: height
1019 };
1037 const tint = tintColor ? normalizeRgb(tintColor) : null;
1038 if (tint)
1039 {
1040 object.renderer.shader = getTintLitSpriteShader();
1041 object.renderer.shaderUniforms = {
1042 u_darkness: dark,
1043 u_strength: flash,
1044 u_wade: wade ? 1 : 0,
1045 u_spriteHeight: height,
1046 u_useTint: 1,
1047 u_tintColor: [tint.r, tint.g, tint.b]
1048 };
1049 }
1050 else
1051 {
1052 object.renderer.shader = getSpriteLightingShader();
1053 object.renderer.shaderUniforms = {
1054 u_darkness: dark,
1055 u_strength: flash,
1056 u_wade: wade ? 1 : 0,
1057 u_spriteHeight: height
1058 };
1059 }
1020 1060 object.renderer.secondaryMap = null;
1021 1061 }
1022 1062
1023 1063 #syncGroundItemSprite (item, darkness)
1024 1064 {
1025 if (item?.potionColor)
1026 { this.#syncPotionSprite(item.object, darkness, item.potionColor); }
1027 else
1028 { this.#syncLitSprite(item?.object, darkness); }
1029 }
1030
1031 #syncPotionSprite (object, darkness, color)
1032 {
1033 if (!object?.renderer || object._lit === false)
1034 { return; }
1035 object._lit = true;
1036 object.renderer.shader = getPotionSpriteShader();
1037 object.renderer.shaderUniforms = {
1038 u_darkness: Math.min(1, Math.max(0, darkness ?? 0)),
1039 u_potionColor: [
1040 Math.min(1, Math.max(0, color?.r ?? 0.4)),
1041 Math.min(1, Math.max(0, color?.g ?? 0.4)),
1042 Math.min(1, Math.max(0, color?.b ?? 0.7))
1043 ]
1044 };
1045 object.renderer.secondaryMap = null;
1065 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
1046 1066 }
1047 1067
1048 1068 #groundTypeAt (tileX, tileY)
@@ -2,7 +2,8 @@ import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BO
2import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
2import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
3import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
4import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
4import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
5import { itemSpriteName } from "/shared/definitions/items.js";
5import { itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
6import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";
6import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";
7import { normalizeGround, isWadeGround, isWaterGround } from "/shared/definitions/tiles.js";
7import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
8import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
8import { bakeChunkAtlases } from "./chunkBake.js";
9import { bakeChunkAtlases } from "./chunkBake.js";
@@ -86,20 +87,36 @@ const WATER_GROUND_FRAG = [
86 "}"
87 "}"
87].join("\n");
88].join("\n");
88
89
89/** Potion bottle: recolor near-white liquid, then apply night darkness. */
90/** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */
90const POTION_SPRITE_FRAG = [
91const TINT_LIT_SPRITE_FRAG = [
91 "precision mediump float;",
92 "precision mediump float;",
92 "varying vec2 v_texCoord;",
93 "varying vec2 v_texCoord;",
93 "uniform sampler2D u_texture;",
94 "uniform sampler2D u_texture;",
94 "uniform float u_darkness;",
95 "uniform float u_darkness;",
95 "uniform vec3 u_potionColor;",
96 "uniform float u_strength;",
97 "uniform float u_wade;",
98 "uniform float u_spriteHeight;",
99 "uniform float u_useTint;",
100 "uniform vec3 u_tintColor;",
96 "void main() {",
101 "void main() {",
97 " vec4 color = texture2D(u_texture, v_texCoord);",
102 " vec4 color = texture2D(u_texture, v_texCoord);",
98 " if (color.a <= 0.0) { discard; }",
103 " if (color.a <= 0.0) { discard; }",
104 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
105 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
99 " vec3 rgb = color.rgb;",
106 " vec3 rgb = color.rgb;",
100 " float liquid = step(0.95, min(min(color.r, color.g), color.b));",
107 " if (u_useTint > 0.5) {",
101 " rgb = mix(rgb, u_potionColor, liquid);",
108 " float eps = 1.0 / 255.0;",
109 " if (abs(color.r - color.b) <= eps && color.g < color.r - eps) {",
110 " float L = color.r;",
111 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
112 " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;",
113 " }",
114 " }",
115 " if (u_wade > 0.5 && fromBottom < 5.0) {",
116 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
117 " }",
102 " rgb = mix(rgb, vec3(0.0), u_darkness);",
118 " rgb = mix(rgb, vec3(0.0), u_darkness);",
119 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
103 " gl_FragColor = vec4(rgb, color.a);",
120 " gl_FragColor = vec4(rgb, color.a);",
104 "}"
121 "}"
105].join("\n");
122].join("\n");
@@ -128,7 +145,7 @@ const ATLAS_LIGHTING_FRAG = [
128let spriteLightingShader = null;
145let spriteLightingShader = null;
129let atlasLightingShader = null;
146let atlasLightingShader = null;
130let waterGroundShader = null;
147let waterGroundShader = null;
131let potionSpriteShader = null;
148let tintLitSpriteShader = null;
132
149
133function getSpriteLightingShader ()
150function getSpriteLightingShader ()
134{
151{
@@ -151,11 +168,11 @@ function getWaterGroundShader ()
151 return waterGroundShader;
168 return waterGroundShader;
152}
169}
153
170
154function getPotionSpriteShader ()
171function getTintLitSpriteShader ()
155{
172{
156 if (!potionSpriteShader)
173 if (!tintLitSpriteShader)
157 { potionSpriteShader = Shader.fragment(POTION_SPRITE_FRAG); }
174 { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); }
158 return potionSpriteShader;
175 return tintLitSpriteShader;
159}
176}
160
177
161export class WorldView
178export class WorldView
@@ -392,7 +409,8 @@ export class WorldView
392 item.displayName = payload.displayName;
409 item.displayName = payload.displayName;
393 item.sprite = spriteName;
410 item.sprite = spriteName;
394 item.instance = payload.instance ?? null;
411 item.instance = payload.instance ?? null;
395 item.potionColor = potion?.color ?? null;
412 const stack = { itemId: payload.itemId, instance: payload.instance ?? null };
413 item.tintColor = resolveItemTint(stack, itemDefinition(payload.itemId));
396 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
414 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
397 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
415 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
398 }
416 }
@@ -930,6 +948,7 @@ export class WorldView
930 for (const overlay of entity.bloomOverlays ?? [])
948 for (const overlay of entity.bloomOverlays ?? [])
931 { overlay.destroy(); }
949 { overlay.destroy(); }
932 entity.overlays = [];
950 entity.overlays = [];
951 entity.overlayTints = [];
933 entity.bloomOverlays = [];
952 entity.bloomOverlays = [];
934 for (const layer of layers.slice(1))
953 for (const layer of layers.slice(1))
935 {
954 {
@@ -939,6 +958,11 @@ export class WorldView
939 const object = new GameObject(0, 0, image, SORT_ENTITY);
958 const object = new GameObject(0, 0, image, SORT_ENTITY);
940 this.scene.addObject(object);
959 this.scene.addObject(object);
941 entity.overlays.push(object);
960 entity.overlays.push(object);
961 entity.overlayTints.push(
962 layer.tint
963 ? normalizeRgb(layer.tint)
964 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)
965 );
942 const bloomName = bloomCompanionName(layer.sprite);
966 const bloomName = bloomCompanionName(layer.sprite);
943 const bloomImage = this.game.images[bloomName];
967 const bloomImage = this.game.images[bloomName];
944 if (!bloomImage)
968 if (!bloomImage)
@@ -980,7 +1004,7 @@ export class WorldView
980 const overlay = entity.overlays[index];
1004 const overlay = entity.overlays[index];
981 const overlaySortY = entity.visualY + 0.5 * (index + 1);
1005 const overlaySortY = entity.visualY + 0.5 * (index + 1);
982 overlay.transform.rotation = walkTilt;
1006 overlay.transform.rotation = walkTilt;
983 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
1007 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null);
984 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
1008 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
985 }
1009 }
986 for (const overlay of entity.bloomOverlays ?? [])
1010 for (const overlay of entity.bloomOverlays ?? [])
@@ -1002,7 +1026,7 @@ export class WorldView
1002 object.renderer.secondaryMap = null;
1026 object.renderer.secondaryMap = null;
1003 }
1027 }
1004
1028
1005 #syncLitSprite (object, darkness, flashStrength = 0, wade = false)
1029 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null)
1006 {
1030 {
1007 if (!object?.renderer || object._lit === false)
1031 if (!object?.renderer || object._lit === false)
1008 { return; }
1032 { return; }
@@ -1010,39 +1034,35 @@ export class WorldView
1010 const dark = Math.min(1, Math.max(0, darkness ?? 0));
1034 const dark = Math.min(1, Math.max(0, darkness ?? 0));
1011 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
1035 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
1012 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
1036 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
1013 object.renderer.shader = getSpriteLightingShader();
1037 const tint = tintColor ? normalizeRgb(tintColor) : null;
1014 object.renderer.shaderUniforms = {
1038 if (tint)
1015 u_darkness: dark,
1039 {
1016 u_strength: flash,
1040 object.renderer.shader = getTintLitSpriteShader();
1017 u_wade: wade ? 1 : 0,
1041 object.renderer.shaderUniforms = {
1018 u_spriteHeight: height
1042 u_darkness: dark,
1019 };
1043 u_strength: flash,
1044 u_wade: wade ? 1 : 0,
1045 u_spriteHeight: height,
1046 u_useTint: 1,
1047 u_tintColor: [tint.r, tint.g, tint.b]
1048 };
1049 }
1050 else
1051 {
1052 object.renderer.shader = getSpriteLightingShader();
1053 object.renderer.shaderUniforms = {
1054 u_darkness: dark,
1055 u_strength: flash,
1056 u_wade: wade ? 1 : 0,
1057 u_spriteHeight: height
1058 };
1059 }
1020 object.renderer.secondaryMap = null;
1060 object.renderer.secondaryMap = null;
1021 }
1061 }
1022
1062
1023 #syncGroundItemSprite (item, darkness)
1063 #syncGroundItemSprite (item, darkness)
1024 {
1064 {
1025 if (item?.potionColor)
1065 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
1026 { this.#syncPotionSprite(item.object, darkness, item.potionColor); }
1027 else
1028 { this.#syncLitSprite(item?.object, darkness); }
1029 }
1030
1031 #syncPotionSprite (object, darkness, color)
1032 {
1033 if (!object?.renderer || object._lit === false)
1034 { return; }
1035 object._lit = true;
1036 object.renderer.shader = getPotionSpriteShader();
1037 object.renderer.shaderUniforms = {
1038 u_darkness: Math.min(1, Math.max(0, darkness ?? 0)),
1039 u_potionColor: [
1040 Math.min(1, Math.max(0, color?.r ?? 0.4)),
1041 Math.min(1, Math.max(0, color?.g ?? 0.4)),
1042 Math.min(1, Math.max(0, color?.b ?? 0.7))
1043 ]
1044 };
1045 object.renderer.secondaryMap = null;
1046 }
1066 }
1047
1067
1048 #groundTypeAt (tileX, tileY)
1068 #groundTypeAt (tileX, tileY)
docs/FEATURES.md +7 −3
@@ -228,8 +228,12 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
228 228 ## Equipment tiers and worn stat bonuses
229 229
230 230 **Status:** partial
231 **Spec:** Metal gear exists in six material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**. Bronze has no extra gate (min relevant skill 1). Every higher tier requires a minimum level of the item's **relevant skill** (weapons → their hit skill e.g. Sword fighting; metal armour & shields → Defence; bows → Archery; wizard cloth & staves → Magic; gathering tools → Woodcutting / Mining / Fishing). Tier min levels and per-tier stat bonuses live in `shared/definitions/materialTiers.js`. Worn items add flat bonuses to **effective** combat stats (not base skill XP): metal weapons & clubs → Strength; metal armour & shields → Defence; bows → Dexterity; wizard cloth → Magic; staves → Mind; leather armour → Dexterity (Agility); cloth armour → Defence. Item defs carry `equipment.tier`, `equipment.kind`, optional `equipment.bonus` override, and `attack.attackType`. Equip checks enforce min skill; combat rolls use `shared/equipment/stats.js`. **TODO:** full tiered item catalog (all metals, bows, shields, wizard sets, leather, tools); placeholder art per tier; client tooltip showing reqs/bonuses.
232 **Code:** `shared/definitions/materialTiers.js`, `shared/definitions/equipmentKinds.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `shared/definitions/items.js` (stick, cloth shirt), `server/src/items/bags.js`, `server/src/combat/service.js`, tests in `server/tests/equipment.test.js`
231 **Spec:** Metal gear exists in six material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**. Bronze has no extra gate (min relevant skill 1). Every higher tier requires a minimum level of the item's **relevant skill** (weapons → their hit skill e.g. Sword fighting; metal armour & shields → Defence; bows → Archery; wizard cloth & staves → Magic; gathering tools → Woodcutting / Mining / Fishing). Tier min levels and per-tier stat bonuses live in `shared/definitions/materialTiers.js`. Worn items add flat bonuses to **effective** combat stats (not base skill XP): metal weapons & clubs → Strength; metal armour & shields → Defence; bows → Dexterity; wizard cloth → Magic; staves → Mind; leather armour → Dexterity (Agility); cloth armour → Defence. Item defs carry `equipment.tier`, `equipment.kind`, optional `equipment.bonus` override, and `attack.attackType`. Equip checks enforce min skill; combat rolls use `shared/equipment/stats.js`.
232
233 **Shared sprites + magenta tint:** Draw one base sprite per shape (sword, ore, bar, …). Tintable pixels use **magenta** (`R == B` and `G < R`); lightness is `R` (e.g. `(50,0,50)` dark … `(255,0,255)` bright); `G > 0` desaturates toward white. Non-magenta pixels stay as-is. World/UI apply `TIER_TINT_COLOR` (or potion `instance.color`) then darkness. See `shared/render/tint.js`.
234
235 **TODO:** full tiered item catalog (all metals, bows, shields, wizard sets, leather, tools); more shared base art; client tooltip showing reqs/bonuses.
236 **Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/equipmentKinds.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `shared/definitions/items.js`, `client/src/render/worldView.js` (tint lit shader), `client/src/render/potionIcon.js`, `server/src/items/bags.js`, `server/src/combat/service.js`, tests in `server/tests/equipment.test.js`, `server/tests/tint.test.js`
233 237
234 238 ## Gathering, crafting, and production skills
235 239
@@ -271,7 +275,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
271 275 **Status:** partial (scaffolding)
272 276 **Spec:** **Herbalism** gathers herbs from herb nodes with **plant clippers** (tiers like mining/woodcutting; gather loop TBD). **Alchemy** uses herbs (and other ingredients) at a **Cauldron** block (`BlockType.cauldron`, editor placeable). Nonstandard UI: four reserve slots above the vessel, ↓ insert arrows under each slot, **Stir / Heat / Cool** actions, **Bottle**, **Clear** (also auto-clears after bottle), and **Save Recipe** after a successful brew when the player has blank **paper**.
273 277
274 Slots register item+quantity without consuming until insert; insert consumes the reserved amount into the brew and records an `insert` step. Recipes list ≤4 unique ingredients as **ratios** (double inputs → double output if bottles allow; excess brew is lost without enough **glass bottles**). Steps must match; wrong order/ratios or Alchemy level below the recipe minimum yields an **Unstable Potion** chosen by hashing the step transcript (same mistakes → same failure potion). Unstable effects are stubs (slow, damage, blind, queasy). Success + paper → Save Recipe writes a unique **recipe paper** (read like a letter: ratios, steps, Alchemy level). Potions of the same type/effect stack to **16**. Shared potion art: clear bottle (= empty bottle) + fill levels 1–5; liquid is recolored per potion `color` (inventory canvas tint; world ground items use a lit shader that tints then applies darkness).
278 Slots register item+quantity without consuming until insert; insert consumes the reserved amount into the brew and records an `insert` step. Recipes list ≤4 unique ingredients as **ratios** (double inputs → double output if bottles allow; excess brew is lost without enough **glass bottles**). Steps must match; wrong order/ratios or Alchemy level below the recipe minimum yields an **Unstable Potion** chosen by hashing the step transcript (same mistakes → same failure potion). Unstable effects are stubs (slow, damage, blind, queasy). Success + paper → Save Recipe writes a unique **recipe paper** (read like a letter: ratios, steps, Alchemy level). Potions of the same type/effect stack to **16**. Shared potion art: clear bottle (= empty bottle) + fill levels 1–5 with **magenta** liquid pixels; liquid is recolored per potion `color` via the shared magenta tint path (inventory canvas; world ground items use the tint+darkness lit shader).
275 279
276 280 Example scaffold recipe: **Green draught** — heat → insert green herb → stir → insert apple → cool → Bottle (ratios 2 green herb : 1 apple).
277 281
@@ -228,8 +228,12 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
228## Equipment tiers and worn stat bonuses
228## Equipment tiers and worn stat bonuses
229
229
230**Status:** partial
230**Status:** partial
231**Spec:** Metal gear exists in six material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**. Bronze has no extra gate (min relevant skill 1). Every higher tier requires a minimum level of the item's **relevant skill** (weapons → their hit skill e.g. Sword fighting; metal armour & shields → Defence; bows → Archery; wizard cloth & staves → Magic; gathering tools → Woodcutting / Mining / Fishing). Tier min levels and per-tier stat bonuses live in `shared/definitions/materialTiers.js`. Worn items add flat bonuses to **effective** combat stats (not base skill XP): metal weapons & clubs → Strength; metal armour & shields → Defence; bows → Dexterity; wizard cloth → Magic; staves → Mind; leather armour → Dexterity (Agility); cloth armour → Defence. Item defs carry `equipment.tier`, `equipment.kind`, optional `equipment.bonus` override, and `attack.attackType`. Equip checks enforce min skill; combat rolls use `shared/equipment/stats.js`. **TODO:** full tiered item catalog (all metals, bows, shields, wizard sets, leather, tools); placeholder art per tier; client tooltip showing reqs/bonuses.
231**Spec:** Metal gear exists in six material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**. Bronze has no extra gate (min relevant skill 1). Every higher tier requires a minimum level of the item's **relevant skill** (weapons → their hit skill e.g. Sword fighting; metal armour & shields → Defence; bows → Archery; wizard cloth & staves → Magic; gathering tools → Woodcutting / Mining / Fishing). Tier min levels and per-tier stat bonuses live in `shared/definitions/materialTiers.js`. Worn items add flat bonuses to **effective** combat stats (not base skill XP): metal weapons & clubs → Strength; metal armour & shields → Defence; bows → Dexterity; wizard cloth → Magic; staves → Mind; leather armour → Dexterity (Agility); cloth armour → Defence. Item defs carry `equipment.tier`, `equipment.kind`, optional `equipment.bonus` override, and `attack.attackType`. Equip checks enforce min skill; combat rolls use `shared/equipment/stats.js`.
232**Code:** `shared/definitions/materialTiers.js`, `shared/definitions/equipmentKinds.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `shared/definitions/items.js` (stick, cloth shirt), `server/src/items/bags.js`, `server/src/combat/service.js`, tests in `server/tests/equipment.test.js`
232
233**Shared sprites + magenta tint:** Draw one base sprite per shape (sword, ore, bar, …). Tintable pixels use **magenta** (`R == B` and `G < R`); lightness is `R` (e.g. `(50,0,50)` dark … `(255,0,255)` bright); `G > 0` desaturates toward white. Non-magenta pixels stay as-is. World/UI apply `TIER_TINT_COLOR` (or potion `instance.color`) then darkness. See `shared/render/tint.js`.
234
235**TODO:** full tiered item catalog (all metals, bows, shields, wizard sets, leather, tools); more shared base art; client tooltip showing reqs/bonuses.
236**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/equipmentKinds.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `shared/definitions/items.js`, `client/src/render/worldView.js` (tint lit shader), `client/src/render/potionIcon.js`, `server/src/items/bags.js`, `server/src/combat/service.js`, tests in `server/tests/equipment.test.js`, `server/tests/tint.test.js`
233
237
234## Gathering, crafting, and production skills
238## Gathering, crafting, and production skills
235
239
@@ -271,7 +275,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
271**Status:** partial (scaffolding)
275**Status:** partial (scaffolding)
272**Spec:** **Herbalism** gathers herbs from herb nodes with **plant clippers** (tiers like mining/woodcutting; gather loop TBD). **Alchemy** uses herbs (and other ingredients) at a **Cauldron** block (`BlockType.cauldron`, editor placeable). Nonstandard UI: four reserve slots above the vessel, ↓ insert arrows under each slot, **Stir / Heat / Cool** actions, **Bottle**, **Clear** (also auto-clears after bottle), and **Save Recipe** after a successful brew when the player has blank **paper**.
276**Spec:** **Herbalism** gathers herbs from herb nodes with **plant clippers** (tiers like mining/woodcutting; gather loop TBD). **Alchemy** uses herbs (and other ingredients) at a **Cauldron** block (`BlockType.cauldron`, editor placeable). Nonstandard UI: four reserve slots above the vessel, ↓ insert arrows under each slot, **Stir / Heat / Cool** actions, **Bottle**, **Clear** (also auto-clears after bottle), and **Save Recipe** after a successful brew when the player has blank **paper**.
273
277
274Slots register item+quantity without consuming until insert; insert consumes the reserved amount into the brew and records an `insert` step. Recipes list ≤4 unique ingredients as **ratios** (double inputs → double output if bottles allow; excess brew is lost without enough **glass bottles**). Steps must match; wrong order/ratios or Alchemy level below the recipe minimum yields an **Unstable Potion** chosen by hashing the step transcript (same mistakes → same failure potion). Unstable effects are stubs (slow, damage, blind, queasy). Success + paper → Save Recipe writes a unique **recipe paper** (read like a letter: ratios, steps, Alchemy level). Potions of the same type/effect stack to **16**. Shared potion art: clear bottle (= empty bottle) + fill levels 1–5; liquid is recolored per potion `color` (inventory canvas tint; world ground items use a lit shader that tints then applies darkness).
278Slots register item+quantity without consuming until insert; insert consumes the reserved amount into the brew and records an `insert` step. Recipes list ≤4 unique ingredients as **ratios** (double inputs → double output if bottles allow; excess brew is lost without enough **glass bottles**). Steps must match; wrong order/ratios or Alchemy level below the recipe minimum yields an **Unstable Potion** chosen by hashing the step transcript (same mistakes → same failure potion). Unstable effects are stubs (slow, damage, blind, queasy). Success + paper → Save Recipe writes a unique **recipe paper** (read like a letter: ratios, steps, Alchemy level). Potions of the same type/effect stack to **16**. Shared potion art: clear bottle (= empty bottle) + fill levels 1–5 with **magenta** liquid pixels; liquid is recolored per potion `color` via the shared magenta tint path (inventory canvas; world ground items use the tint+darkness lit shader).
275
279
276Example scaffold recipe: **Green draught** — heat → insert green herb → stir → insert apple → cool → Bottle (ratios 2 green herb : 1 apple).
280Example scaffold recipe: **Green draught** — heat → insert green herb → stir → insert apple → cool → Bottle (ratios 2 green herb : 1 apple).
277
281
server/src/assets/spriteCatalog.js +4 −4
@@ -48,11 +48,11 @@ function itemScanDefs ()
48 48 const defs = {};
49 49 for (const def of Object.values(ITEM_DEFINITIONS))
50 50 {
51 // Items that reuse another folder's art via iconKey skip the scan.
52 if (def.iconKey && def.iconKey !== def.key)
51 const folderKey = def.iconKey && def.iconKey !== def.key ? def.iconKey : def.key;
52 if (!folderKey || defs[folderKey])
53 53 { continue; }
54 defs[def.key] = {
55 key: def.key,
54 defs[folderKey] = {
55 key: folderKey,
56 56 id: def.itemId,
57 57 frames: def.frames ?? 1,
58 58 framesPerRow: def.framesPerRow ?? 1,
@@ -48,11 +48,11 @@ function itemScanDefs ()
48 const defs = {};
48 const defs = {};
49 for (const def of Object.values(ITEM_DEFINITIONS))
49 for (const def of Object.values(ITEM_DEFINITIONS))
50 {
50 {
51 // Items that reuse another folder's art via iconKey skip the scan.
51 const folderKey = def.iconKey && def.iconKey !== def.key ? def.iconKey : def.key;
52 if (def.iconKey && def.iconKey !== def.key)
52 if (!folderKey || defs[folderKey])
53 { continue; }
53 { continue; }
54 defs[def.key] = {
54 defs[folderKey] = {
55 key: def.key,
55 key: folderKey,
56 id: def.itemId,
56 id: def.itemId,
57 frames: def.frames ?? 1,
57 frames: def.frames ?? 1,
58 framesPerRow: def.framesPerRow ?? 1,
58 framesPerRow: def.framesPerRow ?? 1,
server/src/ecs/serialize.js +1 −1
@@ -106,7 +106,7 @@ export function appearanceLayers (ecs, handle, appearance)
106 106 { continue; }
107 107 const overlay = itemEquipSprite(worn.itemId);
108 108 if (overlay)
109 { layers.push({ sprite: overlay }); }
109 { layers.push({ sprite: overlay, itemId: worn.itemId }); }
110 110 }
111 111 return layers;
112 112 }
@@ -106,7 +106,7 @@ export function appearanceLayers (ecs, handle, appearance)
106 { continue; }
106 { continue; }
107 const overlay = itemEquipSprite(worn.itemId);
107 const overlay = itemEquipSprite(worn.itemId);
108 if (overlay)
108 if (overlay)
109 { layers.push({ sprite: overlay }); }
109 { layers.push({ sprite: overlay, itemId: worn.itemId }); }
110 }
110 }
111 return layers;
111 return layers;
112}
112}
server/tests/tint.test.js added +43 −0
@@ -0,0 +1,43 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import {
4 isMagentaTintable,
5 magentaTintedRgb,
6 tierTintColor,
7 resolveItemTint
8 } from "../../shared/render/tint.js";
9 import { MaterialTier } from "../../shared/definitions/materialTiers.js";
10 import { ItemId } from "../../shared/definitions/items.js";
11
12 test("magenta tintable when R==B and G < R", () =>
13 {
14 assert.equal(isMagentaTintable(1, 0, 1), true);
15 assert.equal(isMagentaTintable(50 / 255, 0, 50 / 255), true);
16 assert.equal(isMagentaTintable(120 / 255, 50 / 255, 120 / 255), true);
17 assert.equal(isMagentaTintable(200 / 255, 100 / 255, 50 / 255), false);
18 assert.equal(isMagentaTintable(0.5, 0.5, 0.5), false);
19 });
20
21 test("magenta tint preserves lightness and desaturates with G", () =>
22 {
23 const tint = { r: 0, g: 1, b: 0 };
24 const dark = magentaTintedRgb(50 / 255, 0, 50 / 255, tint);
25 const light = magentaTintedRgb(1, 0, 1, tint);
26 assert.ok(dark.g < light.g);
27 const desat = magentaTintedRgb(120 / 255, 50 / 255, 120 / 255, tint);
28 const pure = magentaTintedRgb(120 / 255, 0, 120 / 255, tint);
29 assert.ok(desat.r > pure.r);
30 });
31
32 test("resolveItemTint uses potion instance color and tier tints", () =>
33 {
34 const potionTint = resolveItemTint({
35 itemId: ItemId.potion,
36 instance: { kind: "potion", color: { r: 0.25, g: 0.72, b: 0.35 } }
37 });
38 assert.equal(potionTint.g, 0.72);
39 const bronze = tierTintColor(MaterialTier.bronze);
40 assert.ok(bronze.r > bronze.b);
41 const oreTint = resolveItemTint({ itemId: ItemId.bronzeOre });
42 assert.deepEqual(oreTint, bronze);
43 });
@@ -0,0 +1,43 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import {
4 isMagentaTintable,
5 magentaTintedRgb,
6 tierTintColor,
7 resolveItemTint
8} from "../../shared/render/tint.js";
9import { MaterialTier } from "../../shared/definitions/materialTiers.js";
10import { ItemId } from "../../shared/definitions/items.js";
11
12test("magenta tintable when R==B and G < R", () =>
13{
14 assert.equal(isMagentaTintable(1, 0, 1), true);
15 assert.equal(isMagentaTintable(50 / 255, 0, 50 / 255), true);
16 assert.equal(isMagentaTintable(120 / 255, 50 / 255, 120 / 255), true);
17 assert.equal(isMagentaTintable(200 / 255, 100 / 255, 50 / 255), false);
18 assert.equal(isMagentaTintable(0.5, 0.5, 0.5), false);
19});
20
21test("magenta tint preserves lightness and desaturates with G", () =>
22{
23 const tint = { r: 0, g: 1, b: 0 };
24 const dark = magentaTintedRgb(50 / 255, 0, 50 / 255, tint);
25 const light = magentaTintedRgb(1, 0, 1, tint);
26 assert.ok(dark.g < light.g);
27 const desat = magentaTintedRgb(120 / 255, 50 / 255, 120 / 255, tint);
28 const pure = magentaTintedRgb(120 / 255, 0, 120 / 255, tint);
29 assert.ok(desat.r > pure.r);
30});
31
32test("resolveItemTint uses potion instance color and tier tints", () =>
33{
34 const potionTint = resolveItemTint({
35 itemId: ItemId.potion,
36 instance: { kind: "potion", color: { r: 0.25, g: 0.72, b: 0.35 } }
37 });
38 assert.equal(potionTint.g, 0.72);
39 const bronze = tierTintColor(MaterialTier.bronze);
40 assert.ok(bronze.r > bronze.b);
41 const oreTint = resolveItemTint({ itemId: ItemId.bronzeOre });
42 assert.deepEqual(oreTint, bronze);
43});
shared/definitions/craftingItems.js +30 −4
@@ -1,4 +1,6 @@
1 1 import { ItemCategory } from "./itemCategories.js";
2 import { MaterialTier } from "./materialTiers.js";
3 import { EquipmentKind } from "./equipmentKinds.js";
2 4
3 5 const DEFAULT_STACK = 99;
4 6
@@ -65,10 +67,18 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
65 67 description: "Spun wool. Used at a loom."
66 68 }),
67 69 [CraftingItemId.bronzeOre]: stub(CraftingItemId.bronzeOre, "bronze-ore", "Bronze ore", ItemCategory.ingredient, {
68 description: "Mined ore. Smelt at a furnace into bars."
70 description: "Mined ore. Smelt at a furnace into bars.",
71 iconKey: "ore",
72 defaultState: "ore",
73 tier: MaterialTier.bronze,
74 tintFromTier: true
69 75 }),
70 76 [CraftingItemId.bronzeBar]: stub(CraftingItemId.bronzeBar, "bronze-bar", "Bronze bar", ItemCategory.intermediate, {
71 description: "Smelted metal. Smith at an anvil."
77 description: "Smelted metal. Smith at an anvil.",
78 iconKey: "bar",
79 defaultState: "bar",
80 tier: MaterialTier.bronze,
81 tintFromTier: true
72 82 }),
73 83 [CraftingItemId.rawMeat]: stub(CraftingItemId.rawMeat, "raw-meat", "Raw meat", ItemCategory.ingredient, {
74 84 description: "Cook at an oven or campfire."
@@ -88,12 +98,28 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
88 98 [CraftingItemId.bronzeAxe]: stub(CraftingItemId.bronzeAxe, "bronze-axe", "Bronze axe", ItemCategory.tool, {
89 99 stackable: false,
90 100 maxStackSize: 1,
91 description: "Woodcutting tool. Tier and min Woodcutting TBD."
101 description: "Woodcutting tool. Tier and min Woodcutting TBD.",
102 iconKey: "axe",
103 defaultState: "axe",
104 tintFromTier: true,
105 equipment: Object.freeze({
106 slot: "weapon",
107 tier: MaterialTier.bronze,
108 kind: EquipmentKind.axeTool
109 })
92 110 }),
93 111 [CraftingItemId.bronzePickaxe]: stub(CraftingItemId.bronzePickaxe, "bronze-pickaxe", "Bronze pickaxe", ItemCategory.tool, {
94 112 stackable: false,
95 113 maxStackSize: 1,
96 description: "Mining tool. Tier and min Mining TBD."
114 description: "Mining tool. Tier and min Mining TBD.",
115 iconKey: "axe",
116 defaultState: "axe",
117 tintFromTier: true,
118 equipment: Object.freeze({
119 slot: "weapon",
120 tier: MaterialTier.bronze,
121 kind: EquipmentKind.pickaxeTool
122 })
97 123 }),
98 124 [CraftingItemId.fishingRod]: stub(CraftingItemId.fishingRod, "fishing-rod", "Fishing rod", ItemCategory.tool, {
99 125 stackable: false,
@@ -1,4 +1,6 @@
1import { ItemCategory } from "./itemCategories.js";
1import { ItemCategory } from "./itemCategories.js";
2import { MaterialTier } from "./materialTiers.js";
3import { EquipmentKind } from "./equipmentKinds.js";
2
4
3const DEFAULT_STACK = 99;
5const DEFAULT_STACK = 99;
4
6
@@ -65,10 +67,18 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
65 description: "Spun wool. Used at a loom."
67 description: "Spun wool. Used at a loom."
66 }),
68 }),
67 [CraftingItemId.bronzeOre]: stub(CraftingItemId.bronzeOre, "bronze-ore", "Bronze ore", ItemCategory.ingredient, {
69 [CraftingItemId.bronzeOre]: stub(CraftingItemId.bronzeOre, "bronze-ore", "Bronze ore", ItemCategory.ingredient, {
68 description: "Mined ore. Smelt at a furnace into bars."
70 description: "Mined ore. Smelt at a furnace into bars.",
71 iconKey: "ore",
72 defaultState: "ore",
73 tier: MaterialTier.bronze,
74 tintFromTier: true
69 }),
75 }),
70 [CraftingItemId.bronzeBar]: stub(CraftingItemId.bronzeBar, "bronze-bar", "Bronze bar", ItemCategory.intermediate, {
76 [CraftingItemId.bronzeBar]: stub(CraftingItemId.bronzeBar, "bronze-bar", "Bronze bar", ItemCategory.intermediate, {
71 description: "Smelted metal. Smith at an anvil."
77 description: "Smelted metal. Smith at an anvil.",
78 iconKey: "bar",
79 defaultState: "bar",
80 tier: MaterialTier.bronze,
81 tintFromTier: true
72 }),
82 }),
73 [CraftingItemId.rawMeat]: stub(CraftingItemId.rawMeat, "raw-meat", "Raw meat", ItemCategory.ingredient, {
83 [CraftingItemId.rawMeat]: stub(CraftingItemId.rawMeat, "raw-meat", "Raw meat", ItemCategory.ingredient, {
74 description: "Cook at an oven or campfire."
84 description: "Cook at an oven or campfire."
@@ -88,12 +98,28 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
88 [CraftingItemId.bronzeAxe]: stub(CraftingItemId.bronzeAxe, "bronze-axe", "Bronze axe", ItemCategory.tool, {
98 [CraftingItemId.bronzeAxe]: stub(CraftingItemId.bronzeAxe, "bronze-axe", "Bronze axe", ItemCategory.tool, {
89 stackable: false,
99 stackable: false,
90 maxStackSize: 1,
100 maxStackSize: 1,
91 description: "Woodcutting tool. Tier and min Woodcutting TBD."
101 description: "Woodcutting tool. Tier and min Woodcutting TBD.",
102 iconKey: "axe",
103 defaultState: "axe",
104 tintFromTier: true,
105 equipment: Object.freeze({
106 slot: "weapon",
107 tier: MaterialTier.bronze,
108 kind: EquipmentKind.axeTool
109 })
92 }),
110 }),
93 [CraftingItemId.bronzePickaxe]: stub(CraftingItemId.bronzePickaxe, "bronze-pickaxe", "Bronze pickaxe", ItemCategory.tool, {
111 [CraftingItemId.bronzePickaxe]: stub(CraftingItemId.bronzePickaxe, "bronze-pickaxe", "Bronze pickaxe", ItemCategory.tool, {
94 stackable: false,
112 stackable: false,
95 maxStackSize: 1,
113 maxStackSize: 1,
96 description: "Mining tool. Tier and min Mining TBD."
114 description: "Mining tool. Tier and min Mining TBD.",
115 iconKey: "axe",
116 defaultState: "axe",
117 tintFromTier: true,
118 equipment: Object.freeze({
119 slot: "weapon",
120 tier: MaterialTier.bronze,
121 kind: EquipmentKind.pickaxeTool
122 })
97 }),
123 }),
98 [CraftingItemId.fishingRod]: stub(CraftingItemId.fishingRod, "fishing-rod", "Fishing rod", ItemCategory.tool, {
124 [CraftingItemId.fishingRod]: stub(CraftingItemId.fishingRod, "fishing-rod", "Fishing rod", ItemCategory.tool, {
99 stackable: false,
125 stackable: false,
shared/definitions/items.js +6 −3
@@ -284,7 +284,8 @@ export const ITEM_DEFINITIONS = Object.freeze({
284 284 equipment: Object.freeze({
285 285 slot: EQUIPMENT_SLOT.weapon,
286 286 tier: MaterialTier.bronze,
287 kind: EquipmentKind.plantClippers
287 kind: EquipmentKind.plantClippers,
288 tintFromTier: true
288 289 })
289 290 }),
290 291 ...CRAFTING_ITEM_STUBS
@@ -386,7 +387,8 @@ export function itemSpriteName (itemId, instance = null)
386 387 { return spriteImageName("item", "paper", "paper"); }
387 388 if (itemId === ItemId.letter)
388 389 { return spriteImageName("item", "letter", letterVisualState(instance)); }
389 return def.sprite ?? spriteImageName("item", def.key, itemDefaultState(def));
390 const folderKey = def.iconKey ?? def.key;
391 return def.sprite ?? spriteImageName("item", folderKey, itemDefaultState(def));
390 392 }
391 393
392 394 export function itemEquipSprite (itemId)
@@ -395,9 +397,10 @@ export function itemEquipSprite (itemId)
395 397 const equipment = def?.equipment;
396 398 if (!equipment)
397 399 { return null; }
400 const folderKey = def.iconKey ?? def.key;
398 401 return equipment.equipSprite
399 402 ?? equipment.overlaySpriteId
400 ?? equipImageName("item", def.key, itemDefaultState(def));
403 ?? equipImageName("item", folderKey, itemDefaultState(def));
401 404 }
402 405
403 406 /** Largest equipped light radius (e.g. lantern in offhand). */
@@ -284,7 +284,8 @@ export const ITEM_DEFINITIONS = Object.freeze({
284 equipment: Object.freeze({
284 equipment: Object.freeze({
285 slot: EQUIPMENT_SLOT.weapon,
285 slot: EQUIPMENT_SLOT.weapon,
286 tier: MaterialTier.bronze,
286 tier: MaterialTier.bronze,
287 kind: EquipmentKind.plantClippers
287 kind: EquipmentKind.plantClippers,
288 tintFromTier: true
288 })
289 })
289 }),
290 }),
290 ...CRAFTING_ITEM_STUBS
291 ...CRAFTING_ITEM_STUBS
@@ -386,7 +387,8 @@ export function itemSpriteName (itemId, instance = null)
386 { return spriteImageName("item", "paper", "paper"); }
387 { return spriteImageName("item", "paper", "paper"); }
387 if (itemId === ItemId.letter)
388 if (itemId === ItemId.letter)
388 { return spriteImageName("item", "letter", letterVisualState(instance)); }
389 { return spriteImageName("item", "letter", letterVisualState(instance)); }
389 return def.sprite ?? spriteImageName("item", def.key, itemDefaultState(def));
390 const folderKey = def.iconKey ?? def.key;
391 return def.sprite ?? spriteImageName("item", folderKey, itemDefaultState(def));
390}
392}
391
393
392export function itemEquipSprite (itemId)
394export function itemEquipSprite (itemId)
@@ -395,9 +397,10 @@ export function itemEquipSprite (itemId)
395 const equipment = def?.equipment;
397 const equipment = def?.equipment;
396 if (!equipment)
398 if (!equipment)
397 { return null; }
399 { return null; }
400 const folderKey = def.iconKey ?? def.key;
398 return equipment.equipSprite
401 return equipment.equipSprite
399 ?? equipment.overlaySpriteId
402 ?? equipment.overlaySpriteId
400 ?? equipImageName("item", def.key, itemDefaultState(def));
403 ?? equipImageName("item", folderKey, itemDefaultState(def));
401}
404}
402
405
403/** Largest equipped light radius (e.g. lantern in offhand). */
406/** Largest equipped light radius (e.g. lantern in offhand). */
shared/render/tint.js added +143 −0
@@ -0,0 +1,143 @@
1 import { MaterialTier, MATERIAL_TIER_ORDER } from "../definitions/materialTiers.js";
2 import { itemDefinition } from "../definitions/items.js";
3
4 /**
5 * Artist convention for tintable pixels (source sprites):
6 * - Tintable when R == B and G < R (magenta family).
7 * - Lightness L = R (= B): (50,0,50) dark … (255,0,255) max light.
8 * - G > 0 (still G < R) desaturates toward white/gray: mix(tint, white, G/R) * L.
9 * - Otherwise leave RGB as-is. World shaders apply darkness after this pass.
10 */
11
12 export const MAGENTA_CHANNEL_EPS = 1 / 255;
13
14 /** Display tint colors per material tier (0–1 RGB). */
15 export const TIER_TINT_COLOR = Object.freeze({
16 [MaterialTier.bronze]: Object.freeze({ r: 0.72, g: 0.48, b: 0.28 }),
17 [MaterialTier.iron]: Object.freeze({ r: 0.62, g: 0.64, b: 0.68 }),
18 [MaterialTier.steel]: Object.freeze({ r: 0.78, g: 0.80, b: 0.84 }),
19 [MaterialTier.mithril]: Object.freeze({ r: 0.45, g: 0.55, b: 0.85 }),
20 [MaterialTier.adamantium]: Object.freeze({ r: 0.35, g: 0.75, b: 0.45 }),
21 [MaterialTier.orichalcum]: Object.freeze({ r: 0.85, g: 0.35, b: 0.55 })
22 });
23
24 export function normalizeRgb (color, fallback = { r: 0.7, g: 0.7, b: 0.7 })
25 {
26 if (!color)
27 { return { r: fallback.r, g: fallback.g, b: fallback.b }; }
28 return {
29 r: clamp01(color.r ?? fallback.r),
30 g: clamp01(color.g ?? fallback.g),
31 b: clamp01(color.b ?? fallback.b)
32 };
33 }
34
35 export function tierTintColor (tier)
36 {
37 return normalizeRgb(TIER_TINT_COLOR[tier] ?? TIER_TINT_COLOR[MaterialTier.bronze]);
38 }
39
40 /**
41 * Resolve tint for an inventory/ground stack or item def.
42 * Priority: potion instance.color → def.tint → tintFromTier + tier.
43 */
44 export function resolveItemTint (stackOrDef, def = null)
45 {
46 const stack = stackOrDef?.itemId != null ? stackOrDef : null;
47 const definition = def
48 ?? (stack ? itemDefinition(stack.itemId) : stackOrDef)
49 ?? null;
50 if (stack?.instance?.kind === "potion" && stack.instance.color)
51 { return normalizeRgb(stack.instance.color); }
52 if (definition?.tint)
53 { return normalizeRgb(definition.tint); }
54 const tier = resolveTintTier(definition);
55 if (tier)
56 { return tierTintColor(tier); }
57 return null;
58 }
59
60 export function resolveEquipTint (itemIdOrDef)
61 {
62 const definition = typeof itemIdOrDef === "number"
63 ? itemDefinition(itemIdOrDef)
64 : itemIdOrDef;
65 if (!definition)
66 { return null; }
67 if (definition.tint)
68 { return normalizeRgb(definition.tint); }
69 const tier = resolveTintTier(definition);
70 if (tier)
71 { return tierTintColor(tier); }
72 return null;
73 }
74
75 function resolveTintTier (definition)
76 {
77 if (!definition)
78 { return null; }
79 if (typeof definition.tintFromTier === "string")
80 { return definition.tintFromTier; }
81 if (definition.tintFromTier === true)
82 { return definition.equipment?.tier ?? definition.tier ?? null; }
83 if (definition.equipment?.tintFromTier)
84 { return definition.equipment.tier ?? null; }
85 return null;
86 }
87
88 /** Pure pixel transform (channels 0–1). Returns null if pixel is not tintable. */
89 export function magentaTintedRgb (r, g, b, tintRgb)
90 {
91 if (!isMagentaTintable(r, g, b))
92 { return null; }
93 const L = r;
94 const gBlend = r > 0 ? Math.min(1, Math.max(0, g / r)) : 0;
95 const tint = normalizeRgb(tintRgb);
96 return {
97 r: clamp01(mix(tint.r, 1, gBlend) * L),
98 g: clamp01(mix(tint.g, 1, gBlend) * L),
99 b: clamp01(mix(tint.b, 1, gBlend) * L)
100 };
101 }
102
103 export function isMagentaTintable (r, g, b, eps = MAGENTA_CHANNEL_EPS)
104 {
105 return Math.abs(r - b) <= eps && g < r - eps;
106 }
107
108 /** Mutate ImageData in place with magenta→tint (alpha unchanged). */
109 export function applyMagentaTintToImageData (imageData, tintRgb)
110 {
111 const data = imageData.data;
112 const tint = normalizeRgb(tintRgb);
113 for (let i = 0; i < data.length; i += 4)
114 {
115 if (data[i + 3] < 8)
116 { continue; }
117 const r = data[i] / 255;
118 const g = data[i + 1] / 255;
119 const b = data[i + 2] / 255;
120 const next = magentaTintedRgb(r, g, b, tint);
121 if (!next)
122 { continue; }
123 data[i] = Math.round(next.r * 255);
124 data[i + 1] = Math.round(next.g * 255);
125 data[i + 2] = Math.round(next.b * 255);
126 }
127 return imageData;
128 }
129
130 export function listTierTintPreview ()
131 {
132 return MATERIAL_TIER_ORDER.map((tier) => ({ tier, color: tierTintColor(tier) }));
133 }
134
135 function clamp01 (n)
136 {
137 return Math.min(1, Math.max(0, Number(n) || 0));
138 }
139
140 function mix (a, b, t)
141 {
142 return a + (b - a) * t;
143 }
@@ -0,0 +1,143 @@
1import { MaterialTier, MATERIAL_TIER_ORDER } from "../definitions/materialTiers.js";
2import { itemDefinition } from "../definitions/items.js";
3
4/**
5 * Artist convention for tintable pixels (source sprites):
6 * - Tintable when R == B and G < R (magenta family).
7 * - Lightness L = R (= B): (50,0,50) dark … (255,0,255) max light.
8 * - G > 0 (still G < R) desaturates toward white/gray: mix(tint, white, G/R) * L.
9 * - Otherwise leave RGB as-is. World shaders apply darkness after this pass.
10 */
11
12export const MAGENTA_CHANNEL_EPS = 1 / 255;
13
14/** Display tint colors per material tier (0–1 RGB). */
15export const TIER_TINT_COLOR = Object.freeze({
16 [MaterialTier.bronze]: Object.freeze({ r: 0.72, g: 0.48, b: 0.28 }),
17 [MaterialTier.iron]: Object.freeze({ r: 0.62, g: 0.64, b: 0.68 }),
18 [MaterialTier.steel]: Object.freeze({ r: 0.78, g: 0.80, b: 0.84 }),
19 [MaterialTier.mithril]: Object.freeze({ r: 0.45, g: 0.55, b: 0.85 }),
20 [MaterialTier.adamantium]: Object.freeze({ r: 0.35, g: 0.75, b: 0.45 }),
21 [MaterialTier.orichalcum]: Object.freeze({ r: 0.85, g: 0.35, b: 0.55 })
22});
23
24export function normalizeRgb (color, fallback = { r: 0.7, g: 0.7, b: 0.7 })
25{
26 if (!color)
27 { return { r: fallback.r, g: fallback.g, b: fallback.b }; }
28 return {
29 r: clamp01(color.r ?? fallback.r),
30 g: clamp01(color.g ?? fallback.g),
31 b: clamp01(color.b ?? fallback.b)
32 };
33}
34
35export function tierTintColor (tier)
36{
37 return normalizeRgb(TIER_TINT_COLOR[tier] ?? TIER_TINT_COLOR[MaterialTier.bronze]);
38}
39
40/**
41 * Resolve tint for an inventory/ground stack or item def.
42 * Priority: potion instance.color → def.tint → tintFromTier + tier.
43 */
44export function resolveItemTint (stackOrDef, def = null)
45{
46 const stack = stackOrDef?.itemId != null ? stackOrDef : null;
47 const definition = def
48 ?? (stack ? itemDefinition(stack.itemId) : stackOrDef)
49 ?? null;
50 if (stack?.instance?.kind === "potion" && stack.instance.color)
51 { return normalizeRgb(stack.instance.color); }
52 if (definition?.tint)
53 { return normalizeRgb(definition.tint); }
54 const tier = resolveTintTier(definition);
55 if (tier)
56 { return tierTintColor(tier); }
57 return null;
58}
59
60export function resolveEquipTint (itemIdOrDef)
61{
62 const definition = typeof itemIdOrDef === "number"
63 ? itemDefinition(itemIdOrDef)
64 : itemIdOrDef;
65 if (!definition)
66 { return null; }
67 if (definition.tint)
68 { return normalizeRgb(definition.tint); }
69 const tier = resolveTintTier(definition);
70 if (tier)
71 { return tierTintColor(tier); }
72 return null;
73}
74
75function resolveTintTier (definition)
76{
77 if (!definition)
78 { return null; }
79 if (typeof definition.tintFromTier === "string")
80 { return definition.tintFromTier; }
81 if (definition.tintFromTier === true)
82 { return definition.equipment?.tier ?? definition.tier ?? null; }
83 if (definition.equipment?.tintFromTier)
84 { return definition.equipment.tier ?? null; }
85 return null;
86}
87
88/** Pure pixel transform (channels 0–1). Returns null if pixel is not tintable. */
89export function magentaTintedRgb (r, g, b, tintRgb)
90{
91 if (!isMagentaTintable(r, g, b))
92 { return null; }
93 const L = r;
94 const gBlend = r > 0 ? Math.min(1, Math.max(0, g / r)) : 0;
95 const tint = normalizeRgb(tintRgb);
96 return {
97 r: clamp01(mix(tint.r, 1, gBlend) * L),
98 g: clamp01(mix(tint.g, 1, gBlend) * L),
99 b: clamp01(mix(tint.b, 1, gBlend) * L)
100 };
101}
102
103export function isMagentaTintable (r, g, b, eps = MAGENTA_CHANNEL_EPS)
104{
105 return Math.abs(r - b) <= eps && g < r - eps;
106}
107
108/** Mutate ImageData in place with magenta→tint (alpha unchanged). */
109export function applyMagentaTintToImageData (imageData, tintRgb)
110{
111 const data = imageData.data;
112 const tint = normalizeRgb(tintRgb);
113 for (let i = 0; i < data.length; i += 4)
114 {
115 if (data[i + 3] < 8)
116 { continue; }
117 const r = data[i] / 255;
118 const g = data[i + 1] / 255;
119 const b = data[i + 2] / 255;
120 const next = magentaTintedRgb(r, g, b, tint);
121 if (!next)
122 { continue; }
123 data[i] = Math.round(next.r * 255);
124 data[i + 1] = Math.round(next.g * 255);
125 data[i + 2] = Math.round(next.b * 255);
126 }
127 return imageData;
128}
129
130export function listTierTintPreview ()
131{
132 return MATERIAL_TIER_ORDER.map((tier) => ({ tier, color: tierTintColor(tier) }));
133}
134
135function clamp01 (n)
136{
137 return Math.min(1, Math.max(0, Number(n) || 0));
138}
139
140function mix (a, b, t)
141{
142 return a + (b - a) * t;
143}