BlueGit

timfa questward

Add subtle per-tile nature tint from chunk Perlin noise.

Blendable grounds sample a 16×16 world-continuous noise map (1px/tile) in the atlas lighting shader, with a temporary debug panel for scale/contrast/tint/darken.

timfa Tim Falken · pushed by timfa

Authored 2026-09-04 · 2 months ago

Hash
834aa073547f77a18112168714ab28979f32f63a
Parent
ad961024
5 files changed +361 −10
client/src/play/main.js +8 −0
@@ -38,6 +38,7 @@ import { bindHairControls } from "./hairControls.js";
38 38 import { bindCreateClothingControls } from "./createClothingControls.js";
39 39 import { paintCharacterPreview } from "./characterPreview.js";
40 40 import { initGraphicsSettings } from "./graphicsSettings.js";
41 import { initNatureTintDebugPanel } from "./natureTintDebug.js";
41 42 import { CraftingStationId } from "/shared/definitions/craftingStations.js";
42 43 import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
43 44 import { formatQuantity } from "/shared/items/formatQuantity.js";
@@ -1831,6 +1832,13 @@ async function main ()
1831 1832 onChange: applyGraphicsSettings,
1832 1833 onSuppressWorldClick: consumeWorldClick
1833 1834 });
1835 initNatureTintDebugPanel({
1836 onChange ({ rebuildNoise })
1837 {
1838 if (rebuildNoise)
1839 { view?.refreshNatureNoise?.(); }
1840 }
1841 });
1834 1842 social = initSocial({
1835 1843 socket: { send (payload) { socket.send(payload); } },
1836 1844 MessageType,
@@ -38,6 +38,7 @@ import { bindHairControls } from "./hairControls.js";
38import { bindCreateClothingControls } from "./createClothingControls.js";
38import { bindCreateClothingControls } from "./createClothingControls.js";
39import { paintCharacterPreview } from "./characterPreview.js";
39import { paintCharacterPreview } from "./characterPreview.js";
40import { initGraphicsSettings } from "./graphicsSettings.js";
40import { initGraphicsSettings } from "./graphicsSettings.js";
41import { initNatureTintDebugPanel } from "./natureTintDebug.js";
41import { CraftingStationId } from "/shared/definitions/craftingStations.js";
42import { CraftingStationId } from "/shared/definitions/craftingStations.js";
42import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
43import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
43import { formatQuantity } from "/shared/items/formatQuantity.js";
44import { formatQuantity } from "/shared/items/formatQuantity.js";
@@ -1831,6 +1832,13 @@ async function main ()
1831 onChange: applyGraphicsSettings,
1832 onChange: applyGraphicsSettings,
1832 onSuppressWorldClick: consumeWorldClick
1833 onSuppressWorldClick: consumeWorldClick
1833 });
1834 });
1835 initNatureTintDebugPanel({
1836 onChange ({ rebuildNoise })
1837 {
1838 if (rebuildNoise)
1839 { view?.refreshNatureNoise?.(); }
1840 }
1841 });
1834 social = initSocial({
1842 social = initSocial({
1835 socket: { send (payload) { socket.send(payload); } },
1843 socket: { send (payload) { socket.send(payload); } },
1836 MessageType,
1844 MessageType,
client/src/play/natureTintDebug.js added +166 −0
@@ -0,0 +1,166 @@
1 /**
2 * Temporary always-on nature tint debug panel (blendable “nature” grounds).
3 */
4
5 export const DEFAULT_NATURE_TINT = Object.freeze({
6 /** World-space noise frequency (tiles). */
7 scale: 0.08,
8 /** 0..1 how hard to reshape noise around mid-grey. */
9 contrast: 1,
10 /** Warm/cool recolor strength. */
11 tint: 0.12,
12 /** Brightness variation strength. */
13 darken: 0.08
14 });
15
16 const SLIDERS = [
17 { key: "scale", label: "Noise scale", min: 0.01, max: 0.4, step: 0.005 },
18 { key: "contrast", label: "Contrast", min: 0.4, max: 2.5, step: 0.05 },
19 { key: "tint", label: "Tint", min: 0, max: 0.45, step: 0.01 },
20 { key: "darken", label: "Darken", min: 0, max: 0.4, step: 0.01 }
21 ];
22
23 let params = { ...DEFAULT_NATURE_TINT };
24 let panelEl = null;
25 let onChange = null;
26
27 export function getNatureTintParams ()
28 {
29 return { ...params };
30 }
31
32 /** Shader uniforms for atlas nature tint (ground only). */
33 export function natureTintUniforms ()
34 {
35 const p = params;
36 return {
37 u_useNature: 1,
38 u_natureTint: p.tint,
39 u_natureDark: p.darken,
40 u_natureContrast: p.contrast
41 };
42 }
43
44 export function setNatureTintParams (next)
45 {
46 const prevScale = params.scale;
47 params = { ...DEFAULT_NATURE_TINT, ...params, ...next };
48 syncInputs();
49 onChange?.({
50 rebuildNoise: params.scale !== prevScale || next?.scale != null
51 });
52 }
53
54 function syncInputs ()
55 {
56 if (!panelEl)
57 { return; }
58 for (const { key } of SLIDERS)
59 {
60 const input = panelEl.querySelector(`input[data-nature-key="${key}"]`);
61 const valueEl = panelEl.querySelector(`[data-nature-value="${key}"]`);
62 if (input)
63 { input.value = String(params[key]); }
64 if (valueEl)
65 { valueEl.textContent = Number(params[key]).toFixed(3); }
66 }
67 }
68
69 /**
70 * @param {{ onChange?: (info: { rebuildNoise: boolean }) => void }} [opts]
71 */
72 export function initNatureTintDebugPanel (opts = {})
73 {
74 if (panelEl)
75 { return panelEl; }
76 onChange = opts.onChange ?? null;
77
78 panelEl = document.createElement("aside");
79 panelEl.id = "nature-tint-debug-panel";
80 panelEl.innerHTML = `
81 <header style="display:flex;align-items:center;gap:8px;">
82 <strong>Nature tint</strong>
83 </header>
84 <div class="nature-tint-scroll"></div>
85 <footer style="display:flex;gap:6px;">
86 <button type="button" data-nature-reset>Reset</button>
87 </footer>
88 `;
89 Object.assign(panelEl.style, {
90 position: "fixed",
91 top: "8px",
92 right: "8px",
93 width: "240px",
94 zIndex: "9999",
95 display: "flex",
96 flexDirection: "column",
97 gap: "4px",
98 padding: "8px",
99 background: "rgba(12, 16, 22, 0.92)",
100 color: "#e8eef5",
101 font: "11px/1.25 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
102 border: "1px solid rgba(255,255,255,0.18)",
103 borderRadius: "6px",
104 boxShadow: "0 8px 24px rgba(0,0,0,0.45)",
105 pointerEvents: "auto"
106 });
107
108 const scroll = panelEl.querySelector(".nature-tint-scroll");
109 Object.assign(scroll.style, {
110 display: "flex",
111 flexDirection: "column",
112 gap: "3px"
113 });
114
115 for (const spec of SLIDERS)
116 {
117 const row = document.createElement("label");
118 row.style.cssText = "display:grid;grid-template-columns:1fr 48px;gap:2px 6px;align-items:center;";
119 row.innerHTML = `
120 <span style="grid-column:1/-1;opacity:0.85">${spec.label}</span>
121 <input type="range" data-nature-key="${spec.key}" min="${spec.min}" max="${spec.max}" step="${spec.step}" value="${params[spec.key]}">
122 <span data-nature-value="${spec.key}" style="text-align:right;opacity:0.9">${Number(params[spec.key]).toFixed(3)}</span>
123 `;
124 const input = row.querySelector("input");
125 input.addEventListener("input", () =>
126 {
127 const prevScale = params.scale;
128 params[spec.key] = Number(input.value);
129 const valueEl = row.querySelector(`[data-nature-value="${spec.key}"]`);
130 if (valueEl)
131 { valueEl.textContent = Number(params[spec.key]).toFixed(3); }
132 onChange?.({ rebuildNoise: spec.key === "scale" && params.scale !== prevScale });
133 });
134 scroll.appendChild(row);
135 }
136
137 const resetBtn = panelEl.querySelector("[data-nature-reset]");
138 Object.assign(resetBtn.style, {
139 background: "transparent",
140 color: "inherit",
141 border: "1px solid rgba(255,255,255,0.22)",
142 borderRadius: "4px",
143 padding: "3px 8px",
144 cursor: "pointer",
145 font: "inherit"
146 });
147 resetBtn.addEventListener("click", (event) =>
148 {
149 event.preventDefault();
150 event.stopPropagation();
151 params = { ...DEFAULT_NATURE_TINT };
152 syncInputs();
153 onChange?.({ rebuildNoise: true });
154 });
155
156 for (const type of ["mousedown", "mouseup", "click", "wheel", "contextmenu", "pointerdown"])
157 {
158 panelEl.addEventListener(type, (event) =>
159 {
160 event.stopPropagation();
161 });
162 }
163
164 document.body.appendChild(panelEl);
165 return panelEl;
166 }
@@ -0,0 +1,166 @@
1/**
2 * Temporary always-on nature tint debug panel (blendable “nature” grounds).
3 */
4
5export const DEFAULT_NATURE_TINT = Object.freeze({
6 /** World-space noise frequency (tiles). */
7 scale: 0.08,
8 /** 0..1 how hard to reshape noise around mid-grey. */
9 contrast: 1,
10 /** Warm/cool recolor strength. */
11 tint: 0.12,
12 /** Brightness variation strength. */
13 darken: 0.08
14});
15
16const SLIDERS = [
17 { key: "scale", label: "Noise scale", min: 0.01, max: 0.4, step: 0.005 },
18 { key: "contrast", label: "Contrast", min: 0.4, max: 2.5, step: 0.05 },
19 { key: "tint", label: "Tint", min: 0, max: 0.45, step: 0.01 },
20 { key: "darken", label: "Darken", min: 0, max: 0.4, step: 0.01 }
21];
22
23let params = { ...DEFAULT_NATURE_TINT };
24let panelEl = null;
25let onChange = null;
26
27export function getNatureTintParams ()
28{
29 return { ...params };
30}
31
32/** Shader uniforms for atlas nature tint (ground only). */
33export function natureTintUniforms ()
34{
35 const p = params;
36 return {
37 u_useNature: 1,
38 u_natureTint: p.tint,
39 u_natureDark: p.darken,
40 u_natureContrast: p.contrast
41 };
42}
43
44export function setNatureTintParams (next)
45{
46 const prevScale = params.scale;
47 params = { ...DEFAULT_NATURE_TINT, ...params, ...next };
48 syncInputs();
49 onChange?.({
50 rebuildNoise: params.scale !== prevScale || next?.scale != null
51 });
52}
53
54function syncInputs ()
55{
56 if (!panelEl)
57 { return; }
58 for (const { key } of SLIDERS)
59 {
60 const input = panelEl.querySelector(`input[data-nature-key="${key}"]`);
61 const valueEl = panelEl.querySelector(`[data-nature-value="${key}"]`);
62 if (input)
63 { input.value = String(params[key]); }
64 if (valueEl)
65 { valueEl.textContent = Number(params[key]).toFixed(3); }
66 }
67}
68
69/**
70 * @param {{ onChange?: (info: { rebuildNoise: boolean }) => void }} [opts]
71 */
72export function initNatureTintDebugPanel (opts = {})
73{
74 if (panelEl)
75 { return panelEl; }
76 onChange = opts.onChange ?? null;
77
78 panelEl = document.createElement("aside");
79 panelEl.id = "nature-tint-debug-panel";
80 panelEl.innerHTML = `
81 <header style="display:flex;align-items:center;gap:8px;">
82 <strong>Nature tint</strong>
83 </header>
84 <div class="nature-tint-scroll"></div>
85 <footer style="display:flex;gap:6px;">
86 <button type="button" data-nature-reset>Reset</button>
87 </footer>
88 `;
89 Object.assign(panelEl.style, {
90 position: "fixed",
91 top: "8px",
92 right: "8px",
93 width: "240px",
94 zIndex: "9999",
95 display: "flex",
96 flexDirection: "column",
97 gap: "4px",
98 padding: "8px",
99 background: "rgba(12, 16, 22, 0.92)",
100 color: "#e8eef5",
101 font: "11px/1.25 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
102 border: "1px solid rgba(255,255,255,0.18)",
103 borderRadius: "6px",
104 boxShadow: "0 8px 24px rgba(0,0,0,0.45)",
105 pointerEvents: "auto"
106 });
107
108 const scroll = panelEl.querySelector(".nature-tint-scroll");
109 Object.assign(scroll.style, {
110 display: "flex",
111 flexDirection: "column",
112 gap: "3px"
113 });
114
115 for (const spec of SLIDERS)
116 {
117 const row = document.createElement("label");
118 row.style.cssText = "display:grid;grid-template-columns:1fr 48px;gap:2px 6px;align-items:center;";
119 row.innerHTML = `
120 <span style="grid-column:1/-1;opacity:0.85">${spec.label}</span>
121 <input type="range" data-nature-key="${spec.key}" min="${spec.min}" max="${spec.max}" step="${spec.step}" value="${params[spec.key]}">
122 <span data-nature-value="${spec.key}" style="text-align:right;opacity:0.9">${Number(params[spec.key]).toFixed(3)}</span>
123 `;
124 const input = row.querySelector("input");
125 input.addEventListener("input", () =>
126 {
127 const prevScale = params.scale;
128 params[spec.key] = Number(input.value);
129 const valueEl = row.querySelector(`[data-nature-value="${spec.key}"]`);
130 if (valueEl)
131 { valueEl.textContent = Number(params[spec.key]).toFixed(3); }
132 onChange?.({ rebuildNoise: spec.key === "scale" && params.scale !== prevScale });
133 });
134 scroll.appendChild(row);
135 }
136
137 const resetBtn = panelEl.querySelector("[data-nature-reset]");
138 Object.assign(resetBtn.style, {
139 background: "transparent",
140 color: "inherit",
141 border: "1px solid rgba(255,255,255,0.22)",
142 borderRadius: "4px",
143 padding: "3px 8px",
144 cursor: "pointer",
145 font: "inherit"
146 });
147 resetBtn.addEventListener("click", (event) =>
148 {
149 event.preventDefault();
150 event.stopPropagation();
151 params = { ...DEFAULT_NATURE_TINT };
152 syncInputs();
153 onChange?.({ rebuildNoise: true });
154 });
155
156 for (const type of ["mousedown", "mouseup", "click", "wheel", "contextmenu", "pointerdown"])
157 {
158 panelEl.addEventListener(type, (event) =>
159 {
160 event.stopPropagation();
161 });
162 }
163
164 document.body.appendChild(panelEl);
165 return panelEl;
166}
client/src/render/worldView.js +114 −10
@@ -28,6 +28,8 @@ import
28 28 } from "./canvasSprite.js";
29 29 import { setNearestFilter } from "./sprites.js";
30 30 import { waterDebugUniforms, lavaDebugUniforms } from "../play/waterDebug.js";
31 import { getNatureTintParams, natureTintUniforms } from "../play/natureTintDebug.js";
32 import { natureNoise01 } from "/shared/render/natureNoise.js";
31 33 import { SeasonId, seasonIdAt, resolveSeasonalVisualState } from "/shared/world/season.js";
32 34 import
33 35 {
@@ -874,19 +876,38 @@ const ATLAS_LIGHTING_FRAG = [
874 876 "varying vec2 v_texCoord;",
875 877 "uniform sampler2D u_texture;",
876 878 "uniform sampler2D u_secondary;",
879 "uniform sampler2D u_bump;",
877 880 "uniform float u_alpha;",
878 881 "uniform float u_ambientDark;",
879 882 "uniform float u_lightRow;",
883 "uniform float u_useNature;",
884 "uniform float u_natureTint;",
885 "uniform float u_natureDark;",
886 "uniform float u_natureContrast;",
880 887 "void main() {",
881 888 " vec4 color = texture2D(u_texture, v_texCoord);",
882 889 " if (color.a <= 0.0) { discard; }",
890 " vec3 rgb = color.rgb;",
891 " if (u_useNature > 0.5) {",
892 " vec2 tileUv = (floor(v_texCoord * 16.0) + 0.5) / 16.0;",
893 " vec4 nature = texture2D(u_bump, tileUv);",
894 " if (nature.a > 0.5) {",
895 " float n = clamp((nature.r - 0.5) * max(u_natureContrast, 0.01) + 0.5, 0.0, 1.0);",
896 " float c = (n - 0.5) * 2.0;",
897 " rgb *= 1.0 - c * u_natureDark;",
898 " vec3 cool = vec3(0.92, 1.03, 0.97);",
899 " vec3 warm = vec3(1.07, 1.02, 0.90);",
900 " vec3 tint = mix(cool, warm, n);",
901 " rgb *= mix(vec3(1.0), tint, clamp(u_natureTint, 0.0, 1.0));",
902 " }",
903 " }",
883 904 " vec2 lightUV = v_texCoord;",
884 905 " if (u_lightRow >= 0.0) {",
885 906 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
886 907 " }",
887 908 " float lit = texture2D(u_secondary, lightUV).r;",
888 909 " float darkness = u_ambientDark * (1.0 - lit);",
889 " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);",
910 " rgb = mix(rgb, vec3(0.0), darkness);",
890 911 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
891 912 "}"
892 913 ].join("\n");
@@ -4672,30 +4693,36 @@ export class WorldView
4672 4693 if (!baked)
4673 4694 {
4674 4695 const lightmapCanvas = makeLightmapCanvas(atlasPx);
4696 const natureCanvas = makeNatureNoiseCanvas();
4675 4697 baked = {
4676 4698 groundCanvas: atlases.ground,
4677 4699 blockCanvases: atlases.blockRows,
4678 4700 bloomCanvas: atlases.bloom,
4679 4701 lightmapCanvas,
4702 natureCanvas,
4680 4703 groundImage,
4681 4704 blockImages,
4682 4705 bloomImage,
4683 4706 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
4707 natureImage: frameworkImageFromCanvas(natureCanvas),
4684 4708 groundObject: null,
4685 4709 blockObjects: [],
4686 4710 bloomObject: null,
4687 4711 tallBlocks: atlases.tallBlocks,
4688 4712 animatedGrounds: atlases.animatedGrounds,
4689 4713 lightmapPixels: null,
4690 atlasCacheRefs: atlases.cacheRefs
4714 atlasCacheRefs: atlases.cacheRefs,
4715 chunkX: snapshot.chunkX,
4716 chunkY: snapshot.chunkY
4691 4717 };
4718 this.#fillNatureNoise(baked, snapshot);
4692 4719 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
4693 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
4720 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1, baked.natureImage);
4694 4721 this.scene.addObject(baked.groundObject);
4695 4722 for (let row = 0; row < CHUNK_SIZE; row++)
4696 4723 {
4697 4724 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
4698 this.#applyAtlasLighting(object, baked.lightmapImage, row);
4725 this.#applyAtlasLighting(object, baked.lightmapImage, row, null);
4699 4726 this.scene.addObject(object);
4700 4727 baked.blockObjects.push(object);
4701 4728 }
@@ -4707,13 +4734,21 @@ export class WorldView
4707 4734 }
4708 4735 else
4709 4736 {
4737 baked.chunkX = snapshot.chunkX;
4738 baked.chunkY = snapshot.chunkY;
4739 if (!baked.natureCanvas)
4740 {
4741 baked.natureCanvas = makeNatureNoiseCanvas();
4742 baked.natureImage = frameworkImageFromCanvas(baked.natureCanvas);
4743 }
4744 this.#fillNatureNoise(baked, snapshot);
4710 4745 if (baked.groundCanvas !== atlases.ground)
4711 4746 {
4712 4747 baked.groundCanvas = atlases.ground;
4713 4748 baked.groundImage = groundImage;
4714 4749 baked.groundObject.renderer.sprite = groundImage;
4715 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
4716 4750 }
4751 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1, baked.natureImage);
4717 4752 for (let row = 0; row < CHUNK_SIZE; row++)
4718 4753 {
4719 4754 if (baked.blockCanvases[row] !== atlases.blockRows[row])
@@ -4725,7 +4760,8 @@ export class WorldView
4725 4760 this.#applyAtlasLighting(
4726 4761 baked.blockObjects[row],
4727 4762 baked.lightmapImage,
4728 row
4763 row,
4764 null
4729 4765 );
4730 4766 }
4731 4767 if (baked.bloomCanvas !== atlases.bloom)
@@ -4797,6 +4833,7 @@ export class WorldView
4797 4833 { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); }
4798 4834 maybeWarm(baked.bloomCanvas, refs?.bloom);
4799 4835 this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY);
4836 this.#queueCanvasTextureWarm(baked.natureCanvas, chunkX, chunkY);
4800 4837 }
4801 4838
4802 4839 #scheduleTextureWarm ()
@@ -4823,20 +4860,73 @@ export class WorldView
4823 4860 { this.#scheduleTextureWarm(); }
4824 4861 }
4825 4862
4826 #applyAtlasLighting (object, lightmapImage, lightRow)
4863 #applyAtlasLighting (object, lightmapImage, lightRow, natureImage = null)
4827 4864 {
4828 4865 if (!object?.renderer)
4829 4866 { return; }
4830 4867 object._lit = true;
4831 4868 object.renderer.shader = getAtlasLightingShader();
4832 object.renderer.bumpMap = null;
4869 const useNature = natureImage != null && lightRow < 0;
4870 object.renderer.bumpMap = useNature ? natureImage : null;
4833 4871 object.renderer.secondaryMap = lightmapImage;
4834 4872 object.renderer.shaderUniforms = {
4835 4873 u_ambientDark: 0,
4836 u_lightRow: lightRow
4874 u_lightRow: lightRow,
4875 u_useNature: useNature ? 1 : 0,
4876 u_natureTint: 0,
4877 u_natureDark: 0,
4878 u_natureContrast: 1,
4879 ...(useNature ? natureTintUniforms() : {})
4837 4880 };
4838 4881 }
4839 4882
4883 /** Rebuild 16×16 nature noise for every loaded chunk (e.g. debug scale change). */
4884 refreshNatureNoise ()
4885 {
4886 for (const baked of this.bakedChunks.values())
4887 {
4888 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
4889 if (!snapshot || !baked.natureCanvas)
4890 { continue; }
4891 this.#fillNatureNoise(baked, snapshot);
4892 if (baked.groundObject)
4893 { this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1, baked.natureImage); }
4894 }
4895 }
4896
4897 #fillNatureNoise (baked, snapshot)
4898 {
4899 if (!baked?.natureCanvas || !snapshot)
4900 { return; }
4901 const scale = getNatureTintParams().scale;
4902 const ctx = baked.natureCanvas.getContext("2d");
4903 const image = ctx.createImageData(CHUNK_SIZE, CHUNK_SIZE);
4904 const grounds = snapshot.grounds;
4905 const baseX = snapshot.chunkX * CHUNK_SIZE;
4906 const baseY = snapshot.chunkY * CHUNK_SIZE;
4907 for (let ly = 0; ly < CHUNK_SIZE; ly++)
4908 {
4909 for (let lx = 0; lx < CHUNK_SIZE; lx++)
4910 {
4911 const index = ly * CHUNK_SIZE + lx;
4912 const ground = normalizeGround(grounds?.[index]);
4913 const blendable = !!GROUND_DEFINITIONS[ground.typeId]?.blendable;
4914 const n = natureNoise01(baseX + lx, baseY + ly, scale);
4915 const i = index * 4;
4916 const v = Math.round(n * 255);
4917 image.data[i] = v;
4918 image.data[i + 1] = v;
4919 image.data[i + 2] = v;
4920 image.data[i + 3] = blendable ? 255 : 0;
4921 }
4922 }
4923 ctx.putImageData(image, 0, 0);
4924 invalidateCanvasTexture(this.scene, baked.natureCanvas);
4925 this.#queueCanvasTextureWarm(baked.natureCanvas, snapshot.chunkX, snapshot.chunkY);
4926 if (!baked.natureImage)
4927 { baked.natureImage = frameworkImageFromCanvas(baked.natureCanvas); }
4928 }
4929
4840 4930 #syncCliffGroundTopSprite (object, darkness, groundImage, localX, localY)
4841 4931 {
4842 4932 if (!object?.renderer)
@@ -4895,6 +4985,7 @@ export class WorldView
4895 4985 { object.destroy(); }
4896 4986 baked.bloomObject?.destroy();
4897 4987 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
4988 invalidateCanvasTexture(this.scene, baked.natureCanvas);
4898 4989 this.bakedChunks.delete(key);
4899 4990 }
4900 4991
@@ -5398,7 +5489,12 @@ export class WorldView
5398 5489 this.#writeChunkLightmap(baked, lights, mobileLights, blockLights, lightOcclusion, ambientDark);
5399 5490 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
5400 5491 if (baked.groundObject?.renderer?.shaderUniforms)
5401 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = 1; }
5492 {
5493 Object.assign(baked.groundObject.renderer.shaderUniforms, {
5494 u_ambientDark: 1,
5495 ...natureTintUniforms()
5496 });
5497 }
5402 5498 for (const object of baked.blockObjects ?? [])
5403 5499 {
5404 5500 if (object?.renderer?.shaderUniforms)
@@ -6016,6 +6112,14 @@ function makeLightmapCanvas (size)
6016 6112 return canvas;
6017 6113 }
6018 6114
6115 function makeNatureNoiseCanvas ()
6116 {
6117 const canvas = document.createElement("canvas");
6118 canvas.width = CHUNK_SIZE;
6119 canvas.height = CHUNK_SIZE;
6120 return canvas;
6121 }
6122
6019 6123 function copyCanvas (source, dest)
6020 6124 {
6021 6125 const ctx = dest.getContext("2d");
@@ -28,6 +28,8 @@ import
28} from "./canvasSprite.js";
28} from "./canvasSprite.js";
29import { setNearestFilter } from "./sprites.js";
29import { setNearestFilter } from "./sprites.js";
30import { waterDebugUniforms, lavaDebugUniforms } from "../play/waterDebug.js";
30import { waterDebugUniforms, lavaDebugUniforms } from "../play/waterDebug.js";
31import { getNatureTintParams, natureTintUniforms } from "../play/natureTintDebug.js";
32import { natureNoise01 } from "/shared/render/natureNoise.js";
31import { SeasonId, seasonIdAt, resolveSeasonalVisualState } from "/shared/world/season.js";
33import { SeasonId, seasonIdAt, resolveSeasonalVisualState } from "/shared/world/season.js";
32import
34import
33{
35{
@@ -874,19 +876,38 @@ const ATLAS_LIGHTING_FRAG = [
874 "varying vec2 v_texCoord;",
876 "varying vec2 v_texCoord;",
875 "uniform sampler2D u_texture;",
877 "uniform sampler2D u_texture;",
876 "uniform sampler2D u_secondary;",
878 "uniform sampler2D u_secondary;",
879 "uniform sampler2D u_bump;",
877 "uniform float u_alpha;",
880 "uniform float u_alpha;",
878 "uniform float u_ambientDark;",
881 "uniform float u_ambientDark;",
879 "uniform float u_lightRow;",
882 "uniform float u_lightRow;",
883 "uniform float u_useNature;",
884 "uniform float u_natureTint;",
885 "uniform float u_natureDark;",
886 "uniform float u_natureContrast;",
880 "void main() {",
887 "void main() {",
881 " vec4 color = texture2D(u_texture, v_texCoord);",
888 " vec4 color = texture2D(u_texture, v_texCoord);",
882 " if (color.a <= 0.0) { discard; }",
889 " if (color.a <= 0.0) { discard; }",
890 " vec3 rgb = color.rgb;",
891 " if (u_useNature > 0.5) {",
892 " vec2 tileUv = (floor(v_texCoord * 16.0) + 0.5) / 16.0;",
893 " vec4 nature = texture2D(u_bump, tileUv);",
894 " if (nature.a > 0.5) {",
895 " float n = clamp((nature.r - 0.5) * max(u_natureContrast, 0.01) + 0.5, 0.0, 1.0);",
896 " float c = (n - 0.5) * 2.0;",
897 " rgb *= 1.0 - c * u_natureDark;",
898 " vec3 cool = vec3(0.92, 1.03, 0.97);",
899 " vec3 warm = vec3(1.07, 1.02, 0.90);",
900 " vec3 tint = mix(cool, warm, n);",
901 " rgb *= mix(vec3(1.0), tint, clamp(u_natureTint, 0.0, 1.0));",
902 " }",
903 " }",
883 " vec2 lightUV = v_texCoord;",
904 " vec2 lightUV = v_texCoord;",
884 " if (u_lightRow >= 0.0) {",
905 " if (u_lightRow >= 0.0) {",
885 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
906 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
886 " }",
907 " }",
887 " float lit = texture2D(u_secondary, lightUV).r;",
908 " float lit = texture2D(u_secondary, lightUV).r;",
888 " float darkness = u_ambientDark * (1.0 - lit);",
909 " float darkness = u_ambientDark * (1.0 - lit);",
889 " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);",
910 " rgb = mix(rgb, vec3(0.0), darkness);",
890 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
911 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
891 "}"
912 "}"
892].join("\n");
913].join("\n");
@@ -4672,30 +4693,36 @@ export class WorldView
4672 if (!baked)
4693 if (!baked)
4673 {
4694 {
4674 const lightmapCanvas = makeLightmapCanvas(atlasPx);
4695 const lightmapCanvas = makeLightmapCanvas(atlasPx);
4696 const natureCanvas = makeNatureNoiseCanvas();
4675 baked = {
4697 baked = {
4676 groundCanvas: atlases.ground,
4698 groundCanvas: atlases.ground,
4677 blockCanvases: atlases.blockRows,
4699 blockCanvases: atlases.blockRows,
4678 bloomCanvas: atlases.bloom,
4700 bloomCanvas: atlases.bloom,
4679 lightmapCanvas,
4701 lightmapCanvas,
4702 natureCanvas,
4680 groundImage,
4703 groundImage,
4681 blockImages,
4704 blockImages,
4682 bloomImage,
4705 bloomImage,
4683 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
4706 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
4707 natureImage: frameworkImageFromCanvas(natureCanvas),
4684 groundObject: null,
4708 groundObject: null,
4685 blockObjects: [],
4709 blockObjects: [],
4686 bloomObject: null,
4710 bloomObject: null,
4687 tallBlocks: atlases.tallBlocks,
4711 tallBlocks: atlases.tallBlocks,
4688 animatedGrounds: atlases.animatedGrounds,
4712 animatedGrounds: atlases.animatedGrounds,
4689 lightmapPixels: null,
4713 lightmapPixels: null,
4690 atlasCacheRefs: atlases.cacheRefs
4714 atlasCacheRefs: atlases.cacheRefs,
4715 chunkX: snapshot.chunkX,
4716 chunkY: snapshot.chunkY
4691 };
4717 };
4718 this.#fillNatureNoise(baked, snapshot);
4692 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
4719 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
4693 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
4720 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1, baked.natureImage);
4694 this.scene.addObject(baked.groundObject);
4721 this.scene.addObject(baked.groundObject);
4695 for (let row = 0; row < CHUNK_SIZE; row++)
4722 for (let row = 0; row < CHUNK_SIZE; row++)
4696 {
4723 {
4697 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
4724 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
4698 this.#applyAtlasLighting(object, baked.lightmapImage, row);
4725 this.#applyAtlasLighting(object, baked.lightmapImage, row, null);
4699 this.scene.addObject(object);
4726 this.scene.addObject(object);
4700 baked.blockObjects.push(object);
4727 baked.blockObjects.push(object);
4701 }
4728 }
@@ -4707,13 +4734,21 @@ export class WorldView
4707 }
4734 }
4708 else
4735 else
4709 {
4736 {
4737 baked.chunkX = snapshot.chunkX;
4738 baked.chunkY = snapshot.chunkY;
4739 if (!baked.natureCanvas)
4740 {
4741 baked.natureCanvas = makeNatureNoiseCanvas();
4742 baked.natureImage = frameworkImageFromCanvas(baked.natureCanvas);
4743 }
4744 this.#fillNatureNoise(baked, snapshot);
4710 if (baked.groundCanvas !== atlases.ground)
4745 if (baked.groundCanvas !== atlases.ground)
4711 {
4746 {
4712 baked.groundCanvas = atlases.ground;
4747 baked.groundCanvas = atlases.ground;
4713 baked.groundImage = groundImage;
4748 baked.groundImage = groundImage;
4714 baked.groundObject.renderer.sprite = groundImage;
4749 baked.groundObject.renderer.sprite = groundImage;
4715 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
4716 }
4750 }
4751 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1, baked.natureImage);
4717 for (let row = 0; row < CHUNK_SIZE; row++)
4752 for (let row = 0; row < CHUNK_SIZE; row++)
4718 {
4753 {
4719 if (baked.blockCanvases[row] !== atlases.blockRows[row])
4754 if (baked.blockCanvases[row] !== atlases.blockRows[row])
@@ -4725,7 +4760,8 @@ export class WorldView
4725 this.#applyAtlasLighting(
4760 this.#applyAtlasLighting(
4726 baked.blockObjects[row],
4761 baked.blockObjects[row],
4727 baked.lightmapImage,
4762 baked.lightmapImage,
4728 row
4763 row,
4764 null
4729 );
4765 );
4730 }
4766 }
4731 if (baked.bloomCanvas !== atlases.bloom)
4767 if (baked.bloomCanvas !== atlases.bloom)
@@ -4797,6 +4833,7 @@ export class WorldView
4797 { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); }
4833 { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); }
4798 maybeWarm(baked.bloomCanvas, refs?.bloom);
4834 maybeWarm(baked.bloomCanvas, refs?.bloom);
4799 this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY);
4835 this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY);
4836 this.#queueCanvasTextureWarm(baked.natureCanvas, chunkX, chunkY);
4800 }
4837 }
4801
4838
4802 #scheduleTextureWarm ()
4839 #scheduleTextureWarm ()
@@ -4823,20 +4860,73 @@ export class WorldView
4823 { this.#scheduleTextureWarm(); }
4860 { this.#scheduleTextureWarm(); }
4824 }
4861 }
4825
4862
4826 #applyAtlasLighting (object, lightmapImage, lightRow)
4863 #applyAtlasLighting (object, lightmapImage, lightRow, natureImage = null)
4827 {
4864 {
4828 if (!object?.renderer)
4865 if (!object?.renderer)
4829 { return; }
4866 { return; }
4830 object._lit = true;
4867 object._lit = true;
4831 object.renderer.shader = getAtlasLightingShader();
4868 object.renderer.shader = getAtlasLightingShader();
4832 object.renderer.bumpMap = null;
4869 const useNature = natureImage != null && lightRow < 0;
4870 object.renderer.bumpMap = useNature ? natureImage : null;
4833 object.renderer.secondaryMap = lightmapImage;
4871 object.renderer.secondaryMap = lightmapImage;
4834 object.renderer.shaderUniforms = {
4872 object.renderer.shaderUniforms = {
4835 u_ambientDark: 0,
4873 u_ambientDark: 0,
4836 u_lightRow: lightRow
4874 u_lightRow: lightRow,
4875 u_useNature: useNature ? 1 : 0,
4876 u_natureTint: 0,
4877 u_natureDark: 0,
4878 u_natureContrast: 1,
4879 ...(useNature ? natureTintUniforms() : {})
4837 };
4880 };
4838 }
4881 }
4839
4882
4883 /** Rebuild 16×16 nature noise for every loaded chunk (e.g. debug scale change). */
4884 refreshNatureNoise ()
4885 {
4886 for (const baked of this.bakedChunks.values())
4887 {
4888 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
4889 if (!snapshot || !baked.natureCanvas)
4890 { continue; }
4891 this.#fillNatureNoise(baked, snapshot);
4892 if (baked.groundObject)
4893 { this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1, baked.natureImage); }
4894 }
4895 }
4896
4897 #fillNatureNoise (baked, snapshot)
4898 {
4899 if (!baked?.natureCanvas || !snapshot)
4900 { return; }
4901 const scale = getNatureTintParams().scale;
4902 const ctx = baked.natureCanvas.getContext("2d");
4903 const image = ctx.createImageData(CHUNK_SIZE, CHUNK_SIZE);
4904 const grounds = snapshot.grounds;
4905 const baseX = snapshot.chunkX * CHUNK_SIZE;
4906 const baseY = snapshot.chunkY * CHUNK_SIZE;
4907 for (let ly = 0; ly < CHUNK_SIZE; ly++)
4908 {
4909 for (let lx = 0; lx < CHUNK_SIZE; lx++)
4910 {
4911 const index = ly * CHUNK_SIZE + lx;
4912 const ground = normalizeGround(grounds?.[index]);
4913 const blendable = !!GROUND_DEFINITIONS[ground.typeId]?.blendable;
4914 const n = natureNoise01(baseX + lx, baseY + ly, scale);
4915 const i = index * 4;
4916 const v = Math.round(n * 255);
4917 image.data[i] = v;
4918 image.data[i + 1] = v;
4919 image.data[i + 2] = v;
4920 image.data[i + 3] = blendable ? 255 : 0;
4921 }
4922 }
4923 ctx.putImageData(image, 0, 0);
4924 invalidateCanvasTexture(this.scene, baked.natureCanvas);
4925 this.#queueCanvasTextureWarm(baked.natureCanvas, snapshot.chunkX, snapshot.chunkY);
4926 if (!baked.natureImage)
4927 { baked.natureImage = frameworkImageFromCanvas(baked.natureCanvas); }
4928 }
4929
4840 #syncCliffGroundTopSprite (object, darkness, groundImage, localX, localY)
4930 #syncCliffGroundTopSprite (object, darkness, groundImage, localX, localY)
4841 {
4931 {
4842 if (!object?.renderer)
4932 if (!object?.renderer)
@@ -4895,6 +4985,7 @@ export class WorldView
4895 { object.destroy(); }
4985 { object.destroy(); }
4896 baked.bloomObject?.destroy();
4986 baked.bloomObject?.destroy();
4897 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
4987 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
4988 invalidateCanvasTexture(this.scene, baked.natureCanvas);
4898 this.bakedChunks.delete(key);
4989 this.bakedChunks.delete(key);
4899 }
4990 }
4900
4991
@@ -5398,7 +5489,12 @@ export class WorldView
5398 this.#writeChunkLightmap(baked, lights, mobileLights, blockLights, lightOcclusion, ambientDark);
5489 this.#writeChunkLightmap(baked, lights, mobileLights, blockLights, lightOcclusion, ambientDark);
5399 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
5490 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
5400 if (baked.groundObject?.renderer?.shaderUniforms)
5491 if (baked.groundObject?.renderer?.shaderUniforms)
5401 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = 1; }
5492 {
5493 Object.assign(baked.groundObject.renderer.shaderUniforms, {
5494 u_ambientDark: 1,
5495 ...natureTintUniforms()
5496 });
5497 }
5402 for (const object of baked.blockObjects ?? [])
5498 for (const object of baked.blockObjects ?? [])
5403 {
5499 {
5404 if (object?.renderer?.shaderUniforms)
5500 if (object?.renderer?.shaderUniforms)
@@ -6016,6 +6112,14 @@ function makeLightmapCanvas (size)
6016 return canvas;
6112 return canvas;
6017}
6113}
6018
6114
6115function makeNatureNoiseCanvas ()
6116{
6117 const canvas = document.createElement("canvas");
6118 canvas.width = CHUNK_SIZE;
6119 canvas.height = CHUNK_SIZE;
6120 return canvas;
6121}
6122
6019function copyCanvas (source, dest)
6123function copyCanvas (source, dest)
6020{
6124{
6021 const ctx = dest.getContext("2d");
6125 const ctx = dest.getContext("2d");
server/tests/nature-noise.test.js added +19 −0
@@ -0,0 +1,19 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { natureNoise01, perlin2 } from "../../shared/render/natureNoise.js";
4 import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
5
6 test("nature noise is continuous across chunk borders", () =>
7 {
8 const scale = 0.08;
9 const a = natureNoise01(CHUNK_SIZE - 1, 5, scale);
10 const b = natureNoise01(CHUNK_SIZE, 5, scale);
11 assert.ok(Math.abs(a - b) < 0.25, `border jump too large: ${a} vs ${b}`);
12 });
13
14 test("perlin is deterministic and bounded", () =>
15 {
16 assert.equal(perlin2(1.5, 2.5), perlin2(1.5, 2.5));
17 const n = natureNoise01(12, 34, 0.1);
18 assert.ok(n >= 0 && n <= 1);
19 });
@@ -0,0 +1,19 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { natureNoise01, perlin2 } from "../../shared/render/natureNoise.js";
4import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
5
6test("nature noise is continuous across chunk borders", () =>
7{
8 const scale = 0.08;
9 const a = natureNoise01(CHUNK_SIZE - 1, 5, scale);
10 const b = natureNoise01(CHUNK_SIZE, 5, scale);
11 assert.ok(Math.abs(a - b) < 0.25, `border jump too large: ${a} vs ${b}`);
12});
13
14test("perlin is deterministic and bounded", () =>
15{
16 assert.equal(perlin2(1.5, 2.5), perlin2(1.5, 2.5));
17 const n = natureNoise01(12, 34, 0.1);
18 assert.ok(n >= 0 && n <= 1);
19});
shared/render/natureNoise.js added +54 −0
@@ -0,0 +1,54 @@
1 /**
2 * World-space tile noise for subtle nature-ground tint (1 sample per tile).
3 * Uses chunk+local indices so adjacent chunks share a continuous field.
4 */
5
6 function fade (t)
7 {
8 return t * t * t * (t * (t * 6 - 15) + 10);
9 }
10
11 function lerp (a, b, t)
12 {
13 return a + (b - a) * t;
14 }
15
16 function hash2 (ix, iy)
17 {
18 const n = Math.sin(ix * 127.1 + iy * 311.7) * 43758.5453123;
19 return n - Math.floor(n);
20 }
21
22 /** Gradient-style value at integer lattice. */
23 function gradDot (ix, iy, x, y)
24 {
25 const angle = hash2(ix, iy) * Math.PI * 2;
26 return Math.cos(angle) * x + Math.sin(angle) * y;
27 }
28
29 /** Classic 2D Perlin in roughly [-1, 1]. */
30 export function perlin2 (x, y)
31 {
32 const x0 = Math.floor(x);
33 const y0 = Math.floor(y);
34 const fx = x - x0;
35 const fy = y - y0;
36 const u = fade(fx);
37 const v = fade(fy);
38 const n00 = gradDot(x0, y0, fx, fy);
39 const n10 = gradDot(x0 + 1, y0, fx - 1, fy);
40 const n01 = gradDot(x0, y0 + 1, fx, fy - 1);
41 const n11 = gradDot(x0 + 1, y0 + 1, fx - 1, fy - 1);
42 return lerp(lerp(n00, n10, u), lerp(n01, n11, u), v);
43 }
44
45 /** 0..1 FBM of Perlin (2 octaves — cheap for 16×16 fills). */
46 export function natureNoise01 (worldTileX, worldTileY, scale = 0.08)
47 {
48 const s = Math.max(0.001, Number(scale) || 0.08);
49 const x = worldTileX * s;
50 const y = worldTileY * s;
51 let sum = perlin2(x, y);
52 sum += 0.5 * perlin2(x * 2.0 + 19.1, y * 2.0 - 7.3);
53 return Math.min(1, Math.max(0, sum * 0.5 + 0.5));
54 }
@@ -0,0 +1,54 @@
1/**
2 * World-space tile noise for subtle nature-ground tint (1 sample per tile).
3 * Uses chunk+local indices so adjacent chunks share a continuous field.
4 */
5
6function fade (t)
7{
8 return t * t * t * (t * (t * 6 - 15) + 10);
9}
10
11function lerp (a, b, t)
12{
13 return a + (b - a) * t;
14}
15
16function hash2 (ix, iy)
17{
18 const n = Math.sin(ix * 127.1 + iy * 311.7) * 43758.5453123;
19 return n - Math.floor(n);
20}
21
22/** Gradient-style value at integer lattice. */
23function gradDot (ix, iy, x, y)
24{
25 const angle = hash2(ix, iy) * Math.PI * 2;
26 return Math.cos(angle) * x + Math.sin(angle) * y;
27}
28
29/** Classic 2D Perlin in roughly [-1, 1]. */
30export function perlin2 (x, y)
31{
32 const x0 = Math.floor(x);
33 const y0 = Math.floor(y);
34 const fx = x - x0;
35 const fy = y - y0;
36 const u = fade(fx);
37 const v = fade(fy);
38 const n00 = gradDot(x0, y0, fx, fy);
39 const n10 = gradDot(x0 + 1, y0, fx - 1, fy);
40 const n01 = gradDot(x0, y0 + 1, fx, fy - 1);
41 const n11 = gradDot(x0 + 1, y0 + 1, fx - 1, fy - 1);
42 return lerp(lerp(n00, n10, u), lerp(n01, n11, u), v);
43}
44
45/** 0..1 FBM of Perlin (2 octaves — cheap for 16×16 fills). */
46export function natureNoise01 (worldTileX, worldTileY, scale = 0.08)
47{
48 const s = Math.max(0.001, Number(scale) || 0.08);
49 const x = worldTileX * s;
50 const y = worldTileY * s;
51 let sum = perlin2(x, y);
52 sum += 0.5 * perlin2(x * 2.0 + 19.1, y * 2.0 - 7.3);
53 return Math.min(1, Math.max(0, sum * 0.5 + 0.5));
54}