diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cafc3d0..5b13040 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -196,7 +196,7 @@ jobs: - name: Install shader tools run: | sudo apt-get update - sudo apt-get install -y glslc glslang-tools + sudo apt-get install -y glslc glslang-tools spirv-tools # Byte comparison against the committed .spv is not usable here: glslc # embeds its own generator version, so a different toolchain produces @@ -297,6 +297,15 @@ jobs: done exit $fail + - name: Game frame block matches its C++ mirror + working-directory: SleakCraft + run: | + python3 Engine/scripts/check_ubo_layout.py \ + --header Game/include/World/VoxelLighting.hpp \ + --include-dir Engine/assets/shaders/include \ + --include-dir Game/assets/shaders/include \ + --check CraftFrameData:craft/frame.glsl:CraftFrameUBO + # Compiling proves nothing about whether the game runs. Runners have no GPU, # but Mesa's software Vulkan (lavapipe) plus a virtual display is enough to # boot the real binary into a real world and catch startup crashes, missing diff --git a/Engine b/Engine index 5e5f135..49c6b0e 160000 --- a/Engine +++ b/Engine @@ -1 +1 @@ -Subproject commit 5e5f135c66911433df155e4105eceadd0eae8658 +Subproject commit 49c6b0e0eacd9ba8856d62edee518098df66efeb diff --git a/Game/assets/shaders/flat_shader.frag b/Game/assets/shaders/flat_shader.frag index 946920f..bb23d69 100644 --- a/Game/assets/shaders/flat_shader.frag +++ b/Game/assets/shaders/flat_shader.frag @@ -13,6 +13,7 @@ layout(set = 0, binding = 0) uniform sampler2D diffuseTexture; #include "sleak/shadow_light.glsl" #include "sleak/frame.glsl" +#include "sleak/color.glsl" layout(set = 3, binding = 0) uniform sampler2DShadow shadowMap; @@ -73,7 +74,7 @@ void main() { // AO is stored in vertex color. Apply only to ambient. float ao = fragColor.r; - vec3 baseColor = texColor.rgb; + vec3 baseColor = SleakLinearToSrgb(texColor.rgb); vec3 N = normalize(fragWorldNorm); vec3 lightDir = normalize(uLightDir.xyz); diff --git a/Game/assets/shaders/flat_shader.frag.spv b/Game/assets/shaders/flat_shader.frag.spv index 3bc97ba..5c40f2d 100644 Binary files a/Game/assets/shaders/flat_shader.frag.spv and b/Game/assets/shaders/flat_shader.frag.spv differ diff --git a/Game/assets/shaders/flat_shader_gl.frag b/Game/assets/shaders/flat_shader_gl.frag index 60e7a45..f16adb1 100644 --- a/Game/assets/shaders/flat_shader_gl.frag +++ b/Game/assets/shaders/flat_shader_gl.frag @@ -41,6 +41,7 @@ layout(std140, binding = 5) uniform ShadowUBO { }; #include "sleak/frame.glsl" +#include "sleak/color.glsl" layout(binding = 0) uniform sampler2D diffuseTexture; layout(binding = 3) uniform sampler2DShadow shadowMap; @@ -104,7 +105,7 @@ void main() { // AO is stored in vertex color. Apply only to ambient. float ao = fragColor.r; - vec3 baseColor = texColor.rgb; + vec3 baseColor = SleakLinearToSrgb(texColor.rgb); vec3 N = normalize(fragWorldNorm); diff --git a/Game/assets/shaders/gbuffer_voxel.frag b/Game/assets/shaders/gbuffer_voxel.frag index 6ef1d16..dcd41b8 100644 --- a/Game/assets/shaders/gbuffer_voxel.frag +++ b/Game/assets/shaders/gbuffer_voxel.frag @@ -1,10 +1,11 @@ #version 450 #extension GL_GOOGLE_include_directive : require -// GBuffer pass, voxel format: engine gbuffer.frag plus RT3 (voxel model) +// GBuffer pass, voxel format: engine gbuffer.frag with the voxel RT2 and RT3 +// (craft/voxel_surface.glsl) #include "sleak/frame.glsl" -#include "craft/shading_models.glsl" +#include "craft/voxel_surface.glsl" layout(location = 0) in vec3 fragWorldPos; layout(location = 1) in vec3 fragWorldNorm; @@ -90,14 +91,11 @@ void main() { : fragColor.r * aoFactor; ao = clamp(ao, 0.0, 1.0); - // --- Emissive (HDR in RT2.gba) --- - vec3 emissive = hasEmissiveMap != 0u - ? texture(texEmissive, uv).rgb * emissiveFactor.rgb * emissiveFactor.w - : emissiveFactor.rgb * emissiveFactor.w; - outAlbedoAO = SleakFrameGuard(vec4(albedoSample.rgb, ao)); outNormalRough = vec4(N * 0.5 + 0.5, roughness); - outMetalEmit = vec4(metallic, emissive); - outMotionModel = SleakEncodeMotionModel(vec2(0.0), 0.0, - CRAFT_SHADING_MODEL_VOXEL); + outMetalEmit = CraftEncodeVoxelRT2(metallic, + CraftTexelEmission(albedoSample.rgb), + CRAFT_NO_BLOCK_LIGHT); + outMotionModel = CraftEncodeVoxelRT3(CRAFT_SKY_LIGHT_OPEN, + CRAFT_SHADING_MODEL_VOXEL); } diff --git a/Game/assets/shaders/gbuffer_voxel.frag.spv b/Game/assets/shaders/gbuffer_voxel.frag.spv index e7c9917..68c7318 100644 Binary files a/Game/assets/shaders/gbuffer_voxel.frag.spv and b/Game/assets/shaders/gbuffer_voxel.frag.spv differ diff --git a/Game/assets/shaders/gbuffer_voxel.vert.spv b/Game/assets/shaders/gbuffer_voxel.vert.spv index 63927d6..dd43992 100644 Binary files a/Game/assets/shaders/gbuffer_voxel.vert.spv and b/Game/assets/shaders/gbuffer_voxel.vert.spv differ diff --git a/Game/assets/shaders/gbuffer_voxel_gl.frag b/Game/assets/shaders/gbuffer_voxel_gl.frag index ba7ed29..ea45cc8 100644 --- a/Game/assets/shaders/gbuffer_voxel_gl.frag +++ b/Game/assets/shaders/gbuffer_voxel_gl.frag @@ -1,7 +1,8 @@ #version 450 core #extension GL_GOOGLE_include_directive : require -// GBuffer pass, OpenGL, voxel format: engine gbuffer_gl.frag plus RT3 +// GBuffer pass, OpenGL, voxel format: engine gbuffer_gl.frag with the voxel +// RT2 and RT3 (craft/voxel_surface.glsl) in vec3 fragWorldPos; in vec3 fragWorldNorm; @@ -52,7 +53,7 @@ layout(std140, binding = 1) uniform MaterialUBO { }; #include "sleak/frame.glsl" -#include "craft/shading_models.glsl" +#include "craft/voxel_surface.glsl" void main() { vec2 uv = fragUV * matTiling + matOffset; @@ -79,13 +80,12 @@ void main() { : matMetallic; float ao = (HasAOMap != 0u) ? texture(aoTexture, uv).r : (matAO * fragColor.r); - float emitScale = (HasEmissiveMap != 0u) - ? length(texture(emissiveTexture, uv).rgb) - : length(matEmissiveColor) * matEmissiveIntensity; outAlbedoAO = SleakFrameGuard(vec4(albedo.rgb, ao)); outNormalRough = vec4(N * 0.5 + 0.5, roughness); // pack normal to [0,1] - outMetalEmit = vec4(metallic, clamp(emitScale, 0.0, 1.0), 0.0, 1.0); - outMotionModel = SleakEncodeMotionModel(vec2(0.0), 0.0, - CRAFT_SHADING_MODEL_VOXEL); + outMetalEmit = CraftEncodeVoxelRT2(metallic, + CraftTexelEmission(albedo.rgb), + CRAFT_NO_BLOCK_LIGHT); + outMotionModel = CraftEncodeVoxelRT3(CRAFT_SKY_LIGHT_OPEN, + CRAFT_SHADING_MODEL_VOXEL); } diff --git a/Game/assets/shaders/include/craft/frame.glsl b/Game/assets/shaders/include/craft/frame.glsl new file mode 100644 index 0000000..a54abfd --- /dev/null +++ b/Game/assets/shaders/include/craft/frame.glsl @@ -0,0 +1,20 @@ +#ifndef CRAFT_FRAME_GLSL +#define CRAFT_FRAME_GLSL + +#include "sleak/frame.glsl" + +// SleakCraft per-frame block (CraftFrameData in World/VoxelLighting.hpp), +// std140, append only; colors are linear (squared authoring values) +SLEAK_FRAME_USER_BLOCK CraftFrameUBO { + vec4 SunColor; // rgb direct sun or moon light + vec4 AmbientColor; // rgb sky light reaching shadowed faces + vec4 MinLightColor; // rgb floor light where the sky is hidden + vec4 BlockLightColor; // rgb torch tint at full block light + vec4 NightTint; // rgb unit hue of moonlit desaturation + vec4 WeatherTint; // rgb unit hue of rainy desaturation + vec4 Sky; // sun visibility, rain, shadow fade, night vision + vec4 Look; // desaturation, emission gain, albedo balance, + // SSAO exponent +} uCraft; + +#endif diff --git a/Game/assets/shaders/include/craft/lighting.glsl b/Game/assets/shaders/include/craft/lighting.glsl new file mode 100644 index 0000000..086aa5f --- /dev/null +++ b/Game/assets/shaders/include/craft/lighting.glsl @@ -0,0 +1,158 @@ +#ifndef CRAFT_LIGHTING_GLSL +#define CRAFT_LIGHTING_GLSL + +#include "craft/frame.glsl" + +// Face brightness: (up base + up slope * n.y + side spread * (side pivot - +// |n.x|) * (1 - |n.y|))^2, so top 1, z sides 0.72, x sides 0.49, bottom 0.25 +#define CRAFT_FACE_UP_BASE 0.75 +#define CRAFT_FACE_UP_SLOPE 0.25 +#define CRAFT_FACE_SIDE_SPREAD 0.15 +#define CRAFT_FACE_SIDE_PIVOT 0.667 +// Terminator remap of N.L +#define CRAFT_NDOTL_GAIN 1.01 +#define CRAFT_NDOTL_OFFSET 0.01 +// Share of direct light rain removes +#define CRAFT_RAIN_SUN_LOSS 0.95 +// Torch curve (level^power * gain + level * linear)^2 +#define CRAFT_BLOCK_POWER 10.0 +#define CRAFT_BLOCK_GAIN 1.6 +#define CRAFT_BLOCK_LINEAR 0.6 +// Emissive texels: tint toward white, flatten exponent +#define CRAFT_EMISSION_WHITE 0.5 +#define CRAFT_FLATTEN_POWER 128.0 +// Light night vision adds everywhere +#define CRAFT_NIGHT_VISION_LIGHT 0.25 +// Foliage: wrap of N.L and forward scattering lobe +#define CRAFT_SSS_WRAP 0.7 +#define CRAFT_SSS_LOBE_POWER 16.0 +#define CRAFT_HALF 0.5 +// Desaturation: rain keep, block light edges, cave grey, tint gain +#define CRAFT_DESAT_RAIN_KEEP 0.7 +#define CRAFT_DESAT_BLOCK_LOW 0.25 +#define CRAFT_DESAT_BLOCK_HIGH 1.0 +#define CRAFT_DESAT_CAVE_GREY 0.4 +#define CRAFT_DESAT_TINT_GAIN 1.7 +// Rec. 601 luma +#define CRAFT_LUMA vec3(0.299, 0.587, 0.114) +// Keeps normalize away from a zero vector +#define CRAFT_COLOR_EPSILON 1e-5 + +/// Decoded voxel GBuffer texel. +struct CraftSurface { + vec3 albedo; // linear + float ao; // baked vertex AO + vec3 normal; // world, unit length + float sky; // sky light 0..1 + float block; // block light 0..1 + float emission; // 0..1 + float sss; // foliage scattering 0..1 +}; + +/// Light geometry and shadow map result of one pixel. +struct CraftLightSample { + vec3 toLight; // unit, world + vec3 toPixel; // unit, camera to pixel + float shadow; // shadow map visibility 0..1 +}; + +/// Minecraft-like face brightness from the world normal. +float CraftFaceShade(vec3 n) { + float f = CRAFT_FACE_UP_BASE + CRAFT_FACE_UP_SLOPE * n.y + + CRAFT_FACE_SIDE_SPREAD * (CRAFT_FACE_SIDE_PIVOT - abs(n.x)) * + (1.0 - abs(n.y)); + return f * f; +} + +/// True when the shadow map can change this pixel. +bool CraftNeedsShadow(CraftSurface s, vec3 toLight) { + return dot(s.normal, toLight) > 0.0 || s.sss > 0.0; +} + +/// Torch light at a block light level. +vec3 CraftBlockLight(float level) { + float curve = pow(level, CRAFT_BLOCK_POWER) * CRAFT_BLOCK_GAIN + + level * CRAFT_BLOCK_LINEAR; + return uCraft.BlockLightColor.rgb * (curve * curve); +} + +/// 1 for emitters, which skip face shading and AO; 0 for other texels. +float CraftLightFlatten(float emission) { + return 1.0 - pow(1.0 - emission, CRAFT_FLATTEN_POWER); +} + +/// Self light of an emissive texel, tinted by its own hue. +vec3 CraftEmissionLight(vec3 albedo, float emission) { + vec3 hue = normalize(albedo + CRAFT_COLOR_EPSILON); + return mix(hue, vec3(1.0), emission * CRAFT_EMISSION_WHITE) * emission * + uCraft.Look.y; +} + +/// Pulls dark colors away from daylight toward a moon, rain or cave grey. +vec3 CraftDesaturate(vec3 color, CraftSurface s, float flatten) { + float weight = uCraft.Look.x; + if (weight <= 0.0) return color; + float daylight = sqrt(s.sky) * uCraft.Sky.x * + (1.0 - CRAFT_DESAT_RAIN_KEEP * uCraft.Sky.y); + float unlit = 1.0 - s.block; + float amount = clamp(1.0 - daylight, 0.0, 1.0) * + smoothstep(CRAFT_DESAT_BLOCK_LOW, CRAFT_DESAT_BLOCK_HIGH, + unlit * unlit) * + (1.0 - flatten); + vec3 outdoor = mix(uCraft.WeatherTint.rgb, uCraft.NightTint.rgb, + (1.0 - uCraft.Sky.x) * (1.0 - uCraft.Sky.y)); + vec3 tint = mix(vec3(CRAFT_DESAT_CAVE_GREY), outdoor, sqrt(s.sky)) * + CRAFT_DESAT_TINT_GAIN; + vec3 grey = mix(color, dot(color, CRAFT_LUMA) * tint, weight); + return mix(color, grey, amount); +} + +/// Lit voxel color in linear scene units, before SSAO and fog. +vec3 CraftShadeSurface(CraftSurface s, CraftLightSample l) { + // Shadow, terminator + float visibility = clamp(l.shadow, 0.0, 1.0); + visibility *= mix(visibility, 1.0, s.sss); + float nDotL = clamp(dot(s.normal, l.toLight), 0.0, 1.0); + nDotL = clamp(nDotL * CRAFT_NDOTL_GAIN - CRAFT_NDOTL_OFFSET, 0.0, 1.0); + + // Foliage wrap and forward scattering + float scatter = 0.0; + if (s.sss > 0.0) { + float forward = clamp(dot(l.toPixel, l.toLight) * CRAFT_HALF + + CRAFT_HALF, 0.0, 1.0); + scatter = pow(forward, CRAFT_SSS_LOBE_POWER) * (1.0 - uCraft.Sky.y) * + s.sss * uCraft.Sky.z; + nDotL = mix(nDotL, 1.0, sqrt(s.sss) * CRAFT_SSS_WRAP); + nDotL = mix(nDotL, 1.0, scatter); + } + + // Sky: ambient where blocked, sun where lit + float sunShare = visibility * nDotL * + (1.0 - CRAFT_RAIN_SUN_LOSS * uCraft.Sky.y) * uCraft.Sky.z; + vec3 sky = mix(uCraft.AmbientColor.rgb * s.sky, uCraft.SunColor.rgb, + sunShare) * + (s.sky * s.sky) * (1.0 + scatter * visibility); + + // Torch, emission, night vision, cave floor + float flatten = CraftLightFlatten(s.emission); + vec3 light = sky + CraftBlockLight(s.block) + + CraftEmissionLight(s.albedo, s.emission) + + vec3(uCraft.Sky.w * CRAFT_NIGHT_VISION_LIGHT) + + uCraft.MinLightColor.rgb * (1.0 - s.sky * s.sky); + + // Albedo balance, face shading, squared vertex AO + float brightest = max(s.albedo.r, max(s.albedo.g, s.albedo.b)); + vec3 albedo = + s.albedo / (1.0 + brightest * uCraft.Look.z * (1.0 - flatten)); + float face = mix(CraftFaceShade(s.normal), 1.0, flatten); + float ao = mix(s.ao, 1.0, flatten); + vec3 color = albedo * max(light, vec3(0.0)) * face * (ao * ao); + return CraftDesaturate(color, s, flatten); +} + +/// Screen-space AO multiplier of the whole lit color. +float CraftAmbientOcclusion(float ssao) { + return pow(clamp(ssao, 0.0, 1.0), uCraft.Look.w); +} + +#endif diff --git a/Game/assets/shaders/include/craft/lighting_pass.glsl b/Game/assets/shaders/include/craft/lighting_pass.glsl new file mode 100644 index 0000000..aab7cf5 --- /dev/null +++ b/Game/assets/shaders/include/craft/lighting_pass.glsl @@ -0,0 +1,64 @@ +#ifndef CRAFT_LIGHTING_PASS_GLSL +#define CRAFT_LIGHTING_PASS_GLSL + +// Voxel half of SleakCraft's deferred lighting stems (lighting_voxel and +// lighting_voxel_gl); fog stays with each stem. Includes stay outside #ifdef: +// the OpenGL resolver expands them all. + +#include "sleak/lighting_default.glsl" +#include "sleak/frame_output.glsl" +#include "craft/voxel_surface.glsl" +#include "craft/lighting.glsl" + +// No foliage scattering until a foliage shading model exists +#define CRAFT_NO_SCATTERING 0.0 +// N.L that leaves the OpenGL helper's back-face fade at 1 +#define CRAFT_FULL_FACING 1.0 +// Upper HDR clamp that keeps NaNs out of the bloom chain +#define CRAFT_MAX_HDR 1000.0 + +/// Voxel surface of one GBuffer texel. +CraftSurface CraftDecodeSurface(ivec2 px, vec4 rt3) { + vec4 albedoAO = texelFetch(gAlbedoAO, px, 0); + vec4 normalRough = texelFetch(gNormalRough, px, 0); + vec4 metalEmit = texelFetch(gMetalEmit, px, 0); + CraftSurface s; + s.albedo = max(albedoAO.rgb, vec3(0.0)); + s.ao = clamp(albedoAO.a, 0.0, 1.0); + s.normal = normalize(normalRough.rgb * 2.0 - 1.0); + s.sky = CraftVoxelSkyLight(rt3); + s.block = CraftVoxelBlockLight(metalEmit); + s.emission = CraftVoxelEmission(metalEmit); + s.sss = CRAFT_NO_SCATTERING; + return s; +} + +/// Raw sun visibility from the backend's shadow filter. +float CraftShadowVisibility(vec3 worldPos, vec3 n) { +#ifdef VULKAN + return SleakCalcShadow(worldPos, n); +#else + return SleakCalcShadowPCF(worldPos, CRAFT_FULL_FACING); +#endif +} + +/// Voxel lighting of one non-sky pixel in linear scene units, before fog. +vec3 CraftShadeVoxel(ivec2 px, vec2 uv, float depth, vec4 rt3, + out vec3 worldPos) { + worldPos = SleakReconstructWorldPos(uv, depth); + CraftSurface s = CraftDecodeSurface(px, rt3); + + CraftLightSample l; + l.toLight = normalize(uFrame.LightDir.xyz); + l.toPixel = normalize(worldPos - uFrame.CameraPos.xyz); + l.shadow = CraftNeedsShadow(s, l.toLight) + ? CraftShadowVisibility(worldPos, s.normal) + : 0.0; + + vec3 color = CraftShadeSurface(s, l); + if (SleakSSAOEnabled()) + color *= CraftAmbientOcclusion(texture(gSSAO, uv).r); + return clamp(color, vec3(0.0), vec3(CRAFT_MAX_HDR)); +} + +#endif diff --git a/Game/assets/shaders/include/craft/shading_models.glsl b/Game/assets/shaders/include/craft/shading_models.glsl index 838c140..9f81f41 100644 --- a/Game/assets/shaders/include/craft/shading_models.glsl +++ b/Game/assets/shaders/include/craft/shading_models.glsl @@ -5,5 +5,13 @@ // SleakCraft shading model ids in GBuffer RT3.w; 0 belongs to the engine #define CRAFT_SHADING_MODEL_VOXEL 1u +// Last id the voxel lighting shades (phase 11 appends foliage) +#define CRAFT_SHADING_MODEL_LAST_VOXEL CRAFT_SHADING_MODEL_VOXEL + +/// True for ids the voxel lighting composition shades. +bool CraftIsVoxelModel(uint id) { + return id >= CRAFT_SHADING_MODEL_VOXEL && + id <= CRAFT_SHADING_MODEL_LAST_VOXEL; +} #endif diff --git a/Game/assets/shaders/include/craft/voxel_surface.glsl b/Game/assets/shaders/include/craft/voxel_surface.glsl new file mode 100644 index 0000000..218fa3a --- /dev/null +++ b/Game/assets/shaders/include/craft/voxel_surface.glsl @@ -0,0 +1,41 @@ +#ifndef CRAFT_VOXEL_SURFACE_GLSL +#define CRAFT_VOXEL_SURFACE_GLSL + +#include "craft/shading_models.glsl" + +// Voxel GBuffer channels beyond the engine layout: +// RT2 r metallic (0), g emission, b block light, a reserved; +// RT3 z sky light (phase 8 fills it), w shading model +// Sky light written until per-voxel sky light exists +#define CRAFT_SKY_LIGHT_OPEN 1.0 +// No block emits light and no torch light exists yet +#define CRAFT_NO_EMISSION 0.0 +#define CRAFT_NO_BLOCK_LIGHT 0.0 +// RT2 alpha is unused by voxels +#define CRAFT_RT2_RESERVED 0.0 + +/// RT2 of a voxel texel. +vec4 CraftEncodeVoxelRT2(float metallic, float emission, float blockLight) { + return vec4(metallic, clamp(emission, 0.0, 1.0), + clamp(blockLight, 0.0, 1.0), CRAFT_RT2_RESERVED); +} + +/// RT3 of a voxel texel: no object motion yet. +vec4 CraftEncodeVoxelRT3(float skyLight, uint shadingModel) { + return SleakEncodeMotionModel(vec2(0.0), clamp(skyLight, 0.0, 1.0), + shadingModel); +} + +/// Emission strength of an atlas texel; a hook for emissive blocks. +float CraftTexelEmission(vec3 albedo) { return CRAFT_NO_EMISSION; } + +/// Emission strength stored in a voxel texel's RT2. +float CraftVoxelEmission(vec4 rt2) { return clamp(rt2.g, 0.0, 1.0); } + +/// Block light stored in a voxel texel's RT2. +float CraftVoxelBlockLight(vec4 rt2) { return clamp(rt2.b, 0.0, 1.0); } + +/// Sky light stored in a voxel texel's RT3. +float CraftVoxelSkyLight(vec4 rt3) { return clamp(rt3.z, 0.0, 1.0); } + +#endif diff --git a/Game/assets/shaders/lighting_voxel.frag b/Game/assets/shaders/lighting_voxel.frag index d2b2fc9..2a56758 100644 --- a/Game/assets/shaders/lighting_voxel.frag +++ b/Game/assets/shaders/lighting_voxel.frag @@ -1,145 +1,35 @@ #version 450 #extension GL_GOOGLE_include_directive : require -// SleakCraft deferred lighting, Vulkan: voxel pixels get CraftShadeVoxel -#include "sleak/lighting_default.glsl" -#include "craft/shading_models.glsl" - -// Wrap lighting: N.L * scale + offset -const float CRAFT_WRAP_SCALE = 0.85; -const float CRAFT_WRAP_OFFSET = 0.15; -// N.L below which back faces get no direct light -const float CRAFT_SHADOW_FACE_FADE = 0.15; -// Ground bounce relative to the sky ambient -const vec3 CRAFT_GROUND_TINT = vec3(0.55, 0.50, 0.45); -// SSAO can at most halve the ambient term -const float CRAFT_SSAO_FLOOR = 0.5; -// Upper HDR clamp that keeps NaNs out of the bloom chain -const float CRAFT_MAX_HDR = 1000.0; - -/// Voxel lighting of one non-sky pixel: wrap diffuse sun with PCF shadow, -/// hemisphere ambient, extra lights, emissive, fog. Linear HDR. -vec3 CraftShadeVoxel(ivec2 px, vec2 uv, float depth) { - vec3 worldPos = SleakReconstructWorldPos(uv, depth); - vec4 albedoAO = texelFetch(gAlbedoAO, px, 0); - vec4 normalRg = texelFetch(gNormalRough, px, 0); - vec4 metalEmit = texelFetch(gMetalEmit, px, 0); - - vec3 albedo = albedoAO.rgb; - float bakedAO = albedoAO.a; - float ssao = texture(gSSAO, uv).r; - float ao = bakedAO * ssao; - vec3 N = normalize(normalRg.rgb * 2.0 - 1.0); - float roughness = normalRg.a; - float metallic = metalEmit.r; - vec3 emissive = metalEmit.gba; - - vec3 V = normalize(uCameraPos.xyz - worldPos); - float NdotV = max(dot(N, V), 0.0); - - vec3 F0 = mix(SLEAK_DIELECTRIC_F0, albedo, metallic); - - vec3 Lo = vec3(0.0); - vec3 ambient; - if (iblEnabled != 0u) { - // Cook-Torrance sun - vec3 L = normalize(-uLightDir.xyz); - vec3 H = normalize(V + L); - float NdotL = max(dot(N, L), 0.0); - - if (NdotL > 0.0) { - float D = SleakDistributionGGX(N, H, roughness); - float G = SleakGeometrySmith(N, V, L, roughness); - vec3 F = SleakFresnelSchlick(max(dot(H, V), 0.0), F0); - - vec3 kS = F; - vec3 kD = (vec3(1.0) - kS) * (1.0 - metallic); - - vec3 specular = (D * G * F) / - (4.0 * NdotV * NdotL + SLEAK_BRDF_EPSILON); - - float shadow = SleakCalcShadow(worldPos, N); - shadow *= smoothstep(0.0, CRAFT_SHADOW_FACE_FADE, dot(N, L)); - - vec3 lightColor = uLightColor.rgb * uLightColor.a; - Lo = (kD * albedo / SLEAK_PI + specular) * lightColor * NdotL * - shadow; - } - - // Extra directional lights, no shadows - for (uint li = 0u; li < uNumExtraLights; ++li) { - vec3 Lx = normalize(-uExtraDir[li].xyz); - vec3 Hx = normalize(V + Lx); - float NdotLx = max(dot(N, Lx), 0.0); - if (NdotLx > 0.0) { - float Dx = SleakDistributionGGX(N, Hx, roughness); - float Gx = SleakGeometrySmith(N, V, Lx, roughness); - vec3 Fx = SleakFresnelSchlick(max(dot(Hx, V), 0.0), F0); - vec3 kSx = Fx; - vec3 kDx = (vec3(1.0) - kSx) * (1.0 - metallic); - vec3 specx = (Dx * Gx * Fx) / - (4.0 * NdotV * NdotLx + SLEAK_BRDF_EPSILON); - vec3 lightColorx = uExtraColor[li].rgb * uExtraColor[li].a; - Lo += (kDx * albedo / SLEAK_PI + specx) * lightColorx * NdotLx; - } - } - - // Split-sum IBL - vec3 F_amb = SleakFresnelSchlickRoughness(NdotV, F0, roughness); - vec3 kS_amb = F_amb; - vec3 kD_amb = (1.0 - kS_amb) * (1.0 - metallic); - - vec3 irradiance = texture(iblIrradiance, N).rgb; - vec3 diffuse_ibl = kD_amb * irradiance * albedo; - - vec3 R = reflect(-V, N); - vec3 prefilteredColor = - textureLod(iblPrefilter, R, roughness * maxReflectionLOD).rgb; - vec2 brdf = texture(iblBrdfLUT, vec2(NdotV, roughness)).rg; - vec3 specular_ibl = prefilteredColor * (F_amb * brdf.x + brdf.y); - - ambient = (diffuse_ibl + specular_ibl) * ao * iblIntensity; - } else { - // Wrap diffuse sun and hemisphere ambient - vec3 skyAmbient = uAmbient.rgb * uAmbient.a; - vec3 groundAmbient = skyAmbient * CRAFT_GROUND_TINT; - float hemisphere = N.y * 0.5 + 0.5; - vec3 Ldir = normalize(-uLightDir.xyz); - float rawNdL = dot(N, Ldir); - float wrapNdL = - clamp(rawNdL * CRAFT_WRAP_SCALE + CRAFT_WRAP_OFFSET, 0.0, 1.0); - float shad = 0.0; - if (rawNdL > -CRAFT_SHADOW_FACE_FADE) - shad = SleakCalcShadow(worldPos, N) * - smoothstep(-CRAFT_SHADOW_FACE_FADE, 0.0, rawNdL); - vec3 direct = uLightColor.rgb * uLightColor.a * wrapNdL * shad; - for (uint li = 0u; li < uNumExtraLights; ++li) { - vec3 Lx = normalize(-uExtraDir[li].xyz); - float NdLx = max(dot(N, Lx), 0.0); - direct += uExtraColor[li].rgb * uExtraColor[li].a * NdLx; - } - float aoGL = bakedAO * (CRAFT_SSAO_FLOOR + CRAFT_SSAO_FLOOR * ssao); - ambient = albedo * mix(groundAmbient, skyAmbient, hemisphere) * aoGL; - Lo = albedo * direct; - } - - vec3 color = ambient + Lo + emissive; - - // Fog in linear HDR; the composite pass tonemaps - color = SleakApplyFog(color, worldPos); - return clamp(color, vec3(0.0), vec3(CRAFT_MAX_HDR)); +// SleakCraft deferred lighting, Vulkan (Application::SetLightingShader). +// Voxel pixels get the composition in craft/lighting.glsl in linear scene +// units; engine materials keep SleakShadeDefault. The composite tonemaps. + +#include "craft/lighting_pass.glsl" + +/// Today's fog with its colors moved to scene units, so it displays as before. +vec3 CraftApplySceneFog(vec3 color, vec3 worldPos) { + float amount = SleakFogAmount(worldPos); + if (amount <= 0.0) return color; + vec3 fog = SleakLegacyToScene(SleakFogColor(worldPos), SleakFrameOutput()); + return mix(color, fog, amount); } void main() { - ivec2 px = ivec2(gl_FragCoord.xy); + ivec2 px = ivec2(gl_FragCoord.xy); float depth = texelFetch(gDepth, px, 0).r; - if (depth >= 1.0) { outColor = vec4(0.0, 0.0, 0.0, 1.0); return; } - + if (depth >= 1.0) { + outColor = vec4(0.0, 0.0, 0.0, 1.0); + return; + } + vec4 rt3 = SleakReadMotionModel(px); vec3 color; - if (SleakShadingModel(SleakReadMotionModel(px)) == - CRAFT_SHADING_MODEL_VOXEL) - color = CraftShadeVoxel(px, fragUV, depth); - else + if (CraftIsVoxelModel(SleakShadingModel(rt3))) { + vec3 worldPos; + color = CraftShadeVoxel(px, fragUV, depth, rt3, worldPos); + color = CraftApplySceneFog(color, worldPos); + } else { color = SleakShadeDefault(px, fragUV, depth); + } outColor = SleakFrameGuard(vec4(color, 1.0)); } diff --git a/Game/assets/shaders/lighting_voxel.frag.spv b/Game/assets/shaders/lighting_voxel.frag.spv index 256088f..0572b85 100644 Binary files a/Game/assets/shaders/lighting_voxel.frag.spv and b/Game/assets/shaders/lighting_voxel.frag.spv differ diff --git a/Game/assets/shaders/lighting_voxel_gl.frag b/Game/assets/shaders/lighting_voxel_gl.frag index 8002a5d..c506a9d 100644 --- a/Game/assets/shaders/lighting_voxel_gl.frag +++ b/Game/assets/shaders/lighting_voxel_gl.frag @@ -1,111 +1,12 @@ #version 450 core #extension GL_GOOGLE_include_directive : require -// SleakCraft deferred lighting, OpenGL: voxel pixels get CraftShadeVoxel -#include "sleak/lighting_default.glsl" -#include "craft/shading_models.glsl" +// SleakCraft deferred lighting, OpenGL (Application::SetLightingShader). +// Same voxel composition as Vulkan, then the frame's output transform and +// today's display-space fog inline: OpenGL has no post chain. Engine +// materials keep the default lighting, mapped to the same output. -// Wrap lighting: N.L * scale + offset -const float CRAFT_WRAP_SCALE = 0.85; -const float CRAFT_WRAP_OFFSET = 0.15; -// N.L below which back faces get no direct light -const float CRAFT_SHADOW_FACE_FADE = 0.15; -// Ground bounce relative to the sky ambient -const vec3 CRAFT_GROUND_TINT = vec3(0.55, 0.50, 0.45); -// SSAO can at most halve the ambient term -const float CRAFT_SSAO_FLOOR = 0.5; -// Keeps the light range away from a zero divisor -const float CRAFT_RANGE_EPSILON = 1e-4; -// Light types (LightType in Light.hpp) -const uint CRAFT_LIGHT_DIRECTIONAL = 0u; -const uint CRAFT_LIGHT_POINT = 1u; - -/// Voxel lighting of one non-sky pixel: every light in LightUBO (PCF for -/// directional), hemisphere ambient plus IBL, emissive, ACES, then fog. -vec3 CraftShadeVoxel(ivec2 px, vec2 uv, float depth) { - vec4 albedoAO = texture(gAlbedoAO, uv); - vec4 normalRough = texture(gNormalRough, uv); - vec4 metalEmit = texture(gMetalEmit, uv); - - vec3 albedo = albedoAO.rgb; - float ao = albedoAO.a; - if (SleakSSAOEnabled()) { - float ssao = texture(gSSAO, uv).r; - ao *= CRAFT_SSAO_FLOOR + CRAFT_SSAO_FLOOR * ssao; - } - vec3 N = normalize(normalRough.rgb * 2.0 - 1.0); - float roughness = normalRough.a; - float metallic = metalEmit.r; - float emitScale = metalEmit.g; - - vec3 worldPos = SleakReconstructWorldPos(uv, depth); - - vec3 totalDiffuse = vec3(0.0); - for (uint i = 0u; i < NumActiveLights; ++i) { - SleakLightData light = Lights[i]; - - vec3 L; - float attenuation = 1.0; - - if (light.Type == CRAFT_LIGHT_DIRECTIONAL) { - L = normalize(-light.Direction); - } else if (light.Type == CRAFT_LIGHT_POINT) { - vec3 toLight = light.Position - worldPos; - float dist = length(toLight); - L = toLight / dist; - attenuation = 1.0 / (1.0 + dist * dist / - max(light.Range * light.Range, - CRAFT_RANGE_EPSILON)); - } else { - continue; - } - - float rawNdotL = dot(N, L); - float NdotL = clamp(rawNdotL * CRAFT_WRAP_SCALE + CRAFT_WRAP_OFFSET, - 0.0, 1.0); - - float shadow = 1.0; - if (light.Type == CRAFT_LIGHT_DIRECTIONAL) { - shadow = SleakCalcShadowPCF(worldPos, max(rawNdotL, 0.0)); - shadow *= smoothstep(0.0, CRAFT_SHADOW_FACE_FADE, rawNdotL); - } - - totalDiffuse += - light.Color * light.Intensity * attenuation * NdotL * shadow; - } - - // Hemisphere ambient, plus reflected environment light with IBL - vec3 V = normalize(CameraPos - worldPos); - vec3 F0 = mix(SLEAK_DIELECTRIC_F0, albedo, metallic); - vec3 skyAmbient = AmbientColor * AmbientIntensity; - vec3 groundAmbient = skyAmbient * CRAFT_GROUND_TINT; - float hemisphere = N.y * 0.5 + 0.5; - vec3 hemAmbient = mix(groundAmbient, skyAmbient, hemisphere); - vec3 ambient = albedo * hemAmbient; - - if (iblEnabled != 0u) { - float NdotV_ibl = max(dot(N, V), 0.0); - vec3 kS_ibl = - SleakFresnelSchlickRoughness(NdotV_ibl, F0, roughness); - vec3 kD_ibl = (1.0 - kS_ibl) * (1.0 - metallic); - vec3 irradiance = texture(iblIrradiance, N).rgb; - vec3 diffuseIBL = irradiance * albedo; - vec3 R = reflect(-V, N); - vec3 prefilteredColor= textureLod(iblPrefilter, R, - roughness * maxReflectionLOD).rgb; - vec2 envBRDF = texture(iblBrdfLUT, - vec2(NdotV_ibl, roughness)).rg; - vec3 specularIBL = prefilteredColor - * (kS_ibl * envBRDF.x + envBRDF.y); - ambient += (kD_ibl * diffuseIBL + specularIBL) * iblIntensity; - } - ambient *= ao; - - vec3 color = ambient + albedo * totalDiffuse; - color += albedo * emitScale; - color = SleakACESFilm(color); - return SleakApplyFog(color, worldPos); -} +#include "craft/lighting_pass.glsl" void main() { float depth = texture(gDepth, fragUV).r; @@ -113,11 +14,17 @@ void main() { gl_FragDepth = depth; ivec2 px = ivec2(gl_FragCoord.xy); - vec3 color; - if (SleakShadingModel(SleakReadMotionModel(px)) == - CRAFT_SHADING_MODEL_VOXEL) - color = CraftShadeVoxel(px, fragUV, depth); - else - color = SleakShadeDefault(px, fragUV, depth); - outColor = SleakFrameGuard(vec4(color, 1.0)); + vec4 rt3 = SleakReadMotionModel(px); + SleakOutputParams o = SleakFrameOutput(); + vec3 display; + if (CraftIsVoxelModel(SleakShadingModel(rt3))) { + vec3 worldPos; + vec3 scene = CraftShadeVoxel(px, fragUV, depth, rt3, worldPos); + display = SleakApplyFog(SleakOutputTransform(scene, o), worldPos); + } else { + display = SleakLegacyDisplayToOutput( + SleakShadeDefault(px, fragUV, depth), o); + } + display = SleakApplyDither(display, gl_FragCoord.xy, o.dither); + outColor = SleakFrameGuard(vec4(display, 1.0)); } diff --git a/Game/assets/shaders/shadow_depth_voxel.vert.spv b/Game/assets/shaders/shadow_depth_voxel.vert.spv index 5374b5f..2c8ebe5 100644 Binary files a/Game/assets/shaders/shadow_depth_voxel.vert.spv and b/Game/assets/shaders/shadow_depth_voxel.vert.spv differ diff --git a/Game/assets/shaders/water_shader.frag b/Game/assets/shaders/water_shader.frag index 5af8058..d8460bf 100644 --- a/Game/assets/shaders/water_shader.frag +++ b/Game/assets/shaders/water_shader.frag @@ -10,6 +10,7 @@ layout(location = 0) out vec4 outColor; #include "sleak/shadow_light.glsl" #include "sleak/frame.glsl" +#include "sleak/frame_output.glsl" layout(set = 3, binding = 0) uniform sampler2DShadow shadowMap; @@ -46,7 +47,9 @@ vec3 Reconstruct(vec2 uv, float depth) { return w.xyz / w.w; } float DepthToNdc(float depth) { return depth; } -vec3 SceneToLinear(vec3 c) { return c; } +vec3 SceneToLinear(vec3 c) { + return SleakSceneToLegacy(c, SleakFrameOutput()); +} vec3 SkyRadiance(vec3 dir, float lod) { return textureLod(skyCube, dir, lod).rgb; } @@ -102,11 +105,15 @@ float FogAmount(vec3 p) { } return 1.0 - (1.0 - distFog) * (1.0 - heightFog); } -vec3 FogColorAt(vec3 p) { +vec3 LegacyFogColorAt(vec3 p) { vec3 viewDir = normalize(p - uCameraPos.xyz); float t = smoothstep(0.0, 1.0, clamp(SignedToUnit(viewDir.y), 0.0, 1.0)); return mix(uFogColor.rgb, uFogZenithColor.rgb, t); } +// Fog color as the lighting pass applied it to the snapshot +vec3 FogColorAt(vec3 p) { + return SleakLegacyToScene(LegacyFogColorAt(p), SleakFrameOutput()); +} // ==== SHARED WATER BODY (keep identical in water_shader_gl.frag) ==== @@ -528,7 +535,8 @@ void main() { float footprint = max(length(dFdx(P.xz)), length(dFdy(P.xz))); WaterResult w = ShadeWater(P, fragNormal, fragTime, footprint); - vec3 color = mix(w.color, FogColorAt(P), FogAmount(P)); + vec3 color = mix(w.color, LegacyFogColorAt(P), FogAmount(P)); + color = SleakLegacyToScene(color, SleakFrameOutput()); float alpha = 1.0; if (IsSet(uSceneFlags.x)) color = mix(w.backdrop, color, w.edge); diff --git a/Game/assets/shaders/water_shader.frag.spv b/Game/assets/shaders/water_shader.frag.spv index 3e1f3e1..4178e8d 100644 Binary files a/Game/assets/shaders/water_shader.frag.spv and b/Game/assets/shaders/water_shader.frag.spv differ diff --git a/Game/assets/shaders/water_shader.vert.spv b/Game/assets/shaders/water_shader.vert.spv index 3b949a3..d739270 100644 Binary files a/Game/assets/shaders/water_shader.vert.spv and b/Game/assets/shaders/water_shader.vert.spv differ diff --git a/Game/include/MainScene.hpp b/Game/include/MainScene.hpp index dc154cb..e092f60 100644 --- a/Game/include/MainScene.hpp +++ b/Game/include/MainScene.hpp @@ -2,21 +2,23 @@ #define _MAIN_SCENE_HPP_ #include -#include -#include -#include -#include #include -#include "World/ChunkManager.hpp" -#include "World/Block.hpp" -#include "World/SaveManager.hpp" -#include "World/BlockEffects.hpp" -#include "World/WorldPersistence.hpp" -#include "Player/PlayerController.hpp" +#include +#include +#include +#include + #include "Player/BlockInteraction.hpp" +#include "Player/PlayerController.hpp" +#include "UI/Hotbar.hpp" #include "UI/HudPanel.hpp" #include "UI/SettingsPanel.hpp" -#include "UI/Hotbar.hpp" +#include "World/Block.hpp" +#include "World/BlockEffects.hpp" +#include "World/ChunkManager.hpp" +#include "World/SaveManager.hpp" +#include "World/VoxelLighting.hpp" +#include "World/WorldPersistence.hpp" namespace Sleak { class Material; class DirectionalLight; } @@ -69,6 +71,8 @@ class MainScene : public Sleak::Scene { float GetSaveMessageTimer() const { return m_saveMessageTimer; } const std::string& GetSaveMessage() const { return m_saveMessage; } float GetGameTime() const { return m_gameTime; } + /// Voxel palette the settings panel scales. + VoxelLighting& GetVoxelLighting() { return m_voxelLighting; } // Accessors for HudPanel/SettingsPanel (toggles that engine setup code // in MainScene also reads at Initialize time) @@ -92,7 +96,7 @@ class MainScene : public Sleak::Scene { void SetupMaterial(); void SetupSkybox(); /// Creates the sun light and applies the voxel-tuned GraphicsConfig - /// (shadows on, SSAO/SSR/IBL/bloom off) plus fog and culling settings. + /// (BSL output, shadows, SSAO, blend bloom) plus fog and culling settings. void SetupLighting(); void RenderUI(); @@ -116,6 +120,7 @@ class MainScene : public Sleak::Scene { Sleak::RefPtr m_waterMaterial; ChunkManager m_chunkManager; BlockEffects m_blockEffects; + VoxelLighting m_voxelLighting; SaveManager m_saveManager; WorldPersistence m_worldPersistence; PlayerController m_playerController; @@ -153,7 +158,7 @@ class MainScene : public Sleak::Scene { std::string m_keyReleasedHandlerId; // Sun light created here (needs Scene::AddObject/shadow config); live - // elevation/azimuth/color/intensity edits live on SettingsPanel. + // elevation/azimuth edits live on SettingsPanel. Sleak::DirectionalLight* m_sun = nullptr; }; diff --git a/Game/include/UI/SettingsPanel.hpp b/Game/include/UI/SettingsPanel.hpp index 76df20e..15e9e24 100644 --- a/Game/include/UI/SettingsPanel.hpp +++ b/Game/include/UI/SettingsPanel.hpp @@ -4,6 +4,8 @@ #include #include +#include "World/VoxelLighting.hpp" + class ChunkManager; class MainScene; namespace Sleak { class DirectionalLight; class Application; } @@ -31,18 +33,6 @@ class SettingsPanel { // Initial-value accessors for MainScene::SetupMaterial/SetupLighting. /// Converts the elevation/azimuth sliders into a light direction vector. Sleak::Math::Vector3D ComputeSunDirection() const; - void GetSunColor(float& r, float& g, float& b) const { - r = m_sunColorR; - g = m_sunColorG; - b = m_sunColorB; - } - float GetSunIntensity() const { return m_sunIntensity; } - void GetAmbientColor(float& r, float& g, float& b) const { - r = m_ambientColorR; - g = m_ambientColorG; - b = m_ambientColorB; - } - float GetAmbientIntensity() const { return m_ambientIntensity; } void GetFogHorizonColor(float& r, float& g, float& b) const { r = m_fogHorizonR; g = m_fogHorizonG; @@ -72,7 +62,7 @@ class SettingsPanel { void RenderMSAASection(); /// Render distance slider; also re-derives fog distances on change. void RenderRenderDistanceSection(); - /// Sun, ambient, and fog sliders; pushes live edits to the light manager. + /// Sun direction, voxel sun and ambient multipliers, and fog sliders. void RenderLightingSection(); /// SSAO toggle and radius/bias/power sliders. void RenderSSAOSection(); @@ -91,19 +81,13 @@ class SettingsPanel { bool isDeferredEnabled = false; bool isTAAEnabled = false; - // Sun state (live-editable) - float m_sunElevation = 65.0f; // degrees above horizon (0=sunrise, 90=noon) + // Sun direction (live-editable); 50 degrees is BSL's noon height + float m_sunElevation = 50.0f; // degrees above the horizon float m_sunAzimuth = 255.0f; // degrees clockwise from north - float m_sunIntensity = 0.69f; - float m_sunColorR = 1.00f; - float m_sunColorG = 0.96f; - float m_sunColorB = 0.88f; - - // Ambient state - float m_ambientIntensity = 0.725f; - float m_ambientColorR = 0.45f; - float m_ambientColorG = 0.62f; - float m_ambientColorB = 1.00f; + + // Multipliers on the voxel palette's sun and sky ambient (1 = palette) + LightMultiplier m_sunMultiplier; + LightMultiplier m_ambientMultiplier; // Texture quality state Sleak::TextureFilter m_texFilter = Sleak::TextureFilter::Nearest; diff --git a/Game/include/World/BlockEffects.hpp b/Game/include/World/BlockEffects.hpp index d17bc54..44ddd0a 100644 --- a/Game/include/World/BlockEffects.hpp +++ b/Game/include/World/BlockEffects.hpp @@ -1,16 +1,20 @@ #ifndef _BLOCK_EFFECTS_HPP_ #define _BLOCK_EFFECTS_HPP_ -#include "Block.hpp" #include #include +#include +#include +#include #include +#include "Block.hpp" + namespace Sleak { - class Material; - class GameObject; - class SceneBase; -} +class Material; +class GameObject; +class SceneBase; +} // namespace Sleak /// A block's scale-in placement animation, tracked until its duration elapses. struct PlaceEffect { @@ -31,12 +35,16 @@ struct BreakParticle { }; /// Purely visual block place/break effects (scale-in cube, debris particles). -/// Owns their scene objects; the actual voxel edit happens separately once -/// a placement's animation completes (see PopCompletedPlacements). +/// Owns their scene objects, which draw voxel-format meshes built once per +/// block type or tile, so they get the voxel GBuffer, lighting and shadows. +/// The voxel edit happens once a placement's animation completes (see +/// PopCompletedPlacements). /// @ingroup world class BlockEffects { -public: - void Initialize(Sleak::SceneBase* scene, const Sleak::RefPtr& material); + public: + /// Keeps the scene the effect objects join and the block material. + void Initialize(Sleak::SceneBase* scene, + const Sleak::RefPtr& material); /// Spawns a scale-in cube at a block position; the real SetBlockAt call /// is deferred until this effect completes. @@ -44,23 +52,31 @@ class BlockEffects { /// Spawns a burst of camera-facing debris quads at a broken block. void SpawnBreakEffect(int x, int y, int z, BlockType type); - /// Advances place-effect scale and particle physics, removing finished ones. + /// Advances place-effect scale and particle physics, removing finished + /// ones. void Update(float deltaTime, const Sleak::Math::Vector3D& cameraPos); + /// Removes every effect object without committing placements. void Cleanup(); - struct CompletedPlace { int x, y, z; BlockType type; }; + struct CompletedPlace { + int x, y, z; + BlockType type; + }; /// Removes and returns placements whose animation finished this frame. std::vector PopCompletedPlacements(); /// Force-completes every still-animating placement; used by save/exit /// paths so no in-flight placement is lost. std::vector DrainAllPlacements(); - -private: - /// Builds a textured unit-cube GameObject for a place effect. - Sleak::GameObject* CreatePlaceCube(BlockType type); - /// Builds a single-tile textured quad GameObject for a break particle. - Sleak::GameObject* CreateParticleQuad(uint8_t tileIndex); + private: + /// Unit cube of a block type in the voxel format, built on first use. + const Sleak::MeshHandle& CubeMesh(BlockType type); + /// Two-sided quad of an atlas tile in the voxel format, built on first + /// use. + const Sleak::MeshHandle& QuadMesh(uint8_t tile); + /// Scene-ready object drawing a mesh with the block material. + Sleak::GameObject* CreateEffectObject(const char* name, + const Sleak::MeshHandle& mesh); Sleak::SceneBase* m_scene = nullptr; Sleak::RefPtr m_material; @@ -68,8 +84,18 @@ class BlockEffects { std::vector m_placeEffects; std::vector m_breakParticles; + // Shared by every effect object of a type or tile + std::unordered_map m_cubeMeshes; + std::unordered_map m_quadMeshes; + static constexpr float PLACE_DURATION = 0.15f; + static constexpr float PLACE_START_SCALE = 0.3f; static constexpr float BREAK_LIFETIME = 0.6f; + static constexpr float BREAK_LIFETIME_JITTER = 0.1f; + static constexpr float BREAK_SPREAD = 0.3f; + static constexpr float BREAK_SIDE_SPEED = 1.5f; + static constexpr float BREAK_UP_SPEED_MIN = 1.5f; + static constexpr float BREAK_UP_SPEED_MAX = 4.0f; static constexpr float PARTICLE_SIZE = 0.1f; static constexpr int PARTICLES_PER_BLOCK = 8; static constexpr float PARTICLE_GRAVITY = -12.0f; diff --git a/Game/include/World/VoxelLighting.hpp b/Game/include/World/VoxelLighting.hpp new file mode 100644 index 0000000..5c14e22 --- /dev/null +++ b/Game/include/World/VoxelLighting.hpp @@ -0,0 +1,107 @@ +#ifndef _VOXEL_LIGHTING_HPP_ +#define _VOXEL_LIGHTING_HPP_ + +#include + +namespace Sleak { +struct GraphicsConfig; +} + +/// A palette color in authoring space: (r, g, b) / 255 times an intensity. +/// Palettes blend here; shaders get the square, which is linear light. +struct SqrtColor { + float r = 0.0f; + float g = 0.0f; + float b = 0.0f; +}; + +/// A palette key as authored: 0-255 channels and an intensity. +struct AuthoredKey { + float r; + float g; + float b; + float intensity; +}; + +/// Noon sun and sky ambient keys (BSL v10 defaults). +inline constexpr AuthoredKey NOON_SUN_KEY{196.0f, 220.0f, 255.0f, 1.40f}; +inline constexpr AuthoredKey NOON_AMBIENT_KEY{120.0f, 172.0f, 255.0f, 0.60f}; + +/// SqrtColor of an authored key. +SqrtColor ToSqrtColor(const AuthoredKey& key); + +/// Linear blend in authoring space, as time-of-day keys mix. +SqrtColor BlendColor(const SqrtColor& from, const SqrtColor& to, float t); + +/// Light colors and sky state of one moment, in authoring space. +struct LightingPalette { + SqrtColor sun; + SqrtColor ambient; + SqrtColor moon; + SqrtColor weather; + SqrtColor blockLight; + float sunVisibility = 1.0f; + float rain = 0.0f; + float shadowFade = 1.0f; + float nightVision = 0.0f; +}; + +/// Linear multiplier the settings panel applies on top of a palette color. +struct LightMultiplier { + float r = 1.0f; + float g = 1.0f; + float b = 1.0f; + float scale = 1.0f; +}; + +/// SleakCraft's per-frame shader block (craft/frame.glsl), std140, append +/// only. Colors are linear. +struct CraftFrameData { + float SunColor[4]; + float AmbientColor[4]; + float MinLightColor[4]; + float BlockLightColor[4]; + float NightTint[4]; + float WeatherTint[4]; + float Sky[4]; + float Look[4]; +}; +static_assert(offsetof(CraftFrameData, SunColor) == 0); +static_assert(offsetof(CraftFrameData, AmbientColor) == 16); +static_assert(offsetof(CraftFrameData, MinLightColor) == 32); +static_assert(offsetof(CraftFrameData, BlockLightColor) == 48); +static_assert(offsetof(CraftFrameData, NightTint) == 64); +static_assert(offsetof(CraftFrameData, WeatherTint) == 80); +static_assert(offsetof(CraftFrameData, Sky) == 96); +static_assert(offsetof(CraftFrameData, Look) == 112); +static_assert(sizeof(CraftFrameData) == 128); + +/// Owns the voxel lighting palette and sends it as the game frame block. +class VoxelLighting { + public: + /// BSL-style noon: blue-white sun, blue sky ambient, open sky. + static LightingPalette NoonPalette(); + + /// Palette used from the next Upload on. + void SetPalette(const LightingPalette& palette) { m_palette = palette; } + /// Palette of the next Upload. + const LightingPalette& GetPalette() const { return m_palette; } + + /// Settings multipliers on the sun and sky ambient colors. + void SetMultipliers(const LightMultiplier& sun, + const LightMultiplier& ambient) { + m_sunMultiplier = sun; + m_ambientMultiplier = ambient; + } + + /// Builds the block from the palette and the look settings and sends + /// it; called every frame, since scene activation clears the block. + void Upload(const Sleak::GraphicsConfig& config) const; + + private: + LightingPalette m_palette = NoonPalette(); + LightMultiplier m_sunMultiplier; + LightMultiplier m_ambientMultiplier; +}; + +#endif // _VOXEL_LIGHTING_HPP_ diff --git a/Game/src/MainScene.cpp b/Game/src/MainScene.cpp index 4cf4cfb..3af5fe0 100644 --- a/Game/src/MainScene.cpp +++ b/Game/src/MainScene.cpp @@ -28,6 +28,25 @@ // Post-TAA RCAS strength (0 = off, 1 = strongest) #define DEFAULT_SHARPEN_STRENGTH 0.5f +namespace { + +// Engine sun and ambient as before the voxel palette (water, forward path) +constexpr float LEGACY_SUN_COLOR[3] = {1.00f, 0.96f, 0.88f}; +constexpr float LEGACY_SUN_INTENSITY = 0.69f; +constexpr float LEGACY_AMBIENT_COLOR[3] = {0.45f, 0.62f, 1.00f}; +constexpr float LEGACY_AMBIENT_INTENSITY = 0.725f; +// Output look (BSL v10 defaults) +constexpr float LOOK_EXPOSURE = 4.0f; +constexpr float LOOK_GAMMA = 2.2f; +constexpr float LOOK_SATURATION = 1.0f; +constexpr float LOOK_WHITE_CURVE = 2.0f; +constexpr float LOOK_WHITE_PATH = 1.0f; +constexpr float LOOK_BLOOM_BLEND = 0.2f; +constexpr float LOOK_DESATURATION_FACTOR = 1.5f; +constexpr float LOOK_MIN_LIGHT = 0.5f; + +} // namespace + using namespace Sleak; using namespace Sleak::Math; @@ -286,6 +305,9 @@ void MainScene::Update(float deltaTime) { Scene::Update(deltaTime); + if (auto* app = Sleak::Application::GetInstance()) + m_voxelLighting.Upload(app->GetGraphicsConfig()); + m_hudPanel.Update(deltaTime); if (cam) { @@ -384,22 +406,37 @@ void MainScene::SetupSkybox() { void MainScene::SetupLighting() { m_sun = new DirectionalLight("Sun"); m_sun->SetDirection(m_settingsPanel.ComputeSunDirection()); - float sunR, sunG, sunB; - m_settingsPanel.GetSunColor(sunR, sunG, sunB); - m_sun->SetColor(sunR, sunG, sunB); - m_sun->SetIntensity(m_settingsPanel.GetSunIntensity()); + m_sun->SetColor(LEGACY_SUN_COLOR[0], LEGACY_SUN_COLOR[1], + LEGACY_SUN_COLOR[2]); + m_sun->SetIntensity(LEGACY_SUN_INTENSITY); m_sun->SetLightSize(4.0f); m_settingsPanel.AttachSun(m_sun); - // Voxel-tuned graphics config: shadows on, no SSAO/SSR/IBL/bloom. + // Voxel-tuned graphics config: shadows and SSAO on, no SSR/IBL. Sleak::GraphicsConfig cfg = Sleak::GraphicsConfig::Preset(Sleak::GraphicsQuality::Medium); - cfg.ssaoEnabled = false; + cfg.ssaoEnabled = true; cfg.ssrEnabled = false; cfg.iblEnabled = false; - cfg.bloomEnabled = false; // match OpenGL ref (no post-FX bloom chain) cfg.taaEnabled = true; // VK only for now cfg.sharpenStrength = DEFAULT_SHARPEN_STRENGTH; + // BSL output: soft curve, x4 exposure, gamma 2.2, blend bloom, dither + cfg.tonemapEnabled = true; + cfg.tonemapOperator = Sleak::TonemapOperator::SoftRational; + cfg.exposure = LOOK_EXPOSURE; + cfg.gamma = LOOK_GAMMA; + cfg.saturation = LOOK_SATURATION; + cfg.tonemapWhiteCurve = LOOK_WHITE_CURVE; + cfg.tonemapWhitePath = LOOK_WHITE_PATH; + cfg.filmGrainEnabled = true; + cfg.bloomEnabled = true; + cfg.bloomMode = Sleak::BloomMode::Blend; + cfg.bloomBlend = LOOK_BLOOM_BLEND; + cfg.desaturationEnabled = true; + cfg.desaturationFactor = LOOK_DESATURATION_FACTOR; + cfg.minLight = LOOK_MIN_LIGHT; + // Linear albedo keeps sRGB precision in RT0 + cfg.gbufferAlbedoSRGB = true; cfg.shadowMapResolution = 3072; // BSL ULTRA tier; 4096 spiked VK frames cfg.shadowFrustumSize = 128.0f; // half-extent, 256 m ≈ fog range cfg.shadowCasterDistance = 256.0f; @@ -437,10 +474,9 @@ void MainScene::SetupLighting() { auto* lm = GetLightManager(); if (lm) { - float ambR, ambG, ambB; - m_settingsPanel.GetAmbientColor(ambR, ambG, ambB); - lm->SetAmbientColor(ambR, ambG, ambB); - lm->SetAmbientIntensity(m_settingsPanel.GetAmbientIntensity()); + lm->SetAmbientColor(LEGACY_AMBIENT_COLOR[0], LEGACY_AMBIENT_COLOR[1], + LEGACY_AMBIENT_COLOR[2]); + lm->SetAmbientIntensity(LEGACY_AMBIENT_INTENSITY); float horizonR, horizonG, horizonB; m_settingsPanel.GetFogHorizonColor(horizonR, horizonG, horizonB); diff --git a/Game/src/UI/SettingsPanel.cpp b/Game/src/UI/SettingsPanel.cpp index f2a53bb..bfbdc6e 100644 --- a/Game/src/UI/SettingsPanel.cpp +++ b/Game/src/UI/SettingsPanel.cpp @@ -15,6 +15,29 @@ using namespace Sleak; using namespace Sleak::Math; +namespace { + +// Voxel palette multiplier sliders +constexpr float MULTIPLIER_CHANNEL_STEP = 0.005f; +constexpr float MULTIPLIER_CHANNEL_MAX = 2.0f; +constexpr float MULTIPLIER_SCALE_STEP = 0.01f; +constexpr float MULTIPLIER_SCALE_MAX = 4.0f; + +/// Intensity and RGB sliders of one multiplier; true when any changed. +bool DragMultiplier(const char* intensity, const char* r, const char* g, + const char* b, LightMultiplier& m) { + bool changed = UI::DragFloat(intensity, &m.scale, MULTIPLIER_SCALE_STEP, + 0.0f, MULTIPLIER_SCALE_MAX); + changed |= UI::DragFloat(r, &m.r, MULTIPLIER_CHANNEL_STEP, 0.0f, + MULTIPLIER_CHANNEL_MAX); + changed |= UI::DragFloat(g, &m.g, MULTIPLIER_CHANNEL_STEP, 0.0f, + MULTIPLIER_CHANNEL_MAX); + changed |= UI::DragFloat(b, &m.b, MULTIPLIER_CHANNEL_STEP, 0.0f, + MULTIPLIER_CHANNEL_MAX); + return changed; +} + +} // namespace SettingsPanel::SettingsPanel(ChunkManager& chunkManager, MainScene& scene) : m_chunkManager(chunkManager), m_scene(scene) { @@ -163,35 +186,19 @@ void SettingsPanel::RenderLightingSection() { UI::DragFloat("Azimuth", &m_sunAzimuth, 1.0f, 0.0f, 360.0f); if (sunDirChanged && m_sun) m_sun->SetDirection(ComputeSunDirection()); - if (UI::DragFloat("Sun Intensity", &m_sunIntensity, 0.01f, 0.0f, 5.0f) && - m_sun) - m_sun->SetIntensity(m_sunIntensity); - - bool sunColorChanged = false; - sunColorChanged |= UI::DragFloat("Sun R", &m_sunColorR, 0.005f, 0.0f, 1.0f); - sunColorChanged |= UI::DragFloat("Sun G", &m_sunColorG, 0.005f, 0.0f, 1.0f); - sunColorChanged |= UI::DragFloat("Sun B", &m_sunColorB, 0.005f, 0.0f, 1.0f); - if (sunColorChanged && m_sun) - m_sun->SetColor(m_sunColorR, m_sunColorG, m_sunColorB); + bool paletteChanged = DragMultiplier("Sun Intensity", "Sun R", "Sun G", + "Sun B", m_sunMultiplier); UI::Separator(); UI::Text("-- Ambient --"); + paletteChanged |= DragMultiplier("Amb Intensity", "Amb R", "Amb G", "Amb B", + m_ambientMultiplier); + if (paletteChanged) + m_scene.GetVoxelLighting().SetMultipliers(m_sunMultiplier, + m_ambientMultiplier); + auto* lm = m_scene.GetLightManager(); - if (UI::DragFloat("Amb Intensity", &m_ambientIntensity, 0.005f, 0.0f, - 2.0f) && - lm) - lm->SetAmbientIntensity(m_ambientIntensity); - - bool ambColorChanged = false; - ambColorChanged |= - UI::DragFloat("Amb R", &m_ambientColorR, 0.005f, 0.0f, 1.0f); - ambColorChanged |= - UI::DragFloat("Amb G", &m_ambientColorG, 0.005f, 0.0f, 1.0f); - ambColorChanged |= - UI::DragFloat("Amb B", &m_ambientColorB, 0.005f, 0.0f, 1.0f); - if (ambColorChanged && lm) - lm->SetAmbientColor(m_ambientColorR, m_ambientColorG, m_ambientColorB); UI::Separator(); UI::Text("-- Fog --"); diff --git a/Game/src/World/BlockEffects.cpp b/Game/src/World/BlockEffects.cpp index f2c9bf9..c095fa7 100644 --- a/Game/src/World/BlockEffects.cpp +++ b/Game/src/World/BlockEffects.cpp @@ -1,139 +1,154 @@ #include "World/BlockEffects.hpp" -#include "World/TextureAtlas.hpp" + #include #include -#include -#include #include -#include +#include +#include #include +#include #include +#include "World/TextureAtlas.hpp" +#include "World/VoxelVertex.hpp" + using namespace Sleak; using namespace Sleak::Math; +namespace { + +constexpr int QUAD_CORNERS = 4; +constexpr int QUAD_INDICES = 6; + +/// One cube face: corners in the chunk mesher's order, normal, atlas face. +struct FaceInfo { + float positions[QUAD_CORNERS][3]; + float nx, ny, nz; + BlockFace face; +}; + +// Same corner order and winding as Chunk::GenerateMeshData +constexpr int CUBE_FACE_COUNT = 6; +constexpr FaceInfo CUBE_FACES[CUBE_FACE_COUNT] = { + {{{0, 1, 0}, {0, 1, 1}, {1, 1, 1}, {1, 1, 0}}, 0, 1, 0, BlockFace::Top}, + {{{0, 0, 1}, {0, 0, 0}, {1, 0, 0}, {1, 0, 1}}, 0, -1, 0, BlockFace::Bottom}, + {{{1, 0, 1}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, 0, 0, 1, BlockFace::North}, + {{{0, 0, 0}, {0, 1, 0}, {1, 1, 0}, {1, 0, 0}}, 0, 0, -1, BlockFace::South}, + {{{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {1, 0, 1}}, 1, 0, 0, BlockFace::East}, + {{{0, 0, 1}, {0, 1, 1}, {0, 1, 0}, {0, 0, 0}}, -1, 0, 0, BlockFace::West}, +}; +// Front faces of a quad, and the same triangles seen from behind +constexpr uint32_t QUAD_FRONT[QUAD_INDICES] = {0, 2, 1, 0, 3, 2}; +constexpr uint32_t QUAD_BACK[QUAD_INDICES] = {0, 1, 2, 0, 2, 3}; +constexpr float HALF = 0.5f; +// Unit particle quad on z = 0, corners in the north-face order +constexpr float PARTICLE_CORNERS[QUAD_CORNERS][2] = { + {HALF, -HALF}, {HALF, HALF}, {-HALF, HALF}, {-HALF, -HALF}}; +// Particle sides: front faces toward +z, back faces toward -z +constexpr float PARTICLE_SIDE_NORMALS[] = {1.0f, -1.0f}; + /// Uniform random float in [lo, hi). -static float RandFloat(float lo, float hi) { +float RandFloat(float lo, float hi) { float t = static_cast(rand()) / static_cast(RAND_MAX); return lo + t * (hi - lo); } -/// Builds a unit cube (0..1) with correct per-face textures. -static void BuildBlockCube(BlockType type, VertexGroup& verts, IndexGroup& inds) { - struct FaceInfo { - float positions[4][3]; - float nx, ny, nz; - BlockFace face; - }; - - FaceInfo faces[6] = { - {{{0,1,0}, {0,1,1}, {1,1,1}, {1,1,0}}, 0, 1, 0, BlockFace::Top}, - {{{0,0,1}, {0,0,0}, {1,0,0}, {1,0,1}}, 0, -1, 0, BlockFace::Bottom}, - {{{1,0,1}, {1,1,1}, {0,1,1}, {0,0,1}}, 0, 0, 1, BlockFace::North}, - {{{0,0,0}, {0,1,0}, {1,1,0}, {1,0,0}}, 0, 0, -1, BlockFace::South}, - {{{1,0,0}, {1,1,0}, {1,1,1}, {1,0,1}}, 1, 0, 0, BlockFace::East}, - {{{0,0,1}, {0,1,1}, {0,1,0}, {0,0,0}}, -1, 0, 0, BlockFace::West}, - }; - - for (int f = 0; f < 6; f++) { - AtlasUV uv = TextureAtlas::GetTileUV( - GetBlockTextureTile(type, faces[f].face)); +/// Atlas UVs of a quad's corners in the chunk mesher's order. +void QuadUVs(const AtlasUV& uv, float out[QUAD_CORNERS][2]) { + out[0][0] = uv.u0; + out[0][1] = uv.v1; + out[1][0] = uv.u0; + out[1][1] = uv.v0; + out[2][0] = uv.u1; + out[2][1] = uv.v0; + out[3][0] = uv.u1; + out[3][1] = uv.v1; +} - float uvs[4][2] = { - {uv.u0, uv.v1}, {uv.u0, uv.v0}, {uv.u1, uv.v0}, {uv.u1, uv.v1} - }; +/// Appends a quad's six indices, offset to its first vertex. +void AppendIndices(std::vector& indices, uint32_t base, + const uint32_t (&order)[QUAD_INDICES]) { + for (uint32_t i : order) indices.push_back(base + i); +} - uint32_t base = static_cast(verts.GetSize()); - for (int i = 0; i < 4; i++) { - Vertex v(faces[f].positions[i][0], - faces[f].positions[i][1], - faces[f].positions[i][2], - faces[f].nx, faces[f].ny, faces[f].nz, - 1, 0, 0, 1, - uvs[i][0], uvs[i][1]); - v.SetColor(1.0f, 1.0f, 1.0f, 1.0f); - verts.AddVertex(v); - } - inds.add(base); inds.add(base + 2); inds.add(base + 1); - inds.add(base); inds.add(base + 3); inds.add(base + 2); - } +/// GPU mesh of voxel vertices and indices. +MeshHandle UploadVoxelMesh(const VoxelVertexBuffer& vertices, + const std::vector& indices) { + return MeshBatch::CreateMesh(GetVoxelVertexFormat(), vertices.GetData(), + vertices.GetSizeInBytes(), indices.data(), + indices.size()); } -void BlockEffects::Initialize(SceneBase* scene, const RefPtr& material) { +} // namespace + +void BlockEffects::Initialize(SceneBase* scene, + const RefPtr& material) { m_scene = scene; m_material = material; } -GameObject* BlockEffects::CreatePlaceCube(BlockType type) { - VertexGroup verts; - IndexGroup inds; - BuildBlockCube(type, verts, inds); - - MeshData meshData; - meshData.vertices = std::move(verts); - meshData.indices = std::move(inds); - - auto* obj = new GameObject("PlaceEffect"); - obj->AddComponent(Vector3D(0, 0, 0)); - obj->AddComponent(m_material); - obj->AddComponent(std::move(meshData)); - obj->Initialize(); - return obj; +const MeshHandle& BlockEffects::CubeMesh(BlockType type) { + auto it = m_cubeMeshes.find(type); + if (it != m_cubeMeshes.end()) return it->second; + + VoxelVertexBuffer vertices; + std::vector indices; + for (const FaceInfo& f : CUBE_FACES) { + float uvs[QUAD_CORNERS][2]; + QuadUVs(TextureAtlas::GetTileUV(GetBlockTextureTile(type, f.face)), + uvs); + const uint32_t base = static_cast(vertices.GetSize()); + for (int i = 0; i < QUAD_CORNERS; i++) { + vertices.AddVertex(VoxelVertex(f.positions[i][0], f.positions[i][1], + f.positions[i][2], f.nx, f.ny, f.nz, + uvs[i][0], uvs[i][1])); + } + AppendIndices(indices, base, QUAD_FRONT); + } + return m_cubeMeshes.emplace(type, UploadVoxelMesh(vertices, indices)) + .first->second; } -GameObject* BlockEffects::CreateParticleQuad(uint8_t tileIndex) { - VertexGroup verts; - IndexGroup inds; - - AtlasUV uv = TextureAtlas::GetTileUV(tileIndex); - - // Two-sided quad on XY plane facing +Z, centered at origin - // Rotated each frame to face camera via TransformComponent - float h = 0.5f; - uint32_t base = 0; - Vertex v0(-h, -h, 0, 0, 0, 1, 1, 0, 0, 1, uv.u0, uv.v1); - Vertex v1(-h, h, 0, 0, 0, 1, 1, 0, 0, 1, uv.u0, uv.v0); - Vertex v2( h, h, 0, 0, 0, 1, 1, 0, 0, 1, uv.u1, uv.v0); - Vertex v3( h, -h, 0, 0, 0, 1, 1, 0, 0, 1, uv.u1, uv.v1); - v0.SetColor(1, 1, 1, 1); v1.SetColor(1, 1, 1, 1); - v2.SetColor(1, 1, 1, 1); v3.SetColor(1, 1, 1, 1); - verts.AddVertex(v0); verts.AddVertex(v1); - verts.AddVertex(v2); verts.AddVertex(v3); - - // Front - inds.add(base); inds.add(base + 2); inds.add(base + 1); - inds.add(base); inds.add(base + 3); inds.add(base + 2); - // Back (reverse winding) - inds.add(base); inds.add(base + 1); inds.add(base + 2); - inds.add(base); inds.add(base + 2); inds.add(base + 3); - - MeshData meshData; - meshData.vertices = std::move(verts); - meshData.indices = std::move(inds); +const MeshHandle& BlockEffects::QuadMesh(uint8_t tile) { + auto it = m_quadMeshes.find(tile); + if (it != m_quadMeshes.end()) return it->second; + + float uvs[QUAD_CORNERS][2]; + QuadUVs(TextureAtlas::GetTileUV(tile), uvs); + VoxelVertexBuffer vertices; + std::vector indices; + for (float nz : PARTICLE_SIDE_NORMALS) { + const uint32_t base = static_cast(vertices.GetSize()); + for (int i = 0; i < QUAD_CORNERS; i++) { + vertices.AddVertex(VoxelVertex(PARTICLE_CORNERS[i][0], + PARTICLE_CORNERS[i][1], 0.0f, 0.0f, + 0.0f, nz, uvs[i][0], uvs[i][1])); + } + AppendIndices(indices, base, nz > 0.0f ? QUAD_FRONT : QUAD_BACK); + } + return m_quadMeshes.emplace(tile, UploadVoxelMesh(vertices, indices)) + .first->second; +} - auto* obj = new GameObject("BreakParticle"); +GameObject* BlockEffects::CreateEffectObject(const char* name, + const MeshHandle& mesh) { + auto* obj = new GameObject(name); obj->AddComponent(Vector3D(0, 0, 0)); obj->AddComponent(m_material); - obj->AddComponent(std::move(meshData)); + obj->AddComponent(mesh); obj->Initialize(); - - auto* tr = obj->GetComponent(); - if (tr) tr->SetScale(Vector3D(PARTICLE_SIZE, PARTICLE_SIZE, PARTICLE_SIZE)); - return obj; } void BlockEffects::SpawnPlaceEffect(int x, int y, int z, BlockType type) { - auto* obj = CreatePlaceCube(type); + auto* obj = CreateEffectObject("PlaceEffect", CubeMesh(type)); - float startScale = 0.3f; - float offset = (1.0f - startScale) * 0.5f; - auto* tr = obj->GetComponent(); - if (tr) { + const float offset = (1.0f - PLACE_START_SCALE) * HALF; + if (auto* tr = obj->GetComponent()) { tr->SetPosition(Vector3D(x + offset, y + offset, z + offset)); - tr->SetScale(Vector3D(startScale, startScale, startScale)); + tr->SetScale( + Vector3D(PLACE_START_SCALE, PLACE_START_SCALE, PLACE_START_SCALE)); } - m_scene->AddObject(obj); PlaceEffect effect; @@ -148,89 +163,80 @@ void BlockEffects::SpawnPlaceEffect(int x, int y, int z, BlockType type) { } void BlockEffects::SpawnBreakEffect(int x, int y, int z, BlockType type) { - uint8_t tile = GetBlockTextureTile(type, BlockFace::South); - float cx = static_cast(x) + 0.5f; - float cy = static_cast(y) + 0.5f; - float cz = static_cast(z) + 0.5f; + const MeshHandle& quad = + QuadMesh(GetBlockTextureTile(type, BlockFace::South)); + const Vector3D center(static_cast(x) + HALF, + static_cast(y) + HALF, + static_cast(z) + HALF); for (int i = 0; i < PARTICLES_PER_BLOCK; i++) { - float px = cx + RandFloat(-0.3f, 0.3f); - float py = cy + RandFloat(-0.3f, 0.3f); - float pz = cz + RandFloat(-0.3f, 0.3f); - - auto* obj = CreateParticleQuad(tile); - auto* tr = obj->GetComponent(); - if (tr) tr->SetPosition(Vector3D(px, py, pz)); - m_scene->AddObject(obj); - BreakParticle p; - p.pos = Vector3D(px, py, pz); - p.vel = Vector3D(RandFloat(-1.5f, 1.5f), - RandFloat(1.5f, 4.0f), - RandFloat(-1.5f, 1.5f)); + p.pos = center + Vector3D(RandFloat(-BREAK_SPREAD, BREAK_SPREAD), + RandFloat(-BREAK_SPREAD, BREAK_SPREAD), + RandFloat(-BREAK_SPREAD, BREAK_SPREAD)); + p.vel = Vector3D(RandFloat(-BREAK_SIDE_SPEED, BREAK_SIDE_SPEED), + RandFloat(BREAK_UP_SPEED_MIN, BREAK_UP_SPEED_MAX), + RandFloat(-BREAK_SIDE_SPEED, BREAK_SIDE_SPEED)); p.life = 0.0f; - p.maxLife = BREAK_LIFETIME + RandFloat(-0.1f, 0.1f); - p.obj = obj; + p.maxLife = BREAK_LIFETIME + + RandFloat(-BREAK_LIFETIME_JITTER, BREAK_LIFETIME_JITTER); + + p.obj = CreateEffectObject("BreakParticle", quad); + if (auto* tr = p.obj->GetComponent()) { + tr->SetPosition(p.pos); + tr->SetScale(Vector3D(PARTICLE_SIZE, PARTICLE_SIZE, PARTICLE_SIZE)); + } + m_scene->AddObject(p.obj); m_breakParticles.push_back(p); } } void BlockEffects::Update(float deltaTime, const Vector3D& cameraPos) { - // Update place effects — animate scale + // Place effects: ease-out scale-in, centered on the block for (auto& effect : m_placeEffects) { + if (!effect.obj) continue; effect.timer += deltaTime; if (effect.timer >= effect.duration) { - if (effect.obj) { - m_scene->RemoveObject(effect.obj); - effect.obj = nullptr; - } + m_scene->RemoveObject(effect.obj); + effect.obj = nullptr; continue; } float t = effect.timer / effect.duration; t = 1.0f - (1.0f - t) * (1.0f - t); - float scale = 0.3f + t * 0.7f; - float offset = (1.0f - scale) * 0.5f; - - auto* tr = effect.obj->GetComponent(); - if (tr) { - tr->SetPosition(Vector3D(effect.x + offset, - effect.y + offset, + const float scale = PLACE_START_SCALE + t * (1.0f - PLACE_START_SCALE); + const float offset = (1.0f - scale) * HALF; + if (auto* tr = effect.obj->GetComponent()) { + tr->SetPosition(Vector3D(effect.x + offset, effect.y + offset, effect.z + offset)); tr->SetScale(Vector3D(scale, scale, scale)); } } - // Update break particles — move via TransformComponent + // Break particles: gravity, then face the camera for (auto& p : m_breakParticles) { p.life += deltaTime; if (p.life >= p.maxLife) { - if (p.obj) { - m_scene->RemoveObject(p.obj); - p.obj = nullptr; - } + m_scene->RemoveObject(p.obj); + p.obj = nullptr; continue; } p.vel = p.vel + Vector3D(0, PARTICLE_GRAVITY, 0) * deltaTime; p.pos = p.pos + p.vel * deltaTime; - - auto* tr = p.obj->GetComponent(); - if (tr) { + if (auto* tr = p.obj->GetComponent()) { tr->SetPosition(p.pos); tr->LookAt(cameraPos); } } - - // Remove dead particles from list m_breakParticles.erase( std::remove_if(m_breakParticles.begin(), m_breakParticles.end(), - [](const BreakParticle& p) { return p.obj == nullptr; }), + [](const BreakParticle& p) { return p.obj == nullptr; }), m_breakParticles.end()); } - -std::vector BlockEffects::PopCompletedPlacements() { +std::vector +BlockEffects::PopCompletedPlacements() { std::vector result; for (auto it = m_placeEffects.begin(); it != m_placeEffects.end();) { if (it->obj == nullptr) { @@ -244,7 +250,7 @@ std::vector BlockEffects::PopCompletedPlacements() } std::vector BlockEffects::DrainAllPlacements() { - // Commit everything still animating — used by save/exit paths + // Commit everything still animating, for the save and exit paths std::vector result; result.reserve(m_placeEffects.size()); for (auto& e : m_placeEffects) { diff --git a/Game/src/World/TextureAtlas.cpp b/Game/src/World/TextureAtlas.cpp index cc7c47c..4f75216 100644 --- a/Game/src/World/TextureAtlas.cpp +++ b/Game/src/World/TextureAtlas.cpp @@ -1,9 +1,12 @@ #include "World/TextureAtlas.hpp" -#include "World/Block.hpp" + #include #include -#include #include +#include +#include + +#include "World/Block.hpp" using namespace Sleak; using namespace Sleak::UI; @@ -39,6 +42,99 @@ static const char* s_tilePaths[] = { static_assert(sizeof(s_tilePaths) / sizeof(s_tilePaths[0]) == TILE_COUNT, "Tile path count must match TILE_COUNT"); +namespace { + +/// Per-channel linear-light grade that moves a tile's mean to a target. +struct TileGrade { + int tile; + float target[3]; // sRGB 0-255 of the graded texels' mean linear color + bool fringeOnly; // only the grass fringe of a side tile +}; + +// Grass and leaves toward vanilla plains colors under the BSL noon light; +// other tiles keep their colors. Tune against the BSL noon references. +constexpr TileGrade TILE_GRADES[] = { + {TILE_GRASS_TOP, {66.0f, 89.0f, 45.0f}, false}, + {TILE_GRASS_SIDE, {66.0f, 89.0f, 45.0f}, true}, + {TILE_OAK_LEAVES, {68.0f, 92.0f, 42.0f}, false}, +}; + +// Grass fringe texels: green above red and blue by this ratio +constexpr float FRINGE_GREEN_RATIO = 1.15f; +// Texels below this alpha are cut out and stay out of the mean +constexpr unsigned char GRADE_MIN_ALPHA = 128; +// Gain range that keeps a bad target from wiping out a channel +constexpr float GRADE_GAIN_MIN = 0.05f; +constexpr float GRADE_GAIN_MAX = 8.0f; +// sRGB transfer (IEC 61966-2-1) +constexpr float SRGB_LINEAR_KNEE = 0.04045f; +constexpr float SRGB_ENCODE_KNEE = 0.0031308f; +constexpr float SRGB_LINEAR_SLOPE = 12.92f; +constexpr float SRGB_SCALE = 1.055f; +constexpr float SRGB_OFFSET = 0.055f; +constexpr float SRGB_GAMMA = 2.4f; +constexpr float CHANNEL_MAX = 255.0f; +constexpr float ROUND_HALF = 0.5f; +constexpr int RGBA = 4; +constexpr int RGB = 3; +constexpr int ALPHA = 3; + +/// Linear light of an sRGB channel in [0, 1]. +float SrgbToLinear(float c) { + return c <= SRGB_LINEAR_KNEE + ? c / SRGB_LINEAR_SLOPE + : std::pow((c + SRGB_OFFSET) / SRGB_SCALE, SRGB_GAMMA); +} + +/// sRGB encoding of a linear channel, clamped to [0, 1]. +float LinearToSrgb(float c) { + c = std::clamp(c, 0.0f, 1.0f); + return c <= SRGB_ENCODE_KNEE + ? c * SRGB_LINEAR_SLOPE + : SRGB_SCALE * std::pow(c, 1.0f / SRGB_GAMMA) - SRGB_OFFSET; +} + +/// True for the green grass fringe texels of a side tile. +bool IsGrassFringe(const unsigned char* px) { + return px[1] > px[0] * FRINGE_GREEN_RATIO && + px[1] > px[2] * FRINGE_GREEN_RATIO; +} + +/// Grades a tile's RGBA8 texels in place, in linear light. +void GradeTile(unsigned char* pixels, int texels, const TileGrade& grade) { + double sum[RGB] = {}; + int counted = 0; + for (int i = 0; i < texels; ++i) { + const unsigned char* px = pixels + i * RGBA; + if (px[ALPHA] < GRADE_MIN_ALPHA) continue; + if (grade.fringeOnly && !IsGrassFringe(px)) continue; + for (int c = 0; c < RGB; ++c) + sum[c] += SrgbToLinear(px[c] / CHANNEL_MAX); + ++counted; + } + if (counted == 0) return; + + float gain[RGB]; + for (int c = 0; c < RGB; ++c) { + const float mean = static_cast(sum[c] / counted); + const float target = SrgbToLinear(grade.target[c] / CHANNEL_MAX); + gain[c] = mean > 0.0f ? std::clamp(target / mean, GRADE_GAIN_MIN, + GRADE_GAIN_MAX) + : 1.0f; + } + for (int i = 0; i < texels; ++i) { + unsigned char* px = pixels + i * RGBA; + if (grade.fringeOnly && !IsGrassFringe(px)) continue; + for (int c = 0; c < RGB; ++c) { + const float lin = SrgbToLinear(px[c] / CHANNEL_MAX) * gain[c]; + px[c] = static_cast(LinearToSrgb(lin) * CHANNEL_MAX + + ROUND_HALF); + } + } +} + +} // namespace + /// Resamples src (srcW x srcH) into dst (dstW x dstH) using nearest neighbor. static void ResampleNearest(const unsigned char* src, int srcW, int srcH, unsigned char* dst, int dstW, int dstH) { @@ -71,6 +167,12 @@ Sleak::RefPtr TextureAtlas::BuildAtlas() { } } + // Level-0 grades; the GPU builds the mips from the graded texels + for (const TileGrade& grade : TILE_GRADES) { + TileData& t = tiles[grade.tile]; + if (t.pixels) GradeTile(t.pixels, t.w * t.h, grade); + } + if (tileSize == 0) tileSize = 16; // fallback // Wrapped gutters: each cell holds the tile plus PAD px of the tile @@ -130,6 +232,7 @@ Sleak::RefPtr TextureAtlas::BuildAtlas() { desc.width = static_cast(atlasW); desc.height = static_cast(atlasH); desc.mipLevels = maxMips; + desc.srgb = true; // sampled as linear albedo const Sleak::TextureMipLevel level0{atlas.data(), atlas.size()}; return Sleak::CreateTexture(desc, &level0, 1); } diff --git a/Game/src/World/VoxelLighting.cpp b/Game/src/World/VoxelLighting.cpp new file mode 100644 index 0000000..5dfb956 --- /dev/null +++ b/Game/src/World/VoxelLighting.cpp @@ -0,0 +1,106 @@ +#include "World/VoxelLighting.hpp" + +#include +#include +#include +#include +#include + +namespace { + +// Authoring channels run 0-255 +constexpr float CHANNEL_MAX = 255.0f; +// Moon, rain and torch keys (BSL v10 defaults) +constexpr AuthoredKey MOON_KEY{96.0f, 192.0f, 255.0f, 1.00f}; +constexpr AuthoredKey RAIN_KEY{176.0f, 224.0f, 255.0f, 1.20f}; +constexpr AuthoredKey TORCH_KEY{255.0f, 212.0f, 160.0f, 0.85f}; +// Cave floor: grey authored like the palette, then scaled down +constexpr float MIN_LIGHT_GREY = 128.0f; +constexpr float MIN_LIGHT_SCALE = 0.04f; +// Desaturation removes 1 - this * factor of the color's chroma +constexpr float DESAT_PER_FACTOR = 0.4f; +// Emissive gain, albedo balancing, SSAO exponent (BSL defaults) +constexpr float EMISSION_GAIN = 4.0f; +constexpr float ALBEDO_BALANCE = 0.25f; +constexpr float SSAO_EXPONENT = 1.0f; +// Keeps a tint hue defined when its color is black +constexpr float TINT_EPSILON = 1e-6f; +constexpr int RGB = 3; + +/// Linear light of an authored color, written as rgb plus a zero w. +void WriteLinear(const SqrtColor& c, float out[4]) { + out[0] = c.r * c.r; + out[1] = c.g * c.g; + out[2] = c.b * c.b; + out[3] = 0.0f; +} + +/// Linear light of an authored color times a settings multiplier. +void WriteScaled(const SqrtColor& c, const LightMultiplier& m, float out[4]) { + WriteLinear(c, out); + const float gain[RGB] = {m.r, m.g, m.b}; + for (int i = 0; i < RGB; ++i) + out[i] *= std::max(gain[i], 0.0f) * std::max(m.scale, 0.0f); +} + +/// Unit-length hue of an authored color's linear light. +void WriteHue(const SqrtColor& c, float out[4]) { + WriteLinear(c, out); + const float len = + std::sqrt(out[0] * out[0] + out[1] * out[1] + out[2] * out[2]); + for (int i = 0; i < RGB; ++i) out[i] /= std::max(len, TINT_EPSILON); +} + +} // namespace + +SqrtColor ToSqrtColor(const AuthoredKey& key) { + const float scale = key.intensity / CHANNEL_MAX; + return {key.r * scale, key.g * scale, key.b * scale}; +} + +SqrtColor BlendColor(const SqrtColor& from, const SqrtColor& to, float t) { + return {from.r + (to.r - from.r) * t, from.g + (to.g - from.g) * t, + from.b + (to.b - from.b) * t}; +} + +LightingPalette VoxelLighting::NoonPalette() { + LightingPalette p; + p.sun = ToSqrtColor(NOON_SUN_KEY); + p.ambient = ToSqrtColor(NOON_AMBIENT_KEY); + p.moon = ToSqrtColor(MOON_KEY); + p.weather = ToSqrtColor(RAIN_KEY); + p.blockLight = ToSqrtColor(TORCH_KEY); + return p; +} + +void VoxelLighting::Upload(const Sleak::GraphicsConfig& config) const { + CraftFrameData d{}; + WriteScaled(m_palette.sun, m_sunMultiplier, d.SunColor); + WriteScaled(m_palette.ambient, m_ambientMultiplier, d.AmbientColor); + const SqrtColor grey = ToSqrtColor( + {MIN_LIGHT_GREY, MIN_LIGHT_GREY, MIN_LIGHT_GREY, config.minLight}); + WriteLinear(grey, d.MinLightColor); + for (int i = 0; i < RGB; ++i) d.MinLightColor[i] *= MIN_LIGHT_SCALE; + WriteLinear(m_palette.blockLight, d.BlockLightColor); + WriteHue(m_palette.moon, d.NightTint); + WriteHue(m_palette.weather, d.WeatherTint); + + d.Sky[0] = m_palette.sunVisibility; + d.Sky[1] = m_palette.rain; + d.Sky[2] = m_palette.shadowFade; + d.Sky[3] = m_palette.nightVision; + + d.Look[0] = + config.desaturationEnabled + ? std::max(1.0f - DESAT_PER_FACTOR * config.desaturationFactor, + 0.0f) + : 0.0f; + d.Look[1] = EMISSION_GAIN; + d.Look[2] = ALBEDO_BALANCE; + d.Look[3] = SSAO_EXPONENT; + + auto* app = Sleak::Application::GetInstance(); + if (app && !app->SetFrameUserData(&d, sizeof(d))) + SLEAK_ERROR("VoxelLighting: frame block of {} bytes rejected", + sizeof(d)); +} diff --git a/docs/pages/architecture-overview.md b/docs/pages/architecture-overview.md index dbc39d2..8ed9a79 100644 --- a/docs/pages/architecture-overview.md +++ b/docs/pages/architecture-overview.md @@ -233,25 +233,27 @@ and `Game/assets/shaders`. The engine's own `CompileShaders` CMake target only w one before them: ``` -BlockEffects::Update // advance break/place animations +BlockEffects::Update // move break/place effect objects BlockInteraction::DrainCompletedPlacements // finished placements become real blocks -Sleak::Scene::Update // engine objects, lights, physics +Sleak::Scene::Update // engine objects (effects too), lights, physics +VoxelLighting::Upload // voxel palette into the game frame block HudPanel::Update PlayerController::Update // movement + voxel collision ChunkManager::Update // streaming, meshing, visibility ChunkManager::RenderColumns -water material tiling, then ChunkManager::RenderWater +ChunkManager::RenderWater BlockInteraction::RenderOutline auto-save check, message timers HudPanel::RenderCrosshair, HudPanel::Render, SettingsPanel::Render, Hotbar::Render ``` Placements drain before the engine update so a block finishing its animation -this frame is solid by the time collision runs. The player moves before +this frame is solid by the time collision runs. The voxel palette is sent +every frame because activating a scene clears the game frame block; the +lighting stem reads it in the same frame. The player moves before `ChunkManager::Update` so streaming centers on the position the player -actually reached. Water submits after the solid columns and after its -material tiling is advanced by the game clock, which is what animates the -surface. +actually reached. Water submits after the solid columns; its shader animates +the surface from the engine clock in `FrameData`. --- diff --git a/docs/pages/player-and-ui.md b/docs/pages/player-and-ui.md index 6a3f29f..419cd4e 100644 --- a/docs/pages/player-and-ui.md +++ b/docs/pages/player-and-ui.md @@ -104,10 +104,13 @@ ENGINE_API void Text(const char* fmt, ...); currently visible. - **`SettingsPanel`** (`Game/src/UI/SettingsPanel.cpp`) renders general, culling, MSAA, render-distance, lighting, SSAO, IBL, and texture-filter sections, and pushes live - edits straight to the light manager and block material. It owns the sun/ambient/fog - slider state itself; crosshair, vsync, and multithreaded-loading toggles are read and - written through `MainScene`, because `MainScene::SetupLighting` also reads them once - at scene initialize time. + edits straight to the light manager and block material. Its sun elevation and + azimuth turn the engine sun; its sun and ambient intensity and RGB sliders are + multipliers (1 = unchanged) on the voxel palette (`VoxelLighting::SetMultipliers`), + so they change the voxel lighting while the engine sun and ambient that water still + reads stay fixed. It owns that slider state and the fog state itself; crosshair, + vsync, and multithreaded-loading toggles are read and written through `MainScene`, + because `MainScene::SetupLighting` also reads them once at scene initialize time. - **`Hotbar`** (`Game/src/UI/Hotbar.cpp`) lazily loads the nine slot icon textures on first render, then draws the strip; selection state lives on `BlockInteraction`, which `Hotbar` reads by reference rather than duplicating.