From 192dbd9b6ca85025c4e982dcd45bd24f9a48530d Mon Sep 17 00:00:00 2001 From: MihailRis Date: Fri, 24 Jul 2026 20:01:14 +0300 Subject: [PATCH] add math.noise2d --- res/modules/internal/extensions/math.lua | 46 ++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/res/modules/internal/extensions/math.lua b/res/modules/internal/extensions/math.lua index 1d168a377..97bbc33a6 100644 --- a/res/modules/internal/extensions/math.lua +++ b/res/modules/internal/extensions/math.lua @@ -71,3 +71,49 @@ function math.noise(x, octaves) end return value end + +local function lerp(a, b, t) + return a + (b - a) * t +end + +local function rand_2d(x, y) + return noise_rands[math.floor(x * 317 + y) % noise_period + 1] +end + +local function sample_noise2d(x, y) + local x0 = math.floor(x) + local y0 = math.floor(y) + local x1 = x0 + 1 + local y1 = y0 + 1 + + local tx = x - x0 + local ty = y - y0 + + local sx = smoothstep(tx) + local sy = smoothstep(ty) + + local c00 = rand_2d(x0, y0) + local c10 = rand_2d(x1, y0) + local c01 = rand_2d(x0, y1) + local c11 = rand_2d(x1, y1) + + local bottom = lerp(c00, c10, sx) + local top = lerp(c01, c11, sx) + + return lerp(bottom, top, sy) +end + + +function math.noise2d(x, y, octaves) + octaves = octaves or 1 + local value = 0.0 + local mul = 1.0 + for i=1,octaves do + value = value * (1.0 - mul) + + sample_noise2d(x + 37 * i, y + 73 * i) * mul + x = x * 2.0 + y = y * 2.0 + mul = mul * 0.5 + end + return value +end