diff --git a/CMakeLists.txt b/CMakeLists.txt index 538aacbb22..a400c18c34 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -100,6 +100,21 @@ if(MU_ENABLE_SHADER_COMPILATION) set(spv "${MU_SHADER_OUTPUT_DIR}/${shader_name}.${stage}.spv") set(msl "${MU_SHADER_OUTPUT_DIR}/${shader_name}.${stage}.msl") set(dxil "${MU_SHADER_OUTPUT_DIR}/${shader_name}.${stage}.dxil") + # SDL binds uniform buffer, texture and sampler slot N to MSL index N: keep the declared + # bindings (spirv-cross otherwise numbers them in order of use). Not with storage buffers, + # which share the MSL buffer indices and follow the uniform buffers. + file(READ "${src}" shader_source) + # Storage buffers may be declared in an included .hlsli. + string(REGEX MATCHALL "#include \"[^\"]+\"" shader_includes "${shader_source}") + foreach(shader_include IN LISTS shader_includes) + string(REGEX REPLACE "#include \"([^\"]+)\"" "\\1" shader_include "${shader_include}") + file(READ "${MU_SHADER_SOURCE_DIR}/${shader_include}" include_source) + string(APPEND shader_source "${include_source}") + endforeach() + set(msl_flags) + if(NOT shader_source MATCHES "StructuredBuffer|ByteAddressBuffer") + set(msl_flags --msl-decoration-binding) + endif() add_custom_command( OUTPUT "${spv}" @@ -110,7 +125,7 @@ if(MU_ENABLE_SHADER_COMPILATION) ) add_custom_command( OUTPUT "${msl}" - COMMAND "${SPIRV_CROSS_EXE}" --msl "${spv}" --output "${msl}" + COMMAND "${SPIRV_CROSS_EXE}" --msl ${msl_flags} "${spv}" --output "${msl}" DEPENDS "${spv}" "${MU_SHADER_COMPILATION_STAMP}" "${SPIRV_CROSS_EXE}" COMMENT "SPIR-V to MSL: ${shader_name}.${stage}.spv" VERBATIM @@ -126,6 +141,7 @@ if(MU_ENABLE_SHADER_COMPILATION) set(MU_SHADER_BLOBS "${MU_SHADER_BLOBS}" "${spv}" "${msl}" "${dxil}" PARENT_SCOPE) endfunction() + file(GLOB MU_SHADER_INCLUDES CONFIGURE_DEPENDS "${MU_SHADER_SOURCE_DIR}/*.hlsli") set(MU_SHADER_BLOBS) foreach(shader_stage IN LISTS MU_SHADER_STAGE_NAMES) string(REGEX REPLACE "\\.[^.]+$" "" shader_name "${shader_stage}") diff --git a/cmake/ValidateDxilReflection.cmake b/cmake/ValidateDxilReflection.cmake index 3d14e2918e..29ebc234b0 100644 --- a/cmake/ValidateDxilReflection.cmake +++ b/cmake/ValidateDxilReflection.cmake @@ -25,11 +25,17 @@ set(shader_specs "skinned_weighted.vert|cb0,space1+t0,space0" "skinned_shadow.vert|cb0,space1+cb1,space1+t0,space0+t1,space0" "skinned_weighted_shadow.vert|cb0,space1+cb1,space1+t0,space0+t1,space0" - "skinned_lit.frag|cb0,space3+cb1,space3+cb2,space3+s0,space2+s1,space2+t0,space2+t1,space2" + "skinned_lit.frag|cb0,space3+cb1,space3+cb2,space3+s0,space2+s1,space2+s2,space2+t0,space2+t1,space2+t2,space2" + "world_lit.vert|cb0,space1" + "world_lit.frag|cb0,space3+cb1,space3+cb2,space3+s0,space2+s1,space2+s2,space2+s3,space2+t0,space2+t1,space2+t2,space2+t3,space2" + "shadow_mask.frag|-" "post_fullscreen.vert|-" "post_bloom_down.frag|cb0,space3+s0,space2+t0,space2" "post_bloom_up.frag|cb0,space3+s0,space2+t0,space2" - "post_composite.frag|cb0,space3+s0,space2+s1,space2+s2,space2+t0,space2+t1,space2+t2,space2" + "post_composite.frag|cb0,space3+s0,space2+s1,space2+s2,space2+s3,space2+s4,space2+t0,space2+t1,space2+t2,space2+t3,space2+t4,space2" + "post_ao.frag|cb0,space3+s0,space2+t0,space2" + "post_ao_blur.frag|cb0,space3+s0,space2+s1,space2+t0,space2+t1,space2" + "sun_depth.frag|cb0,space3+s0,space2+t0,space2" ) foreach(shader_spec IN LISTS shader_specs) diff --git a/cmake/ValidateShaderBlobs.cmake b/cmake/ValidateShaderBlobs.cmake index dbda6ae3ec..cdd8f299f8 100644 --- a/cmake/ValidateShaderBlobs.cmake +++ b/cmake/ValidateShaderBlobs.cmake @@ -19,11 +19,17 @@ set(MU_SHADER_STAGE_NAMES skinned_shadow.vert skinned_weighted_shadow.vert skinned_lit.frag + world_lit.vert + world_lit.frag + shadow_mask.frag shadow_volume.vert post_fullscreen.vert post_bloom_down.frag post_bloom_up.frag post_composite.frag + post_ao.frag + post_ao_blur.frag + sun_depth.frag ) set(MU_SHADER_BLOB_FORMATS spv msl dxil) set(MU_SHADER_BLOB_NAMES) diff --git a/cmake/ValidateShaderReflection.cmake b/cmake/ValidateShaderReflection.cmake index e3403bbc9d..ce925e6b03 100644 --- a/cmake/ValidateShaderReflection.cmake +++ b/cmake/ValidateShaderReflection.cmake @@ -223,6 +223,24 @@ function(mu_expect_msl_binding_order shader_name json member resource_kind msl) endforeach() endfunction() +# Likewise for uniform buffers: SDL pushes uniform slot N into MSL buffer N, so each block must sit +# at its binding (uniform buffers come first, before any storage buffer). +function(mu_expect_msl_uniform_order shader_name json msl) + mu_json_array_length(uniform_count "${json}" ubos) + if(uniform_count LESS 2) + return() + endif() + math(EXPR last_uniform "${uniform_count} - 1") + foreach(uniform_index RANGE 0 ${last_uniform}) + string(JSON uniform_name GET "${json}" ubos ${uniform_index} name) + string(JSON uniform_binding GET "${json}" ubos ${uniform_index} binding) + if(NOT msl MATCHES "constant[ \t]+${uniform_name}&[ \t]+[A-Za-z0-9_]+[ \t]+\\[\\[buffer\\(${uniform_binding}\\)\\]\\]") + mu_add_shader_validation_error( + "${shader_name}: MSL uniform buffer ${uniform_name} is not at index ${uniform_binding}") + endif() + endforeach() +endfunction() + function(mu_expect_msl_layout shader_name stage msl input_locations sampler_count storage_count uniform_count) # A vertex shader without vertex inputs (generated geometry) has no [[stage_in]]. if(stage STREQUAL "vert" AND NOT input_locations STREQUAL "" AND NOT msl MATCHES "\\[\\[stage_in\\]\\]") @@ -270,11 +288,17 @@ set(shader_specs "skinned_weighted.vert|vert|0,1,2,3,4,5,6,7,8|0|1|1" "skinned_shadow.vert|vert|0,3,4|0|2|2" "skinned_weighted_shadow.vert|vert|0,3,4,6,7|0|2|2" - "skinned_lit.frag|frag||2|0|3" + "skinned_lit.frag|frag||3|0|3" + "world_lit.vert|vert|0,1,2|0|0|1" + "world_lit.frag|frag||4|0|3" + "shadow_mask.frag|frag||0|0|0" "post_fullscreen.vert|vert||0|0|0" "post_bloom_down.frag|frag||1|0|1" "post_bloom_up.frag|frag||1|0|1" - "post_composite.frag|frag||3|0|1" + "post_composite.frag|frag||5|0|1" + "post_ao.frag|frag||1|0|1" + "post_ao_blur.frag|frag||2|0|1" + "sun_depth.frag|frag||1|0|1" ) foreach(shader_spec IN LISTS shader_specs) @@ -295,6 +319,17 @@ foreach(shader_spec IN LISTS shader_specs) set(json_path "${MU_SHADER_REFLECTION_OUTPUT_DIR}/${shader_name}.json") set(msl_path "${MU_SHADER_REFLECTION_OUTPUT_DIR}/${shader_name}.msl") file(READ "${source_path}" hlsl) + # As mu_add_shader: declared bindings, except beside storage buffers (also those of an included .hlsli). + string(REGEX MATCHALL "#include \"[^\"]+\"" shader_includes "${hlsl}") + foreach(shader_include IN LISTS shader_includes) + string(REGEX REPLACE "#include \"([^\"]+)\"" "\\1" shader_include "${shader_include}") + file(READ "${MU_SHADER_SOURCE_DIR}/${shader_include}" include_source) + string(APPEND hlsl "${include_source}") + endforeach() + set(msl_flags) + if(NOT hlsl MATCHES "StructuredBuffer|ByteAddressBuffer") + set(msl_flags --msl-decoration-binding) + endif() execute_process( COMMAND "${GLSLANG_EXE}" -V -D -S "${stage}" -e main -o "${spv_path}" "${source_path}" @@ -322,7 +357,7 @@ foreach(shader_spec IN LISTS shader_specs) file(WRITE "${json_path}" "${reflection_json}") execute_process( - COMMAND "${SPIRV_CROSS_EXE}" "${spv_path}" --msl --output "${msl_path}" + COMMAND "${SPIRV_CROSS_EXE}" "${spv_path}" --msl ${msl_flags} --output "${msl_path}" RESULT_VARIABLE msl_result ERROR_VARIABLE msl_error ) @@ -356,6 +391,7 @@ foreach(shader_spec IN LISTS shader_specs) mu_expect_msl_layout("${shader_name}" "${stage}" "${msl}" "${input_locations}" "${sampler_count}" "${storage_count}" "${uniform_count}") mu_expect_msl_binding_order("${shader_name}" "${reflection_json}" separate_images texture "${msl}") mu_expect_msl_binding_order("${shader_name}" "${reflection_json}" separate_samplers sampler "${msl}") + mu_expect_msl_uniform_order("${shader_name}" "${reflection_json}" "${msl}") endforeach() get_property(validation_errors GLOBAL PROPERTY MU_SHADER_VALIDATION_ERRORS) diff --git a/docs/build/rendering-parity.md b/docs/build/rendering-parity.md index e22c92e33e..62226f29ac 100644 --- a/docs/build/rendering-parity.md +++ b/docs/build/rendering-parity.md @@ -8,7 +8,7 @@ change performance behavior by OS. |----|----------------|--------------------| | macOS | Metal | Identical | | Linux | Vulkan | Identical | -| Windows | D3D12 | Identical | +| Windows | Vulkan (D3D12 via `[Render] Backend`) | Identical | Native drivers, GPUs, and font rasterizers can still expose platform-specific driver defects. Runtime parity therefore requires measurements on each target; diff --git a/docs/enhanced-look-map-environments.md b/docs/enhanced-look-map-environments.md new file mode 100644 index 0000000000..e8acb3292e --- /dev/null +++ b/docs/enhanced-look-map-environments.md @@ -0,0 +1,57 @@ +# Enhanced look: map environments + +Which environment each map has in `Data/Render/Look.json` and why. The environments themselves (what they set) are in [enhanced-look.md](enhanced-look.md#environments). Classic uses none of this. + +**Physical** describes the scene: outdoor, indoor, underground, underwater, aerial or mixed. **Policy** is the lighting it calls for: + +- **day-night:** open air, meant for a day-night cycle (not built yet: these maps keep their fixed sun). +- **hybrid:** mostly open, but dark, dense or special. +- **fixed:** authored lighting, never a day-night cycle. +- **custom:** its own kind of light (sky, underwater). + +The classification is a rendering proposal, not Webzen's own. A map is lit as one region: a mixed map can't light its interior and its open ground differently. + +| World | Map | Physical | Theme | Policy | Environment | +|---:|---|---|---|---|---| +| 0 | Lorencia | outdoor | grassland, town | day-night | `outdoor` | +| 1 | Dungeon | underground | dungeon, catacombs | fixed | `enclosed` | +| 2 | Devias | outdoor | snow, tundra | day-night | `outdoor` | +| 3 | Noria | outdoor | forest | day-night | `outdoor` | +| 4 | Lost Tower | indoor | dark tower | fixed | `enclosed` | +| 6 | Arena | mixed | gladiatorial arena | fixed | `fixed` | +| 7 | Atlans | underwater | submerged ruins | custom | `underwater` | +| 8 | Tarkan | outdoor | desert | day-night | `outdoor` | +| 9, 32 | Devil Square | indoor | demonic arena | fixed | `enclosed` | +| 10 | Icarus | aerial | sky, floating ruins | custom | `sky` | +| 11–17, 52 | Blood Castle 1–8 | aerial, mixed | floating fortress | fixed | `fixed` | +| 18–23, 53 | Chaos Castle 1–7 | indoor | enclosed battleground | fixed | `enclosed` | +| 24–29, 36 | Kalima 1–6, Lost Kalima | mixed | dark realm | fixed | `fixed` | +| 30 | Valley of Loren | outdoor | castle battlefield | day-night | `outdoor` | +| 31 | Land of Trials | outdoor | rocky wilderness | day-night | `outdoor` | +| 33 | Aida | outdoor | dark forest | hybrid | `outdoorDense` | +| 34, 35 | Crywolf | outdoor | mountain fortress | day-night | `outdoor` | +| 37 | Kanturu Ruins | outdoor, mixed | ancient ruins | hybrid | `outdoorDense` | +| 38 | Kanturu Relics | indoor | mechanical ruins | fixed | `enclosed` | +| 39 | Refinery Tower | indoor | boss chamber | fixed | `enclosed` | +| 41 | Barracks of Balgass | outdoor, mixed | military canyon | fixed | `fixed` | +| 42 | Balgass Refuge | indoor | boss refuge | fixed | `enclosed` | +| 45–50 | Illusion Temple 1–6 | indoor | ritual arena | fixed | `enclosed` | +| 51 | Elbeland | outdoor | enchanted forest | day-night | `outdoor` | +| 56 | Swamp of Calmness | outdoor | swamp | hybrid | `outdoorDense` | +| 57 | Raklion | outdoor | glacier | hybrid | `outdoorDense` | +| 58 | Raklion boss cave | underground | ice cavern | fixed | `enclosed` | +| 62 | Santa Village | outdoor | snowy village | fixed | `fixed` | +| 63 | Vulcanus | outdoor | volcanic | hybrid | `outdoorDense` | +| 64 | Duel Arena | arena | combat area | fixed | `fixed` | +| 65–68 | Doppelganger 1–4 | indoor, mixed | dungeon corridors | fixed | `enclosed` | +| 69–72 | Imperial Guardian 1–4 | indoor, mixed | fortress corridors | fixed | `enclosed` | +| 79 | Loren Market | outdoor | trade town | day-night | `outdoor` | +| 80, 81 | Karutan 1–2 | outdoor | rocky desert | day-night | `outdoor` | + +Not listed, so they get only the default values: + +- world 5; +- the GM area (40); +- the login and character scenes (54, 55, 73, 74, 77, 78). + +The later-season maps (Acheron, Debenter, Deep Dungeon, and so on) aren't in this client. diff --git a/docs/enhanced-look.md b/docs/enhanced-look.md index 7ed4646816..dccffc4217 100644 --- a/docs/enhanced-look.md +++ b/docs/enhanced-look.md @@ -12,7 +12,7 @@ options window, without editing those files (see "Tuning it yourself"). |---|---|---| | Texture filtering | mipmaps and anisotropic filtering for world textures | — | | Enhanced lighting | per-pixel model lighting with rim light and, on metal armour, specular highlights | — | -| Dynamic model lights | candles, fires and spells light characters, monsters and NPCs | — | +| Dynamic model lights | candles, fires and spells light characters, monsters, NPCs and world objects per pixel, and the ground as smooth pools instead of patches interpolated between terrain vertices; characters' shadows on the ground are see-through and merge where they overlap | — | | Light mood | darker baked map light, so the light sources stand out | [light-mood.md](light-mood.md) | | Post-processing | bloom around light effects and per-map colour grading | [post-processing.md](post-processing.md) | | Anti-aliasing | multisampled edges (4 samples, or what `Antialiasing` asks for), alpha-to-coverage for cut-out foliage and fences | — | @@ -70,23 +70,38 @@ window. |---|---|---|---|---|---|---| | Enhanced lighting | Directional light | `lighting.diffuse.scale` | 0–2 | 0.05 | 1 | common | | Enhanced lighting | Rim intensity | `lighting.rim.strength` | 0–1 | 0.05 | 0.4 | common | -| Enhanced lighting | Metallic shine | `lighting.specular.scale` | 0–2 | 0.05 | 1 | common | +| Enhanced lighting | Metallic shine | `lighting.specular.scale` | 0–2 | 0.05 | 0.8 | common | | Enhanced lighting | Ambient fill | `lighting.diffuse.ambient` | 0–1 | 0.05 | 0.3 | More settings | | Enhanced lighting | Minimum light | `lighting.diffuse.floor` | 0–1 | 0.05 | 0.15 | More settings | | Enhanced lighting | Highlight knee | `lighting.highlightKnee` | 0.5–0.9 | 0.01 | 0.8 | More settings | | Enhanced lighting | Rim concentration | `lighting.rim.power` | 1–8 | 0.1 | 3 | More settings | | Enhanced lighting | Shine concentration | `lighting.specular.power` | 4–128 | 1 | 32 | More settings | -| Dynamic lights | Skill intensity | `dynamic.effectGain` | 0–4× | 0.1× | 2.5× | common | -| Dynamic lights | Skill radius | `dynamic.effectRange` | 0.5–4× | 0.1× | 3× | common | +| Dynamic lights | Skill intensity | `dynamic.effectGain` | 0–4× | 0.1× | 0.5× | common | +| Dynamic lights | Skill radius | `dynamic.effectRange` | 0.5–4× | 0.1× | 2× | common | | Dynamic lights | Skill fade | `dynamic.effectFade` | 0–2 s | 0.05 s | 0.5 s | common | | Dynamic lights | Overlapping-light cap | `dynamic.effectCap` | 0–8 | 0.1 | 2.5 | common | +| Dynamic lights | Shadow darkness | `dynamic.shadowOpacity` | 0–100 % | 5 % | 60 % | common | +| Dynamic lights | Light shadows | `dynamic.shadowLights` | 0–4 | 1 | 2 | common | | Dynamic lights | Light wrap | `dynamic.wrap` | 0–0.5 | 0.05 | 0.3 | More settings | | Dynamic lights | Map-light smoothing | `dynamic.mapSmoothing` | 0–2 s | 0.05 s | 0.5 s | More settings | | Dynamic lights | Maximum skill radius | `dynamic.effectRangeMax` | 0–16 cells | 1 cell | 8 cells | More settings | +| Dynamic lights | Shadow direction | `dynamic.shadowAngle` | 0–360° | 5° | 135° | More settings | +| Dynamic lights | Sun shadows | `sun.shadow` | 0–100 % | 5 % | 100 % | common | +| Dynamic lights | Sun shadow softness | `sun.softness` | 0–2 | 0.1 | 1 | More settings | +| Dynamic lights | Sun shadow resolution | `sun.resolution` | 1024–4096 | 1024 | 2048 | More settings | +| Dynamic lights | Flat sun shadow | `dynamic.flatSunShadow` | 0–100 % | 5 % | 100 % (0 indoors) | More settings | +| Dynamic lights | Cloud shadows | `clouds.strength` | 0–100 % | 5 % | 35 % | common | +| Dynamic lights | Cloud size | `clouds.scale` | 500–10000 | 250 | 3000 | More settings | +| Dynamic lights | Cloud speed | `clouds.speed` | 0–300 | 5 | 40 | More settings | +| Dynamic lights | Cloud cover | `clouds.cover` | 0–100 % | 5 % | 45 % | More settings | +| Dynamic lights | Sky-blue shade | `sky.fill` | 0–100 % | 5 % | 50 % | common | +| Dynamic lights | Rim light follows the sun | `lighting.rim.sunFollow` | 0–100 % | 5 % | 100 % | More settings | | Darker map light | Mood strength | `mood.strengthPercent` | 0–100 % | 1 % | 100 % | common | | Bloom and colour grading | Bloom intensity | `bloom.strength` | 0–2 | 0.05 | 1 (Icarus 0.3) | common | | Bloom and colour grading | Bloom spread | `bloom.levelFalloff` | 0.25–1 | 0.05 | 0.6 | common | | Bloom and colour grading | Colour grading strength | `grading.strength` | 0–100 % | 1 % | 100 % | common | +| Bloom and colour grading | Contact shadows | `ao.strength` | 0–2 | 0.05 | 0.8 | common | +| Bloom and colour grading | Contact shadow reach | `ao.radius` | 10–300 | 5 | 60 | common | The defaults are the shipped look profile's (and each map's own, where it has one); they are defaults, not a promise that every combination of extremes looks @@ -175,7 +190,8 @@ Classic uses neither file. { "formatVersion": 1, "default": { "bloom.strength": 1.0, "dynamic.effectCap": 2.5 }, - "maps": [ { "world": 10, "name": "Icarus", "bloom.strength": 0.3 } ] + "environments": { "enclosed": { "sun.shadow": 0 } }, + "maps": [ { "world": 10, "name": "Icarus", "environment": "sky", "bloom.strength": 0.3 } ] } ``` @@ -193,18 +209,51 @@ for the whole file. | `lighting.highlightKnee` | 0.8 | 0.8 | 0.5–0.9 | lit colours above it approach white without reaching it | | `lighting.rim.strength` | 0.4 | 0.35 | 0–1 | light along a model's silhouette | | `lighting.rim.power` | 3 | 3 | 1–8 | how narrow the rim is | -| `lighting.specular.scale` | 1 | 1 | 0–2 | highlights on item models that declare specular (`material.specular` in the item-model JSON; the metal armour sets) | +| `lighting.specular.scale` | 0.8 | 1 | 0–2 | highlights on item models that declare specular (`material.specular` in the item-model JSON; the metal armour sets) | | `lighting.specular.power` | 32 | 32 | 4–128 | how small the highlight is | | `dynamic.wrap` | 0.3 | 0.5 | 0–0.5 | how far a point light reaches round a model | | `dynamic.mapSmoothing` | 0.5 | 0 | 0–2 | seconds over which flickering map and character lights (candles, fires) ease to their new brightness | -| `dynamic.effectGain` | 2.5 | 1 | 0–4 | brightness factor of spell and effect lights | -| `dynamic.effectRange` | 3 | 1 | 0.5–4 | range factor of spell and effect lights | +| `dynamic.effectGain` | 0.5 | 1 | 0–4 | brightness factor of spell and effect lights | +| `dynamic.effectRange` | 2 | 1 | 0.5–4 | range factor of spell and effect lights | | `dynamic.effectRangeMax` | 8 | 0 (none) | 0–16 | the most terrain cells the range factor may widen a light to | | `dynamic.effectFade` | 0.5 | 0 | 0–2 | seconds over which a spell's light fades out after it ends | | `dynamic.effectCap` | 2.5 | 0 (none) | 0–8 | the most light overlapping spell lights may add up to | +| `dynamic.shadowOpacity` | 0.6 | 0.6 | 0–1 | how much characters' shadows darken the ground's own light; overlapping shadows darken it once, and point lights still light shadowed ground | +| `dynamic.shadowLights` | 2 | 0 | 0–4 | how many of the strongest point lights near a character cast its shadow away from them; each darkens the point light on the ground by its share of the character's point light, and a light at the character casts none | +| `dynamic.shadowAngle` | 135 | 180 | 0–360 | which way characters' shadows fall, in degrees counter-clockwise from world +x; 135 falls away from the sun the maps' baked light was made for, 180 is the Classic direction. The sun turns with it: its shadow map, the terrain's slope shading and the models' light all follow, each keeping the offset the map's baked light has from that sun, so at 135 every map looks as it always did | | `bloom.strength` | 1.0 (Icarus 0.3) | 0.6 | 0–2 | how strong the halo around light effects is | | `bloom.levelFalloff` | 0.6 | 0.5 | 0.25–1 | how wide the halo spreads | | `grading.strength` | 1 | 1 | 0–1 | how much of a map's grading table applies; 0 grades nothing while the bloom stays | +| `ao.strength` | 0.8 | 0 | 0–2 | how much screen-space ambient occlusion darkens corners, wall bases and the ground under objects; additive effects are left alone. With anti-aliasing on, the scene's solid parts are drawn once more for the depth it reads | +| `ao.radius` | 60 | 60 | 10–300 | how far, in world units, nearby geometry still darkens a surface | +| `sun.shadow` | 1 | 0 | 0–1 | how dark the sun's shadows are, on top of `dynamic.shadowOpacity`. Everything solid (the terrain, buildings, trees, characters) is drawn from the sun into a shadow map, so shadows fall onto slopes, walls and other characters. The sun stands opposite `dynamic.shadowAngle`, as high as the flat character shadows were long. On models it takes away only the direct sunlight, not the ambient light. Characters' see-through parts (wings, capes, auras) cast a lighter shadow by their opacity, or glowing, their brightness. Above 0, characters cast no flat sun shadow; point-light shadows stay flat. Needs dynamic lights; drawn with anti-aliasing too | +| `sun.softness` | 1 | 1 | 0–2 | how many shadow-map texels the sun shadows' edges blur over | +| `dynamic.flatSunShadow` | 1 (Dungeon, Lost Tower, Kanturu Relics, Refinery Tower: 0) | 1 | 0–1 | how dark the flat shadow under characters is while sun shadows are off (`sun.shadow` 0); it falls away from the frame's sun, as long as the sun's slant (at most 3 units per unit of height), on top of the shadow's own darkness. The indoor and underground maps set both to 0: no sun there, so only torches and spells cast character shadows. Classic always draws it | +| `clouds.strength` | 0.35 | 0 | 0–1 | how much a passing cloud dims the sun's light on the ground and characters; drifting procedural clouds whose shadows fall slanted by the sun. Only with sun shadows | +| `clouds.scale` | 3000 | 3000 | 500–10000 | the cloud pattern's size in world units | +| `clouds.speed` | 40 | 40 | 0–300 | how fast the clouds drift along a fixed wind, in world units per second | +| `clouds.cover` | 0.45 | 0.45 | 0–1 | the share of the sky the clouds cover | +| `sky.fill` | 0.5 | 0 | 0–1 | how far shade (from shadows and clouds) turns towards the sky's blue while sunlit places keep the sun's colour; replaces the light mood's `shadeCool` while sun shadows are on. Only with sun shadows | +| `lighting.rim.sunFollow` | 1 | 0 | 0–1 | how much the characters' edge light comes from the sun: brighter and sun-coloured on its side, gone in its shadow; 0 the even Enhanced rim | +| `sun.resolution` | 2048 | 2048 | 1024–4096 | the sun shadow map's size in texels (1024, 2048 or 4096): sharper shadows for more graphics memory and time | + +## Environments + +`environments` names kinds of place; a map entry picks one +with `"environment"`. Their values apply between the default and the map's +own. The shipped ones: + +| Environment | What it sets | Maps | +|---|---|---| +| `outdoor` | nothing yet | Lorencia, Devias, Noria, Tarkan, Valley of Loren, Land of Trials, Crywolf, Elbeland, Loren Market, Karutan | +| `outdoorDense` | nothing yet | Aida, Kanturu Ruins, Swamp of Calmness, Raklion, Vulcanus | +| `sky` | nothing yet | Icarus | +| `underwater` | softer sun shadows | Atlans | +| `enclosed` | no sun shadows | Dungeon, Lost Tower, Devil Square, Chaos Castle, Kanturu Relics, Refinery Tower, Balgass Refuge, Illusion Temple, Raklion boss cave, Doppelganger, Imperial Guardian | +| `fixed` | nothing (open air) | Arena, Blood Castle, Kalima, Barracks of Balgass, Santa Village, Duel Arena | + +[enhanced-look-map-environments.md](enhanced-look-map-environments.md) lists +every map with its world number and why it has its environment. ## Developer commands @@ -233,7 +282,7 @@ Shorter forms of `$look set`: `$lighting rim `, `$lighting specular `, `$lighting diffuse `, `$lightmood knee `, `$dynlights wrap `, `$dynlights smooth `, `$dynlights spell `, `$dynlights cap `, -`$dynlights reach `, `$bloom falloff `, `$bloom `. +`$dynlights reach `, `$dynlights shadow `, `$dynlights shadowangle `, `$dynlights shadowlights `, `$bloom falloff `, `$bloom `, `$ao `, `$ao radius `, `$sun `, `$sun softness `, `$sun resolution `, `$dynlights flatsun `, `$clouds `, `$clouds scale `, `$clouds speed `, `$clouds cover `, `$sky `, `$rim sun `. The DevEditor has the same values in its Look panel. Feature overrides, to compare one feature on and off. They last for the diff --git a/docs/light-mood.md b/docs/light-mood.md index 8afdb88da2..cb8f32024e 100644 --- a/docs/light-mood.md +++ b/docs/light-mood.md @@ -52,7 +52,7 @@ for the reader. | `figures` | the baked light on characters, monsters and NPCs, and the fixed light of the player's own character | `base` to 1 | | `dynamicGain` | the light candles, fires, skills and effects add each frame | 0.5 to 2 | | `background` | the clear and fog colour behind the scene | 0 to 1 | -| `sun` | how much brighter a model face turned to the sun is than one turned away (1 is Classic, 0 leaves only the even fill light) | 0 to 1 | +| `sun` | how much brighter a model face turned to the sun is than one turned away (1 is Classic, 0 leaves only the even fill light); with Enhanced dynamic lights the direction follows `dynamic.shadowAngle` | 0 to 1 | | `shadowKeep` | optional: the baked light at which a place keeps its full brightness; `base` and `figures` then darken the shade only, fading out towards this light (sunlit ground stays day). 0 (the default) darkens everything evenly | 0 to 1.5 | | `brightScale` | optional, with a shadow keep: the scale places at the shadow keep get, never below `base` (figures: never below `figures`) | 0.3 to 1 (default) | | `shadeCool` | optional: how much bluer the darkened shade gets | 0 (default) to 0.5 | diff --git a/src/Localization/Game.en.resx b/src/Localization/Game.en.resx index d2c4f583b9..d8f906f23c 100644 --- a/src/Localization/Game.en.resx +++ b/src/Localization/Game.en.resx @@ -1150,6 +1150,24 @@ The most light several overlapping skills may add up to. No cap lets them add up freely; it does not switch skill lights off. + + Shadow darkness + + + How dark characters' shadows make the ground. Candle, fire and skill light still lights shadowed ground. + + + Light shadows + + + How many of the nearest candle, fire and skill lights cast a character's shadow away from them. 0 leaves only the sun's shadow. + + + Shadow direction + + + Which way characters' shadows fall, away from the map's sun: 0 degrees is east, 90 north, 180 west (as in the original look). + Light wrap @@ -1189,6 +1207,78 @@ Colour grading strength + + Contact shadows + + + Soft darkening where things meet: corners, wall bases, under objects (ambient occlusion). 0 turns it off. Not drawn while anti-aliasing is on. + + + Contact shadow reach + + + How far from a surface nearby geometry still darkens it, in world units (a terrain cell is 100). + + + Cloud shadows + + + How much a passing cloud dims the sunlight on the ground and characters. 0 for a clear sky. Needs sun shadows. + + + Cloud size + + + How large the clouds are, in world units (a terrain cell is 100). + + + Cloud speed + + + How fast the clouds drift, in world units per second. 0 holds them still. + + + Cloud cover + + + How much of the sky the clouds cover, from clear to overcast. + + + Sky-blue shade + + + How blue the shade turns, lit by the sky instead of the sun; sunlit places keep the sun's colour. Needs sun shadows. + + + Rim light follows the sun + + + How much the edge light on characters comes from the sun: brighter and sun-coloured on its side, gone in shade. 0 keeps the even edge light. + + + Flat sun shadow + + + How dark the flat shadow under characters is when sun shadows are off. Indoor and underground maps set it to 0, leaving only the shadows of torches and spells. + + + Sun shadows + + + How dark the sun's shadows are. Everything solid casts them onto the ground, walls and characters, in the shadow direction. 0 turns them off and draws the flat character shadows instead. + + + Sun shadow softness + + + How soft the edges of the sun's shadows are. + + + Sun shadow resolution + + + How sharp the sun's shadows are: 1024, 2048 or 4096. Higher costs more graphics memory and time. + How much of the map's colour grading applies. 0 % applies none, while bloom stays on. diff --git a/src/bin/Data/Render/Look.json b/src/bin/Data/Render/Look.json index 640f82e1cf..b3220708d9 100644 --- a/src/bin/Data/Render/Look.json +++ b/src/bin/Data/Render/Look.json @@ -7,24 +7,114 @@ "lighting.highlightKnee": 0.8, "lighting.rim.strength": 0.4, "lighting.rim.power": 3, - "lighting.specular.scale": 1.0, + "lighting.specular.scale": 0.8, "lighting.specular.power": 32, "dynamic.wrap": 0.3, "dynamic.mapSmoothing": 0.5, - "dynamic.effectGain": 2.5, - "dynamic.effectRange": 3, + "dynamic.effectGain": 0.5, + "dynamic.effectRange": 2, "dynamic.effectRangeMax": 8, "dynamic.effectFade": 0.5, "dynamic.effectCap": 2.5, + "dynamic.shadowOpacity": 0.6, + "dynamic.shadowAngle": 135, + "dynamic.shadowLights": 2, "bloom.strength": 1.0, "bloom.levelFalloff": 0.6, - "grading.strength": 1 + "grading.strength": 1, + "ao.strength": 0.8, + "ao.radius": 60, + "sun.shadow": 1, + "sun.softness": 1, + "sun.resolution": 2048, + "dynamic.flatSunShadow": 1, + "clouds.strength": 0.35, + "clouds.scale": 3000, + "clouds.speed": 40, + "clouds.cover": 0.45, + "sky.fill": 0.5, + "lighting.rim.sunFollow": 1 + }, + "environments": { + "outdoor": {}, + "outdoorDense": {}, + "sky": {}, + "underwater": { + "sun.softness": 2 + }, + "enclosed": { + "sun.shadow": 0, + "dynamic.flatSunShadow": 0 + }, + "fixed": {} }, "maps": [ - { - "world": 10, - "name": "Icarus", - "bloom.strength": 0.3 - } + {"world": 0, "name": "Lorencia", "environment": "outdoor"}, + {"world": 1, "name": "Dungeon", "environment": "enclosed"}, + {"world": 2, "name": "Devias", "environment": "outdoor"}, + {"world": 3, "name": "Noria", "environment": "outdoor"}, + {"world": 4, "name": "Lost Tower", "environment": "enclosed"}, + {"world": 6, "name": "Arena", "environment": "fixed"}, + {"world": 7, "name": "Atlans", "environment": "underwater"}, + {"world": 8, "name": "Tarkan", "environment": "outdoor"}, + {"world": 9, "name": "Devil Square", "environment": "enclosed"}, + {"world": 10, "name": "Icarus", "environment": "sky", "bloom.strength": 0.3}, + {"world": 11, "name": "Blood Castle 1", "environment": "fixed"}, + {"world": 12, "name": "Blood Castle 2", "environment": "fixed"}, + {"world": 13, "name": "Blood Castle 3", "environment": "fixed"}, + {"world": 14, "name": "Blood Castle 4", "environment": "fixed"}, + {"world": 15, "name": "Blood Castle 5", "environment": "fixed"}, + {"world": 16, "name": "Blood Castle 6", "environment": "fixed"}, + {"world": 17, "name": "Blood Castle 7", "environment": "fixed"}, + {"world": 18, "name": "Chaos Castle 1", "environment": "enclosed"}, + {"world": 19, "name": "Chaos Castle 2", "environment": "enclosed"}, + {"world": 20, "name": "Chaos Castle 3", "environment": "enclosed"}, + {"world": 21, "name": "Chaos Castle 4", "environment": "enclosed"}, + {"world": 22, "name": "Chaos Castle 5", "environment": "enclosed"}, + {"world": 23, "name": "Chaos Castle 6", "environment": "enclosed"}, + {"world": 24, "name": "Kalima 1", "environment": "fixed"}, + {"world": 25, "name": "Kalima 2", "environment": "fixed"}, + {"world": 26, "name": "Kalima 3", "environment": "fixed"}, + {"world": 27, "name": "Kalima 4", "environment": "fixed"}, + {"world": 28, "name": "Kalima 5", "environment": "fixed"}, + {"world": 29, "name": "Kalima 6", "environment": "fixed"}, + {"world": 30, "name": "Valley of Loren", "environment": "outdoor"}, + {"world": 31, "name": "Land of Trials", "environment": "outdoor"}, + {"world": 32, "name": "Devil Square", "environment": "enclosed"}, + {"world": 33, "name": "Aida", "environment": "outdoorDense"}, + {"world": 34, "name": "Crywolf", "environment": "outdoor"}, + {"world": 35, "name": "Crywolf", "environment": "outdoor"}, + {"world": 36, "name": "Lost Kalima", "environment": "fixed"}, + {"world": 37, "name": "Kanturu Ruins", "environment": "outdoorDense"}, + {"world": 38, "name": "Kanturu Relics", "environment": "enclosed"}, + {"world": 39, "name": "Refinery Tower", "environment": "enclosed"}, + {"world": 41, "name": "Barracks of Balgass", "environment": "fixed"}, + {"world": 42, "name": "Balgass Refuge", "environment": "enclosed"}, + {"world": 45, "name": "Illusion Temple 1", "environment": "enclosed"}, + {"world": 46, "name": "Illusion Temple 2", "environment": "enclosed"}, + {"world": 47, "name": "Illusion Temple 3", "environment": "enclosed"}, + {"world": 48, "name": "Illusion Temple 4", "environment": "enclosed"}, + {"world": 49, "name": "Illusion Temple 5", "environment": "enclosed"}, + {"world": 50, "name": "Illusion Temple 6", "environment": "enclosed"}, + {"world": 51, "name": "Elbeland", "environment": "outdoor"}, + {"world": 52, "name": "Blood Castle 8", "environment": "fixed"}, + {"world": 53, "name": "Chaos Castle 7", "environment": "enclosed"}, + {"world": 56, "name": "Swamp of Calmness", "environment": "outdoorDense"}, + {"world": 57, "name": "Raklion", "environment": "outdoorDense"}, + {"world": 58, "name": "Raklion boss cave", "environment": "enclosed"}, + {"world": 62, "name": "Santa Village", "environment": "fixed"}, + {"world": 63, "name": "Vulcanus", "environment": "outdoorDense"}, + {"world": 64, "name": "Duel Arena", "environment": "fixed"}, + {"world": 65, "name": "Doppelganger 1", "environment": "enclosed"}, + {"world": 66, "name": "Doppelganger 2", "environment": "enclosed"}, + {"world": 67, "name": "Doppelganger 3", "environment": "enclosed"}, + {"world": 68, "name": "Doppelganger 4", "environment": "enclosed"}, + {"world": 69, "name": "Imperial Guardian 1", "environment": "enclosed"}, + {"world": 70, "name": "Imperial Guardian 2", "environment": "enclosed"}, + {"world": 71, "name": "Imperial Guardian 3", "environment": "enclosed"}, + {"world": 72, "name": "Imperial Guardian 4", "environment": "enclosed"}, + {"world": 79, "name": "Loren Market", "environment": "outdoor"}, + {"world": 80, "name": "Karutan 1", "environment": "outdoor"}, + {"world": 81, "name": "Karutan 2", "environment": "outdoor"} ] } diff --git a/src/shaders/basic_textured_fog.frag.hlsl b/src/shaders/basic_textured_fog.frag.hlsl index f0ace9236f..ab6b19e94a 100644 --- a/src/shaders/basic_textured_fog.frag.hlsl +++ b/src/shaders/basic_textured_fog.frag.hlsl @@ -1,30 +1,10 @@ // basic_textured_fog.frag.hlsl — basic_textured.frag with Enhanced per-pixel exponential fog. // Used by the 3D and GPU-skinned unlit pipelines while Enhanced lighting is on, so terrain, static // objects and model overlays fade into the fog together with skinned_lit.frag models. -// FogUniforms mirrors FogUniform and SceneLighting mirrors mu::SceneLightingUniform (std140). +// The shared uniforms and lighting functions: scene_lighting.hlsli. Texture2D tex : register(t0, space2); SamplerState s : register(s0, space2); -cbuffer FogUniforms : register(b0, space3) -{ - uint fogEnabled; - uint alphaDiscardEnabled; - float alphaThreshold; - uint alphaToCoverage; // 1: the pipeline turns alpha into multisample coverage - float fogStart; - float fogEnd; - float4 fogColor; -}; -cbuffer SceneLighting : register(b1, space3) -{ - float4 sceneLightDirection; - float4 sceneLightColor; - float4 diffuseCurve; - float4 rimParameters; - float4 specularParameters; - float4 sceneFogColor; - float4 sceneFogParameters; - float4 cameraPosition; -}; +#include "scene_lighting.hlsli" struct FSInput { float4 pos : SV_Position; @@ -34,13 +14,6 @@ struct FSInput float eyeDepth : TEXCOORD3; }; -// Same curve as skinned_lit.frag.hlsl and mu::EnhancedFogAmount() (SceneLighting.cpp). -float EnhancedFogAmount(float eyeDepth) -{ - const float scaledDistance = max(eyeDepth - sceneFogParameters.x, 0.0) * sceneFogParameters.z; - return saturate(1.0 - exp(-scaledDistance * scaledDistance)); -} - float4 main(FSInput input) : SV_Target { float4 color = tex.Sample(s, input.uv) * input.color; diff --git a/src/shaders/clouds.hlsli b/src/shaders/clouds.hlsli new file mode 100644 index 0000000000..5fb65c5a18 --- /dev/null +++ b/src/shaders/clouds.hlsli @@ -0,0 +1,38 @@ +// clouds.hlsli — the shadows of drifting clouds: how much of the sun's light reaches a point on the ground +// through a soft, procedural cloud cover. The same function lights the ground and the characters, +// so a cloud's shadow falls on all of them alike. +#ifndef MU_CLOUDS_HLSLI +#define MU_CLOUDS_HLSLI + +float CloudHash(float2 p) +{ + return frac(sin(dot(p, float2(127.1, 311.7))) * 43758.5453); +} + +// Smooth value noise in [0, 1]. +float CloudNoise(float2 p) +{ + const float2 cell = floor(p); + const float2 f = frac(p); + const float2 u = f * f * (3.0 - 2.0 * f); + const float a = CloudHash(cell); + const float b = CloudHash(cell + float2(1.0, 0.0)); + const float c = CloudHash(cell + float2(0.0, 1.0)); + const float d = CloudHash(cell + float2(1.0, 1.0)); + return lerp(lerp(a, b, u.x), lerp(c, d, u.x), u.y); +} + +// The share of the sun's light that reaches world point `xy`: 1 in clear sky, 1 - strength under a cloud. +// `parameters`: x strength (0: no clouds), y 1 / pattern size in world units, z sky cover (0 to 1). +// `offset`: the clouds' drift plus the sun's slant through the cloud layer, in world units. +float CloudLight(float2 xy, float4 parameters, float2 offset) +{ + if (parameters.x <= 0.0) + return 1.0; + const float2 p = (xy + offset) * parameters.y; + const float cover = 0.55 * CloudNoise(p) + 0.3 * CloudNoise(p * 2.03 + 17.1) + 0.15 * CloudNoise(p * 4.07 + 31.7); + const float threshold = 1.0 - parameters.z; + const float cloud = smoothstep(threshold - 0.12, threshold + 0.12, cover); + return 1.0 - parameters.x * cloud; +} +#endif diff --git a/src/shaders/compiled/basic_textured_fog.frag.dxil b/src/shaders/compiled/basic_textured_fog.frag.dxil index 66ca7e6f9b..94eddbb8f6 100644 Binary files a/src/shaders/compiled/basic_textured_fog.frag.dxil and b/src/shaders/compiled/basic_textured_fog.frag.dxil differ diff --git a/src/shaders/compiled/basic_textured_fog.frag.msl b/src/shaders/compiled/basic_textured_fog.frag.msl index 0861043e80..5444104323 100644 --- a/src/shaders/compiled/basic_textured_fog.frag.msl +++ b/src/shaders/compiled/basic_textured_fog.frag.msl @@ -1,8 +1,19 @@ +#pragma clang diagnostic ignored "-Wmissing-prototypes" + #include #include using namespace metal; +struct FSInput +{ + float4 pos; + float2 uv; + float4 color; + float fogFactor; + float eyeDepth; +}; + struct SceneLighting { float4 sceneLightDirection; @@ -13,6 +24,14 @@ struct SceneLighting float4 sceneFogColor; float4 sceneFogParameters; float4 cameraPosition; + float4x4 sunViewProjection; + float4 sunShadowParameters; + float4 lightingParameters; + float4 cloudParameters; + float4 cloudOffset; + float4 skyFill; + float4 sunTowards; + float4 sunColor; }; struct FogUniforms @@ -35,50 +54,61 @@ struct main0_in { float2 input_uv [[user(locn0)]]; float4 input_color [[user(locn1)]]; + float input_fogFactor [[user(locn2)]]; float input_eyeDepth [[user(locn3)]]; }; -fragment main0_out main0(main0_in in [[stage_in]], constant SceneLighting& _24 [[buffer(0)]], constant FogUniforms& _72 [[buffer(1)]], texture2d tex [[texture(0)]], sampler s [[sampler(0)]]) +static inline __attribute__((always_inline)) +float EnhancedFogAmount(thread const float& eyeDepth, constant SceneLighting& _25) { - main0_out out = {}; - float4 _190 = tex.sample(s, in.input_uv); - float4 _193 = _190 * in.input_color; - float4 _310; - if (_72.alphaToCoverage != 0u) + float scaledDistance = fast::max(eyeDepth - _25.sceneFogParameters.x, 0.0) * _25.sceneFogParameters.z; + return fast::clamp(1.0 - exp((-scaledDistance) * scaledDistance), 0.0, 1.0); +} + +static inline __attribute__((always_inline)) +float4 _main(thread const FSInput& _input, constant SceneLighting& _25, texture2d tex, sampler s, constant FogUniforms& _73) +{ + float4 color = tex.sample(s, _input.uv) * _input.color; + if (_73.alphaToCoverage != 0u) { - float _213 = _193.w * fast::clamp(((_193.w - _72.alphaThreshold) / fast::max(fwidth(_193.w), 9.9999997473787516355514526367188e-05)) + 0.5, 0.0, 1.0); - float4 _301 = _193; - _301.w = _213; - if (_213 <= 0.0) + float edge = fast::clamp(((color.w - _73.alphaThreshold) / fast::max(fwidth(color.w), 9.9999997473787516355514526367188e-05)) + 0.5, 0.0, 1.0); + color.w *= edge; + if (color.w <= 0.0) { discard_fragment(); } - _310 = _301; } else { - if ((_72.alphaDiscardEnabled != 0u) && (_193.w <= _72.alphaThreshold)) + if ((_73.alphaDiscardEnabled != 0u) && (color.w <= _73.alphaThreshold)) { discard_fragment(); } - _310 = _193; } - float4 _311; - if ((_72.fogEnabled != 0u) && (_24.sceneFogColor.w > 0.0)) + if ((_73.fogEnabled != 0u) && (_25.sceneFogColor.w > 0.0)) { - float _270 = fast::max(in.input_eyeDepth - _24.sceneFogParameters.x, 0.0) * _24.sceneFogParameters.z; - float3 _250 = mix(_310.xyz, _24.sceneFogColor.xyz, float3(fast::clamp(1.0 - exp((-_270) * _270), 0.0, 1.0))); - float4 _305 = _310; - _305.x = _250.x; - _305.y = _250.y; - _305.z = _250.z; - _311 = _305; + float4 _134 = color; + float param = _input.eyeDepth; + float3 _146 = mix(_134.xyz, _25.sceneFogColor.xyz, float3(EnhancedFogAmount(param, _25))); + color.x = _146.x; + color.y = _146.y; + color.z = _146.z; } - else - { - _311 = _310; - } - out._entryPointOutput = _311; + return color; +} + +fragment main0_out main0(main0_in in [[stage_in]], constant FogUniforms& _73 [[buffer(0)]], constant SceneLighting& _25 [[buffer(1)]], texture2d tex [[texture(0)]], sampler s [[sampler(0)]], float4 gl_FragCoord [[position]]) +{ + main0_out out = {}; + FSInput _input; + _input.pos = gl_FragCoord; + _input.uv = in.input_uv; + _input.color = in.input_color; + _input.fogFactor = in.input_fogFactor; + _input.eyeDepth = in.input_eyeDepth; + FSInput param = _input; + float4 _180 = _main(param, _25, tex, s, _73); + out._entryPointOutput = _180; return out; } diff --git a/src/shaders/compiled/basic_textured_fog.frag.spv b/src/shaders/compiled/basic_textured_fog.frag.spv index b0e8321d44..11304098b5 100644 Binary files a/src/shaders/compiled/basic_textured_fog.frag.spv and b/src/shaders/compiled/basic_textured_fog.frag.spv differ diff --git a/src/shaders/compiled/post_ao.frag.dxil b/src/shaders/compiled/post_ao.frag.dxil new file mode 100644 index 0000000000..c129c352f8 Binary files /dev/null and b/src/shaders/compiled/post_ao.frag.dxil differ diff --git a/src/shaders/compiled/post_ao.frag.msl b/src/shaders/compiled/post_ao.frag.msl new file mode 100644 index 0000000000..7855f674c5 --- /dev/null +++ b/src/shaders/compiled/post_ao.frag.msl @@ -0,0 +1,161 @@ +#pragma clang diagnostic ignored "-Wmissing-prototypes" +#pragma clang diagnostic ignored "-Wmissing-braces" + +#include +#include + +using namespace metal; + +template +struct spvUnsafeArray +{ + T elements[Num ? Num : 1]; + + thread T& operator [] (size_t pos) thread + { + return elements[pos]; + } + constexpr const thread T& operator [] (size_t pos) const thread + { + return elements[pos]; + } + + device T& operator [] (size_t pos) device + { + return elements[pos]; + } + constexpr const device T& operator [] (size_t pos) const device + { + return elements[pos]; + } + + constexpr const constant T& operator [] (size_t pos) const constant + { + return elements[pos]; + } + + threadgroup T& operator [] (size_t pos) threadgroup + { + return elements[pos]; + } + constexpr const threadgroup T& operator [] (size_t pos) const threadgroup + { + return elements[pos]; + } +}; + +struct FSInput +{ + float4 pos; + float2 uv; +}; + +struct AmbientOcclusion +{ + float4x4 projection; + float4x4 inverseProjection; + float2 depthTexelSize; + float radius; + float padding; +}; + +constant spvUnsafeArray _247 = spvUnsafeArray({ 0.0, 0.5, 0.125, 0.625, 0.75, 0.25, 0.875, 0.375, 0.1875, 0.6875, 0.0625, 0.5625, 0.9375, 0.4375, 0.8125, 0.3125 }); +constant spvUnsafeArray _337 = spvUnsafeArray({ float3(0.20999999344348907470703125, 0.0500000007450580596923828125, 0.100000001490116119384765625), float3(-0.100000001490116119384765625, 0.25, 0.1500000059604644775390625), float3(-0.2800000011920928955078125, -0.119999997317790985107421875, 0.07999999821186065673828125), float3(0.14000000059604644775390625, -0.300000011920928955078125, 0.20000000298023223876953125), float3(0.4199999868869781494140625, 0.2199999988079071044921875, 0.25), float3(-0.3499999940395355224609375, 0.4000000059604644775390625, 0.119999997317790985107421875), float3(-0.300000011920928955078125, -0.449999988079071044921875, 0.3499999940395355224609375), float3(0.37999999523162841796875, -0.36000001430511474609375, 0.4199999868869781494140625), float3(0.699999988079071044921875, 0.100000001490116119384765625, 0.300000011920928955078125), float3(-0.1500000059604644775390625, 0.7200000286102294921875, 0.449999988079071044921875), float3(-0.660000026226043701171875, -0.20000000298023223876953125, 0.550000011920928955078125), float3(0.20000000298023223876953125, -0.62000000476837158203125, 0.699999988079071044921875) }); + +struct main0_out +{ + float4 _entryPointOutput [[color(0)]]; +}; + +struct main0_in +{ + float2 input_uv [[user(locn0)]]; +}; + +static inline __attribute__((always_inline)) +float SceneDepth(thread const float2& uv, texture2d depthTexture, sampler depthSampler) +{ + return depthTexture.sample(depthSampler, uv, level(0.0)).x; +} + +static inline __attribute__((always_inline)) +float3 ViewPosition(thread const float2& uv, thread const float& depth, constant AmbientOcclusion& _73) +{ + float4 view = _73.inverseProjection * float4((uv.x * 2.0) - 1.0, 1.0 - (uv.y * 2.0), depth, 1.0); + return view.xyz / float3(view.w); +} + +static inline __attribute__((always_inline)) +float3 ViewPositionAt(thread const float2& uv, texture2d depthTexture, sampler depthSampler, constant AmbientOcclusion& _73) +{ + float2 centre = (floor((uv / _73.depthTexelSize) + float2(0.25)) + float2(0.5)) * _73.depthTexelSize; + float2 param = centre; + float2 param_1 = centre; + float param_2 = SceneDepth(param, depthTexture, depthSampler); + return ViewPosition(param_1, param_2, _73); +} + +static inline __attribute__((always_inline)) +float3 SurfaceNormal(thread const float2& uv, thread const float3& position, texture2d depthTexture, sampler depthSampler, constant AmbientOcclusion& _73) +{ + float2 param = uv + float2(_73.depthTexelSize.x, 0.0); + float3 right = ViewPositionAt(param, depthTexture, depthSampler, _73) - position; + float2 param_1 = uv - float2(_73.depthTexelSize.x, 0.0); + float3 left = position - ViewPositionAt(param_1, depthTexture, depthSampler, _73); + float2 param_2 = uv + float2(0.0, _73.depthTexelSize.y); + float3 down = ViewPositionAt(param_2, depthTexture, depthSampler, _73) - position; + float2 param_3 = uv - float2(0.0, _73.depthTexelSize.y); + float3 up = position - ViewPositionAt(param_3, depthTexture, depthSampler, _73); + float3 alongX = select(left, right, bool3(abs(right.z) < abs(left.z))); + float3 alongY = select(up, down, bool3(abs(down.z) < abs(up.z))); + float3 normal = fast::normalize(cross(alongX, alongY)); + return select(normal, -normal, bool3(dot(normal, position) > 0.0)); +} + +static inline __attribute__((always_inline)) +float4 _main(thread const FSInput& _input, texture2d depthTexture, sampler depthSampler, constant AmbientOcclusion& _73) +{ + float2 param = _input.uv; + if (SceneDepth(param, depthTexture, depthSampler) >= 1.0) + { + return float4(1.0); + } + float2 param_1 = _input.uv; + float3 position = ViewPositionAt(param_1, depthTexture, depthSampler, _73); + float2 param_2 = _input.uv; + float3 param_3 = position; + float3 normal = SurfaceNormal(param_2, param_3, depthTexture, depthSampler, _73); + uint2 cell = uint2(_input.pos.xy) & uint2(3u); + float angle = 6.283185482025146484375 * _247[(cell.y * 4u) + cell.x]; + float3 turn = float3(cos(angle), sin(angle), 0.0); + float3 tangent = fast::normalize((turn - (normal * dot(turn, normal))) + float3(9.9999997473787516355514526367188e-05, 0.0, 0.0)); + float3 bitangent = cross(normal, tangent); + float occlusion = 0.0; + for (uint i = 0u; i < 12u; i++) + { + float3 offset = ((tangent * _337[i].x) + (bitangent * _337[i].y)) + (normal * _337[i].z); + float3 samplePosition = position + (offset * _73.radius); + float4 clip = _73.projection * float4(samplePosition, 1.0); + float2 sampleUv = float2(((clip.x / clip.w) * 0.5) + 0.5, 0.5 - ((clip.y / clip.w) * 0.5)); + float2 param_4 = sampleUv; + float3 toOccluder = ViewPositionAt(param_4, depthTexture, depthSampler, _73) - position; + float distanceSquared = dot(toOccluder, toOccluder); + float rise = dot(toOccluder, normal) * rsqrt(fast::max(distanceSquared, 9.9999999747524270787835121154785e-07)); + float inRange = fast::clamp(1.0 - (distanceSquared / (_73.radius * _73.radius)), 0.0, 1.0); + occlusion += (fast::clamp(rise - 0.1500000059604644775390625, 0.0, 1.0) * inRange); + } + float visibility = 1.0 - (occlusion / 12.0); + return float4(visibility); +} + +fragment main0_out main0(main0_in in [[stage_in]], constant AmbientOcclusion& _73 [[buffer(0)]], texture2d depthTexture [[texture(0)]], sampler depthSampler [[sampler(0)]], float4 gl_FragCoord [[position]]) +{ + main0_out out = {}; + FSInput _input; + _input.pos = gl_FragCoord; + _input.uv = in.input_uv; + FSInput param = _input; + out._entryPointOutput = _main(param, depthTexture, depthSampler, _73); + return out; +} + diff --git a/src/shaders/compiled/post_ao.frag.spv b/src/shaders/compiled/post_ao.frag.spv new file mode 100644 index 0000000000..532c3f1650 Binary files /dev/null and b/src/shaders/compiled/post_ao.frag.spv differ diff --git a/src/shaders/compiled/post_ao_blur.frag.dxil b/src/shaders/compiled/post_ao_blur.frag.dxil new file mode 100644 index 0000000000..4d863c7d06 Binary files /dev/null and b/src/shaders/compiled/post_ao_blur.frag.dxil differ diff --git a/src/shaders/compiled/post_ao_blur.frag.msl b/src/shaders/compiled/post_ao_blur.frag.msl new file mode 100644 index 0000000000..f4395bb3c1 --- /dev/null +++ b/src/shaders/compiled/post_ao_blur.frag.msl @@ -0,0 +1,102 @@ +#pragma clang diagnostic ignored "-Wmissing-prototypes" + +#include +#include + +using namespace metal; + +struct FSInput +{ + float4 pos; + float2 uv; +}; + +struct AmbientOcclusion +{ + float4x4 projection; + float4x4 inverseProjection; + float2 depthTexelSize; + float radius; + float padding; +}; + +struct main0_out +{ + float4 _entryPointOutput [[color(0)]]; +}; + +struct main0_in +{ + float2 input_uv [[user(locn0)]]; +}; + +static inline __attribute__((always_inline)) +float3 ViewPosition(thread float2& uv, constant AmbientOcclusion& _31, texture2d depthTexture, sampler depthSampler) +{ + uv = (floor((uv / _31.depthTexelSize) + float2(0.25)) + float2(0.5)) * _31.depthTexelSize; + float depth = depthTexture.sample(depthSampler, uv, level(0.0)).x; + float4 view = _31.inverseProjection * float4((uv.x * 2.0) - 1.0, 1.0 - (uv.y * 2.0), depth, 1.0); + return view.xyz / float3(view.w); +} + +static inline __attribute__((always_inline)) +float3 SurfaceNormal(thread const float2& uv, thread const float3& position, constant AmbientOcclusion& _31, texture2d depthTexture, sampler depthSampler) +{ + float2 param = uv + float2(_31.depthTexelSize.x, 0.0); + float3 _103 = ViewPosition(param, _31, depthTexture, depthSampler); + float3 right = _103 - position; + float2 param_1 = uv - float2(_31.depthTexelSize.x, 0.0); + float3 _114 = ViewPosition(param_1, _31, depthTexture, depthSampler); + float3 left = position - _114; + float2 param_2 = uv + float2(0.0, _31.depthTexelSize.y); + float3 _123 = ViewPosition(param_2, _31, depthTexture, depthSampler); + float3 down = _123 - position; + float2 param_3 = uv - float2(0.0, _31.depthTexelSize.y); + float3 _134 = ViewPosition(param_3, _31, depthTexture, depthSampler); + float3 up = position - _134; + float3 alongX = select(left, right, bool3(abs(right.z) < abs(left.z))); + float3 alongY = select(up, down, bool3(abs(down.z) < abs(up.z))); + return fast::normalize(cross(alongX, alongY)); +} + +static inline __attribute__((always_inline)) +float4 _main(thread const FSInput& _input, constant AmbientOcclusion& _31, texture2d depthTexture, sampler depthSampler, texture2d occlusionTexture, sampler occlusionSampler) +{ + float2 param = _input.uv; + float3 _173 = ViewPosition(param, _31, depthTexture, depthSampler); + float3 centre = _173; + float2 param_1 = _input.uv; + float3 param_2 = centre; + float3 normal = SurfaceNormal(param_1, param_2, _31, depthTexture, depthSampler); + float2 occlusionTexelSize = _31.depthTexelSize * 2.0; + float planeTolerance = _31.radius * 0.25; + float sum = 0.0; + float weightSum = 0.0; + for (int y = -2; y < 2; y++) + { + for (int x = -2; x < 2; x++) + { + float2 uv = _input.uv + (float2(float(x), float(y)) * occlusionTexelSize); + float2 param_3 = uv; + float3 _224 = ViewPosition(param_3, _31, depthTexture, depthSampler); + float offPlane = abs(dot(_224 - centre, normal)); + float weight = fast::clamp(1.0 - (offPlane / planeTolerance), 0.0, 1.0) + 0.001000000047497451305389404296875; + sum += (occlusionTexture.sample(occlusionSampler, uv, level(0.0)).x * weight); + weightSum += weight; + } + } + float visibility = sum / weightSum; + return float4(visibility); +} + +fragment main0_out main0(main0_in in [[stage_in]], constant AmbientOcclusion& _31 [[buffer(0)]], texture2d depthTexture [[texture(0)]], texture2d occlusionTexture [[texture(1)]], sampler depthSampler [[sampler(0)]], sampler occlusionSampler [[sampler(1)]], float4 gl_FragCoord [[position]]) +{ + main0_out out = {}; + FSInput _input; + _input.pos = gl_FragCoord; + _input.uv = in.input_uv; + FSInput param = _input; + out._entryPointOutput = _main(param, _31, depthTexture, depthSampler, occlusionTexture, occlusionSampler); + return out; +} + diff --git a/src/shaders/compiled/post_ao_blur.frag.spv b/src/shaders/compiled/post_ao_blur.frag.spv new file mode 100644 index 0000000000..838ce0e40b Binary files /dev/null and b/src/shaders/compiled/post_ao_blur.frag.spv differ diff --git a/src/shaders/compiled/post_composite.frag.dxil b/src/shaders/compiled/post_composite.frag.dxil index 9d470866ee..ea8d1243d6 100644 Binary files a/src/shaders/compiled/post_composite.frag.dxil and b/src/shaders/compiled/post_composite.frag.dxil differ diff --git a/src/shaders/compiled/post_composite.frag.msl b/src/shaders/compiled/post_composite.frag.msl index 7b9c9e0155..e0f44ae600 100644 --- a/src/shaders/compiled/post_composite.frag.msl +++ b/src/shaders/compiled/post_composite.frag.msl @@ -1,13 +1,25 @@ +#pragma clang diagnostic ignored "-Wmissing-prototypes" + #include #include using namespace metal; +struct FSInput +{ + float4 pos; + float2 uv; +}; + struct CompositeUniforms { float2 inverseTargetSize; float bloomScale; float gradingStrength; + float toneMapKnee; + float ditherAmount; + float ambientOcclusionStrength; + float ambientOcclusionEffects; }; struct main0_out @@ -15,44 +27,117 @@ struct main0_out float4 _entryPointOutput [[color(0)]]; }; -fragment main0_out main0(constant CompositeUniforms& _31 [[buffer(0)]], texture2d scene [[texture(0)]], texture2d bloom [[texture(1)]], texture2d grading [[texture(2)]], sampler sceneSampler [[sampler(0)]], sampler bloomSampler [[sampler(1)]], sampler gradingSampler [[sampler(2)]], float4 gl_FragCoord [[position]]) +struct main0_in { - main0_out out = {}; - float2 _210 = gl_FragCoord.xy * _31.inverseTargetSize; - float4 _215 = scene.sample(sceneSampler, _210); - float4 _354; - if (_31.bloomScale > 0.0) + float2 input_uv [[user(locn0)]]; +}; + +static inline __attribute__((always_inline)) +float AmbientOcclusion(thread const float2& uv, constant CompositeUniforms& _38, texture2d ambientOcclusion, sampler ambientOcclusionSampler, texture2d bloomSource, sampler bloomSourceSampler) +{ + float visibility = ambientOcclusion.sample(ambientOcclusionSampler, uv).x; + if (_38.ambientOcclusionEffects > 0.0) + { + float effectLight = dot(bloomSource.sample(bloomSourceSampler, uv).xyz, float3(0.2125999927520751953125, 0.715200006961822509765625, 0.072200000286102294921875)); + visibility = mix(visibility, 1.0, fast::clamp(effectLight * 4.0, 0.0, 1.0)); + } + return fast::max(1.0 - ((1.0 - visibility) * _38.ambientOcclusionStrength), 0.0); +} + +static inline __attribute__((always_inline)) +float ToneMapChannel(thread const float& value, constant CompositeUniforms& _38) +{ + float range = 1.0 - _38.toneMapKnee; + return (value > _38.toneMapKnee) ? (_38.toneMapKnee + (range * (1.0 - exp((-(value - _38.toneMapKnee)) / range)))) : value; +} + +static inline __attribute__((always_inline)) +float3 Grade(thread const float3& color, texture2d grading, sampler gradingSampler) +{ + float blue = color.z * 31.0; + float lowerSlice = floor(blue); + float upperSlice = fast::min(lowerSlice + 1.0, 31.0); + float sliceBlend = blue - lowerSlice; + float x = ((color.x * 31.0) + 0.5) / 1024.0; + float y = ((color.y * 31.0) + 0.5) / 32.0; + float3 lower = grading.sample(gradingSampler, float2(x + (lowerSlice * 0.03125), y)).xyz; + float3 upper = grading.sample(gradingSampler, float2(x + (upperSlice * 0.03125), y)).xyz; + return mix(lower, upper, float3(sliceBlend)); +} + +static inline __attribute__((always_inline)) +float DitherNoise(thread const float2& pixel) +{ + return fract(52.98291778564453125 * fract(dot(pixel, float2(0.067110560834407806396484375, 0.005837149918079376220703125)))); +} + +static inline __attribute__((always_inline)) +float4 _main(thread const FSInput& _input, constant CompositeUniforms& _38, texture2d scene, sampler sceneSampler, texture2d bloom, sampler bloomSampler, texture2d grading, sampler gradingSampler, texture2d ambientOcclusion, sampler ambientOcclusionSampler, texture2d bloomSource, sampler bloomSourceSampler) +{ + float2 uv = _input.pos.xy * _38.inverseTargetSize; + float4 color = scene.sample(sceneSampler, uv); + if (_38.ambientOcclusionStrength > 0.0) + { + float2 param = uv; + float4 _112 = color; + float3 _114 = _112.xyz * AmbientOcclusion(param, _38, ambientOcclusion, ambientOcclusionSampler, bloomSource, bloomSourceSampler); + color.x = _114.x; + color.y = _114.y; + color.z = _114.z; + } + if (_38.toneMapKnee < 1.0) { - float3 _241 = float3(1.0) - ((float3(1.0) - _215.xyz) * (float3(1.0) - fast::clamp(bloom.sample(bloomSampler, _210).xyz * _31.bloomScale, float3(0.0), float3(1.0)))); - float4 _337 = _215; - _337.x = _241.x; - _337.y = _241.y; - _337.z = _241.z; - _354 = _337; + float4 _130 = color; + float3 _133 = fast::max(_130.xyz, float3(0.0)); + color.x = _133.x; + color.y = _133.y; + color.z = _133.z; + float param_1 = color.x; + float param_2 = color.y; + float param_3 = color.z; + float3 _152 = float3(ToneMapChannel(param_1, _38), ToneMapChannel(param_2, _38), ToneMapChannel(param_3, _38)); + color.x = _152.x; + color.y = _152.y; + color.z = _152.z; } - else + if (_38.bloomScale > 0.0) { - _354 = _215; + float3 glow = fast::clamp(bloom.sample(bloomSampler, uv).xyz * _38.bloomScale, float3(0.0), float3(1.0)); + float4 _180 = color; + float3 _189 = float3(1.0) - ((float3(1.0) - _180.xyz) * (float3(1.0) - glow)); + color.x = _189.x; + color.y = _189.y; + color.z = _189.z; } - float4 _355; - if (_31.gradingStrength > 0.0) + if (_38.gradingStrength > 0.0) { - float _282 = _354.z * 31.0; - float _284 = floor(_282); - float _295 = ((_354.x * 31.0) + 0.5) * 0.0009765625; - float _300 = ((_354.y * 31.0) + 0.5) * 0.03125; - float3 _261 = mix(_354.xyz, mix(grading.sample(gradingSampler, float2(_295 + (_284 * 0.03125), _300)).xyz, grading.sample(gradingSampler, float2(_295 + (fast::min(_284 + 1.0, 31.0) * 0.03125), _300)).xyz, float3(_282 - _284)), float3(_31.gradingStrength)); - float4 _346 = _354; - _346.x = _261.x; - _346.y = _261.y; - _346.z = _261.z; - _355 = _346; + float4 _202 = color; + float3 param_4 = color.xyz; + float3 _211 = mix(_202.xyz, Grade(param_4, grading, gradingSampler), float3(_38.gradingStrength)); + color.x = _211.x; + color.y = _211.y; + color.z = _211.z; } - else + if (_38.ditherAmount > 0.0) { - _355 = _354; + float2 param_5 = _input.pos.xy; + float4 _234 = color; + float3 _237 = _234.xyz + float3((DitherNoise(param_5) - 0.5) * _38.ditherAmount); + color.x = _237.x; + color.y = _237.y; + color.z = _237.z; } - out._entryPointOutput = _355; + return color; +} + +fragment main0_out main0(main0_in in [[stage_in]], constant CompositeUniforms& _38 [[buffer(0)]], texture2d scene [[texture(0)]], texture2d bloom [[texture(1)]], texture2d grading [[texture(2)]], texture2d ambientOcclusion [[texture(3)]], texture2d bloomSource [[texture(4)]], sampler sceneSampler [[sampler(0)]], sampler bloomSampler [[sampler(1)]], sampler gradingSampler [[sampler(2)]], sampler ambientOcclusionSampler [[sampler(3)]], sampler bloomSourceSampler [[sampler(4)]], float4 gl_FragCoord [[position]]) +{ + main0_out out = {}; + FSInput _input; + _input.pos = gl_FragCoord; + _input.uv = in.input_uv; + FSInput param = _input; + out._entryPointOutput = _main(param, _38, scene, sceneSampler, bloom, bloomSampler, grading, gradingSampler, ambientOcclusion, ambientOcclusionSampler, bloomSource, bloomSourceSampler); return out; } diff --git a/src/shaders/compiled/post_composite.frag.spv b/src/shaders/compiled/post_composite.frag.spv index 21f25565be..ed0673d276 100644 Binary files a/src/shaders/compiled/post_composite.frag.spv and b/src/shaders/compiled/post_composite.frag.spv differ diff --git a/src/shaders/compiled/shadow_mask.frag.dxil b/src/shaders/compiled/shadow_mask.frag.dxil new file mode 100644 index 0000000000..d4a06b9af2 Binary files /dev/null and b/src/shaders/compiled/shadow_mask.frag.dxil differ diff --git a/src/shaders/compiled/shadow_mask.frag.msl b/src/shaders/compiled/shadow_mask.frag.msl new file mode 100644 index 0000000000..2362b915f3 --- /dev/null +++ b/src/shaders/compiled/shadow_mask.frag.msl @@ -0,0 +1,43 @@ +#pragma clang diagnostic ignored "-Wmissing-prototypes" + +#include +#include + +using namespace metal; + +struct FSInput +{ + float4 pos; + float2 uv; + float4 color; +}; + +struct main0_out +{ + float4 _entryPointOutput [[color(0)]]; +}; + +struct main0_in +{ + float2 input_uv [[user(locn0)]]; + float4 input_color [[user(locn1)]]; +}; + +static inline __attribute__((always_inline)) +float4 _main(thread const FSInput& _input) +{ + return float4(1.0 - _input.color.w); +} + +fragment main0_out main0(main0_in in [[stage_in]], float4 gl_FragCoord [[position]]) +{ + main0_out out = {}; + FSInput _input; + _input.pos = gl_FragCoord; + _input.uv = in.input_uv; + _input.color = in.input_color; + FSInput param = _input; + out._entryPointOutput = _main(param); + return out; +} + diff --git a/src/shaders/compiled/shadow_mask.frag.spv b/src/shaders/compiled/shadow_mask.frag.spv new file mode 100644 index 0000000000..9187440a23 Binary files /dev/null and b/src/shaders/compiled/shadow_mask.frag.spv differ diff --git a/src/shaders/compiled/skinned_lit.frag.dxil b/src/shaders/compiled/skinned_lit.frag.dxil index 1a12c61da0..f778a5b4b1 100644 Binary files a/src/shaders/compiled/skinned_lit.frag.dxil and b/src/shaders/compiled/skinned_lit.frag.dxil differ diff --git a/src/shaders/compiled/skinned_lit.frag.msl b/src/shaders/compiled/skinned_lit.frag.msl index 2c0609748d..43d7ba229b 100644 --- a/src/shaders/compiled/skinned_lit.frag.msl +++ b/src/shaders/compiled/skinned_lit.frag.msl @@ -1,8 +1,65 @@ +#pragma clang diagnostic ignored "-Wmissing-prototypes" +#pragma clang diagnostic ignored "-Wmissing-braces" + #include #include using namespace metal; +template +struct spvUnsafeArray +{ + T elements[Num ? Num : 1]; + + thread T& operator [] (size_t pos) thread + { + return elements[pos]; + } + constexpr const thread T& operator [] (size_t pos) const thread + { + return elements[pos]; + } + + device T& operator [] (size_t pos) device + { + return elements[pos]; + } + constexpr const device T& operator [] (size_t pos) const device + { + return elements[pos]; + } + + constexpr const constant T& operator [] (size_t pos) const constant + { + return elements[pos]; + } + + threadgroup T& operator [] (size_t pos) threadgroup + { + return elements[pos]; + } + constexpr const threadgroup T& operator [] (size_t pos) const threadgroup + { + return elements[pos]; + } +}; + +struct FSInput +{ + float4 pos; + float2 uv; + float4 color; + float fogFactor; + float eyeDepth; + float3 normal; + float3 viewVector; + float4 lightDirectionAndSpecular; + float4 worldPositionAndDynamicLights; + float3 worldNormal; + float4 tangent; + float4 worldTangentAndNormalMapScale; +}; + struct SceneLighting { float4 sceneLightDirection; @@ -13,13 +70,22 @@ struct SceneLighting float4 sceneFogColor; float4 sceneFogParameters; float4 cameraPosition; + float4x4 sunViewProjection; + float4 sunShadowParameters; + float4 lightingParameters; + float4 cloudParameters; + float4 cloudOffset; + float4 skyFill; + float4 sunTowards; + float4 sunColor; }; struct DynamicLights { uint dynamicLightCount; float dynamicLightWrap; - uint2 dynamicLightPadding; + uint dynamicWorldLightCount; + float groundShadowOpacity; float4 dynamicLightPositionAndRadius[32]; float4 dynamicLightColor[32]; }; @@ -35,6 +101,8 @@ struct FogUniforms float4 fogColor; }; +constant spvUnsafeArray _276 = spvUnsafeArray({ float2(-0.3260000050067901611328125, -0.4059999883174896240234375), float2(-0.839999973773956298828125, -0.07400000095367431640625), float2(-0.69599997997283935546875, 0.4569999873638153076171875), float2(-0.20299999415874481201171875, 0.620999991893768310546875), float2(0.96200001239776611328125, -0.194999992847442626953125), float2(0.472999989986419677734375, -0.4799999892711639404296875), float2(0.518999993801116943359375, 0.767000019550323486328125), float2(0.185000002384185791015625, -0.89300000667572021484375), float2(0.507000029087066650390625, 0.064000003039836883544921875), float2(0.89600002765655517578125, 0.412000000476837158203125), float2(-0.3219999969005584716796875, -0.933000028133392333984375), float2(-0.791999995708465576171875, -0.597999989986419677734375) }); + struct main0_out { float4 _entryPointOutput [[color(0)]]; @@ -44,6 +112,7 @@ struct main0_in { float2 input_uv [[user(locn0)]]; float4 input_color [[user(locn1)]]; + float input_fogFactor [[user(locn2)]]; float input_eyeDepth [[user(locn3)]]; float3 input_normal [[user(locn4)]]; float3 input_viewVector [[user(locn5)]]; @@ -54,133 +123,283 @@ struct main0_in float4 input_worldTangentAndNormalMapScale [[user(locn10)]]; }; -fragment main0_out main0(main0_in in [[stage_in]], constant SceneLighting& _117 [[buffer(0)]], constant DynamicLights& _163 [[buffer(1)]], constant FogUniforms& _527 [[buffer(2)]], texture2d tex [[texture(0)]], texture2d normalMap [[texture(1)]], sampler s [[sampler(0)]], sampler normalSampler [[sampler(1)]]) +static inline __attribute__((always_inline)) +float3 SafeNormalize(thread const float3& value) { - main0_out out = {}; - float4 _696 = tex.sample(s, in.input_uv); - float2 _699 = dfdx(in.input_uv); - float2 _702 = dfdy(in.input_uv); - float3 _1457; - float3 _1458; - if ((in.input_worldTangentAndNormalMapScale.w > 0.0) && (in.input_tangent.w != 0.0)) - { - float3 _727 = (normalMap.sample(normalSampler, in.input_uv, gradient2d(_699, _702)).xyz * 2.0) - float3(1.0); - float2 _731 = _727.xy * in.input_worldTangentAndNormalMapScale.w; - float _733 = _731.x; - float _735 = _731.y; - float _739 = (in.input_tangent.w > 0.0) ? 1.0 : (-1.0); - float _985 = dot(in.input_normal, in.input_normal); - float3 _993 = select(float3(0.0), in.input_normal * rsqrt(_985), bool3(_985 > 9.9999999600419720025001879548654e-13)); - float _999 = dot(in.input_tangent.xyz, in.input_tangent.xyz); - float3 _1007 = select(float3(0.0), in.input_tangent.xyz * rsqrt(_999), bool3(_999 > 9.9999999600419720025001879548654e-13)); - float3 _978 = ((_1007 * _733) + ((cross(_993, _1007) * _739) * _735)) + (_993 * _727.z); - float _1013 = dot(_978, _978); - float _1059 = dot(in.input_worldNormal, in.input_worldNormal); - float3 _1067 = select(float3(0.0), in.input_worldNormal * rsqrt(_1059), bool3(_1059 > 9.9999999600419720025001879548654e-13)); - float _1073 = dot(in.input_worldTangentAndNormalMapScale.xyz, in.input_worldTangentAndNormalMapScale.xyz); - float3 _1081 = select(float3(0.0), in.input_worldTangentAndNormalMapScale.xyz * rsqrt(_1073), bool3(_1073 > 9.9999999600419720025001879548654e-13)); - float3 _1052 = ((_1081 * _733) + ((cross(_1067, _1081) * _739) * _735)) + (_1067 * _727.z); - float _1087 = dot(_1052, _1052); - _1458 = select(float3(0.0), _1052 * rsqrt(_1087), bool3(_1087 > 9.9999999600419720025001879548654e-13)); - _1457 = select(float3(0.0), _978 * rsqrt(_1013), bool3(_1013 > 9.9999999600419720025001879548654e-13)) * length(in.input_normal); + float lengthSquared = dot(value, value); + return select(float3(0.0), value * rsqrt(lengthSquared), bool3(lengthSquared > 9.9999999600419720025001879548654e-13)); +} + +static inline __attribute__((always_inline)) +float3 PerturbNormal(thread const float3& normal, thread const float3& tangent, thread const float& handedness, thread const float3& mapped) +{ + float3 param = normal; + float3 n = SafeNormalize(param); + float3 param_1 = tangent; + float3 t = SafeNormalize(param_1); + float3 b = cross(n, t) * handedness; + float3 param_2 = ((t * mapped.x) + (b * mapped.y)) + (n * mapped.z); + return SafeNormalize(param_2); +} + +static inline __attribute__((always_inline)) +float SunVisibility(thread const float3& worldPosition, thread const float3& worldNormal, constant SceneLighting& _83, depth2d sunShadowMap, sampler sunShadowSampler) +{ + if (_83.sunShadowParameters.x <= 0.0) + { + return 1.0; } - else + float slope = 1.0 - fast::clamp(dot(worldNormal, fast::normalize(_83.sunTowards.xyz)), 0.0, 1.0); + float3 lifted = worldPosition + (worldNormal * ((1.5 + (2.0 * slope)) * _83.sunShadowParameters.w)); + float4 clip = _83.sunViewProjection * float4(lifted, 1.0); + float3 ndc = clip.xyz / float3(clip.w); + float2 uv = float2((ndc.x * 0.5) + 0.5, 0.5 - (ndc.y * 0.5)); + if ((any(uv < float2(0.0)) || any(uv > float2(1.0))) || (ndc.z >= 1.0)) + { + return 1.0; + } + float turn = 6.283185482025146484375 * fract(52.98291778564453125 * fract(dot(worldPosition.xy, float2(0.067110560834407806396484375, 0.005837149918079376220703125)))); + float2x2 rotation = float2x2(float2(cos(turn), -sin(turn)), float2(sin(turn), cos(turn))); + float radius = (_83.sunShadowParameters.z * fast::max(_83.sunShadowParameters.y, 0.25)) * 1.5; + float visible = 0.0; + float total = 0.0; + for (int i = 0; i < 12; i++) + { + float2 offset = _276[i] * rotation; + float weight = exp((-2.0) * dot(offset, offset)); + float3 _311 = float3(uv + (offset * radius), ndc.z); + visible += (weight * sunShadowMap.sample_compare(sunShadowSampler, _311.xy, _311.z, level(0.0))); + total += weight; + } + return visible / total; +} + +static inline __attribute__((always_inline)) +float CloudHash(thread const float2& p) +{ + return fract(sin(dot(p, float2(127.09999847412109375, 311.70001220703125))) * 43758.546875); +} + +static inline __attribute__((always_inline)) +float CloudNoise(thread const float2& p) +{ + float2 cell = floor(p); + float2 f = fract(p); + float2 u = (f * f) * (float2(3.0) - (f * 2.0)); + float2 param = cell; + float a = CloudHash(param); + float2 param_1 = cell + float2(1.0, 0.0); + float b = CloudHash(param_1); + float2 param_2 = cell + float2(0.0, 1.0); + float c = CloudHash(param_2); + float2 param_3 = cell + float2(1.0); + float d = CloudHash(param_3); + return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); +} + +static inline __attribute__((always_inline)) +float CloudLight(thread const float2& xy, thread const float4& parameters, thread const float2& offset) +{ + if (parameters.x <= 0.0) + { + return 1.0; + } + float2 p = (xy + offset) * parameters.y; + float2 param = p; + float2 param_1 = (p * 2.0299999713897705078125) + float2(17.1000003814697265625); + float2 param_2 = (p * 4.070000171661376953125) + float2(31.700000762939453125); + float cover = ((0.550000011920928955078125 * CloudNoise(param)) + (0.300000011920928955078125 * CloudNoise(param_1))) + (0.1500000059604644775390625 * CloudNoise(param_2)); + float threshold = 1.0 - parameters.z; + float cloud = smoothstep(threshold - 0.119999997317790985107421875, threshold + 0.119999997317790985107421875, cover); + return 1.0 - (parameters.x * cloud); +} + +static inline __attribute__((always_inline)) +float PointLightFalloff(thread const float3& toLight, thread const float& radius) +{ + float horizontal = length(toLight.xy); + return (horizontal < radius) ? ((radius - horizontal) / radius) : 0.0; +} + +static inline __attribute__((always_inline)) +float3 DynamicLighting(thread const float3& worldPosition, thread const float3& worldNormal, constant DynamicLights& _545) +{ + float3 light = float3(0.0); + uint count = min(_545.dynamicLightCount, 32u); + for (uint i = 0u; i < count; i++) { - _1458 = in.input_worldNormal; - _1457 = in.input_normal; - } - float _1101 = dot(_1457, _1457); - float3 _1109 = select(float3(0.0), _1457 * rsqrt(_1101), bool3(_1101 > 9.9999999600419720025001879548654e-13)); - float _1115 = dot(in.input_viewVector, in.input_viewVector); - float3 _1123 = select(float3(0.0), in.input_viewVector * rsqrt(_1115), bool3(_1115 > 9.9999999600419720025001879548654e-13)); - float _774 = dot(_1457, in.input_lightDirectionAndSpecular.xyz); - float _784 = fast::max((_774 * _117.diffuseCurve.x) + _117.diffuseCurve.y, _117.diffuseCurve.z); - float _1129 = dot(_1458, _1458); - float3 _1137 = select(float3(0.0), _1458 * rsqrt(_1129), bool3(_1129 > 9.9999999600419720025001879548654e-13)); - uint _1152 = min(_163.dynamicLightCount, 32u); - float3 _1460; - _1460 = float3(0.0); - float3 _1467; - for (uint _1459 = 0u; _1459 < _1152; _1460 = _1467, _1459++) - { - float3 _1165 = _163.dynamicLightPositionAndRadius[_1459].xyz - in.input_worldPositionAndDynamicLights.xyz; - float _1170 = length(_1165.xy); - if (_1170 >= _163.dynamicLightPositionAndRadius[_1459].w) + float4 positionAndRadius = _545.dynamicLightPositionAndRadius[i]; + float3 toLight = positionAndRadius.xyz - worldPosition; + float3 param = toLight; + float param_1 = positionAndRadius.w; + float falloff = PointLightFalloff(param, param_1); + if (falloff <= 0.0) { - _1467 = _1460; continue; } - float _1213 = dot(_1165, _1165); - _1467 = _1460 + (_163.dynamicLightColor[_1459].xyz * (((_163.dynamicLightPositionAndRadius[_1459].w - _1170) / _163.dynamicLightPositionAndRadius[_1459].w) * fast::clamp((dot(_1137, select(float3(0.0), _1165 * rsqrt(_1213), bool3(_1213 > 9.9999999600419720025001879548654e-13))) * (1.0 - _163.dynamicLightWrap)) + _163.dynamicLightWrap, 0.0, 1.0))); - } - float3 _795 = select(float3(0.0), _1460, bool3(in.input_worldPositionAndDynamicLights.w > 0.5)); - float3 _1462; - if ((_117.diffuseCurve.w > 0.0) && (_117.diffuseCurve.w < 1.0)) - { - float3 _812 = (in.input_color.xyz * _784) + _795; - float _1239 = _812.x; - float _1258 = 1.0 - _117.diffuseCurve.w; - float _1243 = _812.y; - float _1281 = 1.0 - _117.diffuseCurve.w; - float _1247 = _812.z; - float _1304 = 1.0 - _117.diffuseCurve.w; - _1462 = fast::clamp(float3((_1239 > _117.diffuseCurve.w) ? (_117.diffuseCurve.w + (_1258 * (1.0 - exp((-fast::max(_1239 - _117.diffuseCurve.w, 0.0)) / _1258)))) : _1239, (_1243 > _117.diffuseCurve.w) ? (_117.diffuseCurve.w + (_1281 * (1.0 - exp((-fast::max(_1243 - _117.diffuseCurve.w, 0.0)) / _1281)))) : _1243, (_1247 > _117.diffuseCurve.w) ? (_117.diffuseCurve.w + (_1304 * (1.0 - exp((-fast::max(_1247 - _117.diffuseCurve.w, 0.0)) / _1304)))) : _1247), float3(0.0), float3(1.0)); + float3 param_2 = toLight; + float wrapped = fast::clamp((dot(worldNormal, SafeNormalize(param_2)) * (1.0 - _545.dynamicLightWrap)) + _545.dynamicLightWrap, 0.0, 1.0); + light += (_545.dynamicLightColor[i].xyz * (falloff * wrapped)); } - else + return light; +} + +static inline __attribute__((always_inline)) +bool RollsOffHighlight(thread const float& knee) +{ + return (knee > 0.0) && (knee < 1.0); +} + +static inline __attribute__((always_inline)) +float RollOffChannel(thread const float& value, thread const float& knee) +{ + float range = 1.0 - knee; + return (value > knee) ? (knee + (range * (1.0 - exp((-fast::max(value - knee, 0.0)) / range)))) : value; +} + +static inline __attribute__((always_inline)) +float3 RollOffHighlight(thread const float3& color, thread const float& knee) +{ + float param = color.x; + float param_1 = knee; + float param_2 = color.y; + float param_3 = knee; + float param_4 = color.z; + float param_5 = knee; + return fast::clamp(float3(RollOffChannel(param, param_1), RollOffChannel(param_2, param_3), RollOffChannel(param_4, param_5)), float3(0.0), float3(1.0)); +} + +static inline __attribute__((always_inline)) +float EnhancedFogAmount(thread const float& eyeDepth, constant SceneLighting& _83) +{ + float scaledDistance = fast::max(eyeDepth - _83.sceneFogParameters.x, 0.0) * _83.sceneFogParameters.z; + return fast::clamp(1.0 - exp((-scaledDistance) * scaledDistance), 0.0, 1.0); +} + +static inline __attribute__((always_inline)) +float4 _main(thread const FSInput& _input, constant SceneLighting& _83, depth2d sunShadowMap, sampler sunShadowSampler, constant DynamicLights& _545, texture2d tex, sampler s, texture2d normalMap, sampler normalSampler, constant FogUniforms& _983) +{ + float4 texel = tex.sample(s, _input.uv); + float2 uvDx = dfdx(_input.uv); + float2 uvDy = dfdy(_input.uv); + float3 shadingNormal = _input.normal; + float3 worldNormal = _input.worldNormal; + float normalMapScale = _input.worldTangentAndNormalMapScale.w; + if ((normalMapScale > 0.0) && (_input.tangent.w != 0.0)) { - _1462 = fast::clamp((in.input_color.xyz * _784) + _795, float3(0.0), float3(1.0)); + float3 mapped = (normalMap.sample(normalSampler, _input.uv, gradient2d(uvDx, uvDy)).xyz * 2.0) - float3(1.0); + float3 _698 = mapped; + float2 _700 = _698.xy * normalMapScale; + mapped.x = _700.x; + mapped.y = _700.y; + float handedness = (_input.tangent.w > 0.0) ? 1.0 : (-1.0); + float3 param = _input.normal; + float3 param_1 = _input.tangent.xyz; + float param_2 = handedness; + float3 param_3 = mapped; + shadingNormal = PerturbNormal(param, param_1, param_2, param_3) * length(_input.normal); + float3 param_4 = _input.worldNormal; + float3 param_5 = _input.worldTangentAndNormalMapScale.xyz; + float param_6 = handedness; + float3 param_7 = mapped; + worldNormal = PerturbNormal(param_4, param_5, param_6, param_7); } - float _836 = in.input_lightDirectionAndSpecular.w * _117.specularParameters.x; - float3 _1463; - if ((_836 > 0.0) && (_774 > 0.0)) + float3 objectLight = _input.color.xyz; + float3 param_8 = shadingNormal; + float3 normal = SafeNormalize(param_8); + float3 param_9 = _input.viewVector; + float3 view = SafeNormalize(param_9); + float3 light = _input.lightDirectionAndSpecular.xyz; + float lightDot = dot(shadingNormal, light); + bool inWorld = _input.worldPositionAndDynamicLights.w > 0.5; + float3 param_10 = worldNormal; + float3 litNormal = SafeNormalize(param_10); + float3 param_11 = _input.worldPositionAndDynamicLights.xyz; + float3 param_12 = litNormal; + float2 param_13 = _input.worldPositionAndDynamicLights.xy; + float4 param_14 = _83.cloudParameters; + float2 param_15 = _83.cloudOffset.xy; + float sunVisible = (inWorld && (_83.sunShadowParameters.x > 0.0)) ? (SunVisibility(param_11, param_12, _83, sunShadowMap, sunShadowSampler) * CloudLight(param_13, param_14, param_15)) : 1.0; + float sunLight = 1.0 - (_83.sunShadowParameters.x * (1.0 - sunVisible)); + float3 skyShade = mix(float3(1.0), _83.skyFill.xyz, float3(_83.skyFill.w * (1.0 - sunVisible))); + float luminosity = fast::max(((lightDot * _83.diffuseCurve.x) * ((lightDot > 0.0) ? sunLight : 1.0)) + _83.diffuseCurve.y, _83.diffuseCurve.z); + float3 param_16 = _input.worldPositionAndDynamicLights.xyz; + float3 param_17 = litNormal; + float3 dynamicLight = select(float3(0.0), DynamicLighting(param_16, param_17, _545), bool3(inWorld)); + float3 lit = ((objectLight * skyShade) * luminosity) + dynamicLight; + float3 diffuse = fast::clamp(lit, float3(0.0), float3(1.0)); + float param_18 = _83.diffuseCurve.w; + if (RollsOffHighlight(param_18)) { - float _1328 = dot(in.input_lightDirectionAndSpecular.xyz, in.input_lightDirectionAndSpecular.xyz); - float3 _846 = select(float3(0.0), in.input_lightDirectionAndSpecular.xyz * rsqrt(_1328), bool3(_1328 > 9.9999999600419720025001879548654e-13)) + _1123; - float _1342 = dot(_846, _846); - _1463 = (_117.sceneLightColor.xyz * (_836 * powr(fast::clamp(dot(_1109, select(float3(0.0), _846 * rsqrt(_1342), bool3(_1342 > 9.9999999600419720025001879548654e-13))), 0.0, 1.0), _117.specularParameters.y))) * in.input_color.xyz; + float3 param_19 = lit; + float param_20 = _83.diffuseCurve.w; + diffuse = RollOffHighlight(param_19, param_20); } - else + float facing = fast::clamp(abs(dot(normal, view)), 0.0, 1.0); + float3 rim = objectLight * (_83.rimParameters.x * powr(1.0 - facing, _83.rimParameters.y)); + if (inWorld && (_83.sunTowards.w > 0.0)) { - _1463 = float3(0.0); + float towardsSun = fast::clamp((dot(litNormal, fast::normalize(_83.sunTowards.xyz)) * 0.75) + 0.25, 0.0, 1.0) * sunVisible; + rim = mix(rim, (rim * _83.sunColor.xyz) * (2.0 * towardsSun), float3(_83.sunTowards.w)); } - float _877 = _696.w * in.input_color.w; - float4 _881 = float4(((_696.xyz * _1462) + (in.input_color.xyz * (_117.rimParameters.x * powr(1.0 - fast::clamp(abs(dot(_1109, _1123)), 0.0, 1.0), _117.rimParameters.y)))) + _1463, _877); - float4 _1464; - if (_527.alphaToCoverage != 0u) + float specularStrength = _input.lightDirectionAndSpecular.w * _83.specularParameters.x; + float3 specular = float3(0.0); + if ((specularStrength > 0.0) && (lightDot > 0.0)) { - float _901 = _877 * fast::clamp(((_877 - _527.alphaThreshold) / fast::max(fwidth(_877), 9.9999997473787516355514526367188e-05)) + 0.5, 0.0, 1.0); - float4 _1447 = _881; - _1447.w = _901; - if (_901 <= 0.0) + float3 param_21 = light; + float3 param_22 = SafeNormalize(param_21) + view; + float3 halfVector = SafeNormalize(param_22); + float highlight = powr(fast::clamp(dot(normal, halfVector), 0.0, 1.0), _83.specularParameters.y); + specular = (_83.sceneLightColor.xyz * ((specularStrength * highlight) * sunLight)) * objectLight; + } + float4 color = float4(((texel.xyz * diffuse) + rim) + specular, texel.w * _input.color.w); + if (_983.alphaToCoverage != 0u) + { + float edge = fast::clamp(((color.w - _983.alphaThreshold) / fast::max(fwidth(color.w), 9.9999997473787516355514526367188e-05)) + 0.5, 0.0, 1.0); + color.w *= edge; + if (color.w <= 0.0) { discard_fragment(); } - _1464 = _1447; } else { - if ((_527.alphaDiscardEnabled != 0u) && (_877 <= _527.alphaThreshold)) + if ((_983.alphaDiscardEnabled != 0u) && (color.w <= _983.alphaThreshold)) { discard_fragment(); } - _1464 = _881; } - float4 _1465; - if ((_527.fogEnabled != 0u) && (_117.sceneFogColor.w > 0.0)) - { - float _1361 = fast::max(in.input_eyeDepth - _117.sceneFogParameters.x, 0.0) * _117.sceneFogParameters.z; - float3 _938 = mix(_1464.xyz, _117.sceneFogColor.xyz, float3(fast::clamp(1.0 - exp((-_1361) * _1361), 0.0, 1.0))); - float4 _1451 = _1464; - _1451.x = _938.x; - _1451.y = _938.y; - _1451.z = _938.z; - _1465 = _1451; - } - else + if ((_983.fogEnabled != 0u) && (_83.sceneFogColor.w > 0.0)) { - _1465 = _1464; + float4 _1036 = color; + float param_23 = _input.eyeDepth; + float3 _1046 = mix(_1036.xyz, _83.sceneFogColor.xyz, float3(EnhancedFogAmount(param_23, _83))); + color.x = _1046.x; + color.y = _1046.y; + color.z = _1046.z; } - out._entryPointOutput = _1465; + return color; +} + +fragment main0_out main0(main0_in in [[stage_in]], constant FogUniforms& _983 [[buffer(0)]], constant SceneLighting& _83 [[buffer(1)]], constant DynamicLights& _545 [[buffer(2)]], texture2d tex [[texture(0)]], texture2d normalMap [[texture(1)]], depth2d sunShadowMap [[texture(2)]], sampler s [[sampler(0)]], sampler normalSampler [[sampler(1)]], sampler sunShadowSampler [[sampler(2)]], float4 gl_FragCoord [[position]]) +{ + main0_out out = {}; + FSInput _input; + _input.pos = gl_FragCoord; + _input.uv = in.input_uv; + _input.color = in.input_color; + _input.fogFactor = in.input_fogFactor; + _input.eyeDepth = in.input_eyeDepth; + _input.normal = in.input_normal; + _input.viewVector = in.input_viewVector; + _input.lightDirectionAndSpecular = in.input_lightDirectionAndSpecular; + _input.worldPositionAndDynamicLights = in.input_worldPositionAndDynamicLights; + _input.worldNormal = in.input_worldNormal; + _input.tangent = in.input_tangent; + _input.worldTangentAndNormalMapScale = in.input_worldTangentAndNormalMapScale; + FSInput param = _input; + float4 _1101 = _main(param, _83, sunShadowMap, sunShadowSampler, _545, tex, s, normalMap, normalSampler, _983); + out._entryPointOutput = _1101; return out; } diff --git a/src/shaders/compiled/skinned_lit.frag.spv b/src/shaders/compiled/skinned_lit.frag.spv index c30122e9ea..eedc75d07c 100644 Binary files a/src/shaders/compiled/skinned_lit.frag.spv and b/src/shaders/compiled/skinned_lit.frag.spv differ diff --git a/src/shaders/compiled/skinned_shadow.vert.dxil b/src/shaders/compiled/skinned_shadow.vert.dxil index 268c5198ca..65360cd601 100644 Binary files a/src/shaders/compiled/skinned_shadow.vert.dxil and b/src/shaders/compiled/skinned_shadow.vert.dxil differ diff --git a/src/shaders/compiled/skinned_shadow.vert.msl b/src/shaders/compiled/skinned_shadow.vert.msl index 3712ecadde..c19092815e 100644 --- a/src/shaders/compiled/skinned_shadow.vert.msl +++ b/src/shaders/compiled/skinned_shadow.vert.msl @@ -1,8 +1,26 @@ +#pragma clang diagnostic ignored "-Wmissing-prototypes" + #include #include using namespace metal; +struct VSInput +{ + float3 pos; + float4 color; + int positionBoneIndex; +}; + +struct VSOutput +{ + float4 pos; + float2 uv; + float4 color; + float fogFactor; + float clipDist; +}; + struct Skinning { float4x4 mvp; @@ -49,82 +67,158 @@ struct main0_in int input_positionBoneIndex [[attribute(4)]]; }; -vertex main0_out main0(main0_in in [[stage_in]], constant Skinning& _68 [[buffer(0)]], constant Shadow& _80 [[buffer(1)]], const device boneRows& boneRows_1 [[buffer(2)]], const device terrainWords& terrainWords_1 [[buffer(3)]]) +static inline __attribute__((always_inline)) +float4 loadBoneRow(thread const uint& row, const device boneRows& boneRows_1) { - main0_out out = {}; - float3 _947; - do + return boneRows_1._data[row]; +} + +static inline __attribute__((always_inline)) +float3 transformPosition(thread const float3& position, thread const int& boneIndex, constant Skinning& _68, const device boneRows& boneRows_1) +{ + if ((boneIndex < 0) || (boneIndex >= int(_68.palette.y))) + { + return position; + } + uint row = _68.palette.x + (uint(boneIndex) * 3u); + uint param = row; + float4 row0 = loadBoneRow(param, boneRows_1); + uint param_1 = row + 1u; + float4 row1 = loadBoneRow(param_1, boneRows_1); + uint param_2 = row + 2u; + float4 row2 = loadBoneRow(param_2, boneRows_1); + float3 transformed; + if (_68.boneScaleAndRestPoseScale.x == 1.0) + { + float restScale = (_68.boneScaleAndRestPoseScale.y != 0.0) ? _68.boneScaleAndRestPoseScale.y : 1.0; + float4 restPosition = float4(position * restScale, 1.0); + transformed = float3(dot(row0, restPosition), dot(row1, restPosition), dot(row2, restPosition)); + } + else + { + transformed = float3(dot(row0.xyz, position), dot(row1.xyz, position), dot(row2.xyz, position)); + transformed = (transformed * _68.boneScaleAndRestPoseScale.x) + float3(row0.w, row1.w, row2.w); + } + if (_68.palette.z != 0u) + { + transformed = _68.bodyOriginAndScale.xyz + (transformed * _68.bodyOriginAndScale.w); + } + return transformed; +} + +static inline __attribute__((always_inline)) +float3 skinnedPosition(thread const VSInput& _input, constant Skinning& _68, const device boneRows& boneRows_1) +{ + float3 param = _input.pos; + int param_1 = _input.positionBoneIndex; + return transformPosition(param, param_1, _68, boneRows_1); +} + +static inline __attribute__((always_inline)) +float3 shearShadow(thread const float3& position, constant Shadow& _80) +{ + float3 relative = position - _80.shadowOrigin.xyz; + float2 axis = float2(cos(_80.shadowProjection.w), sin(_80.shadowProjection.w)); + float along = dot(relative.xy, axis); + float _106 = relative.z; + float _114 = relative.z; + float3 _121 = relative; + float2 _123 = _121.xy + (axis * ((_106 * (along + _80.shadowProjection.x)) / (_114 - _80.shadowProjection.y))); + relative.x = _123.x; + relative.y = _123.y; + return relative + _80.shadowOrigin.xyz; +} + +static inline __attribute__((always_inline)) +uint loadTerrainWord(thread const uint& word, const device terrainWords& terrainWords_1) +{ + return terrainWords_1._data[word]; +} + +static inline __attribute__((always_inline)) +float terrainCornerHeight(thread const int& x, thread const int& y, const device terrainWords& terrainWords_1) +{ + uint param = (uint(y & 255) * 256u) + uint(x & 255); + return as_type(loadTerrainWord(param, terrainWords_1)); +} + +static inline __attribute__((always_inline)) +float terrainHeight(thread float& x, thread float& y, constant Shadow& _80, const device terrainWords& terrainWords_1) +{ + if (((_80.shadowProjection.z == 0.0) || (x < 0.0)) || (y < 0.0)) { - if ((in.input_positionBoneIndex < 0) || (in.input_positionBoneIndex >= int(_68.palette.y))) - { - _947 = in.input_pos; - break; - } - uint _582 = _68.palette.x + (uint(in.input_positionBoneIndex) * 3u); - float4 _554 = boneRows_1._data[_582]; - uint _586 = _582 + 1u; - float4 _556 = boneRows_1._data[_586]; - uint _589 = _582 + 2u; - float4 _558 = boneRows_1._data[_589]; - float3 _945; - if (_68.boneScaleAndRestPoseScale.x == 1.0) - { - float4 _607 = float4(in.input_pos * ((_68.boneScaleAndRestPoseScale.y != 0.0) ? _68.boneScaleAndRestPoseScale.y : 1.0), 1.0); - _945 = float3(dot(boneRows_1._data[_582], _607), dot(boneRows_1._data[_586], _607), dot(boneRows_1._data[_589], _607)); - } - else - { - _945 = (float3(dot(boneRows_1._data[_582].xyz, in.input_pos), dot(boneRows_1._data[_586].xyz, in.input_pos), dot(boneRows_1._data[_589].xyz, in.input_pos)) * _68.boneScaleAndRestPoseScale.x) + float3(_554.w, _556.w, _558.w); - } - float3 _946; - if (_68.palette.z != 0u) - { - _946 = _68.bodyOriginAndScale.xyz + (_945 * _68.bodyOriginAndScale.w); - } - else - { - _946 = _945; - } - _947 = _946; - break; - } while(false); - float3 _676 = _947 - _80.shadowOrigin.xyz; - _676.x += ((_676.z * (_676.x + _80.shadowProjection.x)) / (_676.z - _80.shadowProjection.y)); - float3 _492 = _676 + _80.shadowOrigin.xyz; - float _948; - do + return 0.0; + } + x /= 100.0; + y /= 100.0; + int xi = int(x); + int yi = int(y); + uint index = uint((yi * 256) + xi); + uint param = 65536u + (index >> uint(5)); + if ((index >= 65536u) || (((loadTerrainWord(param, terrainWords_1) >> (index & 31u)) & 1u) != 0u)) { - if (((_80.shadowProjection.z == 0.0) || (_492.x < 0.0)) || (_492.y < 0.0)) - { - _948 = 0.0; - break; - } - float _744 = _492.x * 0.00999999977648258209228515625; - float _746 = _492.y * 0.00999999977648258209228515625; - int _748 = int(_744); - int _750 = int(_746); - uint _755 = uint((_750 * 256) + _748); - if ((_755 >= 65536u) || (((terrainWords_1._data[65536u + (_755 >> uint(5))] >> (_755 & 31u)) & 1u) != 0u)) - { - _948 = _80.shadowOrigin.w; - break; - } - float _779 = _746 - float(_750); - float _836 = as_type(terrainWords_1._data[(uint(_750 & 255) * 256u) + uint(_748 & 255)]); - float _872 = as_type(terrainWords_1._data[(uint(_750 & 255) * 256u) + uint((_748 + 1) & 255)]); - float _802 = _836 + ((as_type(terrainWords_1._data[(uint((_750 + 1) & 255) * 256u) + uint(_748 & 255)]) - _836) * _779); - _948 = _802 + (((_872 + ((as_type(terrainWords_1._data[(uint((_750 + 1) & 255) * 256u) + uint((_748 + 1) & 255)]) - _872) * _779)) - _802) * (_744 - float(_748))); - break; - } while(false); - _492.z = _948 + 5.0; - float4 _905 = _68.mvp * float4(_492, 1.0); - float4 _911 = _905; - float _527 = _68.fogParameters.y - _68.fogParameters.x; - out.gl_Position = _905; - out._entryPointOutput_uv = float2(0.0); - out._entryPointOutput_color = in.input_color; - out._entryPointOutput_fogFactor = (_527 > 0.001000000047497451305389404296875) ? fast::clamp((_68.fogParameters.y - abs(_911.w)) / _527, 0.0, 1.0) : 1.0; - out.gl_ClipDistance[0] = _911.w - 1.0; + return _80.shadowOrigin.w; + } + float xd = x - float(xi); + float yd = y - float(yi); + int param_1 = xi; + int param_2 = yi; + float h1 = terrainCornerHeight(param_1, param_2, terrainWords_1); + int param_3 = xi; + int param_4 = yi + 1; + float h2 = terrainCornerHeight(param_3, param_4, terrainWords_1); + int param_5 = xi + 1; + int param_6 = yi; + float h3 = terrainCornerHeight(param_5, param_6, terrainWords_1); + int param_7 = xi + 1; + int param_8 = yi + 1; + float h4 = terrainCornerHeight(param_7, param_8, terrainWords_1); + float left = h1 + ((h2 - h1) * yd); + float right = h3 + ((h4 - h3) * yd); + return left + ((right - left) * xd); +} + +static inline __attribute__((always_inline)) +float4 clipPosition(thread const float3& position, constant Skinning& _68) +{ + return _68.mvp * float4(position, 1.0); +} + +static inline __attribute__((always_inline)) +VSOutput _main(thread const VSInput& _input, constant Skinning& _68, constant Shadow& _80, const device boneRows& boneRows_1, const device terrainWords& terrainWords_1) +{ + VSInput param = _input; + float3 param_1 = skinnedPosition(param, _68, boneRows_1); + float3 position = shearShadow(param_1, _80); + float param_2 = position.x; + float param_3 = position.y; + float _415 = terrainHeight(param_2, param_3, _80, terrainWords_1); + position.z = _415 + 5.0; + float3 param_4 = position; + VSOutput _output; + _output.pos = clipPosition(param_4, _68); + _output.uv = float2(0.0); + _output.color = _input.color; + _output.clipDist = _output.pos.w - 1.0; + float range = _68.fogParameters.y - _68.fogParameters.x; + _output.fogFactor = (range > 0.001000000047497451305389404296875) ? fast::clamp((_68.fogParameters.y - abs(_output.pos.w)) / range, 0.0, 1.0) : 1.0; + return _output; +} + +vertex main0_out main0(main0_in in [[stage_in]], constant Skinning& _68 [[buffer(0)]], constant Shadow& _80 [[buffer(1)]], const device boneRows& boneRows_1 [[buffer(2)]], const device terrainWords& terrainWords_1 [[buffer(3)]]) +{ + main0_out out = {}; + VSInput _input; + _input.pos = in.input_pos; + _input.color = in.input_color; + _input.positionBoneIndex = in.input_positionBoneIndex; + VSInput param = _input; + VSOutput flattenTemp = _main(param, _68, _80, boneRows_1, terrainWords_1); + out.gl_Position = flattenTemp.pos; + out._entryPointOutput_uv = flattenTemp.uv; + out._entryPointOutput_color = flattenTemp.color; + out._entryPointOutput_fogFactor = flattenTemp.fogFactor; + out.gl_ClipDistance[0] = flattenTemp.clipDist; out.gl_ClipDistance_0 = out.gl_ClipDistance[0]; return out; } diff --git a/src/shaders/compiled/skinned_shadow.vert.spv b/src/shaders/compiled/skinned_shadow.vert.spv index bdb8748f26..2438d9667f 100644 Binary files a/src/shaders/compiled/skinned_shadow.vert.spv and b/src/shaders/compiled/skinned_shadow.vert.spv differ diff --git a/src/shaders/compiled/skinned_weighted_shadow.vert.dxil b/src/shaders/compiled/skinned_weighted_shadow.vert.dxil index f4e422c42e..43ceefa722 100644 Binary files a/src/shaders/compiled/skinned_weighted_shadow.vert.dxil and b/src/shaders/compiled/skinned_weighted_shadow.vert.dxil differ diff --git a/src/shaders/compiled/skinned_weighted_shadow.vert.msl b/src/shaders/compiled/skinned_weighted_shadow.vert.msl index 48d28f1077..7ccf3d7a17 100644 --- a/src/shaders/compiled/skinned_weighted_shadow.vert.msl +++ b/src/shaders/compiled/skinned_weighted_shadow.vert.msl @@ -1,8 +1,28 @@ +#pragma clang diagnostic ignored "-Wmissing-prototypes" + #include #include using namespace metal; +struct VSInput +{ + float3 pos; + float4 color; + int positionBoneIndex; + uint4 joints; + float4 weights; +}; + +struct VSOutput +{ + float4 pos; + float2 uv; + float4 color; + float fogFactor; + float clipDist; +}; + struct Skinning { float4x4 mvp; @@ -51,143 +71,190 @@ struct main0_in float4 input_weights [[attribute(7)]]; }; -vertex main0_out main0(main0_in in [[stage_in]], constant Skinning& _76 [[buffer(0)]], constant Shadow& _88 [[buffer(1)]], const device boneRows& boneRows_1 [[buffer(2)]], const device terrainWords& terrainWords_1 [[buffer(3)]]) +static inline __attribute__((always_inline)) +float4 loadBoneRow(thread const uint& row, const device boneRows& boneRows_1) { - main0_out out = {}; - float3 _1189; - do + return boneRows_1._data[row]; +} + +static inline __attribute__((always_inline)) +float3 skinWeightedPosition(thread const float3& position, thread const uint4& joints, thread const float4& weights, constant Skinning& _76, const device boneRows& boneRows_1) +{ + float4 bindPosition = float4(position, 1.0); + float3 transformed = float3(0.0); + for (uint k = 0u; k < 4u; k++) { - if (in.input_weights.x > 0.0) + if ((weights[k] > 0.0) && (joints[k] < _76.palette.y)) { - float4 _699 = float4(in.input_pos, 1.0); - float3 _1192; - if ((in.input_weights.x > 0.0) && (in.input_joints.x < _76.palette.y)) - { - uint _723 = _76.palette.x + (in.input_joints.x * 3u); - _1192 = float3(dot(boneRows_1._data[_723], _699), dot(boneRows_1._data[_723 + 1u], _699), dot(boneRows_1._data[_723 + 2u], _699)) * in.input_weights.x; - } - else - { - _1192 = float3(0.0); - } - float3 _1233; - if ((in.input_weights.y > 0.0) && (in.input_joints.y < _76.palette.y)) - { - uint _1215 = _76.palette.x + (in.input_joints.y * 3u); - _1233 = _1192 + (float3(dot(boneRows_1._data[_1215], _699), dot(boneRows_1._data[_1215 + 1u], _699), dot(boneRows_1._data[_1215 + 2u], _699)) * in.input_weights.y); - } - else - { - _1233 = _1192; - } - float3 _1275; - if ((in.input_weights.z > 0.0) && (in.input_joints.z < _76.palette.y)) - { - uint _1257 = _76.palette.x + (in.input_joints.z * 3u); - _1275 = _1233 + (float3(dot(boneRows_1._data[_1257], _699), dot(boneRows_1._data[_1257 + 1u], _699), dot(boneRows_1._data[_1257 + 2u], _699)) * in.input_weights.z); - } - else - { - _1275 = _1233; - } - float3 _1317; - if ((in.input_weights.w > 0.0) && (in.input_joints.w < _76.palette.y)) - { - uint _1299 = _76.palette.x + (in.input_joints.w * 3u); - _1317 = _1275 + (float3(dot(boneRows_1._data[_1299], _699), dot(boneRows_1._data[_1299 + 1u], _699), dot(boneRows_1._data[_1299 + 2u], _699)) * in.input_weights.w); - } - else - { - _1317 = _1275; - } - float3 _1188; - if (_76.palette.z != 0u) - { - _1188 = _76.bodyOriginAndScale.xyz + (_1317 * _76.bodyOriginAndScale.w); - } - else - { - _1188 = _1317; - } - _1189 = _1188; - break; + uint row = _76.palette.x + (joints[k] * 3u); + uint param = row; + uint param_1 = row + 1u; + uint param_2 = row + 2u; + transformed += (float3(dot(loadBoneRow(param, boneRows_1), bindPosition), dot(loadBoneRow(param_1, boneRows_1), bindPosition), dot(loadBoneRow(param_2, boneRows_1), bindPosition)) * weights[k]); } - float3 _1185; - do - { - if ((in.input_positionBoneIndex < 0) || (in.input_positionBoneIndex >= int(_76.palette.y))) - { - _1185 = in.input_pos; - break; - } - uint _810 = _76.palette.x + (uint(in.input_positionBoneIndex) * 3u); - float4 _782 = boneRows_1._data[_810]; - uint _814 = _810 + 1u; - float4 _784 = boneRows_1._data[_814]; - uint _817 = _810 + 2u; - float4 _786 = boneRows_1._data[_817]; - float3 _1183; - if (_76.boneScaleAndRestPoseScale.x == 1.0) - { - float4 _835 = float4(in.input_pos * ((_76.boneScaleAndRestPoseScale.y != 0.0) ? _76.boneScaleAndRestPoseScale.y : 1.0), 1.0); - _1183 = float3(dot(boneRows_1._data[_810], _835), dot(boneRows_1._data[_814], _835), dot(boneRows_1._data[_817], _835)); - } - else - { - _1183 = (float3(dot(boneRows_1._data[_810].xyz, in.input_pos), dot(boneRows_1._data[_814].xyz, in.input_pos), dot(boneRows_1._data[_817].xyz, in.input_pos)) * _76.boneScaleAndRestPoseScale.x) + float3(_782.w, _784.w, _786.w); - } - float3 _1184; - if (_76.palette.z != 0u) - { - _1184 = _76.bodyOriginAndScale.xyz + (_1183 * _76.bodyOriginAndScale.w); - } - else - { - _1184 = _1183; - } - _1185 = _1184; - break; - } while(false); - _1189 = _1185; - break; - } while(false); - float3 _904 = _1189 - _88.shadowOrigin.xyz; - _904.x += ((_904.z * (_904.x + _88.shadowProjection.x)) / (_904.z - _88.shadowProjection.y)); - float3 _607 = _904 + _88.shadowOrigin.xyz; - float _1190; - do + } + if (_76.palette.z != 0u) { - if (((_88.shadowProjection.z == 0.0) || (_607.x < 0.0)) || (_607.y < 0.0)) - { - _1190 = 0.0; - break; - } - float _972 = _607.x * 0.00999999977648258209228515625; - float _974 = _607.y * 0.00999999977648258209228515625; - int _976 = int(_972); - int _978 = int(_974); - uint _983 = uint((_978 * 256) + _976); - if ((_983 >= 65536u) || (((terrainWords_1._data[65536u + (_983 >> uint(5))] >> (_983 & 31u)) & 1u) != 0u)) - { - _1190 = _88.shadowOrigin.w; - break; - } - float _1007 = _974 - float(_978); - float _1064 = as_type(terrainWords_1._data[(uint(_978 & 255) * 256u) + uint(_976 & 255)]); - float _1100 = as_type(terrainWords_1._data[(uint(_978 & 255) * 256u) + uint((_976 + 1) & 255)]); - float _1030 = _1064 + ((as_type(terrainWords_1._data[(uint((_978 + 1) & 255) * 256u) + uint(_976 & 255)]) - _1064) * _1007); - _1190 = _1030 + (((_1100 + ((as_type(terrainWords_1._data[(uint((_978 + 1) & 255) * 256u) + uint((_976 + 1) & 255)]) - _1100) * _1007)) - _1030) * (_972 - float(_976))); - break; - } while(false); - _607.z = _1190 + 5.0; - float4 _1133 = _76.mvp * float4(_607, 1.0); - float4 _1144 = _1133; - float _642 = _76.fogParameters.y - _76.fogParameters.x; - out.gl_Position = _1133; - out._entryPointOutput_uv = float2(0.0); - out._entryPointOutput_color = in.input_color; - out._entryPointOutput_fogFactor = (_642 > 0.001000000047497451305389404296875) ? fast::clamp((_76.fogParameters.y - abs(_1144.w)) / _642, 0.0, 1.0) : 1.0; - out.gl_ClipDistance[0] = _1144.w - 1.0; + transformed = _76.bodyOriginAndScale.xyz + (transformed * _76.bodyOriginAndScale.w); + } + return transformed; +} + +static inline __attribute__((always_inline)) +float3 transformPosition(thread const float3& position, thread const int& boneIndex, constant Skinning& _76, const device boneRows& boneRows_1) +{ + if ((boneIndex < 0) || (boneIndex >= int(_76.palette.y))) + { + return position; + } + uint row = _76.palette.x + (uint(boneIndex) * 3u); + uint param = row; + float4 row0 = loadBoneRow(param, boneRows_1); + uint param_1 = row + 1u; + float4 row1 = loadBoneRow(param_1, boneRows_1); + uint param_2 = row + 2u; + float4 row2 = loadBoneRow(param_2, boneRows_1); + float3 transformed; + if (_76.boneScaleAndRestPoseScale.x == 1.0) + { + float restScale = (_76.boneScaleAndRestPoseScale.y != 0.0) ? _76.boneScaleAndRestPoseScale.y : 1.0; + float4 restPosition = float4(position * restScale, 1.0); + transformed = float3(dot(row0, restPosition), dot(row1, restPosition), dot(row2, restPosition)); + } + else + { + transformed = float3(dot(row0.xyz, position), dot(row1.xyz, position), dot(row2.xyz, position)); + transformed = (transformed * _76.boneScaleAndRestPoseScale.x) + float3(row0.w, row1.w, row2.w); + } + if (_76.palette.z != 0u) + { + transformed = _76.bodyOriginAndScale.xyz + (transformed * _76.bodyOriginAndScale.w); + } + return transformed; +} + +static inline __attribute__((always_inline)) +float3 skinnedPosition(thread const VSInput& _input, constant Skinning& _76, const device boneRows& boneRows_1) +{ + if (_input.weights.x > 0.0) + { + float3 param = _input.pos; + uint4 param_1 = _input.joints; + float4 param_2 = _input.weights; + return skinWeightedPosition(param, param_1, param_2, _76, boneRows_1); + } + float3 param_3 = _input.pos; + int param_4 = _input.positionBoneIndex; + return transformPosition(param_3, param_4, _76, boneRows_1); +} + +static inline __attribute__((always_inline)) +float3 shearShadow(thread const float3& position, constant Shadow& _88) +{ + float3 relative = position - _88.shadowOrigin.xyz; + float2 axis = float2(cos(_88.shadowProjection.w), sin(_88.shadowProjection.w)); + float along = dot(relative.xy, axis); + float _114 = relative.z; + float _122 = relative.z; + float3 _129 = relative; + float2 _131 = _129.xy + (axis * ((_114 * (along + _88.shadowProjection.x)) / (_122 - _88.shadowProjection.y))); + relative.x = _131.x; + relative.y = _131.y; + return relative + _88.shadowOrigin.xyz; +} + +static inline __attribute__((always_inline)) +uint loadTerrainWord(thread const uint& word, const device terrainWords& terrainWords_1) +{ + return terrainWords_1._data[word]; +} + +static inline __attribute__((always_inline)) +float terrainCornerHeight(thread const int& x, thread const int& y, const device terrainWords& terrainWords_1) +{ + uint param = (uint(y & 255) * 256u) + uint(x & 255); + return as_type(loadTerrainWord(param, terrainWords_1)); +} + +static inline __attribute__((always_inline)) +float terrainHeight(thread float& x, thread float& y, constant Shadow& _88, const device terrainWords& terrainWords_1) +{ + if (((_88.shadowProjection.z == 0.0) || (x < 0.0)) || (y < 0.0)) + { + return 0.0; + } + x /= 100.0; + y /= 100.0; + int xi = int(x); + int yi = int(y); + uint index = uint((yi * 256) + xi); + uint param = 65536u + (index >> uint(5)); + if ((index >= 65536u) || (((loadTerrainWord(param, terrainWords_1) >> (index & 31u)) & 1u) != 0u)) + { + return _88.shadowOrigin.w; + } + float xd = x - float(xi); + float yd = y - float(yi); + int param_1 = xi; + int param_2 = yi; + float h1 = terrainCornerHeight(param_1, param_2, terrainWords_1); + int param_3 = xi; + int param_4 = yi + 1; + float h2 = terrainCornerHeight(param_3, param_4, terrainWords_1); + int param_5 = xi + 1; + int param_6 = yi; + float h3 = terrainCornerHeight(param_5, param_6, terrainWords_1); + int param_7 = xi + 1; + int param_8 = yi + 1; + float h4 = terrainCornerHeight(param_7, param_8, terrainWords_1); + float left = h1 + ((h2 - h1) * yd); + float right = h3 + ((h4 - h3) * yd); + return left + ((right - left) * xd); +} + +static inline __attribute__((always_inline)) +float4 clipPosition(thread const float3& position, constant Skinning& _76) +{ + return _76.mvp * float4(position, 1.0); +} + +static inline __attribute__((always_inline)) +VSOutput _main(thread const VSInput& _input, constant Skinning& _76, constant Shadow& _88, const device boneRows& boneRows_1, const device terrainWords& terrainWords_1) +{ + VSInput param = _input; + float3 param_1 = skinnedPosition(param, _76, boneRows_1); + float3 position = shearShadow(param_1, _88); + float param_2 = position.x; + float param_3 = position.y; + float _519 = terrainHeight(param_2, param_3, _88, terrainWords_1); + position.z = _519 + 5.0; + float3 param_4 = position; + VSOutput _output; + _output.pos = clipPosition(param_4, _76); + _output.uv = float2(0.0); + _output.color = _input.color; + _output.clipDist = _output.pos.w - 1.0; + float range = _76.fogParameters.y - _76.fogParameters.x; + _output.fogFactor = (range > 0.001000000047497451305389404296875) ? fast::clamp((_76.fogParameters.y - abs(_output.pos.w)) / range, 0.0, 1.0) : 1.0; + return _output; +} + +vertex main0_out main0(main0_in in [[stage_in]], constant Skinning& _76 [[buffer(0)]], constant Shadow& _88 [[buffer(1)]], const device boneRows& boneRows_1 [[buffer(2)]], const device terrainWords& terrainWords_1 [[buffer(3)]]) +{ + main0_out out = {}; + VSInput _input; + _input.pos = in.input_pos; + _input.color = in.input_color; + _input.positionBoneIndex = in.input_positionBoneIndex; + _input.joints = in.input_joints; + _input.weights = in.input_weights; + VSInput param = _input; + VSOutput flattenTemp = _main(param, _76, _88, boneRows_1, terrainWords_1); + out.gl_Position = flattenTemp.pos; + out._entryPointOutput_uv = flattenTemp.uv; + out._entryPointOutput_color = flattenTemp.color; + out._entryPointOutput_fogFactor = flattenTemp.fogFactor; + out.gl_ClipDistance[0] = flattenTemp.clipDist; out.gl_ClipDistance_0 = out.gl_ClipDistance[0]; return out; } diff --git a/src/shaders/compiled/skinned_weighted_shadow.vert.spv b/src/shaders/compiled/skinned_weighted_shadow.vert.spv index 4e31b7b1b5..85560cf8dd 100644 Binary files a/src/shaders/compiled/skinned_weighted_shadow.vert.spv and b/src/shaders/compiled/skinned_weighted_shadow.vert.spv differ diff --git a/src/shaders/compiled/sun_depth.frag.dxil b/src/shaders/compiled/sun_depth.frag.dxil new file mode 100644 index 0000000000..f2fcdec72c Binary files /dev/null and b/src/shaders/compiled/sun_depth.frag.dxil differ diff --git a/src/shaders/compiled/sun_depth.frag.msl b/src/shaders/compiled/sun_depth.frag.msl new file mode 100644 index 0000000000..71e55252a6 --- /dev/null +++ b/src/shaders/compiled/sun_depth.frag.msl @@ -0,0 +1,67 @@ +#pragma clang diagnostic ignored "-Wmissing-prototypes" + +#include +#include + +using namespace metal; + +struct FSInput +{ + float4 pos; + float2 uv; + float4 color; +}; + +struct FogUniforms +{ + uint coverageMode; + uint alphaDiscardEnabled; + float alphaThreshold; + uint alphaToCoverage; + float fogStart; + float fogEnd; + float4 fogColor; +}; + +struct main0_in +{ + float2 input_uv [[user(locn0)]]; + float4 input_color [[user(locn1)]]; +}; + +static inline __attribute__((always_inline)) +float Dither(thread const float2& position) +{ + return fract(52.98291778564453125 * fract(dot(position, float2(0.067110560834407806396484375, 0.005837149918079376220703125)))); +} + +static inline __attribute__((always_inline)) +void _main(thread const FSInput& _input, texture2d tex, sampler s, constant FogUniforms& _55) +{ + float4 texel = tex.sample(s, _input.uv) * _input.color; + if (_55.coverageMode == 0u) + { + if (((_55.alphaDiscardEnabled != 0u) || (_55.alphaToCoverage != 0u)) && (texel.w <= _55.alphaThreshold)) + { + discard_fragment(); + } + return; + } + float coverage = (_55.coverageMode == 1u) ? texel.w : (fast::max(texel.x, fast::max(texel.y, texel.z)) * texel.w); + float2 param = _input.pos.xy; + if (coverage <= Dither(param)) + { + discard_fragment(); + } +} + +fragment void main0(main0_in in [[stage_in]], constant FogUniforms& _55 [[buffer(0)]], texture2d tex [[texture(0)]], sampler s [[sampler(0)]], float4 gl_FragCoord [[position]]) +{ + FSInput _input; + _input.pos = gl_FragCoord; + _input.uv = in.input_uv; + _input.color = in.input_color; + FSInput param = _input; + _main(param, tex, s, _55); +} + diff --git a/src/shaders/compiled/sun_depth.frag.spv b/src/shaders/compiled/sun_depth.frag.spv new file mode 100644 index 0000000000..66411cc65f Binary files /dev/null and b/src/shaders/compiled/sun_depth.frag.spv differ diff --git a/src/shaders/compiled/world_lit.frag.dxil b/src/shaders/compiled/world_lit.frag.dxil new file mode 100644 index 0000000000..8e681ea733 Binary files /dev/null and b/src/shaders/compiled/world_lit.frag.dxil differ diff --git a/src/shaders/compiled/world_lit.frag.msl b/src/shaders/compiled/world_lit.frag.msl new file mode 100644 index 0000000000..ed8a92a7f7 --- /dev/null +++ b/src/shaders/compiled/world_lit.frag.msl @@ -0,0 +1,288 @@ +#pragma clang diagnostic ignored "-Wmissing-prototypes" +#pragma clang diagnostic ignored "-Wmissing-braces" + +#include +#include + +using namespace metal; + +template +struct spvUnsafeArray +{ + T elements[Num ? Num : 1]; + + thread T& operator [] (size_t pos) thread + { + return elements[pos]; + } + constexpr const thread T& operator [] (size_t pos) const thread + { + return elements[pos]; + } + + device T& operator [] (size_t pos) device + { + return elements[pos]; + } + constexpr const device T& operator [] (size_t pos) const device + { + return elements[pos]; + } + + constexpr const constant T& operator [] (size_t pos) const constant + { + return elements[pos]; + } + + threadgroup T& operator [] (size_t pos) threadgroup + { + return elements[pos]; + } + constexpr const threadgroup T& operator [] (size_t pos) const threadgroup + { + return elements[pos]; + } +}; + +struct FSInput +{ + float4 pos; + float2 uv; + float4 color; + float fogFactor; + float eyeDepth; + float3 worldPosition; +}; + +struct SceneLighting +{ + float4 sceneLightDirection; + float4 sceneLightColor; + float4 diffuseCurve; + float4 rimParameters; + float4 specularParameters; + float4 sceneFogColor; + float4 sceneFogParameters; + float4 cameraPosition; + float4x4 sunViewProjection; + float4 sunShadowParameters; + float4 lightingParameters; + float4 cloudParameters; + float4 cloudOffset; + float4 skyFill; + float4 sunTowards; + float4 sunColor; +}; + +struct DynamicLights +{ + uint dynamicLightCount; + float dynamicLightWrap; + uint dynamicWorldLightCount; + float groundShadowOpacity; + float4 dynamicLightPositionAndRadius[32]; + float4 dynamicLightColor[32]; +}; + +struct FogUniforms +{ + uint fogEnabled; + uint alphaDiscardEnabled; + float alphaThreshold; + uint alphaToCoverage; + float fogStart; + float fogEnd; + float4 fogColor; +}; + +constant spvUnsafeArray _250 = spvUnsafeArray({ float2(-0.3260000050067901611328125, -0.4059999883174896240234375), float2(-0.839999973773956298828125, -0.07400000095367431640625), float2(-0.69599997997283935546875, 0.4569999873638153076171875), float2(-0.20299999415874481201171875, 0.620999991893768310546875), float2(0.96200001239776611328125, -0.194999992847442626953125), float2(0.472999989986419677734375, -0.4799999892711639404296875), float2(0.518999993801116943359375, 0.767000019550323486328125), float2(0.185000002384185791015625, -0.89300000667572021484375), float2(0.507000029087066650390625, 0.064000003039836883544921875), float2(0.89600002765655517578125, 0.412000000476837158203125), float2(-0.3219999969005584716796875, -0.933000028133392333984375), float2(-0.791999995708465576171875, -0.597999989986419677734375) }); + +struct main0_out +{ + float4 _entryPointOutput [[color(0)]]; +}; + +struct main0_in +{ + float2 input_uv [[user(locn0)]]; + float4 input_color [[user(locn1)]]; + float input_fogFactor [[user(locn2)]]; + float input_eyeDepth [[user(locn3)]]; + float3 input_worldPosition [[user(locn4)]]; +}; + +static inline __attribute__((always_inline)) +float SunVisibility(thread const float3& worldPosition, thread const float3& worldNormal, constant SceneLighting& _56, depth2d sunShadowMap, sampler sunShadowSampler) +{ + if (_56.sunShadowParameters.x <= 0.0) + { + return 1.0; + } + float slope = 1.0 - fast::clamp(dot(worldNormal, fast::normalize(_56.sunTowards.xyz)), 0.0, 1.0); + float3 lifted = worldPosition + (worldNormal * ((1.5 + (2.0 * slope)) * _56.sunShadowParameters.w)); + float4 clip = _56.sunViewProjection * float4(lifted, 1.0); + float3 ndc = clip.xyz / float3(clip.w); + float2 uv = float2((ndc.x * 0.5) + 0.5, 0.5 - (ndc.y * 0.5)); + if ((any(uv < float2(0.0)) || any(uv > float2(1.0))) || (ndc.z >= 1.0)) + { + return 1.0; + } + float turn = 6.283185482025146484375 * fract(52.98291778564453125 * fract(dot(worldPosition.xy, float2(0.067110560834407806396484375, 0.005837149918079376220703125)))); + float2x2 rotation = float2x2(float2(cos(turn), -sin(turn)), float2(sin(turn), cos(turn))); + float radius = (_56.sunShadowParameters.z * fast::max(_56.sunShadowParameters.y, 0.25)) * 1.5; + float visible = 0.0; + float total = 0.0; + for (int i = 0; i < 12; i++) + { + float2 offset = _250[i] * rotation; + float weight = exp((-2.0) * dot(offset, offset)); + float3 _285 = float3(uv + (offset * radius), ndc.z); + visible += (weight * sunShadowMap.sample_compare(sunShadowSampler, _285.xy, _285.z, level(0.0))); + total += weight; + } + return visible / total; +} + +static inline __attribute__((always_inline)) +float CloudHash(thread const float2& p) +{ + return fract(sin(dot(p, float2(127.09999847412109375, 311.70001220703125))) * 43758.546875); +} + +static inline __attribute__((always_inline)) +float CloudNoise(thread const float2& p) +{ + float2 cell = floor(p); + float2 f = fract(p); + float2 u = (f * f) * (float2(3.0) - (f * 2.0)); + float2 param = cell; + float a = CloudHash(param); + float2 param_1 = cell + float2(1.0, 0.0); + float b = CloudHash(param_1); + float2 param_2 = cell + float2(0.0, 1.0); + float c = CloudHash(param_2); + float2 param_3 = cell + float2(1.0); + float d = CloudHash(param_3); + return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); +} + +static inline __attribute__((always_inline)) +float CloudLight(thread const float2& xy, thread const float4& parameters, thread const float2& offset) +{ + if (parameters.x <= 0.0) + { + return 1.0; + } + float2 p = (xy + offset) * parameters.y; + float2 param = p; + float2 param_1 = (p * 2.0299999713897705078125) + float2(17.1000003814697265625); + float2 param_2 = (p * 4.070000171661376953125) + float2(31.700000762939453125); + float cover = ((0.550000011920928955078125 * CloudNoise(param)) + (0.300000011920928955078125 * CloudNoise(param_1))) + (0.1500000059604644775390625 * CloudNoise(param_2)); + float threshold = 1.0 - parameters.z; + float cloud = smoothstep(threshold - 0.119999997317790985107421875, threshold + 0.119999997317790985107421875, cover); + return 1.0 - (parameters.x * cloud); +} + +static inline __attribute__((always_inline)) +float PointLightFalloff(thread const float3& toLight, thread const float& radius) +{ + float horizontal = length(toLight.xy); + return (horizontal < radius) ? ((radius - horizontal) / radius) : 0.0; +} + +static inline __attribute__((always_inline)) +float3 WorldDynamicLighting(thread const float3& worldPosition, constant DynamicLights& _449) +{ + float3 light = float3(0.0); + uint count = min(min(_449.dynamicWorldLightCount, _449.dynamicLightCount), 32u); + for (uint i = 0u; i < count; i++) + { + float4 positionAndRadius = _449.dynamicLightPositionAndRadius[i]; + float3 param = positionAndRadius.xyz - worldPosition; + float param_1 = positionAndRadius.w; + light += (_449.dynamicLightColor[i].xyz * PointLightFalloff(param, param_1)); + } + return light; +} + +static inline __attribute__((always_inline)) +float EnhancedFogAmount(thread const float& eyeDepth, constant SceneLighting& _56) +{ + float scaledDistance = fast::max(eyeDepth - _56.sceneFogParameters.x, 0.0) * _56.sceneFogParameters.z; + return fast::clamp(1.0 - exp((-scaledDistance) * scaledDistance), 0.0, 1.0); +} + +static inline __attribute__((always_inline)) +float4 _main(thread const FSInput& _input, constant SceneLighting& _56, depth2d sunShadowMap, sampler sunShadowSampler, constant DynamicLights& _449, texture2d tex, sampler s, texture2d groundShadowMask, sampler groundShadowSampler, texture2d terrainSunLight, sampler terrainSunSampler, constant FogUniforms& _678) +{ + float4 texel = tex.sample(s, _input.uv); + uint2 sizeQueryTemp = uint2(groundShadowMask.get_width(), groundShadowMask.get_height()); + uint maskWidth = sizeQueryTemp.x; + uint maskHeight = sizeQueryTemp.y; + float2 visibility = groundShadowMask.sample(groundShadowSampler, (_input.pos.xy / float2(float(maskWidth), float(maskHeight)))).xy; + float2 shadow = float2(1.0) - ((float2(1.0) - visibility) * _449.groundShadowOpacity); + bool sunShadows = _56.sunShadowParameters.x > 0.0; + float3 param = _input.worldPosition; + float3 param_1 = float3(0.0, 0.0, 1.0); + float sunVisible = sunShadows ? SunVisibility(param, param_1, _56, sunShadowMap, sunShadowSampler) : 1.0; + shadow.x *= (1.0 - (_56.sunShadowParameters.x * (1.0 - sunVisible))); + float2 param_2 = _input.worldPosition.xy; + float4 param_3 = _56.cloudParameters; + float2 param_4 = _56.cloudOffset.xy; + float cloud = sunShadows ? CloudLight(param_2, param_3, param_4) : 1.0; + float3 ground = _input.color.xyz * shadow.x; + if ((cloud < 1.0) && (_56.lightingParameters.y > 0.0)) + { + float2 cellUv = ((_input.worldPosition.xy / float2(100.0)) + float2(0.5)) / float2(256.0); + float3 direct = terrainSunLight.sample(terrainSunSampler, cellUv).xyz; + ground = fast::max(ground - ((direct * sunVisible) * (1.0 - cloud)), float3(0.0)); + } + float3 skyShade = mix(float3(1.0), _56.skyFill.xyz, float3(_56.skyFill.w * (1.0 - (sunVisible * cloud)))); + float3 param_5 = _input.worldPosition; + float3 pointLight = WorldDynamicLighting(param_5, _449) * shadow.y; + float3 light = fast::clamp((ground * skyShade) + pointLight, float3(0.0), float3(1.0)); + float4 color = float4(texel.xyz * light, texel.w * _input.color.w); + if (_678.alphaToCoverage != 0u) + { + float edge = fast::clamp(((color.w - _678.alphaThreshold) / fast::max(fwidth(color.w), 9.9999997473787516355514526367188e-05)) + 0.5, 0.0, 1.0); + color.w *= edge; + if (color.w <= 0.0) + { + discard_fragment(); + } + } + else + { + if ((_678.alphaDiscardEnabled != 0u) && (color.w <= _678.alphaThreshold)) + { + discard_fragment(); + } + } + if ((_678.fogEnabled != 0u) && (_56.sceneFogColor.w > 0.0)) + { + float4 _731 = color; + float param_6 = _input.eyeDepth; + float3 _741 = mix(_731.xyz, _56.sceneFogColor.xyz, float3(EnhancedFogAmount(param_6, _56))); + color.x = _741.x; + color.y = _741.y; + color.z = _741.z; + } + return color; +} + +fragment main0_out main0(main0_in in [[stage_in]], constant FogUniforms& _678 [[buffer(0)]], constant SceneLighting& _56 [[buffer(1)]], constant DynamicLights& _449 [[buffer(2)]], texture2d tex [[texture(0)]], texture2d groundShadowMask [[texture(1)]], depth2d sunShadowMap [[texture(2)]], texture2d terrainSunLight [[texture(3)]], sampler s [[sampler(0)]], sampler groundShadowSampler [[sampler(1)]], sampler sunShadowSampler [[sampler(2)]], sampler terrainSunSampler [[sampler(3)]], float4 gl_FragCoord [[position]]) +{ + main0_out out = {}; + FSInput _input; + _input.pos = gl_FragCoord; + _input.uv = in.input_uv; + _input.color = in.input_color; + _input.fogFactor = in.input_fogFactor; + _input.eyeDepth = in.input_eyeDepth; + _input.worldPosition = in.input_worldPosition; + FSInput param = _input; + float4 _778 = _main(param, _56, sunShadowMap, sunShadowSampler, _449, tex, s, groundShadowMask, groundShadowSampler, terrainSunLight, terrainSunSampler, _678); + out._entryPointOutput = _778; + return out; +} + diff --git a/src/shaders/compiled/world_lit.frag.spv b/src/shaders/compiled/world_lit.frag.spv new file mode 100644 index 0000000000..a322813d37 Binary files /dev/null and b/src/shaders/compiled/world_lit.frag.spv differ diff --git a/src/shaders/compiled/world_lit.vert.dxil b/src/shaders/compiled/world_lit.vert.dxil new file mode 100644 index 0000000000..a266b6faed Binary files /dev/null and b/src/shaders/compiled/world_lit.vert.dxil differ diff --git a/src/shaders/compiled/world_lit.vert.msl b/src/shaders/compiled/world_lit.vert.msl new file mode 100644 index 0000000000..ba77e07fea --- /dev/null +++ b/src/shaders/compiled/world_lit.vert.msl @@ -0,0 +1,88 @@ +#pragma clang diagnostic ignored "-Wmissing-prototypes" + +#include +#include + +using namespace metal; + +struct VSInput +{ + float3 pos; + float2 uv; + float4 color; +}; + +struct VSOutput +{ + float4 pos; + float2 uv; + float4 color; + float fogFactor; + float eyeDepth; + float3 worldPosition; + float clipDist; +}; + +struct Transform +{ + float4x4 mvp; + float fogStart; + float fogEnd; + float2 fogPad; +}; + +struct main0_out +{ + float2 _entryPointOutput_uv [[user(locn0)]]; + float4 _entryPointOutput_color [[user(locn1)]]; + float _entryPointOutput_fogFactor [[user(locn2)]]; + float _entryPointOutput_eyeDepth [[user(locn3)]]; + float3 _entryPointOutput_worldPosition [[user(locn4)]]; + float4 gl_Position [[position]]; + float gl_ClipDistance [[clip_distance]] [1]; + float gl_ClipDistance_0 [[user(clip0)]]; +}; + +struct main0_in +{ + float3 input_pos [[attribute(0)]]; + float2 input_uv [[attribute(1)]]; + float4 input_color [[attribute(2)]]; +}; + +static inline __attribute__((always_inline)) +VSOutput _main(thread const VSInput& _input, constant Transform& _32) +{ + VSOutput o; + o.pos = _32.mvp * float4(_input.pos, 1.0); + o.uv = _input.uv; + o.color = _input.color; + o.clipDist = o.pos.w - 1.0; + float dist = abs(o.pos.w); + float range = _32.fogEnd - _32.fogStart; + o.fogFactor = (range > 0.001000000047497451305389404296875) ? fast::clamp((_32.fogEnd - dist) / range, 0.0, 1.0) : 1.0; + o.eyeDepth = dist; + o.worldPosition = _input.pos; + return o; +} + +vertex main0_out main0(main0_in in [[stage_in]], constant Transform& _32 [[buffer(0)]]) +{ + main0_out out = {}; + VSInput _input; + _input.pos = in.input_pos; + _input.uv = in.input_uv; + _input.color = in.input_color; + VSInput param = _input; + VSOutput flattenTemp = _main(param, _32); + out.gl_Position = flattenTemp.pos; + out._entryPointOutput_uv = flattenTemp.uv; + out._entryPointOutput_color = flattenTemp.color; + out._entryPointOutput_fogFactor = flattenTemp.fogFactor; + out._entryPointOutput_eyeDepth = flattenTemp.eyeDepth; + out._entryPointOutput_worldPosition = flattenTemp.worldPosition; + out.gl_ClipDistance[0] = flattenTemp.clipDist; + out.gl_ClipDistance_0 = out.gl_ClipDistance[0]; + return out; +} + diff --git a/src/shaders/compiled/world_lit.vert.spv b/src/shaders/compiled/world_lit.vert.spv new file mode 100644 index 0000000000..53a5993690 Binary files /dev/null and b/src/shaders/compiled/world_lit.vert.spv differ diff --git a/src/shaders/dynamic_lighting.hlsli b/src/shaders/dynamic_lighting.hlsli new file mode 100644 index 0000000000..8626deb46f --- /dev/null +++ b/src/shaders/dynamic_lighting.hlsli @@ -0,0 +1,64 @@ +// dynamic_lighting.hlsli — the frame's point lights and the sun shadow map lookup, for the shaders +// that light per pixel (world_lit, skinned_lit). Include after scene_lighting.hlsli and after declaring +// sunShadowMap and sunShadowSampler. DynamicLights mirrors mu::DynamicLightsUniform (std140). +#ifndef MU_DYNAMIC_LIGHTING_HLSLI +#define MU_DYNAMIC_LIGHTING_HLSLI +static const uint MaxDynamicLights = 32; // mu::kMaxDynamicLights +cbuffer DynamicLights : register(b2, space3) +{ + uint dynamicLightCount; // lights used + float dynamicLightWrap; // models only + uint dynamicWorldLightCount; // the first lights: the ones the ground's vertex colour leaves out + float groundShadowOpacity; // how much a shadow darkens the vertex colour + float4 dynamicLightPositionAndRadius[MaxDynamicLights]; + float4 dynamicLightColor[MaxDynamicLights]; +}; + +// Twelve points spread evenly over the unit disc (a Poisson disc). +static const float2 SunShadowDisc[12] = { + float2(-0.326, -0.406), float2(-0.840, -0.074), float2(-0.696, 0.457), float2(-0.203, 0.621), + float2(0.962, -0.195), float2(0.473, -0.480), float2(0.519, 0.767), float2(0.185, -0.893), + float2(0.507, 0.064), float2(0.896, 0.412), float2(-0.322, -0.933), float2(-0.792, -0.598), +}; + +// How much sun reaches `worldPosition` (Enhanced sun shadows): 1 lit, 0 in the shadow of what stands +// between it and the sun, softened over sunShadowParameters.y texels. 1 without a shadow map or +// outside it. `worldNormal` pushes the lookup off the surface so that it does not shadow itself, +// further on faces turned away from the sun, where a texel covers more of the surface. +float SunVisibility(float3 worldPosition, float3 worldNormal) +{ + if (sunShadowParameters.x <= 0.0) + return 1.0; + const float slope = 1.0 - saturate(dot(worldNormal, normalize(sunTowards.xyz))); + const float3 lifted = worldPosition + worldNormal * ((1.5 + 2.0 * slope) * sunShadowParameters.w); + const float4 clip = mul(sunViewProjection, float4(lifted, 1.0)); + const float3 ndc = clip.xyz / clip.w; + const float2 uv = float2(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5); + if (any(uv < 0.0) || any(uv > 1.0) || ndc.z >= 1.0) + return 1.0; + // The disc turned by a per-place angle, so the samples' pattern becomes fine noise instead of + // bands; nearer samples weigh more (Gaussian). + const float turn = 6.2831853 * frac(52.9829189 * frac(dot(worldPosition.xy, float2(0.06711056, 0.00583715)))); + const float2x2 rotation = float2x2(cos(turn), -sin(turn), sin(turn), cos(turn)); + const float radius = sunShadowParameters.z * max(sunShadowParameters.y, 0.25) * 1.5; + float visible = 0.0; + float total = 0.0; + [unroll] + for (int i = 0; i < 12; ++i) + { + const float2 offset = mul(rotation, SunShadowDisc[i]); + const float weight = exp(-2.0 * dot(offset, offset)); + visible += weight * sunShadowMap.SampleCmpLevelZero(sunShadowSampler, uv + offset * radius, ndc.z); + total += weight; + } + return visible / total; +} + +// How much of a point light reaches a point `toLight` away from it: the terrain light's linear fade +// over the horizontal distance. +float PointLightFalloff(float3 toLight, float radius) +{ + const float horizontal = length(toLight.xy); + return horizontal < radius ? (radius - horizontal) / radius : 0.0; +} +#endif diff --git a/src/shaders/post_ao.frag.hlsl b/src/shaders/post_ao.frag.hlsl new file mode 100644 index 0000000000..720f3a973d --- /dev/null +++ b/src/shaders/post_ao.frag.hlsl @@ -0,0 +1,100 @@ +// post_ao.frag.hlsl — screen-space ambient occlusion of the 3D scene, at half resolution: how much +// of the hemisphere above each surface nearby geometry hides, from the scene's depth alone. +// post_ao_blur.frag.hlsl then removes its 4x4 rotation pattern. +// AmbientOcclusion mirrors mu::SdlGpuAmbientOcclusionUniform. +Texture2D depthTexture : register(t0, space2); +SamplerState depthSampler : register(s0, space2); // point +cbuffer AmbientOcclusion : register(b0, space3) +{ + float4x4 projection; + float4x4 inverseProjection; + float2 depthTexelSize; // 1 / the depth's size + float radius; // view-space units + float padding; +}; +struct FSInput +{ + float4 pos : SV_Position; + float2 uv : TEXCOORD0; +}; + +static const uint SampleCount = 12; +// Sine of the angle an occluder must rise above the surface's plane before it counts: depth +// precision and slightly bumpy ground stay below it. +static const float PlaneRise = 0.15; +// Points in the unit hemisphere around +z, more of them near the centre. +static const float3 Kernel[SampleCount] = { + float3(0.21, 0.05, 0.10), float3(-0.10, 0.25, 0.15), float3(-0.28, -0.12, 0.08), float3(0.14, -0.30, 0.20), + float3(0.42, 0.22, 0.25), float3(-0.35, 0.40, 0.12), float3(-0.30, -0.45, 0.35), float3(0.38, -0.36, 0.42), + float3(0.70, 0.10, 0.30), float3(-0.15, 0.72, 0.45), float3(-0.66, -0.20, 0.55), float3(0.20, -0.62, 0.70), +}; +// 4x4 ordered rotations: the blur's 4x4 average cancels the pattern. +static const float Rotations[16] = {0.0 / 16.0, 8.0 / 16.0, 2.0 / 16.0, 10.0 / 16.0, 12.0 / 16.0, 4.0 / 16.0, + 14.0 / 16.0, 6.0 / 16.0, 3.0 / 16.0, 11.0 / 16.0, 1.0 / 16.0, 9.0 / 16.0, + 15.0 / 16.0, 7.0 / 16.0, 13.0 / 16.0, 5.0 / 16.0}; + +float SceneDepth(float2 uv) +{ + return depthTexture.SampleLevel(depthSampler, uv, 0).r; +} + +float3 ViewPosition(float2 uv, float depth) +{ + const float4 view = mul(inverseProjection, float4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0)); + return view.xyz / view.w; +} + +// At a depth texel's centre: half-resolution pixels sit on texel corners, where point sampling rounds +// either way from row to row (horizontal lines); a quarter texel past the corner picks one. +float3 ViewPositionAt(float2 uv) +{ + const float2 centre = (floor(uv / depthTexelSize + 0.25) + 0.5) * depthTexelSize; + return ViewPosition(centre, SceneDepth(centre)); +} + +// The surface's direction from its nearer neighbour on each axis, so silhouettes do not bend it. +float3 SurfaceNormal(float2 uv, float3 position) +{ + const float3 right = ViewPositionAt(uv + float2(depthTexelSize.x, 0.0)) - position; + const float3 left = position - ViewPositionAt(uv - float2(depthTexelSize.x, 0.0)); + const float3 down = ViewPositionAt(uv + float2(0.0, depthTexelSize.y)) - position; + const float3 up = position - ViewPositionAt(uv - float2(0.0, depthTexelSize.y)); + const float3 alongX = abs(right.z) < abs(left.z) ? right : left; + const float3 alongY = abs(down.z) < abs(up.z) ? down : up; + float3 normal = normalize(cross(alongX, alongY)); + return dot(normal, position) > 0.0 ? -normal : normal; // towards the camera +} + +float4 main(FSInput input) : SV_Target +{ + if (SceneDepth(input.uv) >= 1.0) + return float4(1.0, 1.0, 1.0, 1.0); // sky + const float3 position = ViewPositionAt(input.uv); + const float3 normal = SurfaceNormal(input.uv, position); + + const uint2 cell = uint2(input.pos.xy) & 3u; + const float angle = 6.2831853 * Rotations[cell.y * 4u + cell.x]; + const float3 turn = float3(cos(angle), sin(angle), 0.0); + const float3 tangent = normalize(turn - normal * dot(turn, normal) + float3(1e-4, 0.0, 0.0)); + const float3 bitangent = cross(normal, tangent); + + float occlusion = 0.0; + [unroll] + for (uint i = 0; i < SampleCount; ++i) + { + const float3 offset = tangent * Kernel[i].x + bitangent * Kernel[i].y + normal * Kernel[i].z; + const float3 samplePosition = position + offset * radius; + const float4 clip = mul(projection, float4(samplePosition, 1.0)); + const float2 sampleUv = float2(clip.x / clip.w * 0.5 + 0.5, 0.5 - clip.y / clip.w * 0.5); + // The surface seen where the sample lands occludes by how far it rises above this surface's + // plane: the same flat ground, wherever its pixel rows put it, does not (no banding). + const float3 toOccluder = ViewPositionAt(sampleUv) - position; + const float distanceSquared = dot(toOccluder, toOccluder); + const float rise = dot(toOccluder, normal) * rsqrt(max(distanceSquared, 1e-6)); + // Only geometry within the radius counts: a far wall behind the sample does not. + const float inRange = saturate(1.0 - distanceSquared / (radius * radius)); + occlusion += saturate(rise - PlaneRise) * inRange; + } + const float visibility = 1.0 - occlusion / SampleCount; + return float4(visibility, visibility, visibility, visibility); +} diff --git a/src/shaders/post_ao_blur.frag.hlsl b/src/shaders/post_ao_blur.frag.hlsl new file mode 100644 index 0000000000..e5046e73d8 --- /dev/null +++ b/src/shaders/post_ao_blur.frag.hlsl @@ -0,0 +1,71 @@ +// post_ao_blur.frag.hlsl — post_ao.frag's occlusion averaged over 4x4 texels, the size of its +// rotation pattern, leaving out texels off the centre's surface (an edge) so edges keep no halo. +// Texels are weighed by their distance from the centre's plane, not by depth: ground far away, whose +// depth changes fast down the screen, still blends fully and the pattern cancels there too. +// AmbientOcclusion mirrors mu::SdlGpuAmbientOcclusionUniform (only some of it is read here). +Texture2D depthTexture : register(t0, space2); +SamplerState depthSampler : register(s0, space2); // point +Texture2D occlusionTexture : register(t1, space2); +SamplerState occlusionSampler : register(s1, space2); // point +cbuffer AmbientOcclusion : register(b0, space3) +{ + float4x4 projection; + float4x4 inverseProjection; + float2 depthTexelSize; + float radius; + float padding; +}; +struct FSInput +{ + float4 pos : SV_Position; + float2 uv : TEXCOORD0; +}; + +// At a depth texel's centre, as post_ao.frag's ViewPositionAt. +float3 ViewPosition(float2 uv) +{ + uv = (floor(uv / depthTexelSize + 0.25) + 0.5) * depthTexelSize; + const float depth = depthTexture.SampleLevel(depthSampler, uv, 0).r; + const float4 view = mul(inverseProjection, float4(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0)); + return view.xyz / view.w; +} + +// As post_ao.frag's SurfaceNormal: from the nearer neighbour on each axis. +float3 SurfaceNormal(float2 uv, float3 position) +{ + const float3 right = ViewPosition(uv + float2(depthTexelSize.x, 0.0)) - position; + const float3 left = position - ViewPosition(uv - float2(depthTexelSize.x, 0.0)); + const float3 down = ViewPosition(uv + float2(0.0, depthTexelSize.y)) - position; + const float3 up = position - ViewPosition(uv - float2(0.0, depthTexelSize.y)); + const float3 alongX = abs(right.z) < abs(left.z) ? right : left; + const float3 alongY = abs(down.z) < abs(up.z) ? down : up; + return normalize(cross(alongX, alongY)); +} + +float4 main(FSInput input) : SV_Target +{ + const float3 centre = ViewPosition(input.uv); + const float3 normal = SurfaceNormal(input.uv, centre); + // The occlusion is at half the depth's resolution. + const float2 occlusionTexelSize = depthTexelSize * 2.0; + // Texels further than this from the centre's plane are another surface. + const float planeTolerance = radius * 0.25; + float sum = 0.0; + float weightSum = 0.0; + [unroll] + for (int y = -2; y < 2; ++y) + { + [unroll] + for (int x = -2; x < 2; ++x) + { + // Whole texels from the centre: four in a row cover all four of the pattern's columns. + const float2 uv = input.uv + float2(x, y) * occlusionTexelSize; + const float offPlane = abs(dot(ViewPosition(uv) - centre, normal)); + const float weight = saturate(1.0 - offPlane / planeTolerance) + 1e-3; + sum += occlusionTexture.SampleLevel(occlusionSampler, uv, 0).r * weight; + weightSum += weight; + } + } + const float visibility = sum / weightSum; + return float4(visibility, visibility, visibility, visibility); +} diff --git a/src/shaders/post_composite.frag.hlsl b/src/shaders/post_composite.frag.hlsl index a609db59b8..ee8a2de423 100644 --- a/src/shaders/post_composite.frag.hlsl +++ b/src/shaders/post_composite.frag.hlsl @@ -1,6 +1,7 @@ -// post_composite.frag.hlsl — the processed 3D scene: the scene image with its bloom screen-blended -// on top, colour graded through the map's lookup table. Draws into the frame's destination before -// the UI. +// post_composite.frag.hlsl — the processed 3D scene: the scene image darkened by its ambient +// occlusion (an HDR scene then tone mapped), +// with its bloom screen-blended on top, colour graded through the map's lookup table and dithered. +// Draws into the frame's destination before the UI. // CompositeUniforms mirrors mu::SdlGpuCompositeUniform. Texture2D scene : register(t0, space2); SamplerState sceneSampler : register(s0, space2); // point: one scene texel per pixel @@ -8,11 +9,19 @@ Texture2D bloom : register(t1, space2); SamplerState bloomSampler : register(s1, space2); // linear: the bloom is half resolution Texture2D grading : register(t2, space2); SamplerState gradingSampler : register(s2, space2); // linear: interpolates between table entries +Texture2D ambientOcclusion : register(t3, space2); +SamplerState ambientOcclusionSampler : register(s3, space2); // linear: half resolution +Texture2D bloomSource : register(t4, space2); +SamplerState bloomSourceSampler : register(s4, space2); // point cbuffer CompositeUniforms : register(b0, space3) { float2 inverseTargetSize; float bloomScale; // 0: no bloom float gradingStrength; // 0: ungraded; else blend of the graded colour with the ungraded one + float toneMapKnee; // channels above it roll off towards 1; 1: none + float ditherAmount; // 0: no dither + float ambientOcclusionStrength; // 0: no ambient occlusion + float ambientOcclusionEffects; // 1: the bloom source holds this frame's additive light }; struct FSInput { @@ -27,11 +36,34 @@ static const float kGradingSize = 32.0; // Defined after main so the compiled shader declares its textures in binding order (scene, // bloom, grading): spirv-cross numbers Metal textures in that order. float3 Grade(float3 color); +float AmbientOcclusion(float2 uv); + +// The HDR scene's tone map: unchanged up to the knee, then an exponential shoulder towards 1, so +// stacked light rolls off instead of clipping. The same curve as skinned_lit.frag's highlight knee. +float ToneMapChannel(float value) +{ + const float range = 1.0 - toneMapKnee; + return value > toneMapKnee ? toneMapKnee + range * (1.0 - exp(-(value - toneMapKnee) / range)) : value; +} + +// Interleaved gradient noise in [0, 1): an ordered dither pattern without a texture. +float DitherNoise(float2 pixel) +{ + return frac(52.9829189 * frac(dot(pixel, float2(0.06711056, 0.00583715)))); +} float4 main(FSInput input) : SV_Target { const float2 uv = input.pos.xy * inverseTargetSize; float4 color = scene.Sample(sceneSampler, uv); + if (ambientOcclusionStrength > 0.0) + color.rgb *= AmbientOcclusion(uv); + if (toneMapKnee < 1.0) + { + // Blending over light above 1 (inverse colour) can leave negative values: black. + color.rgb = max(color.rgb, 0.0); + color.rgb = float3(ToneMapChannel(color.r), ToneMapChannel(color.g), ToneMapChannel(color.b)); + } if (bloomScale > 0.0) { // Screen blend: a dark pixel gains about the glow's light, a bright one little, so glows @@ -44,6 +76,8 @@ float4 main(FSInput input) : SV_Target // Render::PostProcessing::BlendGrading mirrors this blend. color.rgb = lerp(color.rgb, Grade(color.rgb), gradingStrength); } + if (ditherAmount > 0.0) + color.rgb += (DitherNoise(input.pos.xy) - 0.5) * ditherAmount; return color; } @@ -63,3 +97,16 @@ float3 Grade(float3 color) const float3 upper = grading.Sample(gradingSampler, float2(x + upperSlice * sliceWidth, y)).rgb; return lerp(lower, upper, sliceBlend); } + +// The share of the scene's light its ambient occlusion leaves. Additive light (effects, glows) is +// light, not surface: where the bloom source holds it, the occlusion fades out. +float AmbientOcclusion(float2 uv) +{ + float visibility = ambientOcclusion.Sample(ambientOcclusionSampler, uv).r; + if (ambientOcclusionEffects > 0.0) + { + const float effectLight = dot(bloomSource.Sample(bloomSourceSampler, uv).rgb, float3(0.2126, 0.7152, 0.0722)); + visibility = lerp(visibility, 1.0, saturate(effectLight * 4.0)); + } + return max(1.0 - (1.0 - visibility) * ambientOcclusionStrength, 0.0); +} diff --git a/src/shaders/scene_lighting.hlsli b/src/shaders/scene_lighting.hlsli new file mode 100644 index 0000000000..efe437ff96 --- /dev/null +++ b/src/shaders/scene_lighting.hlsli @@ -0,0 +1,41 @@ +// scene_lighting.hlsli — the fog and scene lighting uniforms every Enhanced lit shader shares, and the +// Enhanced fog curve. FogUniforms mirrors FogUniform, SceneLighting mu::SceneLightingUniform (std140). +#ifndef MU_SCENE_LIGHTING_HLSLI +#define MU_SCENE_LIGHTING_HLSLI +cbuffer FogUniforms : register(b0, space3) +{ + uint fogEnabled; + uint alphaDiscardEnabled; + float alphaThreshold; + uint alphaToCoverage; // 1: the pipeline turns alpha into multisample coverage + float fogStart; + float fogEnd; + float4 fogColor; +}; +cbuffer SceneLighting : register(b1, space3) +{ + float4 sceneLightDirection; + float4 sceneLightColor; + float4 diffuseCurve; // scale, ambient, floor, highlight knee + float4 rimParameters; + float4 specularParameters; + float4 sceneFogColor; + float4 sceneFogParameters; + float4 cameraPosition; + float4x4 sunViewProjection; // world to the sun shadow map's clip space + float4 sunShadowParameters; // darkness (0: no shadow map), softness in texels, 1 / map size, texel in world units + float4 lightingParameters; // y: 1 when the terrain's direct-sunlight grid is bound; x, z, w unused + float4 cloudParameters; // x: cloud strength (0: none), y: 1 / pattern size, z: sky cover + float4 cloudOffset; // xy: the clouds' drift plus the sun's slant + float4 skyFill; // rgb: the sky's tint of the shade, w: how far shade takes it + float4 sunTowards; // xyz: towards the sun, w: how far the rim follows it + float4 sunColor; // rgb: the sun's colour +}; + +// The Enhanced exponential fog: the same curve as mu::EnhancedFogAmount() (SceneLighting.cpp). +float EnhancedFogAmount(float eyeDepth) +{ + const float scaledDistance = max(eyeDepth - sceneFogParameters.x, 0.0) * sceneFogParameters.z; + return saturate(1.0 - exp(-scaledDistance * scaledDistance)); +} +#endif diff --git a/src/shaders/shadow_mask.frag.hlsl b/src/shaders/shadow_mask.frag.hlsl new file mode 100644 index 0000000000..731ce7e359 --- /dev/null +++ b/src/shaders/shadow_mask.frag.hlsl @@ -0,0 +1,14 @@ +// shadow_mask.frag.hlsl — a ground shadow into the ground shadow mask (R8, MIN blend): 1 minus the +// shadow's alpha, so the darkest shadow at a pixel wins and overlapping shadows count once. +// world_lit.frag.hlsl reads the mask. Pairs with skinned_shadow.vert and basic_textured.vert. +struct FSInput +{ + float4 pos : SV_Position; + float2 uv : TEXCOORD0; + float4 color : TEXCOORD1; +}; + +float4 main(FSInput input) : SV_Target +{ + return (1.0 - input.color.a).xxxx; +} diff --git a/src/shaders/skinned_lit.frag.hlsl b/src/shaders/skinned_lit.frag.hlsl index 044a80050d..ee51477b2d 100644 --- a/src/shaders/skinned_lit.frag.hlsl +++ b/src/shaders/skinned_lit.frag.hlsl @@ -12,42 +12,18 @@ // of the skinned tangent T, bitangent cross(N, T) x handedness and N, for the diffuse, // rim, specular and point-light terms; without one (scale 0) the interpolated normal // as before, and the flat default map bound at t1 is not read -// FogUniforms mirrors FogUniform, SceneLighting mirrors mu::SceneLightingUniform and DynamicLights -// mirrors mu::DynamicLightsUniform (std140). +// The shared uniforms and lighting functions: scene_lighting.hlsli, dynamic_lighting.hlsli. Texture2D tex : register(t0, space2); SamplerState s : register(s0, space2); Texture2D normalMap : register(t1, space2); SamplerState normalSampler : register(s1, space2); -cbuffer FogUniforms : register(b0, space3) -{ - uint fogEnabled; - uint alphaDiscardEnabled; - float alphaThreshold; - uint alphaToCoverage; // 1: the pipeline turns alpha into multisample coverage - float fogStart; - float fogEnd; - float4 fogColor; -}; -cbuffer SceneLighting : register(b1, space3) -{ - float4 sceneLightDirection; - float4 sceneLightColor; - float4 diffuseCurve; // scale, ambient, floor, highlight knee - float4 rimParameters; - float4 specularParameters; - float4 sceneFogColor; - float4 sceneFogParameters; - float4 cameraPosition; -}; -static const uint MaxDynamicLights = 32; // mu::kMaxDynamicLights -cbuffer DynamicLights : register(b2, space3) -{ - uint dynamicLightCount; // lights used - float dynamicLightWrap; // 0: Lambert, 0.5: half-Lambert (mu::WrappedDiffuse) - uint2 dynamicLightPadding; - float4 dynamicLightPositionAndRadius[MaxDynamicLights]; - float4 dynamicLightColor[MaxDynamicLights]; -}; +// The sun shadow map's depth (Enhanced sun shadows; a far 1x1 map without them). +Texture2D sunShadowMap : register(t2, space2); +SamplerComparisonState sunShadowSampler : register(s2, space2); + +#include "scene_lighting.hlsli" +#include "dynamic_lighting.hlsli" +#include "clouds.hlsli" // The light mood's highlight shoulder (Render::Lighting::LightMood::RollOffHighlight): a lit // colour channel above the knee approaches 1 smoothly instead of being cut off there. Only a knee @@ -86,13 +62,6 @@ struct FSInput float4 worldTangentAndNormalMapScale : TEXCOORD10; // w: the map's scale, 0 without one }; -// Same curve as basic_textured_fog.frag.hlsl and mu::EnhancedFogAmount() (SceneLighting.cpp). -float EnhancedFogAmount(float eyeDepth) -{ - const float scaledDistance = max(eyeDepth - sceneFogParameters.x, 0.0) * sceneFogParameters.z; - return saturate(1.0 - exp(-scaledDistance * scaledDistance)); -} - float3 SafeNormalize(float3 value) { const float lengthSquared = dot(value, value); @@ -110,11 +79,9 @@ float3 DynamicLighting(float3 worldPosition, float3 worldNormal) { const float4 positionAndRadius = dynamicLightPositionAndRadius[i]; const float3 toLight = positionAndRadius.xyz - worldPosition; - const float radius = positionAndRadius.w; - const float horizontalDistance = length(toLight.xy); - if (horizontalDistance >= radius) + const float falloff = PointLightFalloff(toLight, positionAndRadius.w); + if (falloff <= 0.0) continue; - const float falloff = (radius - horizontalDistance) / radius; const float wrapped = saturate(dot(worldNormal, SafeNormalize(toLight)) * (1.0 - dynamicLightWrap) + dynamicLightWrap); light += dynamicLightColor[i].rgb * (falloff * wrapped); @@ -161,18 +128,38 @@ float4 main(FSInput input) : SV_Target const float3 light = input.lightDirectionAndSpecular.xyz; const float lightDot = dot(shadingNormal, light); - const float luminosity = max(lightDot * diffuseCurve.x + diffuseCurve.y, diffuseCurve.z); - const float3 dynamicLight = input.worldPositionAndDynamicLights.w > 0.5 - ? DynamicLighting(input.worldPositionAndDynamicLights.xyz, - SafeNormalize(worldNormal)) - : float3(0.0, 0.0, 0.0); - float3 diffuse = saturate(objectLight * luminosity + dynamicLight); + // In the scene's world (not a model drawn for the UI), the point lights and the sun's shadows apply. + const bool inWorld = input.worldPositionAndDynamicLights.w > 0.5; + const float3 litNormal = SafeNormalize(worldNormal); + // The sun's shadow takes away the direct sunlight only: the ambient part and the point lights stay. + // Clouds dim the sunlight as shadows do. + const float sunVisible = + inWorld && sunShadowParameters.x > 0.0 + ? SunVisibility(input.worldPositionAndDynamicLights.xyz, litNormal) * + CloudLight(input.worldPositionAndDynamicLights.xy, cloudParameters, cloudOffset.xy) + : 1.0; + const float sunLight = 1.0 - sunShadowParameters.x * (1.0 - sunVisible); + // Shade turns towards the sky's blue. + const float3 skyShade = lerp(float3(1.0, 1.0, 1.0), skyFill.rgb, skyFill.w * (1.0 - sunVisible)); + // Shadow dims the light a face receives, never the darkening of faces turned away. + const float luminosity = + max(lightDot * diffuseCurve.x * (lightDot > 0.0 ? sunLight : 1.0) + diffuseCurve.y, diffuseCurve.z); + const float3 dynamicLight = + inWorld ? DynamicLighting(input.worldPositionAndDynamicLights.xyz, litNormal) : float3(0.0, 0.0, 0.0); + const float3 lit = objectLight * skyShade * luminosity + dynamicLight; + float3 diffuse = saturate(lit); if (RollsOffHighlight(diffuseCurve.w)) - diffuse = RollOffHighlight(objectLight * luminosity + dynamicLight, diffuseCurve.w); + diffuse = RollOffHighlight(lit, diffuseCurve.w); // Two-sided meshes show back faces; |dot| keeps their interiors from rim-lighting. const float facing = saturate(abs(dot(normal, view))); - const float3 rim = rimParameters.x * pow(1.0 - facing, rimParameters.y) * objectLight; + float3 rim = rimParameters.x * pow(1.0 - facing, rimParameters.y) * objectLight; + if (inWorld && sunTowards.w > 0.0) + { + // The rim follows the sun: brighter and sun-coloured on the side facing it, gone in its shadow. + const float towardsSun = saturate(dot(litNormal, normalize(sunTowards.xyz)) * 0.75 + 0.25) * sunVisible; + rim = lerp(rim, rim * sunColor.rgb * (2.0 * towardsSun), sunTowards.w); + } const float specularStrength = input.lightDirectionAndSpecular.w * specularParameters.x; float3 specular = float3(0.0, 0.0, 0.0); @@ -180,7 +167,7 @@ float4 main(FSInput input) : SV_Target { const float3 halfVector = SafeNormalize(SafeNormalize(light) + view); const float highlight = pow(saturate(dot(normal, halfVector)), specularParameters.y); - specular = specularStrength * highlight * sceneLightColor.rgb * objectLight; + specular = specularStrength * highlight * sunLight * sceneLightColor.rgb * objectLight; } // Rim and specular are light added on top of the surface, so dark textures still get an diff --git a/src/shaders/skinned_shadow.hlsli b/src/shaders/skinned_shadow.hlsli index 4f717d96f2..74a03abbb6 100644 --- a/src/shaders/skinned_shadow.hlsli +++ b/src/shaders/skinned_shadow.hlsli @@ -27,7 +27,7 @@ cbuffer Skinning : register(b0, space1) cbuffer Shadow : register(b1, space1) { float4 shadowOrigin; // xyz: BodyOrigin, w: height of TW_HEIGHT cells - float4 shadowProjection; // x, y: sx, sy; z: 0 where RequestTerrainHeight() returns 0 + float4 shadowProjection; // x, y: sx, sy; z: 0 where RequestTerrainHeight() returns 0; w: axis angle }; struct VSOutput @@ -53,7 +53,10 @@ float4 clipPosition(float3 position) float3 shearShadow(float3 position) { float3 relative = position - shadowOrigin.xyz; - relative.x += relative.z * (relative.x + shadowProjection.x) / (relative.z - shadowProjection.y); + // The shear acts along the axis at angle w (0: x, as in Classic). + const float2 axis = float2(cos(shadowProjection.w), sin(shadowProjection.w)); + const float along = dot(relative.xy, axis); + relative.xy += axis * (relative.z * (along + shadowProjection.x) / (relative.z - shadowProjection.y)); return relative + shadowOrigin.xyz; } diff --git a/src/shaders/sun_depth.frag.hlsl b/src/shaders/sun_depth.frag.hlsl new file mode 100644 index 0000000000..a6df7335b9 --- /dev/null +++ b/src/shaders/sun_depth.frag.hlsl @@ -0,0 +1,44 @@ +// sun_depth.frag.hlsl — a draw into the sun shadow map (depth only). Pairs with +// basic_textured.vert and skinned_textured.vert, whose matrix the sun pass replaces with the sun's. +// FogUniforms mirrors FogUniform, whose fogEnabled slot carries the coverage mode (SunCoverage - 1): +// solid draws let the sun through where the scene's alpha test drops their texels (leaves, fences, +// hair); a character's blended parts (wings, capes, auras) cover a texel with the chance of their +// alpha, or glowing, their brightness, which the shadow's blur turns into a partial shadow. +Texture2D tex : register(t0, space2); +SamplerState s : register(s0, space2); +cbuffer FogUniforms : register(b0, space3) +{ + uint coverageMode; // 0 solid, 1 by alpha, 2 by brightness + uint alphaDiscardEnabled; + float alphaThreshold; + uint alphaToCoverage; + float fogStart; + float fogEnd; + float4 fogColor; +}; +struct FSInput +{ + float4 pos : SV_Position; + float2 uv : TEXCOORD0; + float4 color : TEXCOORD1; +}; + +// Interleaved gradient noise: a threshold per texel, even over small areas. +float Dither(float2 position) +{ + return frac(52.9829189 * frac(dot(position, float2(0.06711056, 0.00583715)))); +} + +void main(FSInput input) +{ + const float4 texel = tex.Sample(s, input.uv) * input.color; + if (coverageMode == 0) + { + if ((alphaDiscardEnabled || alphaToCoverage) && texel.a <= alphaThreshold) + discard; + return; + } + const float coverage = coverageMode == 1 ? texel.a : max(texel.r, max(texel.g, texel.b)) * texel.a; + if (coverage <= Dither(input.pos.xy)) + discard; +} diff --git a/src/shaders/world_lit.frag.hlsl b/src/shaders/world_lit.frag.hlsl new file mode 100644 index 0000000000..28843cd943 --- /dev/null +++ b/src/shaders/world_lit.frag.hlsl @@ -0,0 +1,90 @@ +// world_lit.frag.hlsl — Enhanced per-pixel point lights for the ground: terrain tiles, their layers, +// grass and terrain decals that take the terrain light. Pairs with world_lit.vert.hlsl. +// The vertex colour is the terrain light without the frame's first dynamicWorldLightCount point +// lights; those are added back here per pixel with the terrain light's own falloff, so the ground +// gets the light it always did, smooth instead of interpolated between grid vertices. +// The shared uniforms and lighting functions: scene_lighting.hlsli, dynamic_lighting.hlsli. + +Texture2D tex : register(t0, space2); +SamplerState s : register(s0, space2); +// The sun shadow map's depth (Enhanced sun shadows; a far 1x1 map without them). +Texture2D sunShadowMap : register(t2, space2); +SamplerComparisonState sunShadowSampler : register(s2, space2); +// Per pixel, 1 minus the darkest ground shadow there: red the sun's, green the point lights' (white +// without shadows). +Texture2D groundShadowMask : register(t1, space2); +SamplerState groundShadowSampler : register(s1, space2); +// Per terrain cell, the direct sunlight inside the vertex colour (the rest is the painted ambient light +// and point lights): what a cloud's shadow takes away. Used while lightingParameters.y is 1. +Texture2D terrainSunLight : register(t3, space2); +SamplerState terrainSunSampler : register(s3, space2); +#include "scene_lighting.hlsli" +#include "dynamic_lighting.hlsli" +#include "clouds.hlsli" +struct FSInput +{ + float4 pos : SV_Position; + float2 uv : TEXCOORD0; + float4 color : TEXCOORD1; + float fogFactor : TEXCOORD2; + float eyeDepth : TEXCOORD3; + float3 worldPosition : TEXCOORD4; +}; + +// The frame's first point lights, which the ground's vertex colour leaves out. +float3 WorldDynamicLighting(float3 worldPosition) +{ + float3 light = float3(0.0, 0.0, 0.0); + const uint count = min(min(dynamicWorldLightCount, dynamicLightCount), MaxDynamicLights); + [loop] + for (uint i = 0; i < count; ++i) + { + const float4 positionAndRadius = dynamicLightPositionAndRadius[i]; + light += dynamicLightColor[i].rgb * PointLightFalloff(positionAndRadius.xyz - worldPosition, positionAndRadius.w); + } + return light; +} + +float4 main(FSInput input) : SV_Target +{ + // Sampled before the mask: spirv-cross numbers the MSL textures in the order the source uses them. + const float4 texel = tex.Sample(s, input.uv); + // The mask covers the render target; a 1x1 white mask clamps to white everywhere. + uint maskWidth; + uint maskHeight; + groundShadowMask.GetDimensions(maskWidth, maskHeight); + const float2 visibility = + groundShadowMask.Sample(groundShadowSampler, input.pos.xy / float2(maskWidth, maskHeight)).rg; + // The sun's shadows dim the ground's own light, the point lights' shadows the point lights. + float2 shadow = 1.0 - groundShadowOpacity * (1.0 - visibility); + const bool sunShadows = sunShadowParameters.x > 0.0; + const float sunVisible = sunShadows ? SunVisibility(input.worldPosition, float3(0.0, 0.0, 1.0)) : 1.0; + shadow.x *= 1.0 - sunShadowParameters.x * (1.0 - sunVisible); + // A cloud takes away direct sunlight only, where the sun reaches. + const float cloud = sunShadows ? CloudLight(input.worldPosition.xy, cloudParameters, cloudOffset.xy) : 1.0; + float3 ground = input.color.rgb * shadow.x; + if (cloud < 1.0 && lightingParameters.y > 0.0) + { + // Cell centres: the terrain's 256 cells of 100 world units (TERRAIN_SIZE, TERRAIN_SCALE). + const float2 cellUv = (input.worldPosition.xy / 100.0 + 0.5) / 256.0; + const float3 direct = terrainSunLight.Sample(terrainSunSampler, cellUv).rgb; + ground = max(ground - direct * sunVisible * (1.0 - cloud), 0.0); + } + // Shade, from shadows and clouds, turns towards the sky's blue. + const float3 skyShade = lerp(float3(1.0, 1.0, 1.0), skyFill.rgb, skyFill.w * (1.0 - sunVisible * cloud)); + const float3 pointLight = WorldDynamicLighting(input.worldPosition) * shadow.y; + const float3 light = saturate(ground * skyShade + pointLight); + float4 color = float4(texel.rgb * light, texel.a * input.color.a); + if (alphaToCoverage) + { + // Anti-aliased cutout, as in basic_textured.frag: coverage keeps the + // texel's translucency; only the alpha test's step becomes a ramp. + const float edge = saturate((color.a - alphaThreshold) / max(fwidth(color.a), 0.0001) + 0.5); + color.a *= edge; + if (color.a <= 0.0) discard; + } + else if (alphaDiscardEnabled && color.a <= alphaThreshold) discard; + if (fogEnabled && sceneFogColor.w > 0.0) + color.rgb = lerp(color.rgb, sceneFogColor.rgb, EnhancedFogAmount(input.eyeDepth)); + return color; +} diff --git a/src/shaders/world_lit.vert.hlsl b/src/shaders/world_lit.vert.hlsl new file mode 100644 index 0000000000..b55bdad242 --- /dev/null +++ b/src/shaders/world_lit.vert.hlsl @@ -0,0 +1,30 @@ +// world_lit.vert.hlsl — basic_textured.vert for the ground lit per pixel (world_lit.frag.hlsl). +// The ground is submitted in world space, so its vertex position is also the fragment's world +// position for the point lights. +cbuffer Transform : register(b0, space1) { float4x4 mvp; float fogStart; float fogEnd; float2 fogPad; }; +struct VSInput { float3 pos : TEXCOORD0; float2 uv : TEXCOORD1; float4 color : TEXCOORD2; }; +struct VSOutput +{ + float4 pos : SV_Position; + float2 uv : TEXCOORD0; + float4 color : TEXCOORD1; + float fogFactor : TEXCOORD2; + float eyeDepth : TEXCOORD3; + float3 worldPosition : TEXCOORD4; + float clipDist : SV_ClipDistance0; +}; +VSOutput main(VSInput input) +{ + VSOutput o; + o.pos = mul(mvp, float4(input.pos, 1.0)); + o.uv = input.uv; + o.color = input.color; + // Near-plane user clip, as in basic_textured.vert. + o.clipDist = o.pos.w - 1.0; + const float dist = abs(o.pos.w); + const float range = fogEnd - fogStart; + o.fogFactor = (range > 0.001) ? saturate((fogEnd - dist) / range) : 1.0; + o.eyeDepth = dist; + o.worldPosition = input.pos; + return o; +} diff --git a/src/source/Core/Utilities/Benchmark/BenchTypes.h b/src/source/Core/Utilities/Benchmark/BenchTypes.h index 9ded8eb47d..437fef4009 100644 --- a/src/source/Core/Utilities/Benchmark/BenchTypes.h +++ b/src/source/Core/Utilities/Benchmark/BenchTypes.h @@ -15,7 +15,7 @@ namespace Core::Benchmark { // Upper bound on the pass/counter dimensions copied out of FrameProfiler. Static-asserted // against the real enum sizes in BenchRecorder.cpp, which is the only file that knows both. -inline constexpr int kMaxPasses = 32; +inline constexpr int kMaxPasses = 40; inline constexpr int kMaxCounters = 32; // Name of the segment every run starts and ends with, so drift across the run is measurable diff --git a/src/source/Core/Utilities/FrameProfiler.h b/src/source/Core/Utilities/FrameProfiler.h index 2de998d990..486fd218b2 100644 --- a/src/source/Core/Utilities/FrameProfiler.h +++ b/src/source/Core/Utilities/FrameProfiler.h @@ -46,6 +46,12 @@ enum class Pass : int ObjectsDraw, // The update's effect spawns and poses for the drawn characters and map objects. UpdateEffects, + // Inside RendererReplay: the sun shadow map, and the scene's depth for ambient occlusion while + // anti-aliasing is on. + SunShadow, + // Inside the terrain's frame start: the static terrain light built again for a moved sun. + TerrainBake, + SceneDepth, Count_ }; @@ -53,7 +59,8 @@ inline constexpr const char* kPassNames[static_cast(Pass::Count_)] = { "Terrain", "Objects", "Chars", "Items", "Effects", "Other", "CharWait", "MoveFx", "MovePart", "Skinning", "UI", "RenderBegin", "RenderEnd", "Submit", "UIUpdate", "RmlInput", "UILayout", "Flush", "Sprites", "Particles", "Joints", "Overlay", "RmlUpd", "RmlRend", - "EndOffscr", "EndStage", "EndReplay", "EndPostUI", "ObjAnim", "ObjDraw", "UpdateFx", + "EndOffscr", "EndStage", "EndReplay", "EndPostUI", "ObjAnim", "ObjDraw", "UpdateFx", "SunShadow", + "TerrainBake", "SceneDepth", }; enum class Counter : int diff --git a/src/source/Core/Utilities/Log/muConsoleDebug.cpp b/src/source/Core/Utilities/Log/muConsoleDebug.cpp index d0e0e72a36..7dde154b26 100644 --- a/src/source/Core/Utilities/Log/muConsoleDebug.cpp +++ b/src/source/Core/Utilities/Log/muConsoleDebug.cpp @@ -126,7 +126,8 @@ bool CheckDeveloperLookCommand(const std::wstring& command) return true; } if (command.starts_with(L"$lightmood ") || command.starts_with(L"$texfilter ") || - command.starts_with(L"$lighting ") || command.starts_with(L"$dynlights ") || command.starts_with(L"$post ")) + command.starts_with(L"$lighting ") || command.starts_with(L"$dynlights ") || command.starts_with(L"$post ") || + command.starts_with(L"$ao ") || command.starts_with(L"$sun ")) { mu::log::Get("render")->warn("{}: not understood (on or off; $lightmood also takes 0 to 100)", Core::Text::ToUtf8(command.c_str())); diff --git a/src/source/Data/GameData/MapData/LookProfile.cpp b/src/source/Data/GameData/MapData/LookProfile.cpp index b79b455cd3..a8858bf6d0 100644 --- a/src/source/Data/GameData/MapData/LookProfile.cpp +++ b/src/source/Data/GameData/MapData/LookProfile.cpp @@ -22,6 +22,8 @@ constexpr const char* DefaultKey = "default"; constexpr const char* MapsKey = "maps"; constexpr const char* WorldKey = "world"; constexpr const char* NameKey = "name"; +constexpr const char* EnvironmentsKey = "environments"; +constexpr const char* EnvironmentKey = "environment"; // The built-in values are the renderer's behaviour before the profile existed; a doctest checks // each against the constant it replaces. @@ -41,9 +43,24 @@ constexpr std::array Infos = {{ {LookValue::DynamicEffectRangeMax, "dynamic.effectRangeMax", 0.0, 0.0, 16.0}, {LookValue::DynamicEffectFade, "dynamic.effectFade", 0.0, 0.0, 2.0}, {LookValue::DynamicEffectCap, "dynamic.effectCap", 0.0, 0.0, 8.0}, + {LookValue::GroundShadowOpacity, "dynamic.shadowOpacity", 0.6, 0.0, 1.0}, + {LookValue::GroundShadowAngle, "dynamic.shadowAngle", 180.0, 0.0, 360.0}, + {LookValue::GroundShadowLights, "dynamic.shadowLights", 0.0, 0.0, 4.0}, {LookValue::BloomStrength, "bloom.strength", 0.6, 0.0, 2.0}, {LookValue::BloomLevelFalloff, "bloom.levelFalloff", 0.5, 0.25, 1.0}, {LookValue::GradingStrength, "grading.strength", 1.0, 0.0, 1.0}, + {LookValue::AmbientOcclusionStrength, "ao.strength", 0.0, 0.0, 2.0}, + {LookValue::AmbientOcclusionRadius, "ao.radius", 60.0, 10.0, 300.0}, + {LookValue::SunShadowStrength, "sun.shadow", 0.0, 0.0, 1.0}, + {LookValue::SunShadowSoftness, "sun.softness", 1.0, 0.0, 2.0}, + {LookValue::SunShadowResolution, "sun.resolution", 2048.0, 1024.0, 4096.0}, + {LookValue::FlatSunShadow, "dynamic.flatSunShadow", 1.0, 0.0, 1.0}, + {LookValue::CloudStrength, "clouds.strength", 0.0, 0.0, 1.0}, + {LookValue::CloudScale, "clouds.scale", 3000.0, 500.0, 10000.0}, + {LookValue::CloudSpeed, "clouds.speed", 40.0, 0.0, 300.0}, + {LookValue::CloudCover, "clouds.cover", 0.45, 0.0, 1.0}, + {LookValue::SkyFill, "sky.fill", 0.0, 0.0, 1.0}, + {LookValue::RimSunFollow, "lighting.rim.sunFollow", 0.0, 0.0, 1.0}, }}; constexpr bool InfosFollowLookValueOrder() @@ -140,7 +157,7 @@ bool CheckRootKeys(const OrderedJson& root, IssueList& issues) bool valid = true; for (const auto& [key, value] : root.items()) { - if (key != Items::Json::Keys::FormatVersion && key != DefaultKey && key != MapsKey) + if (key != Items::Json::Keys::FormatVersion && key != DefaultKey && key != MapsKey && key != EnvironmentsKey) { issues.Fatal(key, "unknown field"); valid = false; @@ -164,6 +181,35 @@ bool ReadDefault(const OrderedJson& root, LookOverrides& overrides, IssueList& i return ReadOverrides(*json, DefaultKey, {}, overrides, issues); } +bool ReadEnvironments(const OrderedJson& root, LookProfileData& data, IssueList& issues) +{ + const auto json = root.find(EnvironmentsKey); + if (json == root.end()) + { + return true; + } + if (!json->is_object()) + { + issues.Fatal(EnvironmentsKey, "must be an object of named environments"); + return false; + } + bool valid = true; + for (const auto& [name, values] : json->items()) + { + const std::string object = Field(EnvironmentsKey, name); + if (!values.is_object()) + { + issues.Fatal(object, "must be an object of look values"); + valid = false; + continue; + } + EnvironmentLookOverrides environment{name, {}}; + valid = ReadOverrides(values, object, {}, environment.overrides, issues) && valid; + data.environments.push_back(std::move(environment)); + } + return valid; +} + bool ReadWorld(const OrderedJson& json, const std::string& object, int& world, IssueList& issues) { const auto field = json.find(WorldKey); @@ -204,7 +250,21 @@ bool ReadMap(const OrderedJson& json, size_t index, std::set& worlds, LookP issues.Fatal(Field(object, NameKey), "must be text"); return false; } - if (!ReadOverrides(json, object, {WorldKey, NameKey}, map.overrides, issues)) + if (const auto environment = json.find(EnvironmentKey); environment != json.end()) + { + const auto known = environment->is_string() + ? std::find_if(data.environments.begin(), data.environments.end(), + [&environment](const EnvironmentLookOverrides& entry) + { return entry.name == environment->get(); }) + : data.environments.end(); + if (known == data.environments.end()) + { + issues.Fatal(Field(object, EnvironmentKey), "must name one of \"environments\""); + return false; + } + map.environment = static_cast(known - data.environments.begin()); + } + if (!ReadOverrides(json, object, {WorldKey, NameKey, EnvironmentKey}, map.overrides, issues)) { return false; } @@ -276,14 +336,23 @@ LookValues BuiltInLookValues() return builtIn; } +const MapLookOverrides* LookProfileData::FindMap(int world) const +{ + const auto map = + std::find_if(maps.begin(), maps.end(), [world](const MapLookOverrides& entry) { return entry.world == world; }); + return map != maps.end() ? &*map : nullptr; +} + LookValues LookProfileData::ForWorld(int world) const { LookValues values = BuiltInLookValues(); defaultOverrides.ApplyTo(values); - const auto map = - std::find_if(maps.begin(), maps.end(), [world](const MapLookOverrides& entry) { return entry.world == world; }); - if (map != maps.end()) + if (const MapLookOverrides* map = FindMap(world)) { + if (map->environment && *map->environment < environments.size()) + { + environments[*map->environment].overrides.ApplyTo(values); + } map->overrides.ApplyTo(values); } return values; @@ -304,8 +373,10 @@ void ReadLookProfileJson(std::string_view text, const std::string& source, LookP // Non-short-circuit: every problem of the file is reported. const bool keys = CheckRootKeys(root, list); const bool defaults = ReadDefault(root, read.defaultOverrides, list); + // Before the maps, which name them. + const bool environments = ReadEnvironments(root, read, list); const bool maps = ReadMaps(root, read, list); - if (keys && defaults && maps) + if (keys && defaults && environments && maps) { data = std::move(read); } diff --git a/src/source/Data/GameData/MapData/LookProfile.h b/src/source/Data/GameData/MapData/LookProfile.h index 60a5414d8a..c7b0bdfe78 100644 --- a/src/source/Data/GameData/MapData/LookProfile.h +++ b/src/source/Data/GameData/MapData/LookProfile.h @@ -15,15 +15,19 @@ // // { "formatVersion": 1, // "default": { "lighting.rim.strength": 0.35, "bloom.strength": 0.6 }, -// "maps": [ { "world": 1, "name": "Dungeon", "grading.strength": 0.8 } ] } +// "environments": { "enclosed": { "sun.shadow": 0 } }, +// "maps": [ { "world": 1, "name": "Dungeon", "environment": "enclosed", "grading.strength": 0.8 } ] } // // Every value has a built-in value (the renderer's behaviour without the file) // and a range. The values apply in the order built-in, "default", the map's -// entry; either may name any subset of them. "world" is the map number as in -// LightMood.json, "name" is for the reader only. A file with an unknown name, a -// value of the wrong type or out of range, a missing or unsupported -// formatVersion, a duplicate world or a world outside 0 to 255 is unusable as a -// whole: the built-in values apply everywhere. +// environment, the map's entry; each may name any subset of them. "world" is +// the map number as in LightMood.json, "name" is for the reader only. +// "environment" names one of "environments": the kind of place a map is. +// +// A file with an unknown name, a value of the wrong type or out of range, a +// missing or unsupported formatVersion, a duplicate world, a world outside 0 to +// 255 or an unknown environment is unusable as a whole: the built-in values +// apply everywhere. namespace Data::Maps { enum class LookValue : std::uint8_t @@ -43,9 +47,24 @@ enum class LookValue : std::uint8_t DynamicEffectRangeMax, DynamicEffectFade, DynamicEffectCap, + GroundShadowOpacity, + GroundShadowAngle, + GroundShadowLights, BloomStrength, BloomLevelFalloff, GradingStrength, + AmbientOcclusionStrength, + AmbientOcclusionRadius, + SunShadowStrength, + SunShadowSoftness, + SunShadowResolution, + FlatSunShadow, + CloudStrength, + CloudScale, + CloudSpeed, + CloudCover, + SkyFill, + RimSunFollow, Count, }; @@ -105,9 +124,19 @@ struct LookOverrides bool operator==(const LookOverrides&) const = default; }; +struct EnvironmentLookOverrides +{ + std::string name; + LookOverrides overrides; + + bool operator==(const EnvironmentLookOverrides&) const = default; +}; + struct MapLookOverrides { int world = 0; + // Index into LookProfileData::environments. + std::optional environment; LookOverrides overrides; bool operator==(const MapLookOverrides&) const = default; @@ -116,10 +145,12 @@ struct MapLookOverrides struct LookProfileData { LookOverrides defaultOverrides; + std::vector environments; std::vector maps; - // Built-in, then the default, then the world's entry. + // Built-in, then the default, the world's environment and the world's entry. [[nodiscard]] LookValues ForWorld(int world) const; + [[nodiscard]] const MapLookOverrides* FindMap(int world) const; bool operator==(const LookProfileData&) const = default; }; diff --git a/src/source/Render/Drawing/DrawCallLog.h b/src/source/Render/Drawing/DrawCallLog.h index 76bc5d65fe..596f2201c4 100644 --- a/src/source/Render/Drawing/DrawCallLog.h +++ b/src/source/Render/Drawing/DrawCallLog.h @@ -206,6 +206,30 @@ class DrawCallLog final : public mu::IMuRenderer { return m_bloomExclusions > 0; } + void BeginWorldLitGeometry() override + { + ++m_worldLit; + } + void EndWorldLitGeometry() override + { + --m_worldLit; + } + void BeginGroundShadow(mu::GroundShadowSource source) override + { + ++m_groundShadows[static_cast(source)]; + } + void EndGroundShadow(mu::GroundShadowSource source) override + { + --m_groundShadows[static_cast(source)]; + } + void BeginCharacterDraws() override + { + ++m_characterDraws; + } + void EndCharacterDraws() override + { + --m_characterDraws; + } [[nodiscard]] std::size_t BeginReorderableDraws() override { return m_reorderable++; @@ -271,6 +295,9 @@ class DrawCallLog final : public mu::IMuRenderer int m_bound = -1; int m_textureMode = 0; int m_bloomExclusions = 0; + int m_worldLit = 0; + int m_groundShadows[2] = {}; + int m_characterDraws = 0; std::size_t m_reorderable = 0; // The scene's camera, which the sprite matrix replaces. std::vector m_matrices{std::string(" camera")}; @@ -283,6 +310,8 @@ class DrawCallLog final : public mu::IMuRenderer std::to_string(m_alphaTest) + " alphaRef " + std::to_string(m_alphaRef) + " texture " + std::to_string(m_texture2D) + " " + std::to_string(m_bound) + " mode " + std::to_string(m_textureMode) + " fog " + std::to_string(m_fog) + " bloomExcluded " + std::to_string(m_bloomExclusions > 0) + + " worldLit " + std::to_string(m_worldLit > 0) + " groundShadow " + std::to_string(m_groundShadows[0] > 0) + + std::to_string(m_groundShadows[1] > 0) + " characters " + std::to_string(m_characterDraws > 0) + " reorderable " + std::to_string(m_reorderable) + " matrix" + m_matrices.back(); } diff --git a/src/source/Render/Drawing/LegacyCalls.cpp b/src/source/Render/Drawing/LegacyCalls.cpp index b57ca27b3b..4c4023bc31 100644 --- a/src/source/Render/Drawing/LegacyCalls.cpp +++ b/src/source/Render/Drawing/LegacyCalls.cpp @@ -110,6 +110,14 @@ void MakeLegacyCall(LegacyCall call, int argument) s_reorderableMarks.pop_back(); } break; + case LegacyCall::BeginCharacterDraws: + if (!RecordsLegacyCall(call, argument)) + mu::GetRenderer().BeginCharacterDraws(); + break; + case LegacyCall::EndCharacterDraws: + if (!RecordsLegacyCall(call, argument)) + mu::GetRenderer().EndCharacterDraws(); + break; case LegacyCall::RenderTerrain: RenderTerrain(argument != 0); break; diff --git a/src/source/Render/Drawing/LegacyCalls.h b/src/source/Render/Drawing/LegacyCalls.h index 7de5dcf376..88b5933080 100644 --- a/src/source/Render/Drawing/LegacyCalls.h +++ b/src/source/Render/Drawing/LegacyCalls.h @@ -35,6 +35,8 @@ enum class LegacyCall : std::uint8_t EndSprite, BeginReorderableDraws, EndReorderableDraws, + BeginCharacterDraws, + EndCharacterDraws, // Argument: the edit flag. RenderTerrain, RenderWaterTerrain, @@ -70,4 +72,21 @@ class ScopedReorderableDraws ScopedReorderableDraws(const ScopedReorderableDraws&) = delete; ScopedReorderableDraws& operator=(const ScopedReorderableDraws&) = delete; }; + +// The draws in its lifetime are the characters (mu::IMuRenderer::BeginCharacterDraws), recorded with them when drawn +// later. +class ScopedCharacterDraws +{ +public: + ScopedCharacterDraws() + { + MakeLegacyCall(LegacyCall::BeginCharacterDraws, 0); + } + ~ScopedCharacterDraws() + { + MakeLegacyCall(LegacyCall::EndCharacterDraws, 0); + } + ScopedCharacterDraws(const ScopedCharacterDraws&) = delete; + ScopedCharacterDraws& operator=(const ScopedCharacterDraws&) = delete; +}; } // namespace Render::Drawing diff --git a/src/source/Render/Lighting/DynamicLight.h b/src/source/Render/Lighting/DynamicLight.h index fef9fc4baf..645be89113 100644 --- a/src/source/Render/Lighting/DynamicLight.h +++ b/src/source/Render/Lighting/DynamicLight.h @@ -22,6 +22,9 @@ struct DynamicLight int range = 0; // range in world units. float radius = 0.0f; + // Whether characters cast a shadow away from it: not for skill lights, whose glow runs along a + // beam or burst rather than from one point. + bool castsShadows = true; }; } // namespace Render::Lighting diff --git a/src/source/Render/Lighting/DynamicLightList.cpp b/src/source/Render/Lighting/DynamicLightList.cpp index 04259f1d99..296c4e3c4c 100644 --- a/src/source/Render/Lighting/DynamicLightList.cpp +++ b/src/source/Render/Lighting/DynamicLightList.cpp @@ -12,6 +12,12 @@ void DynamicLightList::Clear() m_displaceableBegin = kCapacity; m_displaceableEnd = kCapacity; m_marking = false; + m_mark = 0; +} + +void DynamicLightList::Mark() +{ + m_mark = m_count; } void DynamicLightList::MarkDisplaceable() @@ -41,6 +47,10 @@ void DynamicLightList::Add(const DynamicLight& light) std::move(m_lights.begin() + static_cast(m_displaceableEnd), m_lights.begin() + static_cast(m_count), m_lights.begin() + static_cast(m_displaceableEnd) - 1); + if (m_mark >= m_displaceableEnd) + { + --m_mark; + } --m_displaceableEnd; --m_count; m_marking = false; @@ -57,6 +67,11 @@ std::span DynamicLightList::Lights() const return {m_lights.data(), m_count}; } +std::span DynamicLightList::LightsSinceMark() const +{ + return Lights().subspan(m_mark); +} + DynamicLightList& FrameDynamicLights() { static DynamicLightList lights; diff --git a/src/source/Render/Lighting/DynamicLightList.h b/src/source/Render/Lighting/DynamicLightList.h index 21a09115ff..57b0376ec4 100644 --- a/src/source/Render/Lighting/DynamicLightList.h +++ b/src/source/Render/Lighting/DynamicLightList.h @@ -26,8 +26,12 @@ class DynamicLightList void MarkDisplaceable(); // Ends the lingering interval; later additions are called lights, never evictable. void EndDisplaceable(); + // Remembers where the lights added from now on start (WorldDynamicLights). + void Mark(); [[nodiscard]] std::span Lights() const; + // The lights added since Mark(), all of them without a mark. + [[nodiscard]] std::span LightsSinceMark() const; // Lights added this frame that did not fit. [[nodiscard]] std::size_t Overflow() const { @@ -42,6 +46,7 @@ class DynamicLightList std::size_t m_displaceableBegin = kCapacity; std::size_t m_displaceableEnd = kCapacity; bool m_marking = false; + std::size_t m_mark = 0; }; // The list the game's terrain light calls record into. diff --git a/src/source/Render/Lighting/DynamicLightSelection.cpp b/src/source/Render/Lighting/DynamicLightSelection.cpp index 3991f774d4..e9e2f0886e 100644 --- a/src/source/Render/Lighting/DynamicLightSelection.cpp +++ b/src/source/Render/Lighting/DynamicLightSelection.cpp @@ -6,6 +6,7 @@ #include #include #include +#include namespace Render::Lighting { @@ -51,6 +52,7 @@ void PackLight(const DynamicLight& light, std::size_t slot, mu::DynamicLightsUni uniform.color[slot][i] = std::max(light.color[i], 0.f); } uniform.positionAndRadius[slot][3] = light.radius; + uniform.color[slot][3] = light.castsShadows ? 1.f : 0.f; } } // namespace @@ -99,6 +101,23 @@ DynamicLightSelection SelectDynamicLights(std::span lights, return selection; } +DynamicLightSelection SelectDynamicLights(const DynamicLightSelection& pinned, + std::span laterLights, const float (&reference)[3]) +{ + const DynamicLightSelection later = SelectDynamicLights(laterLights, reference); + DynamicLightSelection selection = pinned; + const std::size_t pinnedCount = pinned.uniform.lightCount; + const std::size_t added = std::min(later.uniform.lightCount, mu::kMaxDynamicLights - pinnedCount); + std::memcpy(selection.uniform.positionAndRadius + pinnedCount, later.uniform.positionAndRadius, + added * sizeof(later.uniform.positionAndRadius[0])); + std::memcpy(selection.uniform.color + pinnedCount, later.uniform.color, added * sizeof(later.uniform.color[0])); + selection.uniform.lightCount = static_cast(pinnedCount + added); + selection.uniform.worldLightCount = static_cast(pinnedCount); + selection.brighteningLights += later.brighteningLights; + selection.dropped += later.brighteningLights - added; + return selection; +} + bool DroppedLightReportLimiter::ShouldReport(std::chrono::steady_clock::time_point now) { if (m_lastReport && now - *m_lastReport < kDroppedLightReportInterval) diff --git a/src/source/Render/Lighting/DynamicLightSelection.h b/src/source/Render/Lighting/DynamicLightSelection.h index 79562b681c..3491e1a0da 100644 --- a/src/source/Render/Lighting/DynamicLightSelection.h +++ b/src/source/Render/Lighting/DynamicLightSelection.h @@ -32,6 +32,12 @@ struct DynamicLightSelection [[nodiscard]] DynamicLightSelection SelectDynamicLights(std::span lights, const float (&reference)[3]); +// The pinned selection's lights first, as its worldLightCount lights, then the selection of the +// lights added after it in the slots left. +[[nodiscard]] DynamicLightSelection SelectDynamicLights(const DynamicLightSelection& pinned, + std::span laterLights, + const float (&reference)[3]); + // Shortest time between two log lines about dropped lights. inline constexpr std::chrono::minutes kDroppedLightReportInterval{1}; diff --git a/src/source/Render/Lighting/DynamicLightsSetting.cpp b/src/source/Render/Lighting/DynamicLightsSetting.cpp index 5b3dfc348f..c773d5785f 100644 --- a/src/source/Render/Lighting/DynamicLightsSetting.cpp +++ b/src/source/Render/Lighting/DynamicLightsSetting.cpp @@ -4,6 +4,11 @@ #include "Core/Utilities/Log/MuLogger.h" #include "Render/Lighting/EnhancedLightingSetting.h" +#include "Render/Look/LookProfileSetting.h" +#include "Render/Lighting/SunShadow.h" +#include "Render/Renderer/MuRenderer.h" +#include "World/MapInfra/MapManager.h" +#include "Scenes/SceneCore.h" namespace Render::Lighting { @@ -28,4 +33,41 @@ bool DynamicLightsActive() return s_dynamicLightsEnabled && EnhancedLightingActive(); } +namespace +{ +std::optional s_frameSun; +bool s_frameSunShadows = false; +} // namespace + +bool SunShadowsActive() +{ + return s_frameSunShadows; +} + +std::optional FrameSun() +{ + return s_frameSun; +} + +void UpdateFrameSun() +{ + s_frameSun.reset(); + s_frameSunShadows = false; + if (!DynamicLightsActive()) + { + return; + } + const float fall = gMapManager.InBattleCastle() ? kSunShadowFallBattleCastle : kSunShadowFall; + s_frameSun = FrameSunDirections{SunDirection(Render::Look::Value(Data::Maps::LookValue::GroundShadowAngle), fall), + SunDirection(kBakedSunShadowAngle, fall)}; + s_frameSunShadows = SceneFlag == MAIN_SCENE && + Render::Look::Value(Data::Maps::LookValue::SunShadowStrength) > 0.0 && + mu::GetRenderer().SunShadowsAvailable(); +} + +glm::vec3 FollowFrameSun(const glm::vec3& baked) +{ + return s_frameSun ? FollowSun(baked, s_frameSun->baked, s_frameSun->sun) : baked; +} + } // namespace Render::Lighting diff --git a/src/source/Render/Lighting/DynamicLightsSetting.h b/src/source/Render/Lighting/DynamicLightsSetting.h index f4225d1e63..db09b81690 100644 --- a/src/source/Render/Lighting/DynamicLightsSetting.h +++ b/src/source/Render/Lighting/DynamicLightsSetting.h @@ -1,5 +1,9 @@ #pragma once +#include + +#include + namespace Render::Lighting { @@ -12,4 +16,26 @@ void SetDynamicLightsEnabled(bool enabled); // draws Enhanced lighting. [[nodiscard]] bool DynamicLightsActive(); +// True when the sun's shadows come from the shadow map: in the game, with dynamic lights active, +// sun.shadow above 0 and a renderer that can draw it, taken once per frame (UpdateFrameSun). Characters then cast no +// flat sun shadow. +[[nodiscard]] bool SunShadowsActive(); + +// This frame's sun (towards it): from dynamic.shadowAngle and the map's shadow length, and the sun the +// map's baked light implies (kBakedSunShadowAngle). None without Enhanced dynamic lights (Classic). +// Taken once per frame (UpdateFrameSun), so every part of a frame sees the same sun. +struct FrameSunDirections +{ + glm::vec3 sun{0.0f, 0.0f, 1.0f}; + glm::vec3 baked{0.0f, 0.0f, 1.0f}; +}; +[[nodiscard]] std::optional FrameSun(); + +// Takes this frame's sun; called first thing each frame (InitTerrainLight). +void UpdateFrameSun(); + +// `baked` (a world-space light vector of the baked light) following this frame's sun (FollowSun); +// unchanged without one. +[[nodiscard]] glm::vec3 FollowFrameSun(const glm::vec3& baked); + } // namespace Render::Lighting diff --git a/src/source/Render/Lighting/LightMoodSetting.cpp b/src/source/Render/Lighting/LightMoodSetting.cpp index 8bb2567104..b01fabe3c3 100644 --- a/src/source/Render/Lighting/LightMoodSetting.cpp +++ b/src/source/Render/Lighting/LightMoodSetting.cpp @@ -3,7 +3,9 @@ #include "Render/Lighting/LightMoodSetting.h" #include "Core/Utilities/Log/MuLogger.h" +#include "Render/Lighting/DynamicLightsSetting.h" #include "Render/Look/LookProfileSetting.h" +#include "Render/Renderer/MuRenderer.h" #include "Render/Terrain/ZzzLodTerrain.h" #include "World/MapInfra/MapManager.h" @@ -28,6 +30,8 @@ struct State int world = NoWorld; std::uint32_t lookRevision = 0; Scales scales; + // Bumped whenever the scales change: the static light built with older ones is stale. + std::uint32_t revision = 0; }; State s_state; @@ -52,11 +56,24 @@ void LogScales(const char* event) void Recompute(int world) { + const Scales previous = s_state.scales; s_state.world = world; s_state.lookRevision = Look::Revision(); s_state.scales = s_state.enabled && IsWorldMap(world) ? Blend(s_state.data.ForWorld(world), s_state.strength, Look::Value(Data::Maps::LookValue::HighlightKnee)) : Scales{}; + // Where the sky fill tints the shade (the lit shaders, under sun shadows the renderer can draw), no + // second blue here. + if (s_state.enabled && IsWorldMap(world) && DynamicLightsActive() && + Look::Value(Data::Maps::LookValue::SunShadowStrength) > 0.0f && mu::GetRenderer().SunShadowsAvailable() && + Look::Value(Data::Maps::LookValue::SkyFill) > 0.0f) + { + s_state.scales.shadeCool = 0.f; + } + if (!(s_state.scales == previous)) + { + ++s_state.revision; + } } void RebuildStaticLight() @@ -135,4 +152,10 @@ void ScaleOwnHeroLight(float x, float y, const float classicLight[3], float ligh scales.shadowKeep > 0.f ? RequestStaticLightBrightWeight(x, y) : 0.f); } +std::uint32_t Revision() +{ + (void)Active(); + return s_state.revision; +} + } // namespace Render::Lighting::LightMood diff --git a/src/source/Render/Lighting/LightMoodSetting.h b/src/source/Render/Lighting/LightMoodSetting.h index 68bb2222ef..2947f77112 100644 --- a/src/source/Render/Lighting/LightMoodSetting.h +++ b/src/source/Render/Lighting/LightMoodSetting.h @@ -24,6 +24,10 @@ void UseMood(Data::Maps::LightMoodData data, bool enabled, int strengthPercent); // outside the world maps (login and character selection). const Scales& Active(); +// Changes whenever the active scales do (look values, the tint source): the map's static light built with +// an older one is stale. +[[nodiscard]] std::uint32_t Revision(); + // Logs the scales a map's static light was built with (map load and reload). void LogMapLight(); diff --git a/src/source/Render/Lighting/LightShadowCasters.cpp b/src/source/Render/Lighting/LightShadowCasters.cpp new file mode 100644 index 0000000000..bb59c667f6 --- /dev/null +++ b/src/source/Render/Lighting/LightShadowCasters.cpp @@ -0,0 +1,62 @@ +#include "Render/Lighting/LightShadowCasters.h" + +#include +#include + +namespace Render::Lighting +{ + +LightShadowCasters SelectLightShadowCasters(const mu::DynamicLightsUniform& lights, const float (&position)[3], + std::size_t maxCasters) +{ + struct Candidate + { + float contribution; + float fallAngle; + }; + std::array candidates{}; + std::size_t candidateCount = 0; + float total = 0.f; + + const std::size_t count = std::min(lights.worldLightCount, mu::kMaxDynamicLights); + for (std::size_t i = 0; i < count; ++i) + { + const float radius = lights.positionAndRadius[i][3]; + const float dx = position[0] - lights.positionAndRadius[i][0]; + const float dy = position[1] - lights.positionAndRadius[i][1]; + const float distance = std::sqrt(dx * dx + dy * dy); + if (radius <= 0.f || distance >= radius) + { + continue; + } + const float contribution = + (lights.color[i][0] + lights.color[i][1] + lights.color[i][2]) * (radius - distance) / radius; + total += contribution; + if (distance >= kOwnLightDistance && lights.color[i][3] > 0.f) + { + candidates[candidateCount++] = {contribution, std::atan2(dy, dx)}; + } + } + + LightShadowCasters result; + if (total <= 0.f) + { + return result; + } + const std::size_t wanted = std::min({maxCasters, kMaxLightShadowCasters, candidateCount}); + std::partial_sort(candidates.begin(), candidates.begin() + static_cast(wanted), + candidates.begin() + static_cast(candidateCount), + [](const Candidate& left, const Candidate& right) + { return left.contribution > right.contribution; }); + for (std::size_t i = 0; i < wanted; ++i) + { + const float strength = candidates[i].contribution / total; + if (strength >= kMinLightShadowStrength) + { + result.casters[result.count++] = {candidates[i].fallAngle, strength}; + } + } + return result; +} + +} // namespace Render::Lighting diff --git a/src/source/Render/Lighting/LightShadowCasters.h b/src/source/Render/Lighting/LightShadowCasters.h new file mode 100644 index 0000000000..706dc0ae9f --- /dev/null +++ b/src/source/Render/Lighting/LightShadowCasters.h @@ -0,0 +1,39 @@ +// LightShadowCasters.h: which of the frame's point lights cast a character's shadow on the ground. +#pragma once + +#include "Render/Renderer/SceneLighting.h" + +#include +#include + +namespace Render::Lighting +{ + +inline constexpr std::size_t kMaxLightShadowCasters = 4; + +// A shadow a point light casts: where it falls, in radians counter-clockwise from world +x (away +// from the light), and how strong it is: the light's share of the point light at the character. +struct LightShadowCaster +{ + float fallAngle = 0.f; + float strength = 0.f; +}; + +struct LightShadowCasters +{ + std::array casters{}; + std::size_t count = 0; +}; + +// Lights nearer the character than this (horizontally, in world units) cast none: they are its own. +inline constexpr float kOwnLightDistance = 50.f; +// Weaker shares cast none. +inline constexpr float kMinLightShadowStrength = 0.05f; + +// Up to `maxCasters` (at most kMaxLightShadowCasters) of the ground's lights (the first +// worldLightCount of `lights`) reaching `position`, strongest first. Every light reaching the +// character counts towards the shares, its own and skill lights (color w 0, which cast none) too. +[[nodiscard]] LightShadowCasters SelectLightShadowCasters(const mu::DynamicLightsUniform& lights, + const float (&position)[3], std::size_t maxCasters); + +} // namespace Render::Lighting diff --git a/src/source/Render/Lighting/ModelLight.cpp b/src/source/Render/Lighting/ModelLight.cpp new file mode 100644 index 0000000000..a95ecc943a --- /dev/null +++ b/src/source/Render/Lighting/ModelLight.cpp @@ -0,0 +1,49 @@ +#include "stdafx.h" + +#include "Render/Lighting/ModelLight.h" + +#include "Core/Math/ZzzMathLib.h" +#include "Render/Lighting/DynamicLightsSetting.h" +#include "Render/Lighting/LightMoodSetting.h" +#include "Render/Renderer/MuRenderer.h" +#include "Scenes/SceneCore.h" +#include "World/MapInfra/MapManager.h" + +namespace Render::Lighting +{ + +glm::vec3 ModelLightVector(bool highlight) +{ + vec3_t position; + vec3_t angle = {0.f, 0.f, 0.f}; + if (highlight) + { + Vector(1.3f, 0.f, 2.f, position); + } + else if (gMapManager.InBattleCastle()) + { + Vector(0.5f, -1.f, 1.f, position); + Vector(0.f, 0.f, -45.f, angle); + } + else + { + Vector(0.f, -1.5f, 0.f, position); + } + + // The light mood's sun scales the directional part of the model light. + LightMood::ScaleSunDirection(LightMood::Active(), position); + float matrix[3][4]; + AngleMatrix(angle, matrix); + vec3_t light; + VectorIRotate(position, matrix, light); + const glm::vec3 vector(light[0], light[1], light[2]); + // Models shown in the UI keep their light; in the world it follows the frame's sun. (The game draws + // every model with the highlight light.) + if (!FrameSun() || SceneFlag != MAIN_SCENE || mu::GetRenderer().InScreenSpaceSampling()) + { + return vector; + } + return FollowFrameSun(vector); +} + +} // namespace Render::Lighting diff --git a/src/source/Render/Lighting/ModelLight.h b/src/source/Render/Lighting/ModelLight.h new file mode 100644 index 0000000000..38162d6f91 --- /dev/null +++ b/src/source/Render/Lighting/ModelLight.h @@ -0,0 +1,16 @@ +// ModelLight.h: the directional light models are lit with, whatever format they come from. +#pragma once + +#include + +namespace Render::Lighting +{ + +// World-space vector towards the models' light; its length is the directional part's strength +// (Classic lights a face max(0.8 × dot(n, L) + 0.4, 0.2) with it), so the normals it meets must be +// world-oriented. `highlight`: the brighter light (BMD::HighLight, which the game always sets), otherwise +// the map's baked direction; scaled by the light mood's sun. With Enhanced dynamic lights, models in the +// world follow the frame's sun (FollowFrameSun); models shown in the UI keep theirs. +[[nodiscard]] glm::vec3 ModelLightVector(bool highlight); + +} // namespace Render::Lighting diff --git a/src/source/Render/Lighting/SunShadow.cpp b/src/source/Render/Lighting/SunShadow.cpp new file mode 100644 index 0000000000..3ee996d20a --- /dev/null +++ b/src/source/Render/Lighting/SunShadow.cpp @@ -0,0 +1,112 @@ +#include "Render/Lighting/SunShadow.h" + +#include + +#include +#include +#include +#include + +namespace Render::Lighting +{ +namespace +{ +// The box's size and depth move in these steps, so a walking camera keeps the same box (and the +// same texels) until it has gone far enough. +constexpr float kSizeStep = 256.0f; +constexpr float kDepthStep = 512.0f; + +// World to light space without translation: light-space x and y stay fixed in the world, so +// snapping them to texels keeps the shadows still while the camera moves. +glm::mat4 LightRotation(const glm::vec3& toSun) +{ + const glm::vec3 up = std::abs(toSun.z) > 0.99f ? glm::vec3(0.0f, 1.0f, 0.0f) : glm::vec3(0.0f, 0.0f, 1.0f); + return glm::lookAtRH(glm::vec3(0.0f), -toSun, up); +} +} // namespace + +glm::vec3 SunDirection(float fallAngleDegrees, float fallPerHeight) +{ + const float angle = glm::radians(fallAngleDegrees); + // Shadows fall away from the sun: it stands on the other side, fallPerHeight across per unit up. + return glm::normalize(glm::vec3(-std::cos(angle) * fallPerHeight, -std::sin(angle) * fallPerHeight, 1.0f)); +} + +glm::vec3 FollowSun(const glm::vec3& baked, const glm::vec3& bakedSun, const glm::vec3& sun) +{ + const float length = glm::length(baked); + if (sun == bakedSun || length == 0.0f) + { + return baked; + } + const auto azimuth = [](const glm::vec3& v) { return std::atan2(v.y, v.x); }; + const auto elevation = [](const glm::vec3& v) { return std::atan2(v.z, std::hypot(v.x, v.y)); }; + const float maxElevation = glm::radians(89.0f); + const float turned = azimuth(baked) + azimuth(sun) - azimuth(bakedSun); + const float raised = + std::clamp(elevation(baked) + elevation(sun) - elevation(bakedSun), -maxElevation, maxElevation); + return length * + glm::vec3(std::cos(raised) * std::cos(turned), std::cos(raised) * std::sin(turned), std::sin(raised)); +} + +SunShadowView BuildSunShadowView(const glm::vec3& toSun, const glm::mat4& sceneViewProjection, float groundLow, + float groundHigh, std::uint32_t resolution) +{ + const glm::dmat4 sceneFromClip = glm::inverse(glm::dmat4(sceneViewProjection)); + const auto unproject = [&](double x, double y, double z) + { + const glm::dvec4 point = sceneFromClip * glm::dvec4(x, y, z, 1.0); + return glm::dvec3(point) / point.w; + }; + + // Where the screen's corner rays cross the lowest and highest ground. + const glm::mat4 rotation = LightRotation(toSun); + glm::vec3 low(INFINITY); + glm::vec3 high(-INFINITY); + for (const double x : {-1.0, 1.0}) + { + for (const double y : {-1.0, 1.0}) + { + const glm::dvec3 nearPoint = unproject(x, y, 0.0); + const glm::dvec3 farPoint = unproject(x, y, 1.0); + const double rise = farPoint.z - nearPoint.z; + for (const float height : {groundLow, groundHigh}) + { + const double t = std::abs(rise) > 1e-6 ? std::clamp((height - nearPoint.z) / rise, 0.0, 1.0) : 1.0; + const glm::vec3 lightPoint = + glm::vec3(rotation * glm::vec4(glm::vec3(nearPoint + (farPoint - nearPoint) * t), 1.0f)); + low = glm::min(low, lightPoint); + high = glm::max(high, lightPoint); + } + } + } + + SunShadowView view; + SunShadowBox& box = view.box; + const float extent = (std::max)(high.x - low.x, high.y - low.y); + box.size = (std::floor(extent / kSizeStep) + 2.0f) * kSizeStep; + const float texel = box.size / static_cast((std::max)(resolution, 1u)); + box.origin = glm::floor(glm::vec2(low) / texel) * texel; + // The light looks down its -z: the nearest point to the sun has the largest z. + box.nearDistance = std::floor((-high.z - kSunShadowCasterHeight) / kDepthStep) * kDepthStep; + box.farDistance = std::ceil((-low.z + kDepthStep) / kDepthStep) * kDepthStep; + + const glm::mat4 projection = glm::orthoRH_ZO(box.origin.x, box.origin.x + box.size, box.origin.y, + box.origin.y + box.size, box.nearDistance, box.farDistance); + view.viewProjection = 2.0f * projection * rotation; + view.sunFromScene = glm::mat4(glm::dmat4(view.viewProjection) * sceneFromClip); + return view; +} + +FlatShadowCast FlatShadowFromSun(const glm::vec3& toSun, float maxFall) +{ + const float horizontal = std::hypot(toSun.x, toSun.y); + if (horizontal <= 0.0f) + { + return {0.0f, 0.0f}; + } + const float fall = toSun.z > 0.0f ? std::min(horizontal / toSun.z, maxFall) : maxFall; + return {std::atan2(toSun.y, toSun.x), fall}; +} + +} // namespace Render::Lighting diff --git a/src/source/Render/Lighting/SunShadow.h b/src/source/Render/Lighting/SunShadow.h new file mode 100644 index 0000000000..453a678b4d --- /dev/null +++ b/src/source/Render/Lighting/SunShadow.h @@ -0,0 +1,69 @@ +// SunShadow.h: the sun's direction and the shadow map's view around what the camera sees. +#pragma once + +#include + +#include + +namespace Render::Lighting +{ + +// How far a character's sun shadow falls per unit of its height: the body shadow shear's +// shearX / shearHeight (ZzzBMD.cpp, RenderBodyShadow). +inline constexpr float kSunShadowFall = 0.5f; +inline constexpr float kSunShadowFallBattleCastle = 0.625f; +// How far above the ground the shadow map still catches casters (trees, buildings, flying pets). +inline constexpr float kSunShadowCasterHeight = 3000.0f; + +// Unit vector towards the sun whose shadows fall towards `fallAngleDegrees` (counter-clockwise from +// world +x, as dynamic.shadowAngle) and `fallPerHeight` units per unit of height. +[[nodiscard]] glm::vec3 SunDirection(float fallAngleDegrees, float fallPerHeight); + +// The dynamic.shadowAngle the maps' baked light implies: its terrain sun, (0.5, -0.5, 0.5), stands at +// azimuth 315°, so shadows fall towards 135°. +inline constexpr float kBakedSunShadowAngle = 135.0f; + +// A baked light vector (the terrain's slope shading, the models' light) moved as far as the sun has +// moved from `bakedSun`, the sun the bake implies: its azimuth and elevation each change by the +// sun's, its length stays, and its elevation stays within ±89°. Exactly `baked` while the sun is +// `bakedSun`, so the maps keep their look at the baked angle. +[[nodiscard]] glm::vec3 FollowSun(const glm::vec3& baked, const glm::vec3& bakedSun, const glm::vec3& sun); + +// A flat (sheared) shadow cast by a light towards `toSun`: the projection's axis angle in radians +// (mu::ShadowProjection::axisAngle, the shadow's direction plus a half turn) and how far it falls per +// unit of height, at most `maxFall`. +struct FlatShadowCast +{ + float axisAngle = 0.0f; + float fallPerHeight = 0.0f; +}; +[[nodiscard]] FlatShadowCast FlatShadowFromSun(const glm::vec3& toSun, float maxFall); + +// The square, texel-snapped area of the shadow map: light-space x and y from `origin`, `size` wide, +// depth from `nearDistance` to `farDistance` along the sun's rays. +struct SunShadowBox +{ + glm::vec2 origin{}; + float size = 0.0f; + float nearDistance = 0.0f; + float farDistance = 0.0f; + + friend bool operator==(const SunShadowBox&, const SunShadowBox&) = default; +}; + +struct SunShadowView +{ + SunShadowBox box; + glm::mat4 viewProjection{1.0f}; + // viewProjection * inverse(the scene's view-projection): turns a draw's recorded scene matrix + // into its matrix from the sun. + glm::mat4 sunFromScene{1.0f}; +}; + +// The shadow map's view from the sun at `toSun` over the ground the camera sees between +// `groundLow` and `groundHigh`, at `resolution` texels a side. Clip w is 2 everywhere, so the +// vertex shaders' near-plane clip (w - 1) keeps every vertex. +[[nodiscard]] SunShadowView BuildSunShadowView(const glm::vec3& toSun, const glm::mat4& sceneViewProjection, + float groundLow, float groundHigh, std::uint32_t resolution); + +} // namespace Render::Lighting diff --git a/src/source/Render/Lighting/WorldDynamicLights.cpp b/src/source/Render/Lighting/WorldDynamicLights.cpp new file mode 100644 index 0000000000..b0336194b8 --- /dev/null +++ b/src/source/Render/Lighting/WorldDynamicLights.cpp @@ -0,0 +1,31 @@ +#include "Render/Lighting/WorldDynamicLights.h" + +#include "Render/Lighting/DynamicLightList.h" + +namespace Render::Lighting +{ + +void WorldDynamicLights::Clear() +{ + m_pinned = false; +} + +void WorldDynamicLights::Pin(DynamicLightList& lights, const float (&reference)[3]) +{ + if (m_pinned) + { + return; + } + m_selection = SelectDynamicLights(lights.Lights(), reference); + m_selection.uniform.worldLightCount = m_selection.uniform.lightCount; + lights.Mark(); + m_pinned = true; +} + +WorldDynamicLights& FrameWorldDynamicLights() +{ + static WorldDynamicLights lights; + return lights; +} + +} // namespace Render::Lighting diff --git a/src/source/Render/Lighting/WorldDynamicLights.h b/src/source/Render/Lighting/WorldDynamicLights.h new file mode 100644 index 0000000000..fb6d4c93aa --- /dev/null +++ b/src/source/Render/Lighting/WorldDynamicLights.h @@ -0,0 +1,40 @@ +// WorldDynamicLights.h: the frame's point lights the ground applies per pixel. +#pragma once + +#include "Render/Lighting/DynamicLightSelection.h" + +namespace Render::Lighting +{ + +class DynamicLightList; + +// The ground's vertex light leaves out exactly the lights pinned here and the ground's shader adds +// exactly these back per pixel, so they are chosen once per frame, before the ground is drawn, and +// kept even when lights added later would rank higher. Cleared with the frame's light list. +class WorldDynamicLights +{ +public: + void Clear(); + // Pins the selection SelectDynamicLights makes of `lights` at `reference`, all of them world lights + // (worldLightCount), and marks the list, + // so the lights added after it are told apart. A second call in the frame keeps the first pin. + void Pin(DynamicLightList& lights, const float (&reference)[3]); + + [[nodiscard]] bool IsPinned() const + { + return m_pinned; + } + [[nodiscard]] const DynamicLightSelection& Selection() const + { + return m_selection; + } + +private: + DynamicLightSelection m_selection{}; + bool m_pinned = false; +}; + +// The pin the game's ground and its point-light upload share. +[[nodiscard]] WorldDynamicLights& FrameWorldDynamicLights(); + +} // namespace Render::Lighting diff --git a/src/source/Render/Look/LookTuningCommand.cpp b/src/source/Render/Look/LookTuningCommand.cpp index 83c557a831..8fd09df7ff 100644 --- a/src/source/Render/Look/LookTuningCommand.cpp +++ b/src/source/Render/Look/LookTuningCommand.cpp @@ -27,7 +27,22 @@ const CommandForm CommandForms[] = { {L"$dynlights spell ", {LookValue::DynamicEffectGain, LookValue::DynamicEffectRange, LookValue::DynamicEffectFade}}, {L"$dynlights cap ", {LookValue::DynamicEffectCap}}, {L"$dynlights reach ", {LookValue::DynamicEffectRangeMax}}, + {L"$dynlights shadow ", {LookValue::GroundShadowOpacity}}, + {L"$dynlights shadowangle ", {LookValue::GroundShadowAngle}}, + {L"$dynlights shadowlights ", {LookValue::GroundShadowLights}}, + {L"$dynlights flatsun ", {LookValue::FlatSunShadow}}, {L"$bloom falloff ", {LookValue::BloomLevelFalloff}}, + {L"$ao radius ", {LookValue::AmbientOcclusionRadius}}, + {L"$clouds scale ", {LookValue::CloudScale}}, + {L"$clouds speed ", {LookValue::CloudSpeed}}, + {L"$clouds cover ", {LookValue::CloudCover}}, + {L"$clouds ", {LookValue::CloudStrength}}, + {L"$sky ", {LookValue::SkyFill}}, + {L"$rim sun ", {LookValue::RimSunFollow}}, + {L"$ao ", {LookValue::AmbientOcclusionStrength}}, + {L"$sun softness ", {LookValue::SunShadowSoftness}}, + {L"$sun resolution ", {LookValue::SunShadowResolution}}, + {L"$sun ", {LookValue::SunShadowStrength}}, {L"$bloom ", {LookValue::BloomStrength}}, }; diff --git a/src/source/Render/Look/LookTuningCommand.h b/src/source/Render/Look/LookTuningCommand.h index e78c3b7bce..4cad5588f9 100644 --- a/src/source/Render/Look/LookTuningCommand.h +++ b/src/source/Render/Look/LookTuningCommand.h @@ -28,8 +28,23 @@ // $dynlights spell dynamic.effectGain, .effectRange, .effectFade // $dynlights cap dynamic.effectCap // $dynlights reach dynamic.effectRangeMax +// $dynlights shadow dynamic.shadowOpacity +// $dynlights shadowangle dynamic.shadowAngle +// $dynlights shadowlights dynamic.shadowLights // $bloom falloff bloom.levelFalloff // $bloom bloom.strength +// $ao radius ao.radius +// $clouds scale clouds.scale +// $clouds speed clouds.speed +// $clouds cover clouds.cover +// $clouds clouds.strength +// $sky sky.fill +// $rim sun lighting.rim.sunFollow +// $ao ao.strength +// $sun softness sun.softness +// $sun resolution sun.resolution +// $sun sun.shadow +// $dynlights flatsun dynamic.flatSunShadow namespace Render::Look { diff --git a/src/source/Render/Look/TuningControls.cpp b/src/source/Render/Look/TuningControls.cpp index c78a7eefb2..28cbb150fe 100644 --- a/src/source/Render/Look/TuningControls.cpp +++ b/src/source/Render/Look/TuningControls.cpp @@ -58,12 +58,18 @@ constexpr std::array Specs = {{ TuningUnit::Seconds, 1.0, TuningZero::Immediate}, {TuningControlId::EffectCap, TuningGroup::DynamicLights, false, LookValue::DynamicEffectCap, 0.1, TuningUnit::None, 1.0, TuningZero::NoCap}, + {TuningControlId::ShadowOpacity, TuningGroup::DynamicLights, false, LookValue::GroundShadowOpacity, 0.05, + TuningUnit::Percent, 100.0, TuningZero::Plain}, + {TuningControlId::ShadowLights, TuningGroup::DynamicLights, false, LookValue::GroundShadowLights, 1.0, + TuningUnit::None, 1.0, TuningZero::Plain}, {TuningControlId::Wrap, TuningGroup::DynamicLights, true, LookValue::DynamicWrap, 0.05, TuningUnit::None, 1.0, TuningZero::Plain}, {TuningControlId::MapSmoothing, TuningGroup::DynamicLights, true, LookValue::DynamicMapSmoothing, 0.05, TuningUnit::Seconds, 1.0, TuningZero::Immediate}, {TuningControlId::EffectRangeMax, TuningGroup::DynamicLights, true, LookValue::DynamicEffectRangeMax, 1.0, TuningUnit::Cells, 1.0, TuningZero::NoCap}, + {TuningControlId::ShadowAngle, TuningGroup::DynamicLights, true, LookValue::GroundShadowAngle, 5.0, + TuningUnit::Degrees, 1.0, TuningZero::Plain}, {TuningControlId::MoodStrength, TuningGroup::LightMood, false, std::nullopt, 1.0, TuningUnit::Percent, 1.0, TuningZero::Plain}, {TuningControlId::BloomStrength, TuningGroup::PostProcessing, false, LookValue::BloomStrength, 0.05, @@ -72,6 +78,30 @@ constexpr std::array Specs = {{ TuningUnit::None, 1.0, TuningZero::Plain}, {TuningControlId::GradingStrength, TuningGroup::PostProcessing, false, LookValue::GradingStrength, 0.01, TuningUnit::Percent, 100.0, TuningZero::Plain}, + {TuningControlId::AmbientOcclusionStrength, TuningGroup::PostProcessing, false, LookValue::AmbientOcclusionStrength, + 0.05, TuningUnit::None, 1.0, TuningZero::Plain}, + {TuningControlId::AmbientOcclusionRadius, TuningGroup::PostProcessing, false, LookValue::AmbientOcclusionRadius, + 5.0, TuningUnit::None, 1.0, TuningZero::Plain}, + {TuningControlId::SunShadowStrength, TuningGroup::DynamicLights, false, LookValue::SunShadowStrength, 0.05, + TuningUnit::Percent, 100.0, TuningZero::Plain}, + {TuningControlId::SunShadowSoftness, TuningGroup::DynamicLights, true, LookValue::SunShadowSoftness, 0.1, + TuningUnit::None, 1.0, TuningZero::Plain}, + {TuningControlId::SunShadowResolution, TuningGroup::DynamicLights, true, LookValue::SunShadowResolution, 1024.0, + TuningUnit::None, 1.0, TuningZero::Plain}, + {TuningControlId::FlatSunShadow, TuningGroup::DynamicLights, true, LookValue::FlatSunShadow, 0.05, + TuningUnit::Percent, 100.0, TuningZero::Plain}, + {TuningControlId::CloudStrength, TuningGroup::DynamicLights, false, LookValue::CloudStrength, 0.05, + TuningUnit::Percent, 100.0, TuningZero::Plain}, + {TuningControlId::CloudScale, TuningGroup::DynamicLights, true, LookValue::CloudScale, 250.0, TuningUnit::None, + 1.0, TuningZero::Plain}, + {TuningControlId::CloudSpeed, TuningGroup::DynamicLights, true, LookValue::CloudSpeed, 5.0, TuningUnit::None, 1.0, + TuningZero::Plain}, + {TuningControlId::CloudCover, TuningGroup::DynamicLights, true, LookValue::CloudCover, 0.05, TuningUnit::Percent, + 100.0, TuningZero::Plain}, + {TuningControlId::SkyFill, TuningGroup::DynamicLights, false, LookValue::SkyFill, 0.05, TuningUnit::Percent, 100.0, + TuningZero::Plain}, + {TuningControlId::RimSunFollow, TuningGroup::DynamicLights, true, LookValue::RimSunFollow, 0.05, + TuningUnit::Percent, 100.0, TuningZero::Plain}, }}; constexpr bool SpecsFollowIdOrder() diff --git a/src/source/Render/Look/TuningControls.h b/src/source/Render/Look/TuningControls.h index 4e4896eee0..9559bb30e7 100644 --- a/src/source/Render/Look/TuningControls.h +++ b/src/source/Render/Look/TuningControls.h @@ -39,6 +39,7 @@ enum class TuningUnit : std::uint8_t // Terrain cells. Cells, Percent, + Degrees, }; // What a value of zero means for a control, where it is not simply none of it. @@ -66,13 +67,28 @@ enum class TuningControlId : std::uint8_t EffectRange, EffectFade, EffectCap, + ShadowOpacity, + ShadowLights, Wrap, MapSmoothing, EffectRangeMax, + ShadowAngle, MoodStrength, BloomStrength, BloomLevelFalloff, GradingStrength, + AmbientOcclusionStrength, + AmbientOcclusionRadius, + SunShadowStrength, + SunShadowSoftness, + SunShadowResolution, + FlatSunShadow, + CloudStrength, + CloudScale, + CloudSpeed, + CloudCover, + SkyFill, + RimSunFollow, Count, }; inline constexpr std::size_t TuningControlCount = static_cast(TuningControlId::Count); diff --git a/src/source/Render/Models/ModelDraw.h b/src/source/Render/Models/ModelDraw.h index a386ffab28..01b4f9ba1d 100644 --- a/src/source/Render/Models/ModelDraw.h +++ b/src/source/Render/Models/ModelDraw.h @@ -87,6 +87,14 @@ struct ClothShadow }; // One model's shadow projected on the ground: the call's arguments and the model state the draw reads. +// A shadow a point light casts, taken when the draw is described. +struct ShadowLightCast +{ + // Radians from world +x to the axis the shear acts along. + float axisAngle = 0.f; + float strength = 0.f; +}; + struct ShadowDraw { const BMD* model = nullptr; @@ -98,6 +106,13 @@ struct ShadowDraw // Set: the cloth casts the shadow instead of the meshes. std::span clothes; float alpha = 1.f; + // The shadow's fall and strength under the frame's sun, and what the frame's point lights cast. + float shearX = 2000.f; + float shearHeight = 4000.f; + float axisAngle = 0.f; + float flatStrength = 1.f; + ShadowLightCast lightCasts[4]; + int lightCastCount = 0; float bodyOrigin[3] = {}; float bodyScale = 1.f; diff --git a/src/source/Render/Models/ZzzBMD.cpp b/src/source/Render/Models/ZzzBMD.cpp index a1524276c4..1f24c6d622 100644 --- a/src/source/Render/Models/ZzzBMD.cpp +++ b/src/source/Render/Models/ZzzBMD.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -50,6 +51,12 @@ #include "Core/Utilities/FrameProfiler.h" #include "Scenes/MainScene.h" #include "Render/Lighting/LightMoodSetting.h" +#include "Render/Lighting/DynamicLightsSetting.h" +#include "Render/Lighting/ModelLight.h" +#include "Render/Lighting/SunShadow.h" +#include "Render/Lighting/LightShadowCasters.h" +#include "Render/Lighting/WorldDynamicLights.h" +#include "Render/Look/LookProfileSetting.h" using mu::PackABGR; @@ -611,27 +618,10 @@ void BMD::TransformCheap(float (*BoneMatrix)[3][4], const vec3_t BoundingBoxMin, if (LightEnable) { - vec3_t Position; - - float Matrix[3][4]; - if (HighLight) - { - Vector(1.3f, 0.f, 2.f, Position); - } - else if (gMapManager.InBattleCastle()) - { - Vector(0.5f, -1.f, 1.f, Position); - Vector(0.f, 0.f, -45.f, ShadowAngle); - } - else - { - Vector(0.f, -1.5f, 0.f, Position); - } - - // The light mood's sun scales the directional part of the model light. - Render::Lighting::LightMood::ScaleSunDirection(Render::Lighting::LightMood::Active(), Position); - AngleMatrix(ShadowAngle, Matrix); - VectorIRotate(Position, Matrix, m_LastLightPosition); // for RenderMesh's GPU-skinned in-shader lighting + // For RenderMesh's lighting, CPU and GPU-skinned: normals are world-oriented (the root bone + // carries the object's angle), so one world vector lights every model alike. + const glm::vec3 light = Render::Lighting::ModelLightVector(HighLight); + Vector(light.x, light.y, light.z, m_LastLightPosition); } // Release/gameplay OBB: from the caller-supplied bounding box args, not a vertex-loop-derived @@ -2531,8 +2521,9 @@ void BMD::RenderScriptedMesh(int mesh, int renderFlag, float alpha, int blendMes } } -__forceinline void CalcShadowPosition(vec3_t* position, const vec3_t origin, const float sx, const float sy) +__forceinline void CalcShadowPosition(vec3_t* position, const mu::ShadowProjection& projection) { + const float* origin = projection.origin; vec3_t result; VectorCopy(*position, result); @@ -2540,8 +2531,12 @@ __forceinline void CalcShadowPosition(vec3_t* position, const vec3_t origin, con // The result is the relative coordinate of the vertex to the origin. VectorSubtract(result, origin, result) - // scale the shadow in the x direction - result[0] += result[2] * (result[0] + sx) / (result[2] - sy); + // shear the shadow along its axis (x in Classic, where axisAngle is 0) + const float axis[2] = {std::cos(projection.axisAngle), std::sin(projection.axisAngle)}; + const float along = result[0] * axis[0] + result[1] * axis[1]; + const float shift = result[2] * (along + projection.shearX) / (result[2] - projection.shearHeight); + result[0] += shift * axis[0]; + result[1] += shift * axis[1]; // Add the origin again, to get the absolute coordinate of the vertex again VectorAdd(result, origin, result); @@ -2554,14 +2549,14 @@ __forceinline void CalcShadowPosition(vec3_t* position, const vec3_t origin, con } __forceinline void GetClothShadowPosition(vec3_t* target, const Render::ModelDrawing::ClothShadow& cloth, - const int index, const vec3_t origin, const float sx, const float sy) + const int index, const mu::ShadowProjection& projection) { VectorCopy(cloth.points[index], *target); - CalcShadowPosition(target, origin, sx, sy); + CalcShadowPosition(target, projection); } -void BMD::AddClothesShadowTriangles(std::span clothes, const float* origin, - const float sx, const float sy, const std::uint32_t color) const +void BMD::AddClothesShadowTriangles(std::span clothes, + const mu::ShadowProjection& projection, const std::uint32_t color) const { auto vertices = RenderArrayVertices; int target_vertex_index = -1; @@ -2584,10 +2579,10 @@ void BMD::AddClothesShadowTriangles(std::span(position), *static_cast(context)); +} -void ProjectOntoGround(float position[3], const void* context) +// The body shadow's shear axis: Classic's, or with Enhanced dynamic lights the map's shadow direction +// (dynamic.shadowAngle, where shadows fall; the shear axis points the other way). +float BodyShadowAxisAngle() { - const auto* ground = static_cast(context); - CalcShadowPosition(reinterpret_cast(position), ground->origin, ground->sx, ground->sy); + if (!Render::Lighting::DynamicLightsActive()) + { + return 0.f; + } + constexpr float RadiansPerDegree = 3.14159265358979f / 180.f; + return (Render::Look::Value(Data::Maps::LookValue::GroundShadowAngle) + 180.f) * RadiansPerDegree; } -// CalcShadowPosition's projection for skinned_shadow.vert. -mu::ShadowProjection BodyShadowProjection(const vec3_t origin, const float sx, const float sy) +// The frame's light on a shadow: its fall under the sun, how dark the flat shadow is, what the point lights cast. +void TakeShadowLight(Render::ModelDrawing::ShadowDraw& draw) { + draw.shearX = gMapManager.InBattleCastle() ? 2500.f : 2000.f; + draw.axisAngle = BodyShadowAxisAngle(); + // The sun shadow map shadows the ground itself; only the flat shadow is drawn without it, as dark + // as the map lets it be (dynamic.flatSunShadow: none indoors), falling away from the sun. + const std::optional sun = Render::Lighting::FrameSun(); + if (sun) + { + constexpr float MaxFlatShadowFall = 3.0f; + const Render::Lighting::FlatShadowCast cast = Render::Lighting::FlatShadowFromSun(sun->sun, MaxFlatShadowFall); + draw.axisAngle = cast.axisAngle; + draw.shearX = draw.shearHeight * cast.fallPerHeight; + } + const float flatSunShadow = sun ? Render::Look::Value(Data::Maps::LookValue::FlatSunShadow) : 1.f; + draw.flatStrength = Render::Lighting::SunShadowsActive() ? 0.f : flatSunShadow; + // The ground's strongest point lights cast one more shadow each, away from the light. + const Render::Lighting::WorldDynamicLights& worldLights = Render::Lighting::FrameWorldDynamicLights(); + if (Render::Lighting::DynamicLightsActive() && worldLights.IsPinned()) + { + static_assert(std::extent_v == Render::Lighting::kMaxLightShadowCasters); + const auto maxCasters = + static_cast(Render::Look::Value(Data::Maps::LookValue::GroundShadowLights)); + const Render::Lighting::LightShadowCasters casters = Render::Lighting::SelectLightShadowCasters( + worldLights.Selection().uniform, {draw.bodyOrigin[0], draw.bodyOrigin[1], draw.bodyOrigin[2]}, maxCasters); + constexpr float HalfTurn = 3.14159265358979f; + for (std::size_t i = 0; i < casters.count; ++i) + { + draw.lightCasts[i] = {casters.casters[i].fallAngle + HalfTurn, casters.casters[i].strength}; + } + draw.lightCastCount = static_cast(casters.count); + } +} + +// Where CalcShadowPosition and skinned_shadow.vert put a body shadow. +mu::ShadowProjection BodyShadowProjection(const Render::ModelDrawing::ShadowDraw& draw) +{ + const float* origin = draw.bodyOrigin; return { .origin = {origin[0], origin[1], origin[2]}, - .shearX = sx, - .shearHeight = sy, + .shearX = draw.shearX, + .shearHeight = draw.shearHeight, + .axisAngle = draw.axisAngle, .specialHeight = g_fSpecialHeight, .terrain = SceneFlag != SERVER_LIST_SCENE && SceneFlag != WEBZEN_SCENE && SceneFlag != LOADING_SCENE, }; @@ -2719,7 +2754,7 @@ void BMD::ProjectWeightedShadowMesh(const Render::ModelDrawing::ShadowDraw& draw } void BMD::AddWeightedMeshShadowTriangles(const Render::ModelDrawing::ShadowDraw& draw, const int startMesh, - const int endMesh, const float sx, const float sy, + const int endMesh, const mu::ShadowProjection& projection, const std::uint32_t color) const { constexpr std::size_t indexReach = std::size_t{std::numeric_limits::max()} + 1; @@ -2741,7 +2776,6 @@ void BMD::AddWeightedMeshShadowTriangles(const Render::ModelDrawing::ShadowDraw& batchIndices.clear(); }; - const ShadowGround ground{draw.bodyOrigin, sx, sy}; for (int i = startMesh; i < endMesh; i++) { if (i == draw.hiddenMesh) @@ -2754,7 +2788,7 @@ void BMD::AddWeightedMeshShadowTriangles(const Render::ModelDrawing::ShadowDraw& continue; } - ProjectWeightedShadowMesh(draw, i, ProjectOntoGround, &ground, meshVertices, meshIndices); + ProjectWeightedShadowMesh(draw, i, ProjectOntoGround, &projection, meshVertices, meshIndices); if (meshIndices.empty()) { continue; @@ -2821,8 +2855,8 @@ const vec3_t* BMD::ShadowVertices(const Render::ModelDrawing::ShadowDraw& draw, } void BMD::AddMeshShadowTriangles(const Render::ModelDrawing::ShadowDraw& draw, const int blendMesh, - const int hiddenMesh, const int startMesh, const int endMesh, const float* origin, - const float sx, const float sy, const std::uint32_t color) const + const int hiddenMesh, const int startMesh, const int endMesh, + const mu::ShadowProjection& projection, const std::uint32_t color) const { auto vertices = RenderArrayVertices; int target_vertex_index = -1; @@ -2851,7 +2885,7 @@ void BMD::AddMeshShadowTriangles(const Render::ModelDrawing::ShadowDraw& draw, c VectorCopy(positions[source_vertex_index], vertices[target_vertex_index]); - CalcShadowPosition(&vertices[target_vertex_index], origin, sx, sy); + CalcShadowPosition(&vertices[target_vertex_index], projection); } } } @@ -2872,7 +2906,7 @@ void BMD::AddMeshShadowTriangles(const Render::ModelDrawing::ShadowDraw& draw, c } bool BMD::RenderGpuMeshShadow(const Render::ModelDrawing::ShadowDraw& draw, const int startMesh, const int endMesh, - const float sx, const float sy, const std::uint32_t color) const + const mu::ShadowProjection& projection, const std::uint32_t color) const { if (!draw.skin.bones || startMesh < 0 || endMesh > NumMeshs || endMesh > MAX_MESH) { @@ -2946,11 +2980,11 @@ bool BMD::RenderGpuMeshShadow(const Render::ModelDrawing::ShadowDraw& draw, cons .restPoseScale = draw.skin.restPoseScale, .translate = draw.skin.translate, }; - return renderer.RenderCachedSkinnedShadow(key, color, skinning, BodyShadowProjection(draw.bodyOrigin, sx, sy)); + return renderer.RenderCachedSkinnedShadow(key, color, skinning, projection); } void BMD::RenderWeightedMeshShadow(const Render::ModelDrawing::ShadowDraw& draw, const int startMesh, const int endMesh, - const float sx, const float sy, const std::uint32_t color) const + const mu::ShadowProjection& projection, const std::uint32_t color) const { const auto* gltf = Render::Models::Gltf::SkinnedModelOf(*this); auto& renderer = mu::GetRenderer(); @@ -2958,7 +2992,7 @@ void BMD::RenderWeightedMeshShadow(const Render::ModelDrawing::ShadowDraw& draw, !renderer.SetTerrainHeights({BackTerrainHeight, Render::kTerrainCells}, {TerrainWall, Render::kTerrainCells}, TerrainHeightVersion())) { - AddWeightedMeshShadowTriangles(draw, startMesh, endMesh, sx, sy, color); + AddWeightedMeshShadowTriangles(draw, startMesh, endMesh, projection, color); return; } @@ -2973,7 +3007,6 @@ void BMD::RenderWeightedMeshShadow(const Render::ModelDrawing::ShadowDraw& draw, .restPoseScale = draw.skin.restPoseScale, .translate = draw.skin.translate, }; - const mu::ShadowProjection projection = BodyShadowProjection(draw.bodyOrigin, sx, sy); for (int i = startMesh; i < endMesh; i++) { if (i == draw.hiddenMesh || Meshs[i].NumTriangles <= 0 || Meshs[i].Texture == draw.blendMesh) @@ -2989,7 +3022,7 @@ void BMD::RenderWeightedMeshShadow(const Render::ModelDrawing::ShadowDraw& draw, // As RenderGpuMeshShadow: CPU vertices already skinned this frame draw their own shadow. if (!lodMesh && ShadowOwnsVertices(draw, i)) { - AddWeightedMeshShadowTriangles(draw, i, i + 1, sx, sy, color); + AddWeightedMeshShadowTriangles(draw, i, i + 1, projection, color); continue; } @@ -3000,7 +3033,7 @@ void BMD::RenderWeightedMeshShadow(const Render::ModelDrawing::ShadowDraw& draw, renderer.CacheWeightedSkinnedMesh(key, WeightedCorners(packed, 0.f, 0.f))); if (!cached || !renderer.RenderCachedSkinnedShadow(key, color, skinning, projection)) { - AddWeightedMeshShadowTriangles(draw, i, i + 1, sx, sy, color); + AddWeightedMeshShadowTriangles(draw, i, i + 1, projection, color); } } } @@ -3018,6 +3051,7 @@ void BMD::RenderBodyShadow(const int blendMesh, const int hiddenMesh, const int .lod = ActiveLod, .skin = CurrentSkin()}; VectorCopy(BodyOrigin, draw.bodyOrigin); + TakeShadowLight(draw); // The cloth's points as plain data: the draw reads no simulation, and a drawer that draws later copies them. static thread_local std::vector clothes; static thread_local std::vector> clothPoints; @@ -3097,25 +3131,36 @@ void BMD::DrawShadow(const Render::ModelDrawing::ShadowDraw& draw) const const auto [startMesh, endMesh] = ResolveMeshRange(NumMeshs, draw.startMesh, draw.endMesh); - const float sx = gMapManager.InBattleCastle() ? 2500.f : 2000.f; - const float sy = 4000.f; - const std::uint32_t shadowColor = PackABGR(0.f, 0.f, 0.f, std::clamp(draw.alpha, 0.f, 1.f)); - - if (draw.clothes.empty() && Render::Models::Gltf::SkinnedModelOf(*this)) - { - RenderWeightedMeshShadow(draw, startMesh, endMesh, sx, sy, shadowColor); - } - else if (draw.clothes.empty()) + mu::ShadowProjection projection = BodyShadowProjection(draw); + const auto drawShadow = [&](float shadowAlpha) { - if (!RenderGpuMeshShadow(draw, startMesh, endMesh, sx, sy, shadowColor)) + const std::uint32_t shadowColor = PackABGR(0.f, 0.f, 0.f, std::clamp(shadowAlpha, 0.f, 1.f)); + if (!draw.clothes.empty()) { - AddMeshShadowTriangles(draw, draw.blendMesh, draw.hiddenMesh, startMesh, endMesh, draw.bodyOrigin, sx, sy, - shadowColor); + AddClothesShadowTriangles(draw.clothes, projection, shadowColor); } + else if (Render::Models::Gltf::SkinnedModelOf(*this)) + { + RenderWeightedMeshShadow(draw, startMesh, endMesh, projection, shadowColor); + } + else if (!RenderGpuMeshShadow(draw, startMesh, endMesh, projection, shadowColor)) + { + AddMeshShadowTriangles(draw, draw.blendMesh, draw.hiddenMesh, startMesh, endMesh, projection, shadowColor); + } + }; + if (draw.flatStrength > 0.f) + { + const mu::ScopedGroundShadow groundShadow; + drawShadow(draw.alpha * draw.flatStrength); } - else + if (draw.lightCastCount > 0) { - AddClothesShadowTriangles(draw.clothes, draw.bodyOrigin, sx, sy, shadowColor); + const mu::ScopedGroundShadow lightShadow(mu::GroundShadowSource::PointLight); + for (int i = 0; i < draw.lightCastCount; ++i) + { + projection.axisAngle = draw.lightCasts[i].axisAngle; + drawShadow(draw.alpha * draw.lightCasts[i].strength); + } } EndRender(); diff --git a/src/source/Render/Models/ZzzBMD.h b/src/source/Render/Models/ZzzBMD.h index 2937ed1fb7..d79d16f05e 100644 --- a/src/source/Render/Models/ZzzBMD.h +++ b/src/source/Render/Models/ZzzBMD.h @@ -18,6 +18,11 @@ struct ShadowDraw; struct ClothShadow; } // namespace Render::ModelDrawing +namespace mu +{ +struct ShadowProjection; +} + struct BITMAP_t; extern const float (*g_pActiveBoneTransform)[3][4]; @@ -218,7 +223,6 @@ class BMD vec3_t BodyAngle; float BodyHeight; char StreamMesh; - vec3_t ShadowAngle; char Skin; bool HideSkin; float Velocity; @@ -495,8 +499,8 @@ class BMD // The shadow streams the renderer keeps for the meshes of this slot. void ReleaseShadowStreams(); - void AddClothesShadowTriangles(std::span clothes, const float* origin, - float sx, float sy, std::uint32_t color) const; + void AddClothesShadowTriangles(std::span clothes, const mu::ShadowProjection& projection, + std::uint32_t color) const; // Whether VertexTransform[mesh] holds this model's vertices now: skinned on the CPU, or written by the cloth. [[nodiscard]] bool OwnsCpuVertices(int mesh) const; // Whether a shadow casts a mesh's own CPU vertices instead of skinning it on the GPU. @@ -505,19 +509,18 @@ class BMD // mesh skinned from the draw's skin without writing the scratch (valid until the next call). [[nodiscard]] const vec3_t* ShadowVertices(const Render::ModelDrawing::ShadowDraw& draw, int mesh) const; void AddMeshShadowTriangles(const Render::ModelDrawing::ShadowDraw& draw, int blendMesh, int hiddenMesh, - int startMesh, int endMesh, const float* origin, float sx, float sy, - std::uint32_t color) const; + int startMesh, int endMesh, const mu::ShadowProjection& projection, std::uint32_t color) const; // The same shadow from a cached rest-pose stream skinned on the GPU; false leaves it to the CPU. [[nodiscard]] bool RenderGpuMeshShadow(const Render::ModelDrawing::ShadowDraw& draw, int startMesh, int endMesh, - float sx, float sy, std::uint32_t color) const; + const mu::ShadowProjection& projection, std::uint32_t color) const; // AddMeshShadowTriangles of a model file: the meshes' shadows // (ProjectWeightedShadowMesh) drawn indexed, in mesh and triangle order. void AddWeightedMeshShadowTriangles(const Render::ModelDrawing::ShadowDraw& draw, int startMesh, int endMesh, - float sx, float sy, std::uint32_t color) const; + const mu::ShadowProjection& projection, std::uint32_t color) const; // A model file's shadow, each mesh from the mesh its body draw caches on the GPU; a mesh the GPU cannot // draw gets its CPU shadow (AddWeightedMeshShadowTriangles). - void RenderWeightedMeshShadow(const Render::ModelDrawing::ShadowDraw& draw, int startMesh, int endMesh, float sx, - float sy, std::uint32_t color) const; + void RenderWeightedMeshShadow(const Render::ModelDrawing::ShadowDraw& draw, int startMesh, int endMesh, + const mu::ShadowProjection& projection, std::uint32_t color) const; }; extern BMD* Models; diff --git a/src/source/Render/PostProcessing/PostProcessingSetting.cpp b/src/source/Render/PostProcessing/PostProcessingSetting.cpp index fd4c92f15a..03da2d0dde 100644 --- a/src/source/Render/PostProcessing/PostProcessingSetting.cpp +++ b/src/source/Render/PostProcessing/PostProcessingSetting.cpp @@ -65,9 +65,10 @@ bool SetPostProcessingView(std::wstring_view name) void SubmitPostProcessingLook() { using Data::Maps::LookValue; - mu::GetRenderer().SetPostProcessingLook({Render::Look::Value(LookValue::BloomStrength), - Render::Look::Value(LookValue::BloomLevelFalloff), - Render::Look::Value(LookValue::GradingStrength)}); + mu::GetRenderer().SetPostProcessingLook( + {Render::Look::Value(LookValue::BloomStrength), Render::Look::Value(LookValue::BloomLevelFalloff), + Render::Look::Value(LookValue::GradingStrength), Render::Look::Value(LookValue::AmbientOcclusionStrength), + Render::Look::Value(LookValue::AmbientOcclusionRadius)}); } } // namespace Render::PostProcessing diff --git a/src/source/Render/Renderer/MuRenderer.h b/src/source/Render/Renderer/MuRenderer.h index 4ed8285b06..6e2e907d3e 100644 --- a/src/source/Render/Renderer/MuRenderer.h +++ b/src/source/Render/Renderer/MuRenderer.h @@ -70,6 +70,9 @@ struct PostProcessingLook float bloomStrength = 0.0f; float bloomLevelFalloff = 0.5f; float gradingStrength = 1.0f; + // Ambient occlusion: how much it darkens (0: none) and how far it looks, in world units. + float ambientOcclusionStrength = 0.0f; + float ambientOcclusionRadius = 60.0f; }; // --------------------------------------------------------------------------- @@ -183,12 +186,22 @@ struct SkinningParameters float normalMapScale = 0.0f; }; +// What casts a ground shadow (ScopedGroundShadow). +enum class GroundShadowSource : std::uint8_t +{ + Sun, // the map's light: darkens the ground's own light + PointLight, // a candle, fire or spell light: darkens the point lights +}; + // Where a body shadow lands, as CalcShadowPosition() puts it there. struct ShadowProjection { float origin[3]{}; float shearX = 0.0f; // sx float shearHeight = 0.0f; // sy + // Radians from world +x to the axis the shear acts along; shadows fall the opposite way. 0 is + // Classic (shadows towards -x). + float axisAngle = 0.0f; float specialHeight = 0.0f; // the height of TW_HEIGHT cells bool terrain = true; // false in the scenes where RequestTerrainHeight() returns 0 }; @@ -390,6 +403,11 @@ class IMuRenderer // The frame's point lights for Enhanced-lit draws (Enhanced dynamic lights). The last set in a // frame is the one all of that frame's draws use; set an empty block to turn them off. virtual void SetDynamicLights(const DynamicLightsUniform& /*lights*/) {} + // The terrain's direct sunlight per cell, 256x256 RGBA8 (Enhanced clouds dim only that part of the + // ground's light). Kept until replaced. + virtual void SetTerrainSunLight(std::span /*rgba*/) {} + // True between BeginScreenSpaceSampling and EndScreenSpaceSampling (3D models shown in the UI). + [[nodiscard]] virtual bool InScreenSpaceSampling() const { return false; } // Select Enhanced (per-pixel lighting and fog) or Classic pipelines for the following frames. // Returns false when Enhanced lighting was requested but this backend could not build it; the @@ -428,6 +446,30 @@ class IMuRenderer // does in Classic. Scopes nest; use ScopedBloomExclusion. virtual void BeginBloomExclusion() {} virtual void EndBloomExclusion() {} + + // 3D draws between BeginWorldLitGeometry and EndWorldLitGeometry are ground lit by the + // terrain light: with Enhanced lighting, the frame's first DynamicLightsUniform::worldLightCount + // point lights are added to their vertex colour per pixel. Scopes nest; use + // ScopedWorldLitGeometry. + virtual void BeginWorldLitGeometry() {} + virtual void EndWorldLitGeometry() {} + + // Draws between BeginGroundShadow and EndGroundShadow are shadows cast on the ground. In a frame + // with world-lit ground they darken it through a coverage mask instead (each pixel once, by + // DynamicLightsUniform::groundShadowOpacity): a sun shadow its own light, a point-light shadow + // its point light. Otherwise a sun shadow draws as recorded and a point-light shadow not at all. + // Scopes nest; use ScopedGroundShadow. + virtual void BeginGroundShadow(GroundShadowSource /*source*/) {} + virtual void EndGroundShadow(GroundShadowSource /*source*/) {} + // Draws between BeginCharacterDraws and EndCharacterDraws are the characters, apart from the world's + // objects. Scopes nest; use Render::Drawing::ScopedCharacterDraws. + virtual void BeginCharacterDraws() {} + virtual void EndCharacterDraws() {} + // Whether SetSceneLighting's sun shadow settings draw a shadow map. + [[nodiscard]] virtual bool SunShadowsAvailable() const + { + return false; + } // True while a bloom exclusion is open: what is queued now and drawn later // (a character's glow sprites) can be drawn inside one too. [[nodiscard]] virtual bool IsBloomExcluded() const @@ -862,6 +904,37 @@ class ScopedBloomExclusion ScopedBloomExclusion(const ScopedBloomExclusion&) = delete; ScopedBloomExclusion& operator=(const ScopedBloomExclusion&) = delete; }; +class ScopedWorldLitGeometry +{ +public: + ScopedWorldLitGeometry() + { + GetRenderer().BeginWorldLitGeometry(); + } + ~ScopedWorldLitGeometry() + { + GetRenderer().EndWorldLitGeometry(); + } + ScopedWorldLitGeometry(const ScopedWorldLitGeometry&) = delete; + ScopedWorldLitGeometry& operator=(const ScopedWorldLitGeometry&) = delete; +}; +class ScopedGroundShadow +{ +public: + explicit ScopedGroundShadow(GroundShadowSource source = GroundShadowSource::Sun) : m_source(source) + { + GetRenderer().BeginGroundShadow(source); + } + ~ScopedGroundShadow() + { + GetRenderer().EndGroundShadow(m_source); + } + ScopedGroundShadow(const ScopedGroundShadow&) = delete; + ScopedGroundShadow& operator=(const ScopedGroundShadow&) = delete; + +private: + GroundShadowSource m_source; +}; // The draws recorded in its lifetime may be reordered (BeginReorderableDraws). class ScopedReorderableDraws { diff --git a/src/source/Render/Renderer/MuRendererSDLGpu.cpp b/src/source/Render/Renderer/MuRendererSDLGpu.cpp index 1e10877624..db220fda21 100644 --- a/src/source/Render/Renderer/MuRendererSDLGpu.cpp +++ b/src/source/Render/Renderer/MuRendererSDLGpu.cpp @@ -38,6 +38,8 @@ #include "QuadTopology.h" #include "RangeAllocator.h" #include "SdlGpuPixelFormat.h" +#include "SdlGpuAmbientOcclusion.h" +#include "SdlGpuSunShadowMap.h" #include "SdlGpuPostProcessing.h" #include "SdlGpuReplayState.h" #include "SdlGpuValidation.h" @@ -47,6 +49,7 @@ #include "Core/Utilities/Log/MuLogger.h" #include "Render/PostProcessing/BloomSource.h" #include "Render/PostProcessing/SceneBoundary.h" +#include "Render/Lighting/SunShadow.h" #include "Render/Terrain/TerrainHeightGrid.h" #include "Render/Text/SdlTtfFontSet.h" #ifdef _EDITOR @@ -128,8 +131,11 @@ static_assert(offsetof(SkinningVertexUniforms, eyePositionAndSpecular) == 192, static_assert(offsetof(SkinningVertexUniforms, vertexToWorldRows) == 208, "vertexToWorldRows must follow eyePositionAndSpecular (HLSL cbuffer Skinning)"); -// skinned_lit.frag's normal map (t1, s1 in space2): bound for every draw with that shader. +// Slot 1 (t1, s1 in space2): skinned_lit.frag's normal map, bound for every draw with that shader, or +// world_lit.frag's ground shadow mask. constexpr Uint32 k_FragmentSamplerSlotNormalMap = 1u; +// Slot 2 (t2, s2 in space2): the sun shadow map of both lit shaders, bound once per pass (BindLitSamplers). +constexpr Uint32 k_FragmentSamplerSlotSunShadow = 2u; // The flat tangent-space normal (0, 0, 1) as RGBA8: the normal map of draws without one. constexpr Uint32 k_FlatNormalPixel = 0xFFFF8080u; // R = G = 128, B = A = 255 (little-endian RGBA) @@ -150,7 +156,7 @@ using WorldPipelines = Render::WorldPipelineSet s_singleSamplePipelines; static bool s_singleSamplePass = false; +// The HDR scene: with post-processing, the scene and bloom-source passes draw into float textures +// (kHdrSceneFormat), so additive light stacks above 1 and the composite rolls it off. Each pipeline +// those passes use maps to its twin built for that format; s_hdrScenePass makes ReplayDrawCommand +// use them. Empty when the device cannot render the format at the frame's sample count. +static constexpr SDL_GPUTextureFormat kHdrSceneFormat = SDL_GPU_TEXTUREFORMAT_R16G16B16A16_FLOAT; +static std::unordered_map s_hdrScenePipelines; +static bool s_hdrScenePass = false; +// The colour format CreatePipelines builds for instead of the swapchain's (INVALID: the swapchain's). +static SDL_GPUTextureFormat s_pipelineFormatOverride = SDL_GPU_TEXTUREFORMAT_INVALID; // Whether the built pipelines are multisampled; set by CreatePipelinesForSampleCount. static bool s_pipelinesMultisampled = false; +// Enhanced sun shadows: while s_sunShadowPass replays the scene into the shadow map, each draw's recorded +// scene matrix is turned into the sun's by s_sunFromScene. +static bool s_sunShadowPass = false; +// While the scene's solid draws are replayed depth-only into a single-sample depth (RenderSceneDepth). +static bool s_sceneDepthPass = false; +static glm::mat4 s_sunFromScene{1.0f}; + +// How a draw covers the sun shadow map (sun_depth.frag's coverageMode): solid with its alpha test, +// or a blended character part (wings, capes, auras) dithered by its alpha or, glowing, by its +// brightness, so the shadow's blur turns it into a partial shadow. Darkening blends cast none. +enum class SunCoverage : std::uint32_t +{ + None, + Solid, + Alpha, + Brightness, +}; + +[[nodiscard]] static SunCoverage GetSunCoverage(const RenderCmd& command) +{ + if (!command.blendEnabled) + return SunCoverage::Solid; + switch (command.blendMode) + { + case BlendMode::Alpha: + case BlendMode::Mixed: + return SunCoverage::Alpha; + case BlendMode::Additive: + case BlendMode::Glow: + case BlendMode::Luminance: + return SunCoverage::Brightness; + default: + return SunCoverage::None; + } +} + +// A draw's vertex uniforms in the sun shadow pass: its own, with the sun's matrix. +static void PushSunShadowVertexUniforms(const RenderCmd& command, bool skinned, Render::SdlGpuReplayState& state) +{ + if (skinned) + { + SkinningVertexUniforms uniforms = s_skinningUniforms[command.skinningIndex]; + uniforms.mvp = s_sunFromScene * uniforms.mvp; + PushReplayVertexUniforms(0, &uniforms, sizeof(uniforms), state); + return; + } + VertexUniforms uniforms = command.vu; + uniforms.mvp = s_sunFromScene * uniforms.mvp; + PushReplayVertexUniforms(0, &uniforms, sizeof(uniforms), state); +} + // Replays a recorded draw with `pipeline`: its own, or a variant of it for another pass. static void ReplayDrawCommand(const RenderCmd& command, SDL_GPUGraphicsPipeline* pipeline, bool boneDataReady, const SDL_Rect& scissor, Render::SdlGpuReplayState& state) @@ -1082,6 +1188,11 @@ static void ReplayDrawCommand(const RenderCmd& command, SDL_GPUGraphicsPipeline* const auto twin = s_singleSamplePipelines.find(pipeline); pipeline = twin != s_singleSamplePipelines.end() ? twin->second : nullptr; } + else if (s_hdrScenePass) + { + const auto twin = s_hdrScenePipelines.find(pipeline); + pipeline = twin != s_hdrScenePipelines.end() ? twin->second : nullptr; + } const bool skinned = command.type == RenderCmdType::DrawSkinnedTriangles; const bool shadow = skinned && command.shadowIndex != ~0u; if (!command.texture || !command.sampler || (skinned && (!boneDataReady || !s_boneGpuBuf)) || @@ -1090,7 +1201,9 @@ static void ReplayDrawCommand(const RenderCmd& command, SDL_GPUGraphicsPipeline* return; } - if (skinned) + if (s_sunShadowPass) + PushSunShadowVertexUniforms(command, skinned, state); + else if (skinned) PushReplayVertexUniforms(0, &s_skinningUniforms[command.skinningIndex], sizeof(SkinningVertexUniforms), state); else PushReplayVertexUniforms(0, &command.vu, sizeof(command.vu), state); @@ -1135,7 +1248,15 @@ static void ReplayDrawCommand(const RenderCmd& command, SDL_GPUGraphicsPipeline* } BindReplayFragmentSampler(command, state); - PushReplayFragmentUniforms(command.fogUniform, state); + if (s_sunShadowPass || s_sceneDepthPass) + { + // sun_depth.frag reads fogEnabled's slot as its coverage mode. + FogUniform coverage = command.fogUniform; + coverage.fogEnabled = static_cast(GetSunCoverage(command)) - 1u; + PushReplayFragmentUniforms(coverage, state); + } + else + PushReplayFragmentUniforms(command.fogUniform, state); if (command.type == RenderCmdType::DrawIndexedQuads || command.type == RenderCmdType::DrawIndexedStrip || command.trianglesIndexed) @@ -1168,6 +1289,11 @@ static std::vector s_textureUpdates; // Default white 1×1 texture used for textureId==0 and unknown IDs. static SDL_GPUTexture* s_whiteTexture = nullptr; + +static SDL_GPUTextureSamplerBinding GroundShadowMaskBinding() +{ + return {s_groundShadowMaskReady ? s_groundShadowMask : s_whiteTexture, s_defaultSampler}; +} // 1×1 flat normal map (k_FlatNormalPixel) bound to skinned_lit.frag for draws without a map. static SDL_GPUTexture* s_flatNormalTexture = nullptr; @@ -1183,11 +1309,26 @@ static SDL_GPUShader* s_vertShaderSkinnedShadow = nullptr; // skinned_shadow.ver static SDL_GPUShader* s_vertShaderSkinnedWeightedShadow = nullptr; // skinned_weighted_shadow.vert static SDL_GPUShader* s_fragShaderTexFog = nullptr; // basic_textured_fog.frag (Enhanced, optional) static SDL_GPUShader* s_fragShaderLit = nullptr; // skinned_lit.frag (Enhanced, optional) +static SDL_GPUShader* s_vertShaderWorldLit = nullptr; // world_lit.vert (Enhanced, optional) +static SDL_GPUShader* s_fragShaderWorldLit = nullptr; // world_lit.frag (Enhanced, optional) +static SDL_GPUShader* s_fragShaderShadowMask = nullptr; // shadow_mask.frag (optional) // Post-processing (optional): without them post-processing is unavailable. static SDL_GPUShader* s_vertShaderPostFullscreen = nullptr; // post_fullscreen.vert static SDL_GPUShader* s_fragShaderBloomDown = nullptr; // post_bloom_down.frag static SDL_GPUShader* s_fragShaderBloomUp = nullptr; // post_bloom_up.frag static SDL_GPUShader* s_fragShaderComposite = nullptr; // post_composite.frag +static SDL_GPUShader* s_fragShaderAmbientOcclusion = nullptr; // post_ao.frag +static SDL_GPUShader* s_fragShaderAmbientOcclusionBlur = nullptr; // post_ao_blur.frag +// The scene's ambient occlusion (one sample only), and the scene's projection it reconstructs from. +static mu::SdlGpuAmbientOcclusion s_ambientOcclusion; +static float s_sceneProjection[16]{}; +// Enhanced sun shadows (one sample): the shadow map's pipelines for 3D, skinned and glTF draws, and its +// textures. +static SDL_GPUGraphicsPipeline* s_sunShadowPipelines[3]{}; // [ShadowPassLayout] +// The same draws, unbiased, into the scene's single-sample depth (RenderSceneDepth). +static SDL_GPUGraphicsPipeline* s_sceneDepthPipelines[3]{}; // [ShadowPassLayout] +static SDL_GPUShader* s_fragShaderSunDepth = nullptr; // sun_depth.frag +static mu::SdlGpuSunShadowMap s_sunShadowMap; // Depth buffer texture for correct 3D depth testing. // Created in Init() at swapchain dimensions, recreated on window resize. @@ -1217,6 +1358,9 @@ static bool s_alphaCoverageDrawLogged = false; static Render::Antialiasing::SupportedSampleCounts s_supportedSampleCounts{}; static SDL_GPUTexture* s_multisampleColorTexture = nullptr; static SDL_GPUTextureCreateInfo s_multisampleColorInfo{}; +// The HDR scene's multisampled colour target (kHdrSceneFormat), while anti-aliasing is on. +static SDL_GPUTexture* s_hdrMultisampleColorTexture = nullptr; +static SDL_GPUTextureCreateInfo s_hdrMultisampleColorInfo{}; // The depth of a single-sample pass at the frame's size while the frame's own depth is multisampled. static SDL_GPUTexture* s_singleSampleDepthTexture = nullptr; static Uint32 s_singleSampleDepthW = 0u; @@ -2044,6 +2188,13 @@ class MuRendererSDLGpu : public IMuRenderer s_bitmapGpuResources.LastStage(), s_bitmapGpuResources.LastError()); } + ReleaseSunShadowResources(); + if (s_terrainSunLight) + { + SDL_ReleaseGPUTexture(s_device, s_terrainSunLight); + s_terrainSunLight = nullptr; + } + // Release the independently owned white fallback texture. if (s_whiteTexture) { @@ -2107,6 +2258,8 @@ class MuRendererSDLGpu : public IMuRenderer DestroySkinnedMeshCache(); DestroyPipelines(); ReleaseShaders(); + ReleaseGroundShadowMask(); + s_ambientOcclusion.Release(); s_postProcessing.Release(); SDL_ReleaseWindowFromGPUDevice(s_device, s_window); @@ -2183,6 +2336,12 @@ class MuRendererSDLGpu : public IMuRenderer s_bloomExclusionDepth); s_bloomExclusionDepth = 0; } + s_worldLitGeometryDepth = 0; + s_groundShadowDepth = 0; + s_characterDrawDepth = 0; + s_lightShadowDepth = 0; + s_frameHasWorldLit = false; + s_groundShadowMaskReady = false; s_replayedCmdCount = 0u; s_mainColorPassOpenedThisFrame = false; @@ -2296,6 +2455,9 @@ class MuRendererSDLGpu : public IMuRenderer { AllCommands, BloomSources, + GroundShadows, // the ground shadows, into the ground shadow mask + SunShadowCasters, // solid world draws, into the sun shadow map + SceneDepth, // the scene's solid draws, into a single-sample depth }; [[nodiscard]] static ReplayView FullFrameView() @@ -2340,6 +2502,68 @@ class MuRendererSDLGpu : public IMuRenderer return nullptr; } + // The vertex layout a shadow pass replays `command` with: 0 3D, 1 skinned, 2 weighted skinned (glTF). + [[nodiscard]] static int ShadowPassLayout(const RenderCmd& command) + { + return command.type != RenderCmdType::DrawSkinnedTriangles ? 0 + : command.vtxStride == sizeof(mu::SkinnedWeightedVertex3D) ? 2 + : 1; + } + + [[nodiscard]] static SDL_GPUGraphicsPipeline* GetGroundShadowMaskPipeline(const RenderCmd& command) + { + return s_groundShadowMaskPipelines[command.lightShadow ? 1 : 0][ShadowPassLayout(command)]; + } + + // A solid draw of the scene's world: depth-tested and depth-writing, not blended, not a ground shadow, + // not 2D; or a character's blended part (GetSunCoverage). Models drawn for the UI (their own view, + // Enhanced without the point lights) are left out. + [[nodiscard]] static bool IsSunShadowCaster(const RenderCmd& command) + { + if (command.groundShadow || !command.depthTestEnabled) + { + return false; + } + if (command.blendEnabled || !command.depthMaskEnabled) + { + const bool characterPart = command.characterDraw && command.type == RenderCmdType::DrawSkinnedTriangles && + command.blendEnabled && GetSunCoverage(command) != SunCoverage::None; + if (!characterPart) + { + return false; + } + } + if (command.type == RenderCmdType::DrawSkinnedTriangles) + { + return s_skinningUniforms[command.skinningIndex].palette[3] != k_SkinningLightingEnhanced; + } + return command.type != RenderCmdType::DrawTriangles2D && command.vtxStride == sizeof(Vertex3D); + } + + // The pipeline `command` replays with in a pass of `selection`, or null when it is not drawn there. + // Once the mask holds the ground shadows, the other passes leave them out. + [[nodiscard]] static SDL_GPUGraphicsPipeline* GetReplayPipeline(const RenderCmd& command, ReplaySelection selection) + { + if (selection == ReplaySelection::GroundShadows) + { + return command.groundShadow ? GetGroundShadowMaskPipeline(command) : nullptr; + } + if (selection == ReplaySelection::SceneDepth) + { + const bool solid = IsSunShadowCaster(command) && !command.blendEnabled && command.depthMaskEnabled; + return solid ? s_sceneDepthPipelines[ShadowPassLayout(command)] : nullptr; + } + if (selection == ReplaySelection::SunShadowCasters) + { + return IsSunShadowCaster(command) ? s_sunShadowPipelines[ShadowPassLayout(command)] : nullptr; + } + if (command.lightShadow || (command.groundShadow && s_groundShadowMaskReady)) + { + return nullptr; + } + return selection == ReplaySelection::BloomSources ? GetBloomSourcePipeline(command) : command.pipeline; + } + // Replays commands [begin, end) into s_renderPass, starting from `view`; // `view` ends as the last replayed command left it. static void ReplayCommands(std::size_t begin, std::size_t end, bool boneDataReady, ReplaySelection selection, @@ -2353,7 +2577,9 @@ class MuRendererSDLGpu : public IMuRenderer if (replayState.SelectScissor(view.scissor)) SDL_SetGPUScissor(s_renderPass, &view.scissor); - const bool bloomSourcesOnly = selection == ReplaySelection::BloomSources; + const bool allCommands = selection == ReplaySelection::AllCommands; + // The shadow map keeps its own viewport and scissor. + const bool ownView = selection == ReplaySelection::SunShadowCasters; for (std::size_t index = begin; index < end; ++index) { const RenderCmd& cmd = s_renderCmds[index]; @@ -2367,10 +2593,14 @@ class MuRendererSDLGpu : public IMuRenderer { continue; // already drawn into its own offscreen texture above } - if (!bloomSourcesOnly) + if (allCommands) { ++s_dbgRenderCmdsReplayedThisFrame; } + if (ownView && !IsDrawCommand(cmd.type)) + { + continue; + } switch (cmd.type) { @@ -2397,7 +2627,7 @@ class MuRendererSDLGpu : public IMuRenderer case RenderCmdType::DrawIndexedStrip: case RenderCmdType::DrawTriangles2D: { - SDL_GPUGraphicsPipeline* pipeline = bloomSourcesOnly ? GetBloomSourcePipeline(cmd) : cmd.pipeline; + SDL_GPUGraphicsPipeline* pipeline = GetReplayPipeline(cmd, selection); if (pipeline) { ReplayDrawCommand(cmd, pipeline, boneDataReady, view.scissor, replayState); @@ -2448,9 +2678,162 @@ class MuRendererSDLGpu : public IMuRenderer return false; } PushSceneLightingUniforms(); + BindLitSamplers(); return true; } + // The Enhanced-lit shaders' slot 2, the sun shadow map: this frame's once drawn, otherwise the far + // 1x1 map. Slot 1 is bound per draw (BindReplayFragmentSampler). + static void BindLitSamplers() + { + SDL_GPUTexture* const sunShadow = s_sunShadowMap.Bound(); + SDL_GPUSampler* const sunShadowSampler = s_sunShadowMap.Sampler(); + // Slot 3, the terrain's direct sunlight (world_lit reads it only while lightingParameters.y is 1). + SDL_GPUTexture* const terrainSun = s_terrainSunLight ? s_terrainSunLight : s_whiteTexture; + const SDL_GPUTextureSamplerBinding terrainSunBinding{terrainSun, s_defaultSampler}; + if (sunShadow && sunShadowSampler) + { + const SDL_GPUTextureSamplerBinding bindings[] = {{sunShadow, sunShadowSampler}, terrainSunBinding}; + SDL_BindGPUFragmentSamplers(s_renderPass, k_FragmentSamplerSlotSunShadow, bindings, 2); + } + else + { + SDL_BindGPUFragmentSamplers(s_renderPass, k_FragmentSamplerSlotSunShadow + 1, &terrainSunBinding, 1); + } + } + + // The ground shadow mask at the frame's size, recreated when that changed. Null when it fails. + [[nodiscard]] static SDL_GPUTexture* EnsureGroundShadowMask() + { + if (s_groundShadowMask && s_groundShadowMaskW == s_swapW && s_groundShadowMaskH == s_swapH) + { + return s_groundShadowMask; + } + ReleaseGroundShadowMask(); + SDL_GPUTextureCreateInfo maskInfo{}; + maskInfo.type = SDL_GPU_TEXTURETYPE_2D; + maskInfo.format = SDL_GPU_TEXTUREFORMAT_R8G8_UNORM; + maskInfo.width = s_swapW; + maskInfo.height = s_swapH; + maskInfo.layer_count_or_depth = 1; + maskInfo.num_levels = 1; + maskInfo.sample_count = SDL_GPU_SAMPLECOUNT_1; + maskInfo.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER; + s_groundShadowMask = SDL_CreateGPUTexture(s_device, &maskInfo); + if (!s_groundShadowMask) + { + mu::log::Get("render")->error("SDL_gpu -- ground shadow mask creation failed ({}x{}): {}", s_swapW, s_swapH, + SDL_GetError()); + return nullptr; + } + s_groundShadowMaskW = s_swapW; + s_groundShadowMaskH = s_swapH; + return s_groundShadowMask; + } + + static void ReleaseGroundShadowMask() + { + if (s_groundShadowMask) + { + SDL_ReleaseGPUTexture(s_device, s_groundShadowMask); + s_groundShadowMask = nullptr; + } + s_groundShadowMaskW = 0u; + s_groundShadowMaskH = 0u; + } + + // In a frame with world-lit ground, its shadows [0, end) into the ground shadow mask, after which + // the other passes leave them out. + static void RenderGroundShadowMask(std::size_t end, bool boneDataReady) + { + if (!s_frameHasWorldLit || !s_groundShadowMaskPipelines[0][0] || !EnsureGroundShadowMask()) + { + return; + } + SDL_GPUColorTargetInfo maskTarget{}; + maskTarget.texture = s_groundShadowMask; + maskTarget.clear_color = {1.0f, 1.0f, 1.0f, 1.0f}; + maskTarget.load_op = SDL_GPU_LOADOP_CLEAR; + maskTarget.store_op = SDL_GPU_STOREOP_STORE; + maskTarget.cycle = true; + s_renderPass = SDL_BeginGPURenderPass(s_cmdBuf, &maskTarget, 1, nullptr); + if (!s_renderPass) + { + return; + } + ReplayView view = FullFrameView(); + ReplayCommands(0u, end, boneDataReady, ReplaySelection::GroundShadows, view); + EndReplayPass(); + s_groundShadowMaskReady = true; + } + + // A depth-only pass into `depth`, cleared to the far plane. Null when it cannot begin. + [[nodiscard]] static SDL_GPURenderPass* BeginDepthOnlyPass(SDL_GPUTexture* depth) + { + SDL_GPUDepthStencilTargetInfo target{}; + target.texture = depth; + target.clear_depth = 1.0f; + target.load_op = SDL_GPU_LOADOP_CLEAR; + target.store_op = SDL_GPU_STOREOP_STORE; + target.stencil_load_op = SDL_GPU_LOADOP_DONT_CARE; + target.stencil_store_op = SDL_GPU_STOREOP_DONT_CARE; + target.cycle = true; + return SDL_BeginGPURenderPass(s_cmdBuf, nullptr, 0, &target); + } + + // The frame's sun shadow map: the scene's solid draws [0, end) seen from the sun. Without a request + // (SetSceneLighting) the map is released and the lit shaders read the far 1x1 one. + // shortcut: every solid draw is drawn again each frame, the map's still parts too; cache them + // apart from the characters if the pass shows up in the profile. + static void RenderSunShadowMap(std::size_t end, bool boneDataReady) + { + FRAME_PROFILE(SunShadow); + if (SDL_GPUTexture* const fallback = s_sunShadowMap.FallbackToClear()) + { + if ((s_renderPass = BeginDepthOnlyPass(fallback)) != nullptr) + { + EndReplayPass(); + s_sunShadowMap.MarkFallbackCleared(); + } + } + SDL_GPUTexture* const map = s_sunShadowMap.PrepareMap(); + if (!map || (s_renderPass = BeginDepthOnlyPass(map)) == nullptr) + { + return; + } + const int texels = static_cast(s_sunShadowMap.Resolution()); + const float size = static_cast(texels); + ReplayView view{{0.0f, 0.0f, size, size, 0.0f, 1.0f}, {0, 0, texels, texels}}; + s_sunShadowPass = true; + ReplayCommands(0u, end, boneDataReady, ReplaySelection::SunShadowCasters, view); + s_sunShadowPass = false; + EndReplayPass(); + s_sunShadowMap.MarkReady(); + } + + // The scene's depth for ambient occlusion: the frame's own with one sample; multisampled, which + // cannot be read, its solid draws [0, end) again into the single-sample pass depth. Null without. + [[nodiscard]] static SDL_GPUTexture* RenderSceneDepth(std::size_t end, bool boneDataReady) + { + if (!IsMultisampled()) + { + return s_depthTexture; + } + FRAME_PROFILE(SceneDepth); + SDL_GPUTexture* const depth = SingleSamplePassDepth(); + if (!depth || !s_sceneDepthPipelines[0] || !s_sceneDepthPipelines[1] || + (s_renderPass = BeginDepthOnlyPass(depth)) == nullptr) + { + return nullptr; + } + ReplayView view = FullFrameView(); + s_sceneDepthPass = true; + ReplayCommands(0u, end, boneDataReady, ReplaySelection::SceneDepth, view); + s_sceneDepthPass = false; + EndReplayPass(); + return depth; + } + static void EndReplayPass() { SDL_EndGPURenderPass(s_renderPass); @@ -2466,6 +2849,8 @@ class MuRendererSDLGpu : public IMuRenderer // Nothing reads depth after the pass; skip storing every sample of it. const SDL_GPUDepthStencilTargetInfo depthTarget = MakeDepthTarget(SDL_GPU_LOADOP_CLEAR, IsMultisampled() ? SDL_GPU_STOREOP_DONT_CARE : SDL_GPU_STOREOP_STORE); + RenderSunShadowMap(s_renderCmds.size(), boneDataReady); + RenderGroundShadowMask(s_renderCmds.size(), boneDataReady); if (!BeginReplayPass(colorTarget, depthTarget)) { return false; @@ -2521,7 +2906,7 @@ class MuRendererSDLGpu : public IMuRenderer depthInfo.layer_count_or_depth = 1; depthInfo.num_levels = 1; depthInfo.sample_count = SDL_GPU_SAMPLECOUNT_1; - depthInfo.usage = SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET; + depthInfo.usage = SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER; s_singleSampleDepthTexture = SDL_CreateGPUTexture(s_device, &depthInfo); if (!s_singleSampleDepthTexture) { @@ -2551,8 +2936,7 @@ class MuRendererSDLGpu : public IMuRenderer { constexpr SDL_FColor noLight{0.0f, 0.0f, 0.0f, 0.0f}; const SDL_GPUColorTargetInfo colorTarget = CycledTarget(mu::GetSdlGpuFrameColorTarget( - {s_postProcessing.GetBloomSourceTexture(), IsMultisampled() ? s_multisampleColorTexture : nullptr}, - noLight)); + {s_postProcessing.GetBloomSourceTexture(), SceneMultisampleTexture()}, noLight)); // The UI pass tests against the same depth, so it is kept. if (!BeginReplayPass(colorTarget, MakeDepthTarget(SDL_GPU_LOADOP_LOAD, SDL_GPU_STOREOP_STORE))) { @@ -2564,6 +2948,17 @@ class MuRendererSDLGpu : public IMuRenderer s_postProcessing.RenderBloom(s_cmdBuf, s_postProcessingLook.bloomLevelFalloff); } + // The multisampled colour target of the scene and bloom-source passes: the HDR one with the HDR + // scene; null with one sample. + [[nodiscard]] static SDL_GPUTexture* SceneMultisampleTexture() + { + if (!IsMultisampled()) + { + return nullptr; + } + return s_hdrScenePass ? s_hdrMultisampleColorTexture : s_multisampleColorTexture; + } + // The scene into the scene texture, its bloom, then the processed scene and // the UI on top of it into `destination`. [[nodiscard]] static bool ReplayPostProcessedFrame(SDL_GPUTexture* destination, std::size_t sceneEnd, @@ -2571,22 +2966,37 @@ class MuRendererSDLGpu : public IMuRenderer { SDL_GPUTexture* const multisampled = IsMultisampled() ? s_multisampleColorTexture : nullptr; ReplayView view = FullFrameView(); + RenderSunShadowMap(sceneEnd, boneDataReady); + RenderGroundShadowMask(sceneEnd, boneDataReady); + const bool sceneView = s_postProcessingView == mu::PostProcessingView::Scene; + // The scene texture's format says whether this frame's scene is HDR (EnsureTargets). + s_hdrScenePass = s_postProcessing.IsHdrScene(); // Its depth stays for the bloom and UI passes, which test against it as // the UI did when it shared the scene's pass. - const SDL_GPUColorTargetInfo sceneTarget = CycledTarget( - mu::GetSdlGpuFrameColorTarget({s_postProcessing.GetSceneTexture(), multisampled}, s_clearColor)); + const SDL_GPUColorTargetInfo sceneTarget = CycledTarget(mu::GetSdlGpuFrameColorTarget( + {s_postProcessing.GetSceneTexture(), SceneMultisampleTexture()}, s_clearColor)); if (!BeginReplayPass(sceneTarget, MakeDepthTarget(SDL_GPU_LOADOP_CLEAR, SDL_GPU_STOREOP_STORE))) { + s_hdrScenePass = false; return false; } ReplayCommands(0u, sceneEnd, boneDataReady, ReplaySelection::AllCommands, view); EndReplayPass(); - if (s_postProcessingLook.bloomStrength > 0.0f) + if (s_postProcessingLook.bloomStrength > 0.0f && s_postProcessing.EnsureBloomTargets()) { RenderBloomSources(sceneEnd, boneDataReady); } + s_hdrScenePass = false; + + SDL_GPUTexture* const sceneDepth = s_postProcessingLook.ambientOcclusionStrength > 0.0f && sceneView + ? RenderSceneDepth(sceneEnd, boneDataReady) + : nullptr; + SDL_GPUTexture* const ambientOcclusion = + sceneDepth ? s_ambientOcclusion.Render(s_cmdBuf, sceneDepth, {s_swapW, s_swapH}, s_sceneProjection, + s_postProcessingLook.ambientOcclusionRadius) + : nullptr; // The composite covers every pixel: the target's old content is not loaded. // A diagnostic view without its image this frame leaves black instead. @@ -2601,7 +3011,7 @@ class MuRendererSDLGpu : public IMuRenderer return false; } s_postProcessing.DrawComposite(s_cmdBuf, s_renderPass, {s_swapW, s_swapH}, s_postProcessingLook, - s_postProcessingView); + s_postProcessingView, ambientOcclusion); ReplayCommands(sceneEnd, s_renderCmds.size(), boneDataReady, ReplaySelection::AllCommands, view); EndReplayPass(); return true; @@ -2823,6 +3233,7 @@ class MuRendererSDLGpu : public IMuRenderer { // These passes render into single-sample textures (see s_singleSamplePipelines). PushSceneLightingUniforms(); + BindLitSamplers(); s_singleSamplePass = true; ReplayView view = FullFrameView(); ReplayCommands(startIdx, endIdx, boneDataReady, ReplaySelection::AllCommands, view); @@ -2981,13 +3392,24 @@ class MuRendererSDLGpu : public IMuRenderer std::optional replayScope(std::in_place, FrameProfiler::Pass::RendererReplay); const Render::PostProcessing::FrameSplit split = s_sceneBoundary.Split(s_renderCmds.size(), IsPostProcessingActive()); + // Passes that will not run this frame free their targets, whichever way the frame is drawn. + { + const bool scene = split.postProcessed && s_postProcessingView == mu::PostProcessingView::Scene; + if (!scene || s_postProcessingLook.ambientOcclusionStrength <= 0.0f) + s_ambientOcclusion.ReleaseTargets(); + // The bloom views show the bloom too. + if (!split.postProcessed || s_postProcessingLook.bloomStrength <= 0.0f) + s_postProcessing.ReleaseBloomTargets(); + } if (s_mainColorPassOpenedThisFrame && frameColorTexture == FrameColorTexture()) { // FlushRenderCommands already drew part of this frame into its target with one // sample: the rest follows the same way, without multisampling or post-processing. renderPassCompleted = ContinueFlushedFrame(frameColorTexture, boneDataReady); } - else if (split.postProcessed && s_postProcessing.EnsureTargets({s_swapW, s_swapH})) + else if (split.postProcessed && + s_postProcessing.EnsureTargets({s_swapW, s_swapH}, + UsesHdrScene() ? kHdrSceneFormat : SDL_GPU_TEXTUREFORMAT_INVALID)) { renderPassCompleted = ReplayPostProcessedFrame(frameColorTexture, split.sceneEnd, boneDataReady); } @@ -3641,6 +4063,46 @@ class MuRendererSDLGpu : public IMuRenderer } } + void BeginWorldLitGeometry() override + { + ++s_worldLitGeometryDepth; + } + + void EndWorldLitGeometry() override + { + if (s_worldLitGeometryDepth > 0) + { + --s_worldLitGeometryDepth; + } + } + + void BeginCharacterDraws() override + { + ++s_characterDrawDepth; + } + + void EndCharacterDraws() override + { + if (s_characterDrawDepth > 0) + { + --s_characterDrawDepth; + } + } + + void BeginGroundShadow(GroundShadowSource source) override + { + ++(source == GroundShadowSource::PointLight ? s_lightShadowDepth : s_groundShadowDepth); + } + + void EndGroundShadow(GroundShadowSource source) override + { + int& depth = source == GroundShadowSource::PointLight ? s_lightShadowDepth : s_groundShadowDepth; + if (depth > 0) + { + --depth; + } + } + [[nodiscard]] bool IsBloomExcluded() const override { return s_bloomExclusionDepth > 0; @@ -4978,8 +5440,74 @@ class MuRendererSDLGpu : public IMuRenderer fog.color[1] = m_fogUniform.fogColor[1]; fog.color[2] = m_fogUniform.fogColor[2]; s_sceneLightingUniform = PackSceneLightingUniform(lighting, fog); - // The scene sets its lighting right after its camera, so the model-view is the view. + s_sceneLightingUniform.lightingParameters[1] = s_terrainSunLight ? 1.0f : 0.0f; + // The scene sets its lighting right after its camera, so the model-view is the view and the + // projection the scene's. m_worldFromViewMatrix = glm::inverse(m_modelViewMatrix); + std::memcpy(s_sceneProjection, glm::value_ptr(m_projMatrix), sizeof(s_sceneProjection)); + const glm::mat4 viewProjection = m_projMatrix * m_modelViewMatrix; + + s_sunShadowMap.Cancel(); + if (lighting.sunShadowDarkness > 0.0f && SunShadowsAvailable()) + { + s_sunShadowMap.Request(lighting.sunShadowResolution); + const Uint32 resolution = s_sunShadowMap.Resolution(); + const glm::vec3 toSun(lighting.sunDirection[0], lighting.sunDirection[1], lighting.sunDirection[2]); + const Render::Lighting::SunShadowView sun = Render::Lighting::BuildSunShadowView( + toSun, viewProjection, lighting.groundLow, lighting.groundHigh, resolution); + s_sunFromScene = sun.sunFromScene; + std::memcpy(s_sceneLightingUniform.sunViewProjection, glm::value_ptr(sun.viewProjection), + sizeof(s_sceneLightingUniform.sunViewProjection)); + const float texel = 1.0f / static_cast(resolution); + s_sceneLightingUniform.sunShadowParameters[0] = lighting.sunShadowDarkness; + s_sceneLightingUniform.sunShadowParameters[1] = lighting.sunShadowSoftness; + s_sceneLightingUniform.sunShadowParameters[2] = texel; + s_sceneLightingUniform.sunShadowParameters[3] = sun.box.size * texel; + } + } + + [[nodiscard]] bool SunShadowsAvailable() const override + { + return s_enhancedLightingAvailable && s_sunShadowPipelines[0] && s_sunShadowPipelines[1] && + s_sunShadowMap.IsAvailable(); + } + + void SetTerrainSunLight(std::span rgba) override + { + if (rgba.size() != kTerrainSunLightSize * kTerrainSunLightSize * 4u || !s_device) + { + return; + } + if (!s_terrainSunLight) + { + SDL_GPUTextureCreateInfo info{}; + info.type = SDL_GPU_TEXTURETYPE_2D; + info.format = SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; + info.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER; + info.width = kTerrainSunLightSize; + info.height = kTerrainSunLightSize; + info.layer_count_or_depth = 1; + info.num_levels = 1; + info.sample_count = SDL_GPU_SAMPLECOUNT_1; + s_terrainSunLight = SDL_CreateGPUTexture(s_device, &info); + if (!s_terrainSunLight) + { + return; + } + } + DiscardQueuedTextureUpdates(s_terrainSunLight); + TextureUpdateCmd cmd{}; + cmd.gpuTexture = s_terrainSunLight; + cmd.pixelsCopy.assign(rgba.begin(), rgba.end()); + cmd.width = kTerrainSunLightSize; + cmd.height = kTerrainSunLightSize; + cmd.bytesPerRow = kTerrainSunLightSize * 4u; + s_textureUpdates.push_back(std::move(cmd)); + } + + [[nodiscard]] bool InScreenSpaceSampling() const override + { + return s_screenSpaceSamplingDepth > 0; } void SetDynamicLights(const DynamicLightsUniform& lights) override @@ -5235,6 +5763,7 @@ class MuRendererSDLGpu : public IMuRenderer shadowVu.projection[0] = shadow->shearX; shadowVu.projection[1] = shadow->shearHeight; shadowVu.projection[2] = shadow->terrain ? 1.0f : 0.0f; + shadowVu.projection[3] = shadow->axisAngle; } cmd.fogUniform = m_fogUniform; cmd.fogUniform.alphaToCoverage = coverage.alphaToCoverage ? 1u : 0u; @@ -5324,6 +5853,14 @@ class MuRendererSDLGpu : public IMuRenderer command.depthMaskEnabled = m_depthMaskEnabled; command.cullFaceEnabled = m_cullFaceEnabled; command.bloomExcluded = s_bloomExclusionDepth > 0; + command.lightShadow = s_lightShadowDepth > 0; + command.groundShadow = s_groundShadowDepth > 0 || command.lightShadow; + command.worldLit = s_worldLitGeometryDepth > 0; + command.characterDraw = s_characterDrawDepth > 0; + if (command.worldLit) + { + s_frameHasWorldLit = true; + } } // ----------------------------------------------------------------------- @@ -5345,7 +5882,9 @@ class MuRendererSDLGpu : public IMuRenderer [[nodiscard]] SDL_GPUGraphicsPipeline* GetActive3DPipeline() const { - const WorldPipelines& set = UsesEnhancedLighting() ? s_pipelines3DEnhancedFog : s_pipelines3D; + const WorldPipelines& set = !UsesEnhancedLighting() ? s_pipelines3D + : s_worldLitGeometryDepth > 0 ? s_pipelinesWorldLit + : s_pipelines3DEnhancedFog; return set.Select(static_cast(GetActivePipelineIndex()), m_depthTestEnabled, m_depthMaskEnabled, m_cullFaceEnabled && !s_disableD3D12Culling); } @@ -5631,8 +6170,19 @@ class MuRendererSDLGpu : public IMuRenderer s_fragShaderTexFog = createShader("basic_textured_fog", "frag", SDL_GPU_SHADERSTAGE_FRAGMENT, 1, 0, 2, /*fatal=*/false); // skinned_lit.frag also reads the frame's point lights, DynamicLights (b2). - // skinned_lit.frag samples the texture and the normal map (k_FragmentSamplerSlotNormalMap). - s_fragShaderLit = createShader("skinned_lit", "frag", SDL_GPU_SHADERSTAGE_FRAGMENT, 2, 0, 3, /*fatal=*/false); + // skinned_lit.frag samples the texture, the normal map (k_FragmentSamplerSlotNormalMap) and the sun + // shadow map (k_FragmentSamplerSlotSunShadow). + s_fragShaderLit = createShader("skinned_lit", "frag", SDL_GPU_SHADERSTAGE_FRAGMENT, 3, 0, 3, /*fatal=*/false); + // The ground lit per pixel: the Transform (b0) of basic_textured.vert, and the uniforms of skinned_lit.frag. + s_vertShaderWorldLit = createShader("world_lit", "vert", SDL_GPU_SHADERSTAGE_VERTEX, 0, 0, 1, /*fatal=*/false); + // world_lit.frag also samples the sun shadow map (s1) and the ground shadow mask (s2). + s_fragShaderWorldLit = + createShader("world_lit", "frag", SDL_GPU_SHADERSTAGE_FRAGMENT, 4, 0, 3, /*fatal=*/false); + s_fragShaderShadowMask = + createShader("shadow_mask", "frag", SDL_GPU_SHADERSTAGE_FRAGMENT, 0, 0, 0, /*fatal=*/false); + // Sun shadows: the draw's texture (t0) for its alpha test, FogUniforms (b0). + s_fragShaderSunDepth = + createShader("sun_depth", "frag", SDL_GPU_SHADERSTAGE_FRAGMENT, 1, 0, 1, /*fatal=*/false); // Post-processing — non-fatal: without them post-processing is unavailable. // Bloom passes: source texture (t0) and BloomUniforms (b0); composite: scene, bloom and @@ -5643,8 +6193,14 @@ class MuRendererSDLGpu : public IMuRenderer createShader("post_bloom_down", "frag", SDL_GPU_SHADERSTAGE_FRAGMENT, 1, 0, 1, /*fatal=*/false); s_fragShaderBloomUp = createShader("post_bloom_up", "frag", SDL_GPU_SHADERSTAGE_FRAGMENT, 1, 0, 1, /*fatal=*/false); + // The composite also reads the ambient occlusion and the bloom source (t3, t4). s_fragShaderComposite = - createShader("post_composite", "frag", SDL_GPU_SHADERSTAGE_FRAGMENT, 3, 0, 1, /*fatal=*/false); + createShader("post_composite", "frag", SDL_GPU_SHADERSTAGE_FRAGMENT, 5, 0, 1, /*fatal=*/false); + // Ambient occlusion: the depth (t0), and for the blur the occlusion (t1); AmbientOcclusion (b0). + s_fragShaderAmbientOcclusion = + createShader("post_ao", "frag", SDL_GPU_SHADERSTAGE_FRAGMENT, 1, 0, 1, /*fatal=*/false); + s_fragShaderAmbientOcclusionBlur = + createShader("post_ao_blur", "frag", SDL_GPU_SHADERSTAGE_FRAGMENT, 2, 0, 1, /*fatal=*/false); mu::log::Get("render")->info("SDL_gpu -- shaders loaded for driver: {}", driverName ? driverName : "unknown"); return true; @@ -5712,7 +6268,9 @@ class MuRendererSDLGpu : public IMuRenderer s_fragShaderLit = nullptr; } for (SDL_GPUShader** shader : - {&s_vertShaderPostFullscreen, &s_fragShaderBloomDown, &s_fragShaderBloomUp, &s_fragShaderComposite}) + {&s_vertShaderWorldLit, &s_fragShaderWorldLit, &s_fragShaderShadowMask, &s_vertShaderPostFullscreen, + &s_fragShaderBloomDown, &s_fragShaderBloomUp, &s_fragShaderComposite, &s_fragShaderAmbientOcclusion, + &s_fragShaderAmbientOcclusionBlur, &s_fragShaderSunDepth}) { if (*shader) { @@ -5730,6 +6288,7 @@ class MuRendererSDLGpu : public IMuRenderer { TwoDimensional, ThreeDimensional, + ThreeDimensionalWorldLit, // the 3D layout, with world_lit.vert Skinned, SkinnedWeighted, // SkinnedWeightedVertex3D, with skinned_weighted.vert SkinnedShadow, // the skinned layout, with skinned_shadow.vert @@ -5741,6 +6300,9 @@ class MuRendererSDLGpu : public IMuRenderer Textured, TexturedEnhancedFog, SkinnedLit, + WorldLit, + ShadowMask, + SunDepth, }; struct PipelineBuildDescription @@ -5754,6 +6316,12 @@ class MuRendererSDLGpu : public IMuRenderer bool cullFaceEnabled; FragmentShader fragmentShader = FragmentShader::Textured; bool alphaToCoverage = false; + // Into the ground shadow mask: one sample, no depth, instead of the frame's targets. + bool groundShadowMaskTarget = false; + // Into the sun shadow map: depth only, one sample, biased against self-shadowing. + bool sunShadowTarget = false; + // Into the scene's single-sample depth: depth only, one sample, unbiased. + bool sceneDepthTarget = false; }; // The world sets built together, and what a failed pipeline means for them. @@ -5795,6 +6363,8 @@ class MuRendererSDLGpu : public IMuRenderer FragmentShader::TexturedEnhancedFog, WorldSetFamily::EnhancedLighting}, {&s_pipelinesSkinnedWeightedLit, "skinned-weighted-lit", VertexLayout::SkinnedWeighted, FragmentShader::SkinnedLit, WorldSetFamily::EnhancedLighting}, + {&s_pipelinesWorldLit, "world-lit", VertexLayout::ThreeDimensionalWorldLit, FragmentShader::WorldLit, + WorldSetFamily::EnhancedLighting}, }; return sets; } @@ -5842,6 +6412,12 @@ class MuRendererSDLGpu : public IMuRenderer return s_fragShaderTexFog; case FragmentShader::SkinnedLit: return s_fragShaderLit; + case FragmentShader::WorldLit: + return s_fragShaderWorldLit; + case FragmentShader::ShadowMask: + return s_fragShaderShadowMask; + case FragmentShader::SunDepth: + return s_fragShaderSunDepth; case FragmentShader::Textured: break; } @@ -5856,6 +6432,12 @@ class MuRendererSDLGpu : public IMuRenderer return "basic_textured_fog.frag"; case FragmentShader::SkinnedLit: return "skinned_lit.frag"; + case FragmentShader::WorldLit: + return "world_lit.frag"; + case FragmentShader::ShadowMask: + return "shadow_mask.frag"; + case FragmentShader::SunDepth: + return "sun_depth.frag"; case FragmentShader::Textured: break; } @@ -5894,7 +6476,9 @@ class MuRendererSDLGpu : public IMuRenderer const SDL_GPUTextureFormat swapchainFmt = SDL_GetGPUSwapchainTextureFormat(s_device, s_window); SDL_GPUColorTargetDescription colorTargetDesc{}; - colorTargetDesc.format = swapchainFmt; + colorTargetDesc.format = description.groundShadowMaskTarget ? SDL_GPU_TEXTUREFORMAT_R8G8_UNORM + : s_pipelineFormatOverride != SDL_GPU_TEXTUREFORMAT_INVALID ? s_pipelineFormatOverride + : swapchainFmt; colorTargetDesc.blend_state = blendState; SDL_GPUVertexAttribute vertexAttribs[9]; @@ -5930,7 +6514,8 @@ class MuRendererSDLGpu : public IMuRenderer vtxBufDesc.pitch = sizeof(Vertex2D); numAttribs = 3; } - else if (description.vertexLayout == VertexLayout::ThreeDimensional) + else if (description.vertexLayout == VertexLayout::ThreeDimensional || + description.vertexLayout == VertexLayout::ThreeDimensionalWorldLit) { // Vertex3D mapped to the 2D shader's input locations: // location 0 (TEXCOORD0 → pos): float3 pos — shader reads float2 (x,y), z dropped @@ -6039,11 +6624,12 @@ class MuRendererSDLGpu : public IMuRenderer vtxInputState.num_vertex_attributes = numAttribs; SDL_GPUGraphicsPipelineTargetInfo targetInfo{}; - targetInfo.color_target_descriptions = &colorTargetDesc; - targetInfo.num_color_targets = 1; + const bool depthOnly = description.sunShadowTarget || description.sceneDepthTarget; + targetInfo.color_target_descriptions = depthOnly ? nullptr : &colorTargetDesc; + targetInfo.num_color_targets = depthOnly ? 0u : 1u; // Enable depth-stencil target so pipelines match // the render pass that now includes a depth buffer. - targetInfo.has_depth_stencil_target = true; + targetInfo.has_depth_stencil_target = !description.groundShadowMaskTarget; targetInfo.depth_stencil_format = mu::SdlGpuDepthFormat; // Back-face culling as the descriptor asks: on for opaque 3D geometry (depth write ON), @@ -6052,14 +6638,21 @@ class MuRendererSDLGpu : public IMuRenderer rasterState.fill_mode = SDL_GPU_FILLMODE_FILL; rasterState.cull_mode = description.cullFaceEnabled ? SDL_GPU_CULLMODE_BACK : SDL_GPU_CULLMODE_NONE; rasterState.front_face = SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE; + if (description.sunShadowTarget) + { + rasterState.enable_depth_bias = true; + rasterState.depth_bias_constant_factor = 2.0f; + rasterState.depth_bias_slope_factor = 2.0f; + } SDL_GPUGraphicsPipelineCreateInfo pipelineInfo{}; pipelineInfo.vertex_shader = - description.vertexLayout == VertexLayout::Skinned ? s_vertShaderSkinned - : description.vertexLayout == VertexLayout::SkinnedWeighted ? s_vertShaderSkinnedWeighted - : description.vertexLayout == VertexLayout::SkinnedShadow ? s_vertShaderSkinnedShadow - : description.vertexLayout == VertexLayout::SkinnedWeightedShadow ? s_vertShaderSkinnedWeightedShadow - : s_vertShader2D; + description.vertexLayout == VertexLayout::Skinned ? s_vertShaderSkinned + : description.vertexLayout == VertexLayout::SkinnedWeighted ? s_vertShaderSkinnedWeighted + : description.vertexLayout == VertexLayout::SkinnedShadow ? s_vertShaderSkinnedShadow + : description.vertexLayout == VertexLayout::SkinnedWeightedShadow ? s_vertShaderSkinnedWeightedShadow + : description.vertexLayout == VertexLayout::ThreeDimensionalWorldLit ? s_vertShaderWorldLit + : s_vertShader2D; pipelineInfo.fragment_shader = GetFragmentShader(description.fragmentShader); pipelineInfo.vertex_input_state = vtxInputState; pipelineInfo.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST; @@ -6069,7 +6662,9 @@ class MuRendererSDLGpu : public IMuRenderer pipelineInfo.props = 0; pipelineInfo.multisample_state.sample_count = - mu::GetSdlGpuSampleCount(s_sampleCount).value_or(SDL_GPU_SAMPLECOUNT_1); + description.groundShadowMaskTarget || depthOnly + ? SDL_GPU_SAMPLECOUNT_1 + : mu::GetSdlGpuSampleCount(s_sampleCount).value_or(SDL_GPU_SAMPLECOUNT_1); pipelineInfo.multisample_state.enable_alpha_to_coverage = description.alphaToCoverage; result.pipeline = SDL_CreateGPUGraphicsPipeline(s_device, &pipelineInfo); @@ -6087,15 +6682,18 @@ class MuRendererSDLGpu : public IMuRenderer static void LogPipelineFailure(const char* driverName, const PipelineBuildResult& result, bool required) { const PipelineBuildDescription& description = result.description; - const char* layoutName = description.vertexLayout == VertexLayout::TwoDimensional ? "2D" - : description.vertexLayout == VertexLayout::ThreeDimensional ? "3D" - : "skinned"; + const char* layoutName = description.vertexLayout == VertexLayout::TwoDimensional ? "2D" + : description.vertexLayout == VertexLayout::ThreeDimensional || + description.vertexLayout == VertexLayout::ThreeDimensionalWorldLit + ? "3D" + : "skinned"; const char* vertexShaderName = - description.vertexLayout == VertexLayout::Skinned ? "skinned_textured.vert" - : description.vertexLayout == VertexLayout::SkinnedWeighted ? "skinned_weighted.vert" - : description.vertexLayout == VertexLayout::SkinnedShadow ? "skinned_shadow.vert" - : description.vertexLayout == VertexLayout::SkinnedWeightedShadow ? "skinned_weighted_shadow.vert" - : "basic_textured.vert"; + description.vertexLayout == VertexLayout::Skinned ? "skinned_textured.vert" + : description.vertexLayout == VertexLayout::SkinnedWeighted ? "skinned_weighted.vert" + : description.vertexLayout == VertexLayout::SkinnedShadow ? "skinned_shadow.vert" + : description.vertexLayout == VertexLayout::SkinnedWeightedShadow ? "skinned_weighted_shadow.vert" + : description.vertexLayout == VertexLayout::ThreeDimensionalWorldLit ? "world_lit.vert" + : "basic_textured.vert"; const char* fragmentShaderName = GetFragmentShaderName(description.fragmentShader); const char* cullMode = description.cullFaceEnabled ? "back" : "none"; if (required) @@ -6311,6 +6909,7 @@ class MuRendererSDLGpu : public IMuRenderer static void DestroyPipelines() { + DestroyHdrScenePipelines(); DestroySingleSamplePipelines(); s_pipelinesMultisampled = false; DestroyEnhancedPipelines(); @@ -6328,6 +6927,33 @@ class MuRendererSDLGpu : public IMuRenderer } } } + for (auto& layouts : s_groundShadowMaskPipelines) + { + for (SDL_GPUGraphicsPipeline*& pipeline : layouts) + { + if (pipeline) + { + SDL_ReleaseGPUGraphicsPipeline(s_device, pipeline); + pipeline = nullptr; + } + } + } + for (SDL_GPUGraphicsPipeline*& pipeline : s_sceneDepthPipelines) + { + if (pipeline) + { + SDL_ReleaseGPUGraphicsPipeline(s_device, pipeline); + pipeline = nullptr; + } + } + for (SDL_GPUGraphicsPipeline*& pipeline : s_sunShadowPipelines) + { + if (pipeline) + { + SDL_ReleaseGPUGraphicsPipeline(s_device, pipeline); + pipeline = nullptr; + } + } DestroyAlphaCoveragePipelines(); s_postProcessing.DestroyPipelines(); } @@ -6449,6 +7075,8 @@ class MuRendererSDLGpu : public IMuRenderer } } CreateAlphaCoveragePipelines(); + CreateGroundShadowMaskPipelines(); + CreateSunShadowPipelines(); CreatePostProcessingPipelines(); if (!CreateSingleSamplePipelines()) { @@ -6463,12 +7091,148 @@ class MuRendererSDLGpu : public IMuRenderer { return false; } + CreateGroundShadowMaskPipelines(); + CreateSunShadowPipelines(); CreatePostProcessingPipelines(); } s_pipelinesMultisampled = s_sampleCount != Render::Antialiasing::OffSampleCount; + CreateHdrScenePipelines(); return true; } + // The HDR scene's twins of every pipeline the scene and bloom-source passes replay, built for + // kHdrSceneFormat at s_sampleCount (an alpha-to-coverage variant maps to the variant built for its + // twin). Optional: without a complete set the scene stays in the swapchain's format. + static void CreateHdrScenePipelines() + { + DestroyHdrScenePipelines(); + const SDL_GPUTextureUsageFlags usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER; + const SDL_GPUSampleCount sampleCount = mu::GetSdlGpuSampleCount(s_sampleCount).value_or(SDL_GPU_SAMPLECOUNT_1); + if (!SDL_GPUTextureSupportsFormat(s_device, kHdrSceneFormat, SDL_GPU_TEXTURETYPE_2D, usage) || + !SDL_GPUTextureSupportsSampleCount(s_device, kHdrSceneFormat, sampleCount)) + { + mu::log::Get("render")->info("SDL_gpu -- HDR scene unavailable at {}x: format unsupported", s_sampleCount); + return; + } + + const std::vector slots = ReplayPipelineSlots(); + std::vector frameFormat; + frameFormat.reserve(slots.size()); + for (SDL_GPUGraphicsPipeline** slot : slots) + { + frameFormat.push_back(*slot); + *slot = nullptr; + } + const bool enhancedLightingAvailable = s_enhancedLightingAvailable; + std::vector frameFormatCoverage; + frameFormatCoverage.swap(s_alphaCoveragePipelines); + + s_pipelineFormatOverride = kHdrSceneFormat; + const bool created = CreatePipelines(); + CreateAlphaCoveragePipelines(); + s_pipelineFormatOverride = SDL_GPU_TEXTUREFORMAT_INVALID; + + for (std::size_t i = 0; i < slots.size(); ++i) + { + if (frameFormat[i] && *slots[i]) + { + s_hdrScenePipelines[frameFormat[i]] = *slots[i]; + } + else if (*slots[i]) + { + SDL_ReleaseGPUGraphicsPipeline(s_device, *slots[i]); + } + *slots[i] = frameFormat[i]; + } + s_enhancedLightingAvailable = enhancedLightingAvailable; + // Both coverage lists were built for the same slots in the same order: pair them by slot. + for (const AlphaCoveragePipeline& hdr : s_alphaCoveragePipelines) + { + const auto original = std::ranges::find(frameFormatCoverage, hdr.opaque, &AlphaCoveragePipeline::opaque); + if (original != frameFormatCoverage.end()) + { + s_hdrScenePipelines[original->variant] = hdr.variant; + } + else + { + SDL_ReleaseGPUGraphicsPipeline(s_device, hdr.variant); + } + } + s_alphaCoveragePipelines.swap(frameFormatCoverage); + for (const AlphaCoveragePipeline& entry : s_alphaCoveragePipelines) + { + frameFormat.push_back(entry.variant); + } + + if (!created || !Render::SingleSampleTwinsComplete(frameFormat, s_hdrScenePipelines)) + { + mu::log::Get("render")->warn("SDL_gpu -- HDR scene pipelines incomplete at {}x; HDR scene off", + s_sampleCount); + DestroyHdrScenePipelines(); + return; + } + mu::log::Get("render")->info("SDL_gpu -- {} HDR scene pipelines at {}x", s_hdrScenePipelines.size(), + s_sampleCount); + } + + static void DestroyHdrScenePipelines() + { + std::unordered_set released; + for (const auto& [frameFormat, twin] : s_hdrScenePipelines) + { + if (twin && released.insert(twin).second) + { + SDL_ReleaseGPUGraphicsPipeline(s_device, twin); + } + } + s_hdrScenePipelines.clear(); + } + + // The HDR scene this frame: its pipelines, and with anti-aliasing its multisampled target. + [[nodiscard]] static bool UsesHdrScene() + { + return !s_hdrScenePipelines.empty() && (!IsMultisampled() || EnsureHdrMultisampleColorTexture()); + } + + [[nodiscard]] static bool EnsureHdrMultisampleColorTexture() + { + const SDL_GPUSampleCount sampleCount = mu::GetSdlGpuSampleCount(s_sampleCount).value_or(SDL_GPU_SAMPLECOUNT_1); + if (s_hdrMultisampleColorTexture && s_hdrMultisampleColorInfo.width == s_swapW && + s_hdrMultisampleColorInfo.height == s_swapH && s_hdrMultisampleColorInfo.sample_count == sampleCount) + { + return true; + } + ReleaseHdrMultisampleColorTexture(); + SDL_GPUTextureCreateInfo info{}; + info.type = SDL_GPU_TEXTURETYPE_2D; + info.format = kHdrSceneFormat; + info.usage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET; + info.width = s_swapW; + info.height = s_swapH; + info.layer_count_or_depth = 1; + info.num_levels = 1; + info.sample_count = sampleCount; + s_hdrMultisampleColorTexture = SDL_CreateGPUTexture(s_device, &info); + if (!s_hdrMultisampleColorTexture) + { + mu::log::Get("render")->error("SDL_gpu -- HDR multisampled colour target creation failed ({}x{}): {}", + s_swapW, s_swapH, SDL_GetError()); + return false; + } + s_hdrMultisampleColorInfo = info; + return true; + } + + static void ReleaseHdrMultisampleColorTexture() + { + if (s_hdrMultisampleColorTexture) + { + SDL_ReleaseGPUTexture(s_device, s_hdrMultisampleColorTexture); + s_hdrMultisampleColorTexture = nullptr; + } + s_hdrMultisampleColorInfo = {}; + } + // Every pipeline slot CreatePipelines() fills, in one fixed order. [[nodiscard]] static std::vector ReplayPipelineSlots() { @@ -6579,6 +7343,129 @@ class MuRendererSDLGpu : public IMuRenderer mu::GetSdlGpuSampleCount(s_sampleCount).value_or(SDL_GPU_SAMPLECOUNT_1)); mu::log::Get("render")->info("SDL_gpu -- post-processing {} at {}x", created ? "available" : "unavailable", s_sampleCount); + (void)s_ambientOcclusion.CreatePipelines( + s_device, {s_vertShaderPostFullscreen, s_fragShaderAmbientOcclusion, s_fragShaderAmbientOcclusionBlur}); + } + + // The pipelines replaying solid draws into the sun shadow map, with its comparison sampler and far + // 1x1 map. Optional: without them there are no sun shadows. + static void CreateSunShadowPipelines() + { + if (!s_fragShaderSunDepth) + { + return; + } + // Indexed by ShadowPassLayout. + const VertexLayout layouts[] = {VertexLayout::ThreeDimensional, VertexLayout::Skinned, + VertexLayout::SkinnedWeighted}; + for (std::size_t layout = 0; layout < 3; ++layout) + { + if (layout == 2 && !s_vertShaderSkinnedWeighted) + { + continue; + } + PipelineBuildDescription description{"sun-shadow", "opaque", k_PipelineDisabled, true, true, + layouts[layout], false, FragmentShader::SunDepth}; + description.sunShadowTarget = true; + PipelineBuildResult result = BuildBlendPipeline(SDL_GPUColorTargetBlendState{}, description); + s_sunShadowPipelines[layout] = result.pipeline; + if (result.pipeline) + { + description.setName = "scene-depth"; + description.sunShadowTarget = false; + description.sceneDepthTarget = true; + result = BuildBlendPipeline(SDL_GPUColorTargetBlendState{}, description); + s_sceneDepthPipelines[layout] = result.pipeline; + } + if (!result.pipeline) + { + const char* driver = SDL_GetGPUDeviceDriver(s_device); + LogPipelineFailure(driver ? driver : "unknown", result, false); + } + } + (void)s_sunShadowMap.CreateResources(s_device); + } + + static void ReleaseSunShadowResources() + { + s_sunShadowMap.Release(); + } + + // The ground shadow mask's pipelines (one sample, whatever s_sampleCount is). Optional: without them + // ground shadows draw as recorded. + static void CreateGroundShadowMaskPipelines() + { + const SDL_GPUTextureUsageFlags maskUsage = SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER; + if (!s_fragShaderShadowMask || !SDL_GPUTextureSupportsFormat(s_device, SDL_GPU_TEXTUREFORMAT_R8G8_UNORM, + SDL_GPU_TEXTURETYPE_2D, maskUsage)) + { + return; + } + // The darkest shadow wins: overlapping shadows darken a pixel once. + SDL_GPUColorTargetBlendState darkest{}; + darkest.src_color_blendfactor = SDL_GPU_BLENDFACTOR_ONE; + darkest.dst_color_blendfactor = SDL_GPU_BLENDFACTOR_ONE; + darkest.color_blend_op = SDL_GPU_BLENDOP_MIN; + darkest.src_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE; + darkest.dst_alpha_blendfactor = SDL_GPU_BLENDFACTOR_ONE; + darkest.alpha_blend_op = SDL_GPU_BLENDOP_MIN; + darkest.enable_blend = true; + darkest.enable_color_write_mask = true; + const char* deviceDriver = SDL_GetGPUDeviceDriver(s_device); + const auto build = [&](int lightShadow, int layout, const char* name) + { + PipelineBuildDescription description{name, + "darkest", + k_PipelineDisabled, + false, + false, + layout == 2 ? VertexLayout::SkinnedWeightedShadow + : layout == 1 ? VertexLayout::SkinnedShadow + : VertexLayout::ThreeDimensional, + false, + FragmentShader::ShadowMask}; + description.groundShadowMaskTarget = true; + darkest.color_write_mask = lightShadow ? SDL_GPU_COLORCOMPONENT_G : SDL_GPU_COLORCOMPONENT_R; + const PipelineBuildResult result = BuildBlendPipeline(darkest, description); + s_groundShadowMaskPipelines[lightShadow][layout] = result.pipeline; + if (!result.pipeline) + { + LogPipelineFailure(deviceDriver ? deviceDriver : "unknown", result, false); + } + }; + build(0, 0, "ground-shadow-mask-3d"); + build(1, 0, "ground-light-shadow-mask-3d"); + if (s_vertShaderSkinnedShadow) + { + build(0, 1, "ground-shadow-mask-skinned"); + build(1, 1, "ground-light-shadow-mask-skinned"); + } + if (s_vertShaderSkinnedWeightedShadow) + { + build(0, 2, "ground-shadow-mask-weighted"); + build(1, 2, "ground-light-shadow-mask-weighted"); + } + // All or none: once the mask is ready the scene leaves every ground shadow to it, so a shadow + // the mask cannot draw would vanish. Without them, ground shadows draw as recorded. + const bool skinnedComplete = + !s_vertShaderSkinnedShadow || (s_groundShadowMaskPipelines[0][1] && s_groundShadowMaskPipelines[1][1]); + const bool weightedComplete = !s_vertShaderSkinnedWeightedShadow || + (s_groundShadowMaskPipelines[0][2] && s_groundShadowMaskPipelines[1][2]); + if (!s_groundShadowMaskPipelines[0][0] || !s_groundShadowMaskPipelines[1][0] || !skinnedComplete || + !weightedComplete) + { + for (auto& layouts : s_groundShadowMaskPipelines) + { + for (SDL_GPUGraphicsPipeline*& pipeline : layouts) + { + if (pipeline) + { + SDL_ReleaseGPUGraphicsPipeline(s_device, pipeline); + pipeline = nullptr; + } + } + } + } } // Alpha-to-coverage variants for s_sampleCount; none with one sample. @@ -6652,6 +7539,7 @@ class MuRendererSDLGpu : public IMuRenderer } s_multisampleColorInfo = {}; ReleaseSingleSampleDepthTexture(); + ReleaseHdrMultisampleColorTexture(); } // The multisampled colour target for this frame's swapchain format, size @@ -6882,6 +7770,7 @@ class MuRendererSDLGpu : public IMuRenderer const SDL_Rect scissor{0, 0, static_cast(capture.width), static_cast(capture.height)}; SDL_SetGPUScissor(s_renderPass, &scissor); PushSceneLightingUniforms(); + BindLitSamplers(); s_singleSamplePass = true; Render::SdlGpuReplayState replayState; diff --git a/src/source/Render/Renderer/SceneLighting.cpp b/src/source/Render/Renderer/SceneLighting.cpp index 30eba330d8..4b49991b85 100644 --- a/src/source/Render/Renderer/SceneLighting.cpp +++ b/src/source/Render/Renderer/SceneLighting.cpp @@ -80,6 +80,18 @@ SceneLightingUniform PackSceneLightingUniform(const SceneLighting& lighting, con uniform.cameraPosition[0] = lighting.cameraPosition[0]; uniform.cameraPosition[1] = lighting.cameraPosition[1]; uniform.cameraPosition[2] = lighting.cameraPosition[2]; + uniform.cloudParameters[0] = lighting.cloudStrength; + uniform.cloudParameters[1] = 1.0f / std::max(lighting.cloudScale, 1.0f); + uniform.cloudParameters[2] = lighting.cloudCover; + uniform.cloudOffset[0] = lighting.cloudOffset[0]; + uniform.cloudOffset[1] = lighting.cloudOffset[1]; + // The clear sky's blue the shade turns towards. + constexpr float SkyTint[3] = {0.72f, 0.84f, 1.0f}; + CopyColor(SkyTint, uniform.skyFill); + uniform.skyFill[3] = lighting.skyFill; + NormalizeInto(lighting.sunDirection, uniform.sunTowards); + uniform.sunTowards[3] = lighting.rimSunFollow; + CopyColor(lighting.sunColor, uniform.sunColor); return uniform; } diff --git a/src/source/Render/Renderer/SceneLighting.h b/src/source/Render/Renderer/SceneLighting.h index 565557292d..e74def5ab1 100644 --- a/src/source/Render/Renderer/SceneLighting.h +++ b/src/source/Render/Renderer/SceneLighting.h @@ -45,6 +45,26 @@ struct SceneLighting float specularPower = kDefaultSpecularPower; // World-space camera position. float cameraPosition[3]{}; + // Enhanced sun shadows: the direction towards the sun, how much a shadow darkens (0: no shadow + // map), how many texels its edges blur over, the map's size in texels, and the heights between + // which the camera's view meets the ground. + float sunDirection[3]{0.0f, 0.0f, 1.0f}; + float sunShadowDarkness = 0.0f; + float sunShadowSoftness = 1.0f; + std::uint32_t sunShadowResolution = 2048; + float groundLow = 0.0f; + float groundHigh = 0.0f; + // Enhanced cloud shadows: how much a cloud dims the sun's light (0: none), the pattern's size in + // world units, the share of sky covered and the pattern's offset (drift and the sun's slant). + float cloudStrength = 0.0f; + float cloudScale = 3000.0f; + float cloudCover = 0.45f; + float cloudOffset[2]{}; + // How far the shade takes the sky's blue (0: not at all), and how far the rim light follows the sun. + float skyFill = 0.0f; + float rimSunFollow = 0.0f; + // The sun's colour. + float sunColor[3]{1.0f, 1.0f, 1.0f}; }; // The frame's fog as configured through IMuRenderer::SetFog() when the scene lighting was set. @@ -68,6 +88,14 @@ struct SceneLightingUniform float fogColor[4]; // rgb, w = 1 when the scene has fog float fogParameters[4]; // start, end, Enhanced density, unused float cameraPosition[4]; // xyz world space, w unused + float sunViewProjection[16]; // column-major, world to the sun shadow map's clip space + float sunShadowParameters[4]; // darkness (0: no shadow map), softness in texels, 1 / map size, texel size + float lightingParameters[4]; // unused, terrain sunlight grid bound, unused, unused + float cloudParameters[4]; // strength (0: no clouds), 1 / pattern size, sky cover, unused + float cloudOffset[4]; // xy: drift plus the sun's slant through the clouds, zw unused + float skyFill[4]; // rgb: the sky's tint of the shade, w: how far shade takes it + float sunTowards[4]; // xyz: towards the sun, w: how far the rim follows it + float sunColor[4]; // rgb: the sun's colour, w unused }; inline constexpr std::size_t kSceneLightingRegisterSize = 16; @@ -79,13 +107,22 @@ static_assert(offsetof(SceneLightingUniform, specularParameters) == 4 * kSceneLi static_assert(offsetof(SceneLightingUniform, fogColor) == 5 * kSceneLightingRegisterSize); static_assert(offsetof(SceneLightingUniform, fogParameters) == 6 * kSceneLightingRegisterSize); static_assert(offsetof(SceneLightingUniform, cameraPosition) == 7 * kSceneLightingRegisterSize); -static_assert(sizeof(SceneLightingUniform) == 8 * kSceneLightingRegisterSize); +static_assert(offsetof(SceneLightingUniform, sunViewProjection) == 8 * kSceneLightingRegisterSize); +static_assert(offsetof(SceneLightingUniform, sunShadowParameters) == 12 * kSceneLightingRegisterSize); +static_assert(offsetof(SceneLightingUniform, lightingParameters) == 13 * kSceneLightingRegisterSize); +static_assert(offsetof(SceneLightingUniform, cloudParameters) == 14 * kSceneLightingRegisterSize); +static_assert(offsetof(SceneLightingUniform, sunColor) == 18 * kSceneLightingRegisterSize); +static_assert(sizeof(SceneLightingUniform) == 19 * kSceneLightingRegisterSize); [[nodiscard]] SceneLightingUniform PackSceneLightingUniform(const SceneLighting& lighting, const SceneFog& fog); // Point lights on models light a face with saturate(dot(n, l) * (1 - wrap) + wrap): 0 is Lambert, // 0.5 (the built-in value) half-Lambert. Up to 0.5 a face turned away from the light gets nothing. inline constexpr float kDefaultDynamicWrap = 0.5f; +// How much a character's shadow darkens the world-lit ground's own light (the built-in value). +inline constexpr float kDefaultGroundShadowOpacity = 0.6f; +// Where characters' shadows fall, in degrees counter-clockwise from world +x: towards -x, as in Classic. +inline constexpr float kClassicGroundShadowAngle = 180.0f; // CPU mirror of the wrapped diffuse in skinned_lit.frag.hlsl's DynamicLighting(); the shader is the // implementation. [[nodiscard]] float WrappedDiffuse(float normalDotLight, float wrap); @@ -100,9 +137,12 @@ struct DynamicLightsUniform { std::uint32_t lightCount = 0; // lights used float wrap = kDefaultDynamicWrap; // see WrappedDiffuse() - std::uint32_t padding[2]{}; + // The first lights, which the ground's vertex colour leaves out (ScopedWorldLitGeometry). + std::uint32_t worldLightCount = 0; + // How much a ground shadow darkens the ground's own light, 0 to 1 (ScopedGroundShadow). + float groundShadowOpacity = 0.f; float positionAndRadius[kMaxDynamicLights][4]; // xyz world position, w radius in world units - float color[kMaxDynamicLights][4]; // rgb, w unused + float color[kMaxDynamicLights][4]; // rgb, w 1 when it casts character shadows }; static_assert(offsetof(DynamicLightsUniform, lightCount) == 0); diff --git a/src/source/Render/Renderer/SdlGpuAmbientOcclusion.cpp b/src/source/Render/Renderer/SdlGpuAmbientOcclusion.cpp new file mode 100644 index 0000000000..aaf5fc22f8 --- /dev/null +++ b/src/source/Render/Renderer/SdlGpuAmbientOcclusion.cpp @@ -0,0 +1,210 @@ +#include "SdlGpuAmbientOcclusion.h" + +#include "Core/Utilities/Log/MuLogger.h" + +#include +#include + +#include +#include + +namespace mu +{ +namespace +{ +// Three vertices cover the target with one triangle (post_fullscreen.vert.hlsl). +constexpr Uint32 FullscreenVertexCount = 3u; +constexpr SDL_GPUTextureFormat OcclusionFormat = SDL_GPU_TEXTUREFORMAT_R8_UNORM; + +SDL_GPUGraphicsPipeline* BuildPipeline(SDL_GPUDevice* device, SDL_GPUShader* vertexShader, + SDL_GPUShader* fragmentShader) +{ + SDL_GPUColorTargetDescription colorTarget{}; + colorTarget.format = OcclusionFormat; + + SDL_GPUGraphicsPipelineCreateInfo info{}; + info.vertex_shader = vertexShader; + info.fragment_shader = fragmentShader; + info.primitive_type = SDL_GPU_PRIMITIVETYPE_TRIANGLELIST; + info.rasterizer_state.fill_mode = SDL_GPU_FILLMODE_FILL; + info.rasterizer_state.cull_mode = SDL_GPU_CULLMODE_NONE; + info.rasterizer_state.front_face = SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE; + info.multisample_state.sample_count = SDL_GPU_SAMPLECOUNT_1; + info.target_info.color_target_descriptions = &colorTarget; + info.target_info.num_color_targets = 1; + return SDL_CreateGPUGraphicsPipeline(device, &info); +} + +SDL_GPUTexture* CreateTarget(SDL_GPUDevice* device, SdlGpuTargetSize size) +{ + SDL_GPUTextureCreateInfo info{}; + info.type = SDL_GPU_TEXTURETYPE_2D; + info.format = OcclusionFormat; + info.usage = SDL_GPU_TEXTUREUSAGE_SAMPLER | SDL_GPU_TEXTUREUSAGE_COLOR_TARGET; + info.width = size.width; + info.height = size.height; + info.layer_count_or_depth = 1u; + info.num_levels = 1u; + info.sample_count = SDL_GPU_SAMPLECOUNT_1; + return SDL_CreateGPUTexture(device, &info); +} + +void ReleaseTexture(SDL_GPUDevice* device, SDL_GPUTexture*& texture) +{ + if (texture) + { + SDL_ReleaseGPUTexture(device, texture); + texture = nullptr; + } +} + +void ReleasePipeline(SDL_GPUDevice* device, SDL_GPUGraphicsPipeline*& pipeline) +{ + if (pipeline) + { + SDL_ReleaseGPUGraphicsPipeline(device, pipeline); + pipeline = nullptr; + } +} +} // namespace + +bool SdlGpuAmbientOcclusion::CreatePipelines(SDL_GPUDevice* device, const SdlGpuAmbientOcclusionShaders& shaders) +{ + if (m_device && m_device != device) + { + // Handles of an earlier device, destroyed with it: forget them. + *this = SdlGpuAmbientOcclusion{}; + } + DestroyPipelines(); + if (!device || !shaders.fullscreenVertex || !shaders.occlusion || !shaders.blur) + { + return false; + } + m_device = device; + m_occlusionPipeline = BuildPipeline(device, shaders.fullscreenVertex, shaders.occlusion); + m_blurPipeline = BuildPipeline(device, shaders.fullscreenVertex, shaders.blur); + if (!m_pointSampler) + { + SDL_GPUSamplerCreateInfo info{}; + info.min_filter = SDL_GPU_FILTER_NEAREST; + info.mag_filter = SDL_GPU_FILTER_NEAREST; + info.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_NEAREST; + info.address_mode_u = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + info.address_mode_v = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + info.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + m_pointSampler = SDL_CreateGPUSampler(device, &info); + } + if (!IsAvailable()) + { + log::Get("render")->warn("SDL_gpu -- ambient occlusion unavailable: {}", SDL_GetError()); + DestroyPipelines(); + return false; + } + return true; +} + +void SdlGpuAmbientOcclusion::DestroyPipelines() +{ + ReleasePipeline(m_device, m_occlusionPipeline); + ReleasePipeline(m_device, m_blurPipeline); +} + +bool SdlGpuAmbientOcclusion::IsAvailable() const +{ + return m_occlusionPipeline && m_blurPipeline && m_pointSampler; +} + +SDL_GPUTexture* SdlGpuAmbientOcclusion::Render(SDL_GPUCommandBuffer* commandBuffer, SDL_GPUTexture* depth, + SdlGpuTargetSize size, const float (&projection)[16], float radius) +{ + if (!IsAvailable() || !depth || !EnsureTargets(size)) + { + return nullptr; + } + + SdlGpuAmbientOcclusionUniform uniform{}; + const glm::mat4 projectionMatrix = glm::make_mat4(projection); + std::memcpy(uniform.projection, projection, sizeof(uniform.projection)); + std::memcpy(uniform.inverseProjection, glm::value_ptr(glm::inverse(projectionMatrix)), + sizeof(uniform.inverseProjection)); + uniform.depthTexelSize[0] = 1.0f / static_cast(size.width); + uniform.depthTexelSize[1] = 1.0f / static_cast(size.height); + uniform.radius = radius; + + const SDL_GPUTextureSamplerBinding occlusionInputs[] = {{depth, m_pointSampler}}; + if (!RunPass(commandBuffer, m_occlusionPipeline, m_occlusion, occlusionInputs, 1u, uniform)) + { + return nullptr; + } + const SDL_GPUTextureSamplerBinding blurInputs[] = {{depth, m_pointSampler}, {m_occlusion, m_pointSampler}}; + return RunPass(commandBuffer, m_blurPipeline, m_blurred, blurInputs, 2u, uniform) ? m_blurred : nullptr; +} + +void SdlGpuAmbientOcclusion::Release() +{ + DestroyPipelines(); + ReleaseTargets(); + if (m_pointSampler) + { + SDL_ReleaseGPUSampler(m_device, m_pointSampler); + m_pointSampler = nullptr; + } + m_device = nullptr; +} + +bool SdlGpuAmbientOcclusion::EnsureTargets(SdlGpuTargetSize size) +{ + const SdlGpuTargetSize half{std::max(size.width / 2u, 1u), std::max(size.height / 2u, 1u)}; + if (m_occlusion && m_size.width == half.width && m_size.height == half.height) + { + return true; + } + ReleaseTargets(); + m_occlusion = CreateTarget(m_device, half); + m_blurred = CreateTarget(m_device, half); + if (!m_occlusion || !m_blurred) + { + log::Get("render")->error("SDL_gpu -- ambient occlusion targets failed ({}x{}): {}", half.width, half.height, + SDL_GetError()); + ReleaseTargets(); + return false; + } + m_size = half; + return true; +} + +void SdlGpuAmbientOcclusion::ReleaseTargets() +{ + ReleaseTexture(m_device, m_occlusion); + ReleaseTexture(m_device, m_blurred); + m_size = {}; +} + +bool SdlGpuAmbientOcclusion::RunPass(SDL_GPUCommandBuffer* commandBuffer, SDL_GPUGraphicsPipeline* pipeline, + SDL_GPUTexture* target, const SDL_GPUTextureSamplerBinding* inputs, + Uint32 inputCount, const SdlGpuAmbientOcclusionUniform& uniform) +{ + SDL_GPUColorTargetInfo colorTarget{}; + colorTarget.texture = target; + colorTarget.load_op = SDL_GPU_LOADOP_DONT_CARE; + colorTarget.store_op = SDL_GPU_STOREOP_STORE; + colorTarget.cycle = true; + SDL_GPURenderPass* pass = SDL_BeginGPURenderPass(commandBuffer, &colorTarget, 1, nullptr); + if (!pass) + { + return false; + } + const SDL_GPUViewport viewport{0.0f, 0.0f, static_cast(m_size.width), static_cast(m_size.height), + 0.0f, 1.0f}; + const SDL_Rect scissor{0, 0, static_cast(m_size.width), static_cast(m_size.height)}; + SDL_SetGPUViewport(pass, &viewport); + SDL_SetGPUScissor(pass, &scissor); + SDL_BindGPUGraphicsPipeline(pass, pipeline); + SDL_BindGPUFragmentSamplers(pass, 0, inputs, inputCount); + SDL_PushGPUFragmentUniformData(commandBuffer, 0, &uniform, sizeof(uniform)); + SDL_DrawGPUPrimitives(pass, FullscreenVertexCount, 1, 0, 0); + SDL_EndGPURenderPass(pass); + return true; +} + +} // namespace mu diff --git a/src/source/Render/Renderer/SdlGpuAmbientOcclusion.h b/src/source/Render/Renderer/SdlGpuAmbientOcclusion.h new file mode 100644 index 0000000000..62eb833777 --- /dev/null +++ b/src/source/Render/Renderer/SdlGpuAmbientOcclusion.h @@ -0,0 +1,68 @@ +// SdlGpuAmbientOcclusion.h: screen-space ambient occlusion of the Enhanced scene, from its depth. +#pragma once + +#include "SdlGpuPixelFormat.h" + +#include + +#include + +namespace mu +{ + +struct SdlGpuAmbientOcclusionShaders +{ + SDL_GPUShader* fullscreenVertex = nullptr; + SDL_GPUShader* occlusion = nullptr; + SDL_GPUShader* blur = nullptr; +}; + +// Mirrors AmbientOcclusion in post_ao.frag.hlsl and post_ao_blur.frag.hlsl. Matrices column-major, +// as glm keeps them. +struct SdlGpuAmbientOcclusionUniform +{ + float projection[16]; + float inverseProjection[16]; + float depthTexelSize[2]; + float radius; + float padding; +}; +static_assert(offsetof(SdlGpuAmbientOcclusionUniform, depthTexelSize) == 128); +static_assert(sizeof(SdlGpuAmbientOcclusionUniform) == 144); + +// The occlusion pass at half the frame's size and its blur, into R8 textures the composite reads +// (1: open, 0: hidden). Needs a single-sample, sampleable scene depth. +class SdlGpuAmbientOcclusion +{ +public: + [[nodiscard]] bool CreatePipelines(SDL_GPUDevice* device, const SdlGpuAmbientOcclusionShaders& shaders); + void DestroyPipelines(); + [[nodiscard]] bool IsAvailable() const; + + // The blurred occlusion of `depth` (of `size`) seen through `projection` (column-major), or null + // when it cannot be rendered. `radius` is in view-space units. + [[nodiscard]] SDL_GPUTexture* Render(SDL_GPUCommandBuffer* commandBuffer, SDL_GPUTexture* depth, + SdlGpuTargetSize size, const float (&projection)[16], float radius); + + // Everything, at shutdown. + void Release(); + // The targets, while the pass is off. + void ReleaseTargets(); + +private: + [[nodiscard]] bool EnsureTargets(SdlGpuTargetSize size); + // False when the pass could not be opened. + [[nodiscard]] bool RunPass(SDL_GPUCommandBuffer* commandBuffer, SDL_GPUGraphicsPipeline* pipeline, + SDL_GPUTexture* target, const SDL_GPUTextureSamplerBinding* inputs, Uint32 inputCount, + const SdlGpuAmbientOcclusionUniform& uniform); + + SDL_GPUDevice* m_device = nullptr; + SDL_GPUGraphicsPipeline* m_occlusionPipeline = nullptr; + SDL_GPUGraphicsPipeline* m_blurPipeline = nullptr; + SDL_GPUSampler* m_pointSampler = nullptr; + SdlGpuTargetSize m_size{}; + SDL_GPUTexture* m_occlusion = nullptr; + SDL_GPUTexture* m_blurred = nullptr; +}; + +} // namespace mu diff --git a/src/source/Render/Renderer/SdlGpuPixelFormat.cpp b/src/source/Render/Renderer/SdlGpuPixelFormat.cpp index 2f1ab6578f..f27531fbe1 100644 --- a/src/source/Render/Renderer/SdlGpuPixelFormat.cpp +++ b/src/source/Render/Renderer/SdlGpuPixelFormat.cpp @@ -87,6 +87,11 @@ std::optional GetSdlGpuDepthTextureInfo(SdlGpuTargetSi info.type = SDL_GPU_TEXTURETYPE_2D; info.format = SdlGpuDepthFormat; info.usage = SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET; + // A single-sample depth is also read: the ambient occlusion. + if (sampleCount == SDL_GPU_SAMPLECOUNT_1) + { + info.usage |= SDL_GPU_TEXTUREUSAGE_SAMPLER; + } info.width = size.width; info.height = size.height; info.layer_count_or_depth = 1u; diff --git a/src/source/Render/Renderer/SdlGpuPixelFormat.h b/src/source/Render/Renderer/SdlGpuPixelFormat.h index 4d98238997..a0e82aa409 100644 --- a/src/source/Render/Renderer/SdlGpuPixelFormat.h +++ b/src/source/Render/Renderer/SdlGpuPixelFormat.h @@ -33,7 +33,7 @@ struct SdlGpuTargetSize GetSdlGpuMultisampleColorTextureInfo(SDL_GPUTextureFormat format, SdlGpuTargetSize size, SDL_GPUSampleCount sampleCount); -// The frame's depth buffer, with the frame's sample count. +// The frame's depth buffer, with the frame's sample count; with one sample also sampleable. [[nodiscard]] std::optional GetSdlGpuDepthTextureInfo(SdlGpuTargetSize size, SDL_GPUSampleCount sampleCount); diff --git a/src/source/Render/Renderer/SdlGpuPostProcessing.cpp b/src/source/Render/Renderer/SdlGpuPostProcessing.cpp index 71f67afd39..014d84f7ad 100644 --- a/src/source/Render/Renderer/SdlGpuPostProcessing.cpp +++ b/src/source/Render/Renderer/SdlGpuPostProcessing.cpp @@ -209,22 +209,49 @@ bool SdlGpuPostProcessing::CreateGradingTexture() return m_gradingTexture != nullptr; } -bool SdlGpuPostProcessing::EnsureTargets(SdlGpuTargetSize size) +bool SdlGpuPostProcessing::EnsureTargets(SdlGpuTargetSize size, SDL_GPUTextureFormat sceneFormat) { if (!m_device || size.width == 0u || size.height == 0u) { return false; } - if (m_sceneTexture && m_targetSize.width == size.width && m_targetSize.height == size.height) + if (sceneFormat == SDL_GPU_TEXTUREFORMAT_INVALID) + { + sceneFormat = m_frameFormat; + } + if (m_sceneTexture && m_targetSize.width == size.width && m_targetSize.height == size.height && + m_sceneFormat == sceneFormat) { return true; } ReleaseTargets(); - m_sceneTexture = CreateTarget(m_device, m_frameFormat, size); - m_bloomSourceTexture = CreateTarget(m_device, m_frameFormat, size); - SdlGpuTargetSize levelSize = HalfSize(size); - bool created = m_sceneTexture && m_bloomSourceTexture; + m_sceneFormat = sceneFormat; + m_sceneTexture = CreateTarget(m_device, m_sceneFormat, size); + if (!m_sceneTexture) + { + log::Get("render")->error("SDL_gpu -- post-processing targets failed ({}x{}): {}", size.width, size.height, + SDL_GetError()); + ReleaseTargets(); + return false; + } + m_targetSize = size; + return true; +} + +bool SdlGpuPostProcessing::EnsureBloomTargets() +{ + if (m_bloomSourceTexture) + { + return true; + } + if (!m_sceneTexture) + { + return false; + } + m_bloomSourceTexture = CreateTarget(m_device, m_sceneFormat, m_targetSize); + SdlGpuTargetSize levelSize = HalfSize(m_targetSize); + bool created = m_bloomSourceTexture != nullptr; for (BloomLevel& level : m_bloomLevels) { level.size = levelSize; @@ -234,15 +261,30 @@ bool SdlGpuPostProcessing::EnsureTargets(SdlGpuTargetSize size) } if (!created) { - log::Get("render")->error("SDL_gpu -- post-processing targets failed ({}x{}): {}", size.width, size.height, - SDL_GetError()); - ReleaseTargets(); + log::Get("render")->error("SDL_gpu -- bloom targets failed ({}x{}): {}", m_targetSize.width, + m_targetSize.height, SDL_GetError()); + ReleaseBloomTargets(); return false; } - m_targetSize = size; return true; } +void SdlGpuPostProcessing::ReleaseBloomTargets() +{ + ReleaseTexture(m_device, m_bloomSourceTexture); + for (BloomLevel& level : m_bloomLevels) + { + ReleaseTexture(m_device, level.texture); + level.size = {}; + } + m_bloomRendered = false; +} + +bool SdlGpuPostProcessing::IsHdrScene() const +{ + return m_sceneTexture && m_sceneFormat != m_frameFormat; +} + SDL_GPUTexture* SdlGpuPostProcessing::GetSceneTexture() const { return m_sceneTexture; @@ -256,14 +298,8 @@ SDL_GPUTexture* SdlGpuPostProcessing::GetBloomSourceTexture() const void SdlGpuPostProcessing::ReleaseTargets() { ReleaseTexture(m_device, m_sceneTexture); - ReleaseTexture(m_device, m_bloomSourceTexture); - for (BloomLevel& level : m_bloomLevels) - { - ReleaseTexture(m_device, level.texture); - level.size = {}; - } + ReleaseBloomTargets(); m_targetSize = {}; - m_bloomRendered = false; } void SdlGpuPostProcessing::RunBloomPass(SDL_GPUCommandBuffer* commandBuffer, SDL_GPUGraphicsPipeline* pipeline, @@ -327,7 +363,8 @@ void SdlGpuPostProcessing::RenderBloom(SDL_GPUCommandBuffer* commandBuffer, floa } void SdlGpuPostProcessing::DrawComposite(SDL_GPUCommandBuffer* commandBuffer, SDL_GPURenderPass* pass, - SdlGpuTargetSize size, const PostProcessingLook& look, PostProcessingView view) + SdlGpuTargetSize size, const PostProcessingLook& look, PostProcessingView view, + SDL_GPUTexture* ambientOcclusion) { if (!IsAvailable() || !m_sceneTexture || size.width == 0u || size.height == 0u) { @@ -376,6 +413,8 @@ void SdlGpuPostProcessing::DrawComposite(SDL_GPUCommandBuffer* commandBuffer, SD {shown, shownSampler}, {bloom ? m_bloomLevels[0].texture : m_sceneTexture, m_linearSampler}, {grading ? m_gradingTexture : m_sceneTexture, m_linearSampler}, + {ambientOcclusion ? ambientOcclusion : m_sceneTexture, m_linearSampler}, + {bloomRendered ? m_bloomSourceTexture : m_sceneTexture, m_pointSampler}, }; const SDL_GPUViewport viewport{0.0f, 0.0f, static_cast(size.width), static_cast(size.height), @@ -385,8 +424,17 @@ void SdlGpuPostProcessing::DrawComposite(SDL_GPUCommandBuffer* commandBuffer, SD SDL_SetGPUScissor(pass, &scissor); SDL_BindGPUGraphicsPipeline(pass, m_compositePipeline); SDL_BindGPUFragmentSamplers(pass, 0, bindings, static_cast(std::size(bindings))); + // One step of the 8-bit target: enough to break up banding in the smooth HDR gradients. + constexpr float DitherAmount = 1.0f / 255.0f; + const bool hdr = IsHdrScene() && view == PostProcessingView::Scene; const SdlGpuCompositeUniform uniform{ - {1.0f / static_cast(size.width), 1.0f / static_cast(size.height)}, bloomScale, gradingStrength}; + {1.0f / static_cast(size.width), 1.0f / static_cast(size.height)}, + bloomScale, + gradingStrength, + hdr ? HdrToneMapKnee : 1.0f, + hdr ? DitherAmount : 0.0f, + ambientOcclusion && view == PostProcessingView::Scene ? look.ambientOcclusionStrength : 0.0f, + bloomRendered ? 1.0f : 0.0f}; SDL_PushGPUFragmentUniformData(commandBuffer, 0, &uniform, sizeof(uniform)); SDL_DrawGPUPrimitives(pass, FullscreenVertexCount, 1, 0, 0); } diff --git a/src/source/Render/Renderer/SdlGpuPostProcessing.h b/src/source/Render/Renderer/SdlGpuPostProcessing.h index aa66300c63..ae68235f5a 100644 --- a/src/source/Render/Renderer/SdlGpuPostProcessing.h +++ b/src/source/Render/Renderer/SdlGpuPostProcessing.h @@ -41,10 +41,22 @@ struct SdlGpuCompositeUniform // 0: ungraded; otherwise the blend of the graded colour with the ungraded one // (Render::PostProcessing::CompositeGradingStrength). float gradingStrength; + // Scene channels above it roll off towards 1 (the HDR scene); 1 leaves the scene as it is. + float toneMapKnee; + // Amplitude of the ordered dither added before the 8-bit target; 0 for none. + float ditherAmount; + // How much the ambient occlusion darkens the scene; 0 for none. + float ambientOcclusionStrength; + // 1 when the bloom source holds this frame's additive light, which the occlusion leaves alone. + float ambientOcclusionEffects; }; static_assert(offsetof(SdlGpuCompositeUniform, bloomScale) == 8); static_assert(offsetof(SdlGpuCompositeUniform, gradingStrength) == 12); -static_assert(sizeof(SdlGpuCompositeUniform) == 16); +static_assert(offsetof(SdlGpuCompositeUniform, toneMapKnee) == 16); +static_assert(sizeof(SdlGpuCompositeUniform) == 32); + +// Where the HDR scene's tone map starts rolling channels off: below it the scene is unchanged. +inline constexpr float HdrToneMapKnee = 0.9f; // The textures and passes that turn the rendered 3D scene into the processed // image the UI is then drawn on: the scene texture the scene pass resolves into, @@ -69,9 +81,14 @@ class SdlGpuPostProcessing void DestroyPipelines(); [[nodiscard]] bool IsAvailable() const; - // The scene, bloom source and bloom chain textures for frames of `size`, - // recreated when the size changed. - [[nodiscard]] bool EnsureTargets(SdlGpuTargetSize size); + // The scene texture for frames of `size` in `sceneFormat` (INVALID: the frame's format; another + // one makes an HDR scene, which the composite tone maps and dithers), recreated when either changed. + [[nodiscard]] bool EnsureTargets(SdlGpuTargetSize size, SDL_GPUTextureFormat sceneFormat); + // The bloom source (in the scene's format) and the bloom chain, at the scene's size; only bloom + // uses them. False when they cannot be created. + [[nodiscard]] bool EnsureBloomTargets(); + void ReleaseBloomTargets(); + [[nodiscard]] bool IsHdrScene() const; [[nodiscard]] SDL_GPUTexture* GetSceneTexture() const; [[nodiscard]] SDL_GPUTexture* GetBloomSourceTexture() const; @@ -84,8 +101,10 @@ class SdlGpuPostProcessing // RenderBloom ran (with the same level falloff), graded through the grading // table at the look's grading strength when one is set. The diagnostic // views show the bloom source or the bloom instead, ungraded. + // `ambientOcclusion` (SdlGpuAmbientOcclusion, or null for none) darkens the scene at the look's + // strength. void DrawComposite(SDL_GPUCommandBuffer* commandBuffer, SDL_GPURenderPass* pass, SdlGpuTargetSize size, - const PostProcessingLook& look, PostProcessingView view); + const PostProcessingLook& look, PostProcessingView view, SDL_GPUTexture* ambientOcclusion); // Replaces the grading table (Render::PostProcessing::LoadGradingTable's // RGBA8 texels), or empty for none. False (and no table) when it cannot be uploaded. @@ -111,6 +130,7 @@ class SdlGpuPostProcessing SDL_GPUDevice* m_device = nullptr; SDL_GPUTextureFormat m_frameFormat = SDL_GPU_TEXTUREFORMAT_INVALID; SDL_GPUTextureFormat m_bloomFormat = SDL_GPU_TEXTUREFORMAT_INVALID; + SDL_GPUTextureFormat m_sceneFormat = SDL_GPU_TEXTUREFORMAT_INVALID; SDL_GPUGraphicsPipeline* m_bloomDownPipeline = nullptr; SDL_GPUGraphicsPipeline* m_bloomUpPipeline = nullptr; SDL_GPUGraphicsPipeline* m_compositePipeline = nullptr; diff --git a/src/source/Render/Renderer/SdlGpuReplayState.h b/src/source/Render/Renderer/SdlGpuReplayState.h index b6f25b8e05..a7d87d4e52 100644 --- a/src/source/Render/Renderer/SdlGpuReplayState.h +++ b/src/source/Render/Renderer/SdlGpuReplayState.h @@ -13,7 +13,7 @@ class SdlGpuReplayState final public: bool SelectPipeline(SDL_GPUGraphicsPipeline* pipeline); bool SelectFragmentSampler(SDL_GPUTexture* texture, SDL_GPUSampler* sampler); - // The second fragment texture slot (skinned_lit.frag's normal map). + // The second fragment texture slot (skinned_lit.frag's normal map, world_lit.frag's ground shadow mask). bool SelectNormalMapSampler(SDL_GPUTexture* texture, SDL_GPUSampler* sampler); bool SelectVertexUniforms(Uint32 slot, std::span bytes); bool SelectFragmentUniforms(std::span bytes); diff --git a/src/source/Render/Renderer/SdlGpuSunShadowMap.cpp b/src/source/Render/Renderer/SdlGpuSunShadowMap.cpp new file mode 100644 index 0000000000..2c0571c94e --- /dev/null +++ b/src/source/Render/Renderer/SdlGpuSunShadowMap.cpp @@ -0,0 +1,124 @@ +#include "stdafx.h" + +#include "Render/Renderer/SdlGpuSunShadowMap.h" + +#include "Core/Utilities/Log/MuLogger.h" +#include "Render/Renderer/SdlGpuPixelFormat.h" + +namespace mu +{ + +Uint32 SdlGpuSunShadowMap::ResolutionFor(Uint32 requested) +{ + return requested < 1536u ? 1024u : requested < 3072u ? 2048u : 4096u; +} + +bool SdlGpuSunShadowMap::CreateResources(SDL_GPUDevice* device) +{ + m_device = device; + if (!m_sampler) + { + SDL_GPUSamplerCreateInfo samplerInfo{}; + samplerInfo.min_filter = SDL_GPU_FILTER_LINEAR; + samplerInfo.mag_filter = SDL_GPU_FILTER_LINEAR; + samplerInfo.mipmap_mode = SDL_GPU_SAMPLERMIPMAPMODE_NEAREST; + samplerInfo.address_mode_u = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + samplerInfo.address_mode_v = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + samplerInfo.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE; + samplerInfo.enable_compare = true; + // Lit where the surface is no further from the sun than what the map saw first. + samplerInfo.compare_op = SDL_GPU_COMPAREOP_LESS_OR_EQUAL; + m_sampler = SDL_CreateGPUSampler(m_device, &samplerInfo); + } + if (!m_fallback) + { + m_fallback = CreateDepth(1u); + m_fallbackCleared = false; + } + return IsAvailable(); +} + +bool SdlGpuSunShadowMap::IsAvailable() const +{ + return m_sampler && m_fallback; +} + +void SdlGpuSunShadowMap::Release() +{ + ReleaseMap(); + if (m_fallback) + { + SDL_ReleaseGPUTexture(m_device, m_fallback); + m_fallback = nullptr; + } + if (m_sampler) + { + SDL_ReleaseGPUSampler(m_device, m_sampler); + m_sampler = nullptr; + } +} + +void SdlGpuSunShadowMap::Request(Uint32 requested) +{ + m_requested = true; + m_resolution = ResolutionFor(requested); +} + +void SdlGpuSunShadowMap::Cancel() +{ + m_requested = false; +} + +SDL_GPUTexture* SdlGpuSunShadowMap::FallbackToClear() const +{ + return m_fallbackCleared ? nullptr : m_fallback; +} + +SDL_GPUTexture* SdlGpuSunShadowMap::PrepareMap() +{ + m_ready = false; + if (!m_requested) + { + ReleaseMap(); + return nullptr; + } + if (m_mapSize != m_resolution) + { + ReleaseMap(); + m_map = CreateDepth(m_resolution); + m_mapSize = m_map ? m_resolution : 0u; + } + return m_map; +} + +SDL_GPUTexture* SdlGpuSunShadowMap::CreateDepth(Uint32 size) const +{ + SDL_GPUTextureCreateInfo info{}; + info.type = SDL_GPU_TEXTURETYPE_2D; + info.format = SdlGpuDepthFormat; + info.width = size; + info.height = size; + info.layer_count_or_depth = 1; + info.num_levels = 1; + info.sample_count = SDL_GPU_SAMPLECOUNT_1; + info.usage = SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER; + SDL_GPUTexture* const texture = SDL_CreateGPUTexture(m_device, &info); + if (!texture) + { + mu::log::Get("render")->error("SDL_gpu -- sun shadow map creation failed ({0}x{0}): {1}", size, + SDL_GetError()); + } + return texture; +} + +void SdlGpuSunShadowMap::ReleaseMap() +{ + if (m_map) + { + SDL_ReleaseGPUTexture(m_device, m_map); + m_map = nullptr; + } + m_mapSize = 0u; +} + +} // namespace mu diff --git a/src/source/Render/Renderer/SdlGpuSunShadowMap.h b/src/source/Render/Renderer/SdlGpuSunShadowMap.h new file mode 100644 index 0000000000..c18d9ec51a --- /dev/null +++ b/src/source/Render/Renderer/SdlGpuSunShadowMap.h @@ -0,0 +1,56 @@ +// SdlGpuSunShadowMap.h: the Enhanced sun shadow map's textures and sampler. The renderer replays the +// scene into Map(); the lit shaders read Bound(). +#pragma once + +#include + +namespace mu +{ + +class SdlGpuSunShadowMap +{ +public: + // The map's size for a requested sun.resolution: 1024, 2048 or 4096 texels a side. + [[nodiscard]] static Uint32 ResolutionFor(Uint32 requested); + + // The comparison sampler and the far 1x1 map bound while there is no map. False when either failed. + bool CreateResources(SDL_GPUDevice* device); + [[nodiscard]] bool IsAvailable() const; + // Everything, at shutdown. + void Release(); + + // This frame asks for a map of ResolutionFor(`requested`) (SetSceneLighting), or for none. + void Request(Uint32 requested); + void Cancel(); + [[nodiscard]] Uint32 Resolution() const { return m_resolution; } + + // The far 1x1 map while it still needs its one clear, then null. + [[nodiscard]] SDL_GPUTexture* FallbackToClear() const; + void MarkFallbackCleared() { m_fallbackCleared = true; } + + // Starts the frame: the map to draw into at the requested size, or null without a request (the map + // is then released). + [[nodiscard]] SDL_GPUTexture* PrepareMap(); + // The map holds this frame's shadows. + void MarkReady() { m_ready = true; } + + // What the lit shaders sample: this frame's map once drawn, otherwise the far 1x1 one. + [[nodiscard]] SDL_GPUTexture* Bound() const { return m_ready ? m_map : m_fallback; } + [[nodiscard]] SDL_GPUSampler* Sampler() const { return m_sampler; } + +private: + [[nodiscard]] SDL_GPUTexture* CreateDepth(Uint32 size) const; + void ReleaseMap(); + + SDL_GPUDevice* m_device = nullptr; + SDL_GPUSampler* m_sampler = nullptr; + SDL_GPUTexture* m_fallback = nullptr; + bool m_fallbackCleared = false; + SDL_GPUTexture* m_map = nullptr; + Uint32 m_mapSize = 0u; + bool m_requested = false; + Uint32 m_resolution = 0u; + bool m_ready = false; +}; + +} // namespace mu diff --git a/src/source/Render/Terrain/TerrainLightGrid.cpp b/src/source/Render/Terrain/TerrainLightGrid.cpp index 17dfa19b0f..f237fc2af8 100644 --- a/src/source/Render/Terrain/TerrainLightGrid.cpp +++ b/src/source/Render/Terrain/TerrainLightGrid.cpp @@ -129,12 +129,14 @@ void AddLight(float (*grid)[3], float x, float y, const float* color, int range) } void AddDynamicLight(float (*grid)[3], Lighting::DynamicLightList& frameLights, float x, float y, const float* color, - int range, float terrainHeight) + int range, float terrainHeight, bool castsShadows) { AddLight(grid, x, y, color, range); if (range > 0) { - frameLights.Add(MakeDynamicLight(x, y, color, range, terrainHeight)); + Lighting::DynamicLight light = MakeDynamicLight(x, y, color, range, terrainHeight); + light.castsShadows = castsShadows; + frameLights.Add(light); } } @@ -145,7 +147,8 @@ void ApplyCall(const FrameLightTarget& target, const Lighting::LightCall& call) float color[kColorComponents]; for (int k = 0; k < kColorComponents; ++k) color[k] = call.color[k] > 0.f ? call.color[k] * target.dynamicGain : call.color[k]; - AddDynamicLight(target.grid, *target.frameLights, call.x, call.y, color, call.range, target.height(call.x, call.y)); + AddDynamicLight(target.grid, *target.frameLights, call.x, call.y, color, call.range, target.height(call.x, call.y), + call.source != Lighting::LightSource::Effect); } } // namespace diff --git a/src/source/Render/Terrain/TerrainLightGrid.h b/src/source/Render/Terrain/TerrainLightGrid.h index 8df3cfae74..f3a610d605 100644 --- a/src/source/Render/Terrain/TerrainLightGrid.h +++ b/src/source/Render/Terrain/TerrainLightGrid.h @@ -25,7 +25,7 @@ void AddLight(float (*grid)[3], float x, float y, const float* color, int range) // AddLight, and records the light in the frame's light list as a point light over terrain of the // given height. A light without range changes no vertex and is not recorded. void AddDynamicLight(float (*grid)[3], Lighting::DynamicLightList& frameLights, float x, float y, const float* color, - int range, float terrainHeight); + int range, float terrainHeight, bool castsShadows = true); using HeightSampler = float (*)(float, float); diff --git a/src/source/Render/Terrain/ZzzLodTerrain.cpp b/src/source/Render/Terrain/ZzzLodTerrain.cpp index 5b5d72b8a9..59f598774c 100644 --- a/src/source/Render/Terrain/ZzzLodTerrain.cpp +++ b/src/source/Render/Terrain/ZzzLodTerrain.cpp @@ -28,10 +28,12 @@ #include "Render/Renderer/MuRenderer.h" #include "Render/Renderer/RenderUtils.h" #include "Render/Terrain/TerrainHeightGrid.h" +#include "Core/Utilities/FrameProfiler.h" #include "Render/Lighting/DynamicLightHistory.h" #include "Render/Lighting/DynamicLightList.h" #include "Render/Lighting/DynamicLightsSetting.h" #include "Render/Lighting/LightMoodSetting.h" +#include "Render/Lighting/WorldDynamicLights.h" #include "Render/Look/LookProfileSetting.h" #include "Render/Terrain/TerrainLightGrid.h" #include "Scenes/SceneCore.h" @@ -40,6 +42,8 @@ #include #include +#include +#include #include "GameLogic/Events/CSChaosCastle.h" #include "GameLogic/Events/Cinematic/CMVP1stDirection.h" @@ -77,6 +81,12 @@ bool DetailLowEnable = false; char LodBuffer[64 * 64]; vec3_t TerrainNormal[TERRAIN_SIZE * TERRAIN_SIZE]; +// The terrain light, one value per cell, from the map file to the frame: +// TerrainLight: the map's painted lightmap, as loaded. +// BackTerrainLight: the static light, the lightmap × the sun's slope shading × the light mood +// (CreateStaticLightCell); rebuilt when the sun or the mood changes. +// PrimaryTerrainLight: this frame's light, the static light plus the frame's dynamic lights (game +// code adds them through AddTerrainLight); what the ground and the models sample. vec3_t PrimaryTerrainLight[TERRAIN_SIZE * TERRAIN_SIZE]; vec3_t BackTerrainLight[TERRAIN_SIZE * TERRAIN_SIZE]; vec3_t TerrainLight[TERRAIN_SIZE * TERRAIN_SIZE]; @@ -542,11 +552,15 @@ void CreateTerrainNormal_Part(int xi, int yi) // How much of each cell keeps its Classic brightness under the light mood (its // bright weight, the same in all three channels so the grid sampler reads it). static vec3_t StaticLightBrightWeight[TERRAIN_SIZE * TERRAIN_SIZE]; +// The static light figures stand in: BackTerrainLight with the mood's figure scale instead of its base. static vec3_t FigureStaticTerrainLight[TERRAIN_SIZE * TERRAIN_SIZE]; // The static light of one cell: the baked light, shaded by the slope towards // the sun and darkened by the map's light mood: by its base where the baked // light is dark, less towards its shadow keep. +// Per cell, the direct sunlight inside BackTerrainLight (RGBA8): what Enhanced clouds take away. +static std::vector s_terrainSunLight(TERRAIN_SIZE * TERRAIN_SIZE * 4, 0); + static void CreateStaticLightCell(int Index, const vec3_t Sun, const Render::Lighting::LightMood::Scales& scales) { float Luminosity = VectorDotProduct(TerrainNormal[Index], Sun) + 0.5f; @@ -554,6 +568,8 @@ static void CreateStaticLightCell(int Index, const vec3_t Sun, const Render::Lig Luminosity = 0.f; else if (Luminosity > 1.f) Luminosity = 1.f; + // The sun's share: the slope term above the half Classic gives every face. + const float direct = std::max(Luminosity - 0.5f, 0.f); vec3_t undarkened; for (int i = 0; i < 3; i++) { @@ -568,6 +584,11 @@ static void CreateStaticLightCell(int Index, const vec3_t Sun, const Render::Lig BackTerrainLight[Index][i] = undarkened[i] * factor[i]; } Vector(weight, weight, weight, StaticLightBrightWeight[Index]); + for (int i = 0; i < 3; i++) + { + const float value = TerrainLight[Index][i] * direct * factor[i]; + s_terrainSunLight[Index * 4 + i] = static_cast(std::clamp(value, 0.f, 1.f) * 255.f + 0.5f); + } VectorCopy(BackTerrainLight[Index], FigureStaticTerrainLight[Index]); Render::Lighting::LightMood::CorrectFigureLight(scales, undarkened, FigureStaticTerrainLight[Index], weight); } @@ -590,17 +611,23 @@ float RequestStaticLightBrightWeight(float xf, float yf) return weight[0]; } +// The sun the slope shading leans towards: the map's baked one, following the frame's sun. +static glm::vec3 TerrainSunVector() +{ + const glm::vec3 baked = gMapManager.InBattleCastle() ? glm::vec3(0.5f, -1.f, 1.f) : glm::vec3(0.5f, -0.5f, 0.5f); + return Render::Lighting::FollowFrameSun(baked); +} + +// The vector BackTerrainLight was last built with. +static glm::vec3 s_terrainLightSun{0.f}; +// The light mood revision the static light was last built with. +static std::uint32_t s_bakedMoodRevision = 0; + void CreateTerrainLight() { - vec3_t Light; - if (gMapManager.InBattleCastle()) - { - Vector(0.5f, -1.f, 1.f, Light); - } - else - { - Vector(0.5f, -0.5f, 0.5f, Light); - } + s_terrainLightSun = TerrainSunVector(); + s_bakedMoodRevision = Render::Lighting::LightMood::Revision(); + const vec3_t Light = {s_terrainLightSun.x, s_terrainLightSun.y, s_terrainLightSun.z}; const Render::Lighting::LightMood::Scales& scales = Render::Lighting::LightMood::Active(); for (int y = 0; y < TERRAIN_SIZE; y++) { @@ -609,6 +636,7 @@ void CreateTerrainLight() CreateStaticLightCell(TERRAIN_INDEX(x, y), Light, scales); } } + mu::GetRenderer().SetTerrainSunLight(s_terrainSunLight); } void CreateTerrainLight_Part(int xi, int yi) @@ -619,8 +647,7 @@ void CreateTerrainLight_Part(int xi, int yi) if (yi > TERRAIN_SIZE - 4) yi = TERRAIN_SIZE - 4; else if (yi < 4) yi = 4; - vec3_t Light; - Vector(0.5f, -0.5f, 0.5f, Light); + const vec3_t Light = {s_terrainLightSun.x, s_terrainLightSun.y, s_terrainLightSun.z}; const Render::Lighting::LightMood::Scales& scales = Render::Lighting::LightMood::Active(); for (int y = yi - 4; y < yi + 4; y++) { @@ -1394,6 +1421,61 @@ inline void Interpolation(int mx, int my) } } +// The terrain light without the brightening part of the frame's pinned point lights +// (WorldDynamicLights): the ground lit per pixel adds that part back in its shader. +static vec3_t GroundTerrainLight[TERRAIN_SIZE * TERRAIN_SIZE]; +static bool s_groundLightBuilt = false; +// The light the ground's faces take: GroundTerrainLight inside a lit GroundLightScope. +static vec3_t* s_faceLight = PrimaryTerrainLight; + +extern int FrustrumBoundMinX, FrustrumBoundMinY, FrustrumBoundMaxX, FrustrumBoundMaxY; + +void BuildGroundLight() +{ + for (int yi = FrustrumBoundMinY; yi <= FrustrumBoundMaxY + 3; ++yi) + { + for (int xi = FrustrumBoundMinX; xi <= FrustrumBoundMaxX + 3; ++xi) + { + const int index = TERRAIN_INDEX_REPEAT(xi, yi); + VectorCopy(PrimaryTerrainLight[index], GroundTerrainLight[index]); + } + } + const mu::DynamicLightsUniform& lights = Render::Lighting::FrameWorldDynamicLights().Selection().uniform; + for (std::uint32_t i = 0; i < lights.lightCount; ++i) + { + const float removed[3] = {-lights.color[i][0], -lights.color[i][1], -lights.color[i][2]}; + const int range = static_cast(std::lround(lights.positionAndRadius[i][3] / TERRAIN_SCALE)); + Render::Terrain::LightGrid::AddLight(GroundTerrainLight, lights.positionAndRadius[i][0], + lights.positionAndRadius[i][1], removed, range); + } + s_groundLightBuilt = true; +} + +// While alive, the ground's faces take the ground light and draw lit per pixel, once the frame's +// ground light is built and `lit` holds; otherwise they keep the terrain light. +class GroundLightScope +{ +public: + explicit GroundLightScope(bool lit) : m_previous(s_faceLight) + { + if (lit && s_groundLightBuilt) + { + s_faceLight = GroundTerrainLight; + m_worldLit.emplace(); + } + } + ~GroundLightScope() + { + s_faceLight = m_previous; + } + GroundLightScope(const GroundLightScope&) = delete; + GroundLightScope& operator=(const GroundLightScope&) = delete; + +private: + vec3_t* m_previous; + std::optional m_worldLit; +}; + void RenderFace(int Texture, int mx, int my) { if (gMapManager.WorldActive == WD_39KANTURU_3RD) @@ -1459,10 +1541,10 @@ void RenderFace(int Texture, int mx, int my) return {pos[0], pos[1], pos[2], 0.f, 0.f, 1.f, tc[0], tc[1], mu::PackABGR(light[0], light[1], light[2], 1.f)}; }; - const mu::Vertex3D v0 = MakeVert(TerrainVertex[0], TerrainTextureCoord[0], PrimaryTerrainLight[TerrainIndex1]); - const mu::Vertex3D v1 = MakeVert(TerrainVertex[1], TerrainTextureCoord[1], PrimaryTerrainLight[TerrainIndex2]); - const mu::Vertex3D v2 = MakeVert(TerrainVertex[2], TerrainTextureCoord[2], PrimaryTerrainLight[TerrainIndex3]); - const mu::Vertex3D v3 = MakeVert(TerrainVertex[3], TerrainTextureCoord[3], PrimaryTerrainLight[TerrainIndex4]); + const mu::Vertex3D v0 = MakeVert(TerrainVertex[0], TerrainTextureCoord[0], s_faceLight[TerrainIndex1]); + const mu::Vertex3D v1 = MakeVert(TerrainVertex[1], TerrainTextureCoord[1], s_faceLight[TerrainIndex2]); + const mu::Vertex3D v2 = MakeVert(TerrainVertex[2], TerrainTextureCoord[2], s_faceLight[TerrainIndex3]); + const mu::Vertex3D v3 = MakeVert(TerrainVertex[3], TerrainTextureCoord[3], s_faceLight[TerrainIndex4]); const mu::Vertex3D vertices[4] = {v0, v1, v2, v3}; mu::GetRenderer().RenderQuad3D(vertices, 0u); } @@ -1483,10 +1565,10 @@ void RenderFace_After(int Texture, int mx, int my) return {pos[0], pos[1], pos[2], 0.f, 0.f, 1.f, tc[0], tc[1], mu::PackABGR(light[0], light[1], light[2], 1.f)}; }; - const mu::Vertex3D v0 = MakeVert(TerrainVertex[0], TerrainTextureCoord[0], PrimaryTerrainLight[TerrainIndex1]); - const mu::Vertex3D v1 = MakeVert(TerrainVertex[1], TerrainTextureCoord[1], PrimaryTerrainLight[TerrainIndex2]); - const mu::Vertex3D v2 = MakeVert(TerrainVertex[2], TerrainTextureCoord[2], PrimaryTerrainLight[TerrainIndex3]); - const mu::Vertex3D v3 = MakeVert(TerrainVertex[3], TerrainTextureCoord[3], PrimaryTerrainLight[TerrainIndex4]); + const mu::Vertex3D v0 = MakeVert(TerrainVertex[0], TerrainTextureCoord[0], s_faceLight[TerrainIndex1]); + const mu::Vertex3D v1 = MakeVert(TerrainVertex[1], TerrainTextureCoord[1], s_faceLight[TerrainIndex2]); + const mu::Vertex3D v2 = MakeVert(TerrainVertex[2], TerrainTextureCoord[2], s_faceLight[TerrainIndex3]); + const mu::Vertex3D v3 = MakeVert(TerrainVertex[3], TerrainTextureCoord[3], s_faceLight[TerrainIndex4]); const mu::Vertex3D vertices[4] = {v0, v1, v2, v3}; mu::GetRenderer().RenderQuad3D(vertices, 0u); } @@ -1498,6 +1580,7 @@ struct LayerFace int texture; bool blend; mu::Vertex3D vertices[4]; + bool groundLit = false; // coloured by the ground light (GroundLightScope) }; static std::vector s_layerFaces; @@ -1508,6 +1591,7 @@ static void RenderLayerFaces() EnableDepthTest(); for (const LayerFace& face : s_layerFaces) { + const GroundLightScope ground(face.groundLit); if (face.blend) EnableAlphaBlend(); else @@ -1525,11 +1609,15 @@ void RenderFaceAlpha(int Texture, int mx, int my) return {pos[0], pos[1], pos[2], 0.f, 0.f, 1.f, tc[0], tc[1], mu::PackABGR(light[0], light[1], light[2], alpha)}; }; - const mu::Vertex3D v0 = MakeVert(TerrainVertex[0], TerrainTextureCoord[0], PrimaryTerrainLight[TerrainIndex1], TerrainMappingAlpha[TerrainIndex1]); - const mu::Vertex3D v1 = MakeVert(TerrainVertex[1], TerrainTextureCoord[1], PrimaryTerrainLight[TerrainIndex2], TerrainMappingAlpha[TerrainIndex2]); - const mu::Vertex3D v2 = MakeVert(TerrainVertex[2], TerrainTextureCoord[2], PrimaryTerrainLight[TerrainIndex3], TerrainMappingAlpha[TerrainIndex3]); - const mu::Vertex3D v3 = MakeVert(TerrainVertex[3], TerrainTextureCoord[3], PrimaryTerrainLight[TerrainIndex4], TerrainMappingAlpha[TerrainIndex4]); - s_layerFaces.push_back({Texture, false, {v0, v1, v2, v3}}); + const mu::Vertex3D v0 = MakeVert(TerrainVertex[0], TerrainTextureCoord[0], s_faceLight[TerrainIndex1], + TerrainMappingAlpha[TerrainIndex1]); + const mu::Vertex3D v1 = MakeVert(TerrainVertex[1], TerrainTextureCoord[1], s_faceLight[TerrainIndex2], + TerrainMappingAlpha[TerrainIndex2]); + const mu::Vertex3D v2 = MakeVert(TerrainVertex[2], TerrainTextureCoord[2], s_faceLight[TerrainIndex3], + TerrainMappingAlpha[TerrainIndex3]); + const mu::Vertex3D v3 = MakeVert(TerrainVertex[3], TerrainTextureCoord[3], s_faceLight[TerrainIndex4], + TerrainMappingAlpha[TerrainIndex4]); + s_layerFaces.push_back({Texture, false, {v0, v1, v2, v3}, s_faceLight == GroundTerrainLight}); } void RenderFaceBlend(int Texture, int mx, int my) @@ -1730,14 +1818,10 @@ void RenderTerrainFace(float xf, float yf, int xi, int yi, float lodf) return {pos[0], pos[1], pos[2], 0.f, 0.f, 1.f, tc[0], tc[1], mu::PackABGR(light[0], light[1], light[2], 1.f)}; }; - const mu::Vertex3D v0 = - MakeVert(TerrainVertex[0], TerrainTextureCoord[0], PrimaryTerrainLight[TerrainIndex1]); - const mu::Vertex3D v1 = - MakeVert(TerrainVertex[1], TerrainTextureCoord[1], PrimaryTerrainLight[TerrainIndex2]); - const mu::Vertex3D v2 = - MakeVert(TerrainVertex[2], TerrainTextureCoord[2], PrimaryTerrainLight[TerrainIndex3]); - const mu::Vertex3D v3 = - MakeVert(TerrainVertex[3], TerrainTextureCoord[3], PrimaryTerrainLight[TerrainIndex4]); + const mu::Vertex3D v0 = MakeVert(TerrainVertex[0], TerrainTextureCoord[0], s_faceLight[TerrainIndex1]); + const mu::Vertex3D v1 = MakeVert(TerrainVertex[1], TerrainTextureCoord[1], s_faceLight[TerrainIndex2]); + const mu::Vertex3D v2 = MakeVert(TerrainVertex[2], TerrainTextureCoord[2], s_faceLight[TerrainIndex3]); + const mu::Vertex3D v3 = MakeVert(TerrainVertex[3], TerrainTextureCoord[3], s_faceLight[TerrainIndex4]); const mu::Vertex3D vertices[4] = {v0, v1, v2, v3}; mu::GetRenderer().RenderQuad3D(vertices, 0u); @@ -1947,13 +2031,14 @@ void RenderTerrainBitmapTile(int Texture, float xf, float yf, float lodf, int lo Vector(sx + TileScale, sy + TileScale, BackTerrainHeight[TerrainIndex3] + Height, TerrainVertex[2]); Vector(sx, sy + TileScale, BackTerrainHeight[TerrainIndex4] + Height, TerrainVertex[3]); + const GroundLightScope ground(LightEnable); vec3_t Light[4]; if (LightEnable) { - VectorCopy(PrimaryTerrainLight[TerrainIndex1], Light[0]); - VectorCopy(PrimaryTerrainLight[TerrainIndex2], Light[1]); - VectorCopy(PrimaryTerrainLight[TerrainIndex3], Light[2]); - VectorCopy(PrimaryTerrainLight[TerrainIndex4], Light[3]); + VectorCopy(s_faceLight[TerrainIndex1], Light[0]); + VectorCopy(s_faceLight[TerrainIndex2], Light[1]); + VectorCopy(s_faceLight[TerrainIndex3], Light[2]); + VectorCopy(s_faceLight[TerrainIndex4], Light[3]); } mu::Vertex3D verts[4]; @@ -2819,7 +2904,19 @@ extern int EnableEvent; void InitTerrainLight() { + Render::Lighting::UpdateFrameSun(); + // The sun moved (dynamic.shadowAngle), or look values or the tint source changed the mood's scales since + // the last build: the static light follows. + const glm::vec3 sun = TerrainSunVector(); + if (glm::any(glm::greaterThan(glm::abs(sun - s_terrainLightSun), glm::vec3(1e-4f))) || + Render::Lighting::LightMood::Revision() != s_bakedMoodRevision) + { + FRAME_PROFILE(TerrainBake); + CreateTerrainLight(); + } Render::Lighting::FrameDynamicLights().Clear(); + Render::Lighting::FrameWorldDynamicLights().Clear(); + s_groundLightBuilt = false; if (UseLightHistory()) { Render::Lighting::FrameLightHistory().BeginTick(); @@ -3326,7 +3423,10 @@ void RenderTerrain(bool EditFlag) } TerrainFlag = TERRAIN_MAP_NORMAL; - RenderTerrainFrustrum(EditFlag); + { + const GroundLightScope ground(!EditFlag); + RenderTerrainFrustrum(EditFlag); + } RenderLayerFaces(); // if (EditFlag && SelectFlag) @@ -3343,6 +3443,7 @@ void RenderTerrain(bool EditFlag) if (TerrainGrassEnable && gMapManager.WorldActive != WD_7ATLANSE && !IsDoppelGanger3()) { TerrainFlag = TERRAIN_MAP_GRASS; + const GroundLightScope ground(true); RenderTerrainFrustrum(EditFlag); } #ifdef _EDITOR @@ -3364,6 +3465,7 @@ void RenderTerrain_After(bool EditFlag) return; TerrainFlag = TERRAIN_MAP_NORMAL; + const GroundLightScope ground(!EditFlag); RenderTerrainFrustrum_After(EditFlag); } diff --git a/src/source/Render/Terrain/ZzzLodTerrain.h b/src/source/Render/Terrain/ZzzLodTerrain.h index 9d106305e2..4c5759b488 100644 --- a/src/source/Render/Terrain/ZzzLodTerrain.h +++ b/src/source/Render/Terrain/ZzzLodTerrain.h @@ -58,6 +58,8 @@ void AddTerrainHeight(float xf, float yf, float Height, int Range, float* Buffer void InitTerrainRay(int HeroX, int HeroY); void InitTerrainLight(); +// The ground's light without the pinned lights, over the frame's culled terrain: built by the update, read by the draw. +void BuildGroundLight(); void InitTerrainShadow(); void SetTerrainLight(float xf, float yf, vec3_t Light, int Range, vec3_t* Buffer); void AddTerrainLight(float xf, float yf, vec3_t Light, int Range, vec3_t* Buffer); diff --git a/src/source/Scenes/CharacterScene.cpp b/src/source/Scenes/CharacterScene.cpp index 5f628010ab..22144cde71 100644 --- a/src/source/Scenes/CharacterScene.cpp +++ b/src/source/Scenes/CharacterScene.cpp @@ -339,6 +339,7 @@ void NewMoveCharacterScene() MoveCharacterSceneState(); PlaceCharactersForDraw(); CullWorld(); + Scenes::Lighting::PinWorldDynamicLights(); } /** diff --git a/src/source/Scenes/LoginScene.cpp b/src/source/Scenes/LoginScene.cpp index 219ccfae2c..cdf62e4412 100644 --- a/src/source/Scenes/LoginScene.cpp +++ b/src/source/Scenes/LoginScene.cpp @@ -326,7 +326,10 @@ static void UpdateLogInSceneView() ResetFrustrumBoundsFullTerrain(); // Behind the credits the world is not drawn. if (!g_CreditWin.IsVisible()) + { CullWorld(); + Scenes::Lighting::PinWorldDynamicLights(); + } } void NewMoveLogInScene() @@ -431,7 +434,10 @@ bool NewRenderLogInScene(HDC hDC) if (!g_CreditWin.IsVisible()) { - { FRAME_PROFILE(Terrain); RenderTerrain(false); } + { + FRAME_PROFILE(Terrain); + RenderTerrain(false); + } { FRAME_PROFILE(Characters); RenderCharactersClient(); } { FRAME_PROFILE(Objects); RenderMount(); } { diff --git a/src/source/Scenes/MainScene.cpp b/src/source/Scenes/MainScene.cpp index 9290e6ccd9..c789c81b6f 100644 --- a/src/source/Scenes/MainScene.cpp +++ b/src/source/Scenes/MainScene.cpp @@ -354,6 +354,7 @@ static void UpdateMainSceneView() CullWorld(); // The frame's lights, from every light the update added; the draw only shows them. AddFrameHistoryLights(); + Scenes::Lighting::PinWorldDynamicLights(); } /** @@ -579,7 +580,10 @@ static void RenderGameWorldPass(BYTE& byWaterMap, int width, int height) if (gMapManager.WorldActive == WD_39KANTURU_3RD) { if (!g_Direction.m_CKanturu.IsMayaScene()) - { FRAME_PROFILE(Terrain); RenderTerrain(false); } + { + FRAME_PROFILE(Terrain); + RenderTerrain(false); + } } else if (gMapManager.WorldActive != WD_10HEAVEN && gMapManager.WorldActive != -1) @@ -591,7 +595,10 @@ static void RenderGameWorldPass(BYTE& byWaterMap, int width, int height) Render::Drawing::ScopedReorderableDraws reorderable; RenderObjects(); } - { FRAME_PROFILE(Terrain); RenderTerrain(false); } + { + FRAME_PROFILE(Terrain); + RenderTerrain(false); + } } } @@ -609,7 +616,11 @@ static void RenderGameWorldPass(BYTE& byWaterMap, int width, int height) RenderBoids(); } - { FRAME_PROFILE(Characters); RenderCharactersClient(); } + { + FRAME_PROFILE(Characters); + Render::Drawing::ScopedCharacterDraws characterDraws; + RenderCharactersClient(); + } if (EditFlag != EDIT_NONE && renderTerrain) { diff --git a/src/source/Scenes/SceneLightingSetup.cpp b/src/source/Scenes/SceneLightingSetup.cpp index c363739a44..48b8a31abb 100644 --- a/src/source/Scenes/SceneLightingSetup.cpp +++ b/src/source/Scenes/SceneLightingSetup.cpp @@ -8,14 +8,20 @@ #include "Render/Lighting/DynamicLightList.h" #include "Render/Lighting/DynamicLightSelection.h" #include "Render/Lighting/DynamicLightsSetting.h" +#include "Render/Lighting/SunShadow.h" #include "Render/Lighting/EnhancedLightingSetting.h" #include "Render/Lighting/LightMoodSetting.h" +#include "Render/Lighting/WorldDynamicLights.h" #include "Render/Look/LookProfileSetting.h" #include "Render/Renderer/MuRenderer.h" +#include "Render/Lighting/SunShadow.h" #include "Render/Renderer/SceneLighting.h" +#include "Render/Terrain/ZzzLodTerrain.h" #include "Scenes/SceneCore.h" +#include #include +#include #include namespace Scenes::Lighting @@ -45,6 +51,18 @@ void SelectionReference(float (&reference)[3]) } } // namespace +// How far the clouds have drifted at `speed` world units per second, along one fixed wind. +// shortcut: wraps every 2^20 world units (a jump every few hours of play); fine while clouds stay subtle. +static glm::vec2 CloudDrift(float speed) +{ + constexpr float WindDegrees = 30.0f; + constexpr double Wrap = 1048576.0; + const double seconds = std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); + const float along = static_cast(std::fmod(seconds * speed, Wrap)); + const float wind = glm::radians(WindDegrees); + return glm::vec2(std::cos(wind), std::sin(wind)) * along; +} + void SubmitSceneLighting() { mu::SceneLighting lighting{}; @@ -53,11 +71,68 @@ void SubmitSceneLighting() lighting.cameraPosition[2] = g_Camera.Position[2]; Render::Lighting::ApplyTuning(lighting); lighting.highlightKnee = Render::Lighting::LightMood::Active().highlightKnee; + const std::optional sun = Render::Lighting::FrameSun(); + if (Render::Lighting::SunShadowsActive() && Hero && sun) + { + using Data::Maps::LookValue; + // The sun stands where the flat character shadows said it did: they fall towards + // dynamic.shadowAngle, as long as before. + const glm::vec3 toSun = sun->sun; + lighting.sunDirection[0] = toSun.x; + lighting.sunDirection[1] = toSun.y; + lighting.sunDirection[2] = toSun.z; + lighting.sunShadowDarkness = + Render::Look::Value(LookValue::SunShadowStrength) * Render::Look::Value(LookValue::GroundShadowOpacity); + lighting.sunShadowSoftness = Render::Look::Value(LookValue::SunShadowSoftness); + lighting.sunShadowResolution = static_cast(Render::Look::Value(LookValue::SunShadowResolution)); + // Around the hero: the ground the camera sees lies within these heights. + constexpr float GroundReach = 400.0f; + lighting.groundLow = Hero->Object.Position[2] - GroundReach; + lighting.groundHigh = Hero->Object.Position[2] + GroundReach; + } + if (sun) + { + if (!Render::Lighting::SunShadowsActive()) + { + lighting.sunDirection[0] = sun->sun.x; + lighting.sunDirection[1] = sun->sun.y; + lighting.sunDirection[2] = sun->sun.z; + } + } + // Clouds, the sky's tint of the shade and the sun-following rim: only under a sun that casts shadows. + if (Render::Lighting::SunShadowsActive() && sun) + { + using Data::Maps::LookValue; + lighting.cloudStrength = Render::Look::Value(LookValue::CloudStrength); + lighting.cloudScale = Render::Look::Value(LookValue::CloudScale); + lighting.cloudCover = Render::Look::Value(LookValue::CloudCover); + const glm::vec2 drift = CloudDrift(Render::Look::Value(LookValue::CloudSpeed)); + // The cloud layer stands this high: its shadow falls slanted by the sun. + constexpr float CloudHeight = 2000.0f; + const glm::vec2 slant = glm::vec2(sun->sun.x, sun->sun.y) * (CloudHeight / std::max(sun->sun.z, 0.2f)); + lighting.cloudOffset[0] = drift.x + slant.x; + lighting.cloudOffset[1] = drift.y + slant.y; + lighting.skyFill = Render::Look::Value(LookValue::SkyFill); + lighting.rimSunFollow = Render::Look::Value(LookValue::RimSunFollow); + } mu::GetRenderer().SetSceneLighting(lighting); } +void PinWorldDynamicLights() +{ + if (!Render::Lighting::DynamicLightsActive()) + { + return; + } + float reference[3]; + SelectionReference(reference); + Render::Lighting::FrameWorldDynamicLights().Pin(Render::Lighting::FrameDynamicLights(), reference); + BuildGroundLight(); +} + void SubmitDynamicLights() { + if (!Render::Lighting::DynamicLightsActive()) { mu::GetRenderer().SetDynamicLights({}); @@ -65,11 +140,14 @@ void SubmitDynamicLights() } const Render::Lighting::DynamicLightList& lights = Render::Lighting::FrameDynamicLights(); + const Render::Lighting::WorldDynamicLights& world = Render::Lighting::FrameWorldDynamicLights(); float reference[3]; SelectionReference(reference); Render::Lighting::DynamicLightSelection selection = - Render::Lighting::SelectDynamicLights(lights.Lights(), reference); + world.IsPinned() ? Render::Lighting::SelectDynamicLights(world.Selection(), lights.LightsSinceMark(), reference) + : Render::Lighting::SelectDynamicLights(lights.Lights(), reference); selection.uniform.wrap = Render::Look::Value(Data::Maps::LookValue::DynamicWrap); + selection.uniform.groundShadowOpacity = Render::Look::Value(Data::Maps::LookValue::GroundShadowOpacity); mu::GetRenderer().SetDynamicLights(selection.uniform); if (selection.dropped > 0 || lights.Overflow() > 0) diff --git a/src/source/Scenes/SceneLightingSetup.h b/src/source/Scenes/SceneLightingSetup.h index 3b3f3808e2..be124d86c5 100644 --- a/src/source/Scenes/SceneLightingSetup.h +++ b/src/source/Scenes/SceneLightingSetup.h @@ -12,4 +12,8 @@ void SubmitSceneLighting(); // count too; the renderer applies them when it replays the frame. void SubmitDynamicLights(); +// The point lights the ground applies per pixel (Enhanced dynamic lights), from the lights the update +// recorded. Call at the end of the update, after the view and the cull; the draw only reads them. +void PinWorldDynamicLights(); + } // namespace Scenes::Lighting diff --git a/src/source/UI/Options/TuningRows.cpp b/src/source/UI/Options/TuningRows.cpp index 8b94354bc2..2ab26f4519 100644 --- a/src/source/UI/Options/TuningRows.cpp +++ b/src/source/UI/Options/TuningRows.cpp @@ -54,6 +54,32 @@ ControlTexts TextsOf(TuningControlId id) return {I18N::Game::TuningSkillFade, I18N::Game::TuningSkillFadeHelp}; case TuningControlId::EffectCap: return {I18N::Game::TuningOverlappingLightCap, I18N::Game::TuningOverlappingLightCapHelp}; + case TuningControlId::ShadowOpacity: + return {I18N::Game::TuningShadowOpacity, I18N::Game::TuningShadowOpacityHelp}; + case TuningControlId::ShadowLights: + return {I18N::Game::TuningLightShadows, I18N::Game::TuningLightShadowsHelp}; + case TuningControlId::ShadowAngle: + return {I18N::Game::TuningShadowDirection, I18N::Game::TuningShadowDirectionHelp}; + case TuningControlId::SunShadowStrength: + return {I18N::Game::TuningSunShadows, I18N::Game::TuningSunShadowsHelp}; + case TuningControlId::CloudStrength: + return {I18N::Game::TuningCloudStrength, I18N::Game::TuningCloudStrengthHelp}; + case TuningControlId::CloudScale: + return {I18N::Game::TuningCloudScale, I18N::Game::TuningCloudScaleHelp}; + case TuningControlId::CloudSpeed: + return {I18N::Game::TuningCloudSpeed, I18N::Game::TuningCloudSpeedHelp}; + case TuningControlId::CloudCover: + return {I18N::Game::TuningCloudCover, I18N::Game::TuningCloudCoverHelp}; + case TuningControlId::SkyFill: + return {I18N::Game::TuningSkyFill, I18N::Game::TuningSkyFillHelp}; + case TuningControlId::RimSunFollow: + return {I18N::Game::TuningRimSunFollow, I18N::Game::TuningRimSunFollowHelp}; + case TuningControlId::FlatSunShadow: + return {I18N::Game::TuningFlatSunShadow, I18N::Game::TuningFlatSunShadowHelp}; + case TuningControlId::SunShadowSoftness: + return {I18N::Game::TuningSunShadowSoftness, I18N::Game::TuningSunShadowSoftnessHelp}; + case TuningControlId::SunShadowResolution: + return {I18N::Game::TuningSunShadowResolution, I18N::Game::TuningSunShadowResolutionHelp}; case TuningControlId::Wrap: return {I18N::Game::TuningLightWrap, I18N::Game::TuningLightWrapHelp}; case TuningControlId::MapSmoothing: @@ -68,6 +94,10 @@ ControlTexts TextsOf(TuningControlId id) return {I18N::Game::TuningBloomSpread, I18N::Game::TuningBloomSpreadHelp}; case TuningControlId::GradingStrength: return {I18N::Game::TuningColourGradingStrength, I18N::Game::TuningColourGradingStrengthHelp}; + case TuningControlId::AmbientOcclusionStrength: + return {I18N::Game::TuningContactShadows, I18N::Game::TuningContactShadowsHelp}; + case TuningControlId::AmbientOcclusionRadius: + return {I18N::Game::TuningContactShadowReach, I18N::Game::TuningContactShadowReachHelp}; case TuningControlId::Count: break; } @@ -163,6 +193,9 @@ std::string FormatTuningText(const TuningControl& control, double value) case TuningUnit::Percent: // The spacing of the UI Scale row ("100 %"). return number + " %"; + case TuningUnit::Degrees: + // U+00B0 DEGREE SIGN in UTF-8, the text encoding of the rows. + return number + "\xC2\xB0"; case TuningUnit::None: break; } diff --git a/tests/data/test_draw_parity.cpp b/tests/data/test_draw_parity.cpp index d7142a1bb4..23ba25860c 100644 --- a/tests/data/test_draw_parity.cpp +++ b/tests/data/test_draw_parity.cpp @@ -569,6 +569,34 @@ TEST_CASE("Draws asked for inside a bloom exclusion and drawn later are drawn in CheckDrawnLaterAsAtOnce(scene, "CachedSkinned"); } +TEST_CASE("Characters drawn later are drawn inside the character scope they were asked for in [draw-parity]") +{ + PlayerModels models; + static float firstBones[MAX_BONES][3][4]; + static float secondBones[MAX_BONES][3][4]; + OBJECT first; + OBJECT second; + Place(first, 100.f, 2.5f, firstBones); + Place(second, 400.f, 5.5f, secondBones); + AnimateCharacterBones(&first); + AnimateCharacterBones(&second); + BeginObjectDraws(); + Engine::Object::Attachments::BeginFrame(); + + const vec3_t light = {1.f, 1.f, 1.f}; + const auto scene = [&] + { + { + const Render::Drawing::ScopedCharacterDraws characters; + RenderPartObject(&first, MODEL_BODY_ARMOR, nullptr, light, 1.f, 0, 0, 0, false, false, true, 0, + RENDER_TEXTURE); + } + RenderPartObject(&second, MODEL_BODY_ARMOR, nullptr, light, 1.f, 0, 0, 0, false, false, true, 0, + RENDER_TEXTURE); + }; + CheckDrawnLaterAsAtOnce(scene, "CachedSkinned"); +} + TEST_CASE("A cloth's shadow drawn later falls where the cloth was when it was asked for [draw-parity]") { PlayerModels models; diff --git a/tests/data/test_look_profile_json.cpp b/tests/data/test_look_profile_json.cpp index 3e263ee4ad..583ad24e9a 100644 --- a/tests/data/test_look_profile_json.cpp +++ b/tests/data/test_look_profile_json.cpp @@ -261,10 +261,14 @@ TEST_CASE("the shipped look profile holds the tuned Enhanced values [data][look] {LookValue::DiffuseScale, 1.0}, {LookValue::DiffuseAmbient, 0.3}, {LookValue::DiffuseFloor, 0.15}, {LookValue::RimStrength, 0.4}, {LookValue::DynamicWrap, 0.3}, {LookValue::DynamicMapSmoothing, 0.5}, - {LookValue::DynamicEffectGain, 2.5}, {LookValue::DynamicEffectRange, 3.0}, + {LookValue::DynamicEffectGain, 0.5}, {LookValue::DynamicEffectRange, 2.0}, {LookValue::DynamicEffectRangeMax, 8}, {LookValue::DynamicEffectFade, 0.5}, {LookValue::DynamicEffectCap, 2.5}, {LookValue::BloomStrength, 1.0}, - {LookValue::BloomLevelFalloff, 0.6}, + {LookValue::BloomLevelFalloff, 0.6}, {LookValue::GroundShadowAngle, 135}, + {LookValue::GroundShadowLights, 2}, {LookValue::AmbientOcclusionStrength, 0.8}, + {LookValue::SpecularScale, 0.8}, {LookValue::SunShadowStrength, 1.0}, + {LookValue::CloudStrength, 0.35}, {LookValue::SkyFill, 0.5}, + {LookValue::RimSunFollow, 1.0}, }; for (const Data::Maps::LookValueInfo& info : Data::Maps::LookValueInfos()) { @@ -284,4 +288,33 @@ TEST_CASE("the shipped look profile holds the tuned Enhanced values [data][look] // Icarus: less bloom, which widened its fog clouds. CHECK(loaded.data.ForWorld(Icarus)[LookValue::BloomStrength] == doctest::Approx(0.3)); CHECK(loaded.data.ForWorld(Lorencia)[LookValue::BloomStrength] == doctest::Approx(1.0)); + // Indoor and underground maps: no sun, and no flat sun shadow under characters. + for (const int world : {1, 4, 38, 39}) + { + CAPTURE(world); + CHECK(loaded.data.ForWorld(world)[LookValue::SunShadowStrength] == 0.0); + CHECK(loaded.data.ForWorld(world)[LookValue::FlatSunShadow] == 0.0); + } + CHECK(loaded.data.ForWorld(Lorencia)[LookValue::FlatSunShadow] == 1.0); +} + +TEST_CASE("a map's environment applies between the default and the map's own values [data][look]") +{ + const ReadResult result = Read(R"({"formatVersion": 1, + "default": {"bloom.strength": 1.0, "sun.shadow": 1}, + "environments": {"enclosed": {"sun.shadow": 0, "bloom.strength": 0.8}}, + "maps": [{"world": 1, "environment": "enclosed", "bloom.strength": 0.5}, + {"world": 10, "environment": "enclosed"}]})"); + REQUIRE_MESSAGE(!HasFatal(result.issues), Messages(result.issues)); + CHECK(result.data.ForWorld(Lorencia)[LookValue::SunShadowStrength] == 1.0); + CHECK(result.data.ForWorld(Dungeon)[LookValue::SunShadowStrength] == 0.0); + // The map's own value wins over its environment's. + CHECK(result.data.ForWorld(Dungeon)[LookValue::BloomStrength] == doctest::Approx(0.5)); + CHECK(result.data.ForWorld(Icarus)[LookValue::BloomStrength] == doctest::Approx(0.8)); +} + +TEST_CASE("an unknown environment makes the file unusable [data][look]") +{ + CheckBuiltInEverywhere(Read(R"({"formatVersion": 1, "maps": [{"world": 1, "environment": "cave"}]})")); + CheckBuiltInEverywhere(Read(R"({"formatVersion": 1, "environments": {"cave": 1}})")); } diff --git a/tests/render/CMakeLists.txt b/tests/render/CMakeLists.txt index 164a105292..894f72012e 100644 --- a/tests/render/CMakeLists.txt +++ b/tests/render/CMakeLists.txt @@ -235,9 +235,20 @@ mu_add_test( ${CMAKE_SOURCE_DIR}/src/source/Render/Lighting/DynamicLightHistory.cpp ${CMAKE_SOURCE_DIR}/src/source/Render/Lighting/DynamicLightList.cpp ${CMAKE_SOURCE_DIR}/src/source/Render/Lighting/DynamicLightSelection.cpp + ${CMAKE_SOURCE_DIR}/src/source/Render/Lighting/WorldDynamicLights.cpp + ${CMAKE_SOURCE_DIR}/src/source/Render/Lighting/LightShadowCasters.cpp ${CMAKE_SOURCE_DIR}/src/source/Render/Terrain/TerrainLightGrid.cpp ) +mu_add_test( + NAME sun_shadow_tests + SOURCES + test_sun_shadow.cpp + ${CMAKE_SOURCE_DIR}/src/source/Render/Lighting/SunShadow.cpp + LINK_LIBS glm::glm +) +target_compile_definitions(sun_shadow_tests PRIVATE GLM_FORCE_DEPTH_ZERO_TO_ONE) + mu_add_test( NAME single_sample_twins_tests SOURCES test_single_sample_twins.cpp diff --git a/tests/render/test_dynamic_lights.cpp b/tests/render/test_dynamic_lights.cpp index c352452256..2aa6b94e4d 100644 --- a/tests/render/test_dynamic_lights.cpp +++ b/tests/render/test_dynamic_lights.cpp @@ -4,6 +4,8 @@ #include "Core/Globals/_define.h" #include "Render/Lighting/DynamicLightList.h" #include "Render/Lighting/DynamicLightSelection.h" +#include "Render/Lighting/LightShadowCasters.h" +#include "Render/Lighting/WorldDynamicLights.h" #include "Render/Terrain/TerrainLightGrid.h" #include @@ -312,6 +314,118 @@ TEST_CASE("over the cap the lights contributing most at the hero win [render][dy } } +TEST_CASE("the lights added after a mark stay apart when a lingering light gives way [render][dynamic_lights]") +{ + DynamicLightList frameLights; + CHECK(frameLights.LightsSinceMark().empty()); + frameLights.MarkDisplaceable(); + for (std::size_t i = 0; i + 1 < DynamicLightList::kCapacity; ++i) + { + frameLights.Add(MakeLight(static_cast(i), 0.f, 1.f, 1.f, 1.f, 1)); + } + frameLights.EndDisplaceable(); + CHECK(frameLights.LightsSinceMark().size() == DynamicLightList::kCapacity - 1); + + frameLights.Mark(); + frameLights.Add(MakeLight(5000.f, 0.f, 1.f, 1.f, 1.f, 1)); + // The list is full: the last lingering light gives way to this one. + frameLights.Add(MakeLight(6000.f, 0.f, 1.f, 1.f, 1.f, 1)); + + REQUIRE(frameLights.LightsSinceMark().size() == 2); + CHECK(frameLights.LightsSinceMark()[0].position[0] == 5000.f); + CHECK(frameLights.LightsSinceMark()[1].position[0] == 6000.f); +} + +TEST_CASE("the ground's pinned lights come first and later lights fill the slots left [render][dynamic_lights]") +{ + const float hero[3] = {1000.f, 1000.f, 0.f}; + const std::vector early = {MakeLight(1100.f, 1000.f, 0.5f, 0.5f, 0.5f, 3), + MakeLight(1000.f, 1000.f, 1.f, 1.f, 1.f, 3)}; + const std::vector later = {MakeLight(1000.f, 1000.f, 2.f, 2.f, 2.f, 3)}; + + const Render::Lighting::DynamicLightSelection pinned = Render::Lighting::SelectDynamicLights(early, hero); + const Render::Lighting::DynamicLightSelection selection = + Render::Lighting::SelectDynamicLights(pinned, later, hero); + + REQUIRE(selection.uniform.lightCount == 3); + CHECK(selection.uniform.worldLightCount == 2); + CHECK(selection.uniform.positionAndRadius[0][0] == 1000.f); + CHECK(selection.uniform.positionAndRadius[1][0] == 1100.f); + CHECK(selection.uniform.color[2][0] == 2.f); // stronger, but added after the pin + CHECK(selection.brighteningLights == 3); + CHECK(selection.dropped == 0); + + SUBCASE("a full pin leaves later lights out") + { + const std::vector many(mu::kMaxDynamicLights, early.front()); + const Render::Lighting::DynamicLightSelection full = + Render::Lighting::SelectDynamicLights(Render::Lighting::SelectDynamicLights(many, hero), later, hero); + CHECK(full.uniform.lightCount == mu::kMaxDynamicLights); + CHECK(full.uniform.worldLightCount == mu::kMaxDynamicLights); + CHECK(full.dropped == 1); + } +} + +TEST_CASE("the ground's lights are pinned once per frame [render][dynamic_lights]") +{ + const float hero[3] = {1000.f, 1000.f, 0.f}; + DynamicLightList frameLights; + frameLights.Add(MakeLight(1000.f, 1000.f, 1.f, 1.f, 1.f, 3)); + Render::Lighting::WorldDynamicLights world; + CHECK_FALSE(world.IsPinned()); + + world.Pin(frameLights, hero); + frameLights.Add(MakeLight(1100.f, 1000.f, 1.f, 1.f, 1.f, 3)); + world.Pin(frameLights, hero); + + CHECK(world.IsPinned()); + CHECK(world.Selection().uniform.lightCount == 1); + CHECK(world.Selection().uniform.worldLightCount == 1); + CHECK(frameLights.LightsSinceMark().size() == 1); + world.Clear(); + CHECK_FALSE(world.IsPinned()); +} + +TEST_CASE("point lights cast a character's shadow away from them by their share of its light [render][dynamic_lights]") +{ + const float hero[3] = {1000.f, 1000.f, 0.f}; + const std::vector lights = { + MakeLight(1000.f, 1000.f, 1.f, 1.f, 1.f, 3), // the character's own light: casts none, still counts + MakeLight(1200.f, 1000.f, 1.f, 1.f, 1.f, 3), // east of it + MakeLight(1000.f, 900.f, 0.45f, 0.45f, 0.45f, 3), // south of it, weaker + }; + mu::DynamicLightsUniform uniform = Render::Lighting::SelectDynamicLights(lights, hero).uniform; + uniform.worldLightCount = uniform.lightCount; + + const Render::Lighting::LightShadowCasters casters = Render::Lighting::SelectLightShadowCasters(uniform, hero, 4); + + REQUIRE(casters.count == 2); + // East light: the shadow falls west. Contributions 3, 3 * 1/3 = 1 and 1.35 * 2/3 = 0.9 of 4.9. + CHECK(casters.casters[0].fallAngle == doctest::Approx(3.14159265f)); + CHECK(casters.casters[0].strength == doctest::Approx(1.f / 4.9f)); + CHECK(casters.casters[1].fallAngle == doctest::Approx(3.14159265f / 2.f)); + CHECK(casters.casters[1].strength == doctest::Approx(0.9f / 4.9f)); + CHECK(Render::Lighting::SelectLightShadowCasters(uniform, hero, 1).count == 1); + CHECK(Render::Lighting::SelectLightShadowCasters(uniform, hero, 0).count == 0); +} + +TEST_CASE("skill lights light the ground but cast no character shadow [render][dynamic_lights]") +{ + const float hero[3] = {1000.f, 1000.f, 0.f}; + DynamicLight beam = MakeLight(1200.f, 1000.f, 1.f, 1.f, 1.f, 3); + beam.castsShadows = false; + const std::vector lights = {beam, MakeLight(1000.f, 1200.f, 1.f, 1.f, 1.f, 3)}; + mu::DynamicLightsUniform uniform = Render::Lighting::SelectDynamicLights(lights, hero).uniform; + uniform.worldLightCount = uniform.lightCount; + + const Render::Lighting::LightShadowCasters casters = Render::Lighting::SelectLightShadowCasters(uniform, hero, 4); + + REQUIRE(casters.count == 1); + // Only the north light casts, with its half of the light. + CHECK(casters.casters[0].fallAngle == doctest::Approx(-3.14159265f / 2.f)); + CHECK(casters.casters[0].strength == doctest::Approx(0.5f)); +} + TEST_CASE("the dropped-light report runs at most once per minute [render][dynamic_lights]") { using std::chrono::seconds; diff --git a/tests/render/test_frame_pixel_readback.cpp b/tests/render/test_frame_pixel_readback.cpp index cdcb2c33fb..fb51090537 100644 --- a/tests/render/test_frame_pixel_readback.cpp +++ b/tests/render/test_frame_pixel_readback.cpp @@ -271,7 +271,7 @@ TEST_CASE("depth buffer carries the frame's sample count [frame readback][antial const auto single = mu::GetSdlGpuDepthTextureInfo({1920u, 1080u}, SDL_GPU_SAMPLECOUNT_1); REQUIRE(single.has_value()); CHECK(single->format == mu::SdlGpuDepthFormat); - CHECK(single->usage == SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET); + CHECK(single->usage == (SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET | SDL_GPU_TEXTUREUSAGE_SAMPLER)); CHECK(single->sample_count == SDL_GPU_SAMPLECOUNT_1); const auto multisampled = mu::GetSdlGpuDepthTextureInfo({1920u, 1080u}, SDL_GPU_SAMPLECOUNT_8); diff --git a/tests/render/test_look_profile.cpp b/tests/render/test_look_profile.cpp index c7db2b0639..2a9845df2e 100644 --- a/tests/render/test_look_profile.cpp +++ b/tests/render/test_look_profile.cpp @@ -55,12 +55,20 @@ TEST_CASE("the look profile's built-in values are the renderer's values before i CHECK(BuiltInFloat(LookValue::DynamicEffectRangeMax) == classicHistory.effectRangeMax); CHECK(BuiltInFloat(LookValue::DynamicEffectFade) == classicHistory.effectFadeSeconds); CHECK(BuiltInFloat(LookValue::DynamicEffectCap) == classicHistory.effectCap); + CHECK(BuiltInFloat(LookValue::GroundShadowOpacity) == mu::kDefaultGroundShadowOpacity); + CHECK(BuiltInFloat(LookValue::GroundShadowAngle) == mu::kClassicGroundShadowAngle); + CHECK(BuiltIn(LookValue::GroundShadowLights) == 0.0); // Post-processing: the former config.ini default bloom strength, the level weight, full grading. CHECK(BuiltIn(LookValue::BloomStrength) == Approx(0.6)); CHECK(BuiltInFloat(LookValue::BloomLevelFalloff) == mu::SdlGpuPostProcessing::BloomLevelWeight); CHECK(BuiltInFloat(LookValue::BloomLevelFalloff) == mu::PostProcessingLook{}.bloomLevelFalloff); CHECK(BuiltIn(LookValue::GradingStrength) == 1.0); + // Ambient occlusion: off, at the renderer's default reach. + CHECK(BuiltIn(LookValue::AmbientOcclusionStrength) == 0.0); + CHECK(BuiltInFloat(LookValue::AmbientOcclusionRadius) == mu::PostProcessingLook{}.ambientOcclusionRadius); + // Sun shadows: off. + CHECK(BuiltIn(LookValue::SunShadowStrength) == 0.0); } TEST_CASE("dynamic.wrap: the point-light diffuse from Lambert to half-Lambert [render][look]") @@ -201,7 +209,7 @@ TEST_CASE( // The strength replaces the former gradingEnabled flag in the last register lane. CHECK(offsetof(mu::SdlGpuCompositeUniform, bloomScale) == 8); CHECK(offsetof(mu::SdlGpuCompositeUniform, gradingStrength) == 12); - CHECK(sizeof(mu::SdlGpuCompositeUniform) == 16); + CHECK(sizeof(mu::SdlGpuCompositeUniform) == 32); } TEST_CASE("the developer tuning commands name their look values [render][look]") @@ -222,8 +230,23 @@ TEST_CASE("the developer tuning commands name their look values [render][look]") single(L"$dynlights wrap 0.3", LookValue::DynamicWrap, 0.3); single(L"$dynlights smooth 0.4", LookValue::DynamicMapSmoothing, 0.4); single(L"$dynlights cap 1", LookValue::DynamicEffectCap, 1.0); + single(L"$dynlights shadow 0.4", LookValue::GroundShadowOpacity, 0.4); + single(L"$dynlights shadowangle 90", LookValue::GroundShadowAngle, 90.0); + single(L"$dynlights shadowlights 3", LookValue::GroundShadowLights, 3.0); single(L"$bloom falloff 0.6", LookValue::BloomLevelFalloff, 0.6); single(L"$bloom 0.9", LookValue::BloomStrength, 0.9); + single(L"$ao radius 80", LookValue::AmbientOcclusionRadius, 80.0); + single(L"$clouds scale 4000", LookValue::CloudScale, 4000.0); + single(L"$clouds speed 60", LookValue::CloudSpeed, 60.0); + single(L"$clouds cover 0.5", LookValue::CloudCover, 0.5); + single(L"$clouds 0.3", LookValue::CloudStrength, 0.3); + single(L"$sky 0.5", LookValue::SkyFill, 0.5); + single(L"$rim sun 1", LookValue::RimSunFollow, 1.0); + single(L"$ao 0.5", LookValue::AmbientOcclusionStrength, 0.5); + single(L"$sun softness 1.5", LookValue::SunShadowSoftness, 1.5); + single(L"$sun resolution 4096", LookValue::SunShadowResolution, 4096.0); + single(L"$sun 0.5", LookValue::SunShadowStrength, 0.5); + single(L"$dynlights flatsun 0.5", LookValue::FlatSunShadow, 0.5); const std::optional diffuse = ParseLookTuningCommand(L"$lighting diffuse 1.0 0.3 0.15"); diff --git a/tests/render/test_model_draw.cpp b/tests/render/test_model_draw.cpp index 9698daec31..87ec6536ee 100644 --- a/tests/render/test_model_draw.cpp +++ b/tests/render/test_model_draw.cpp @@ -3,11 +3,15 @@ #include #include "Engine/Physics/PhysicsManager.h" +#include "Render/Drawing/DrawCallLog.h" +#include "Render/Renderer/MuRenderer.h" #include "Render/Models/ModelDraw.h" #include "Render/Models/ZzzBMD.h" #include "Render/Sprites/TextureScript.h" +#include #include +#include #include namespace @@ -171,6 +175,41 @@ TEST_CASE("RenderBodyShadow hands the active drawer the call and the model state CHECK(draw.lod == 2); } +TEST_CASE("A shadow draws the casts it carries, whatever the frame's light is by then [render][model_draw]") +{ + auto model = std::make_unique(); + GridCloth cloth(0.f); + RecordingDrawer drawer; + { + DrawerScope scope(drawer); + model->RenderBodyShadow(-1, -1, -1, -1, &cloth, 1, 1.f); + } + REQUIRE(drawer.shadows.size() == 1); + Render::ModelDrawing::ShadowDraw draw = drawer.shadows.front(); + + const auto countsOf = [&](const char* state) + { + Render::Drawing::DrawCallLog log; + mu::SetRendererOverride(&log); + model->DrawShadow(draw); + mu::SetRendererOverride(nullptr); + return std::count_if(log.calls.begin(), log.calls.end(), [&](const std::string& call) + { return call.starts_with("Triangles") && call.find(state) != std::string::npos; }); + }; + + draw.flatStrength = 1.f; + draw.lightCastCount = 0; + CHECK(countsOf("groundShadow 10") == 1); + CHECK(countsOf("groundShadow 01") == 0); + + draw.flatStrength = 0.f; + draw.lightCastCount = 2; + draw.lightCasts[0] = {0.f, 0.5f}; + draw.lightCasts[1] = {1.f, 0.25f}; + CHECK(countsOf("groundShadow 10") == 0); + CHECK(countsOf("groundShadow 01") == 2); +} + TEST_CASE("Both draws carry the skinning the model's last Transform set up [render][model_draw]") { extern float BoneScale; diff --git a/tests/render/test_pipeline_fail_fast.cmake b/tests/render/test_pipeline_fail_fast.cmake index 125bb52bf3..f2e96f7f0b 100644 --- a/tests/render/test_pipeline_fail_fast.cmake +++ b/tests/render/test_pipeline_fail_fast.cmake @@ -137,6 +137,7 @@ require_world_set(s_pipelinesSkinned "skinned" Skinned Textured Classic) require_world_set(s_pipelines3DEnhancedFog "3d-enhanced-fog" ThreeDimensional TexturedEnhancedFog EnhancedLighting) require_world_set(s_pipelinesSkinnedEnhancedFog "skinned-enhanced-fog" Skinned TexturedEnhancedFog EnhancedLighting) require_world_set(s_pipelinesSkinnedLit "skinned-lit" Skinned SkinnedLit EnhancedLighting) +require_world_set(s_pipelinesWorldLit "world-lit" ThreeDimensionalWorldLit WorldLit EnhancedLighting) # The four depth/cull states every world set is built in: suffix, depth test, depth write, culling. function(require_world_state member suffix depth_test depth_write cull) @@ -188,7 +189,7 @@ require_source("${renderer_source}" "depth_write=\\{\\}" "pipeline diagnostics m require_source("${renderer_source}" "cull=\\{\\}" "pipeline diagnostics must include cull state") require_source("${renderer_source}" "error=\\{\\}" "pipeline diagnostics must include the SDL error") require_source("${build_source}" - "pipelineInfo\\.vertex_shader[ \t\r\n]*=[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::Skinned[ \t\r\n]*\\?[ \t\r\n]*s_vertShaderSkinned[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::SkinnedWeighted[ \t\r\n]*\\?[ \t\r\n]*s_vertShaderSkinnedWeighted[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::SkinnedShadow[ \t\r\n]*\\?[ \t\r\n]*s_vertShaderSkinnedShadow[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::SkinnedWeightedShadow[ \t\r\n]*\\?[ \t\r\n]*s_vertShaderSkinnedWeightedShadow[ \t\r\n]*:[ \t\r\n]*s_vertShader2D" + "pipelineInfo\\.vertex_shader[ \t\r\n]*=[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::Skinned[ \t\r\n]*\\?[ \t\r\n]*s_vertShaderSkinned[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::SkinnedWeighted[ \t\r\n]*\\?[ \t\r\n]*s_vertShaderSkinnedWeighted[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::SkinnedShadow[ \t\r\n]*\\?[ \t\r\n]*s_vertShaderSkinnedShadow[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::SkinnedWeightedShadow[ \t\r\n]*\\?[ \t\r\n]*s_vertShaderSkinnedWeightedShadow[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::ThreeDimensionalWorldLit[ \t\r\n]*\\?[ \t\r\n]*s_vertShaderWorldLit[ \t\r\n]*:[ \t\r\n]*s_vertShader2D" "pipeline vertex shader handles must remain selected from the pipeline layout") require_source("${build_source}" "pipelineInfo\\.fragment_shader[ \t\r\n]*=[ \t\r\n]*GetFragmentShader\\(description\\.fragmentShader\\)" @@ -210,7 +211,7 @@ require_source("${depth_state_source}" "\\.compare_op[ \t\r\n]*=[ \t\r\n]*SDL_GP reject_source("${renderer_source}" "SDL_GPU_COMPAREOP_LESS([^_]|$)" "no pipeline may compare depth with strict LESS") require_source("${log_source}" - "vertexShaderName[ \t\r\n]*=[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::Skinned[ \t\r\n]*\\?[ \t\r\n]*\"skinned_textured\\.vert\"[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::SkinnedWeighted[ \t\r\n]*\\?[ \t\r\n]*\"skinned_weighted\\.vert\"[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::SkinnedShadow[ \t\r\n]*\\?[ \t\r\n]*\"skinned_shadow\\.vert\"[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::SkinnedWeightedShadow[ \t\r\n]*\\?[ \t\r\n]*\"skinned_weighted_shadow\\.vert\"[ \t\r\n]*:[ \t\r\n]*\"basic_textured\\.vert\"" + "vertexShaderName[ \t\r\n]*=[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::Skinned[ \t\r\n]*\\?[ \t\r\n]*\"skinned_textured\\.vert\"[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::SkinnedWeighted[ \t\r\n]*\\?[ \t\r\n]*\"skinned_weighted\\.vert\"[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::SkinnedShadow[ \t\r\n]*\\?[ \t\r\n]*\"skinned_shadow\\.vert\"[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::SkinnedWeightedShadow[ \t\r\n]*\\?[ \t\r\n]*\"skinned_weighted_shadow\\.vert\"[ \t\r\n]*:[ \t\r\n]*description\\.vertexLayout[ \t\r\n]*==[ \t\r\n]*VertexLayout::ThreeDimensionalWorldLit[ \t\r\n]*\\?[ \t\r\n]*\"world_lit\\.vert\"[ \t\r\n]*:[ \t\r\n]*\"basic_textured\\.vert\"" "pipeline diagnostics must map the built vertex layout to its exact shader identifier") require_source("${log_source}" "fragmentShaderName[ \t\r\n]*=[ \t\r\n]*GetFragmentShaderName\\(description\\.fragmentShader\\)" diff --git a/tests/render/test_projected_shadow_state.cmake b/tests/render/test_projected_shadow_state.cmake index 8bebd40881..508b9d161f 100644 --- a/tests/render/test_projected_shadow_state.cmake +++ b/tests/render/test_projected_shadow_state.cmake @@ -18,6 +18,14 @@ endif() math(EXPR shadow_length "${shadow_end} - ${shadow_start}") string(SUBSTRING "${bmd_source}" ${shadow_start} ${shadow_length} projected_shadow_source) +# Every path (GPU, CPU fallback, cloth) records inside the ground-shadow scope, so a world-lit frame +# draws them into the ground shadow mask. +string(FIND "${projected_shadow_source}" "const mu::ScopedGroundShadow groundShadow;" scope_position) +string(FIND "${projected_shadow_source}" "drawShadow(draw.alpha * draw.flatStrength);" first_draw_position) +if(scope_position EQUAL -1 OR first_draw_position LESS scope_position) + message(FATAL_ERROR "Projected body shadows must be recorded inside a ScopedGroundShadow") +endif() + foreach(required_call IN ITEMS AddMeshShadowTriangles AddClothesShadowTriangles) string(FIND "${projected_shadow_source}" "${required_call}(" call_position) if(call_position EQUAL -1) diff --git a/tests/render/test_scene_lighting.cpp b/tests/render/test_scene_lighting.cpp index b988d4fd1b..2130783885 100644 --- a/tests/render/test_scene_lighting.cpp +++ b/tests/render/test_scene_lighting.cpp @@ -6,7 +6,7 @@ TEST_CASE("scene lighting uniform matches the HLSL cbuffer registers [render][scene_lighting]") { - CHECK(sizeof(mu::SceneLightingUniform) == 128); + CHECK(sizeof(mu::SceneLightingUniform) == 304); CHECK(offsetof(mu::SceneLightingUniform, lightDirection) == 0); CHECK(offsetof(mu::SceneLightingUniform, lightColor) == 16); CHECK(offsetof(mu::SceneLightingUniform, diffuseCurve) == 32); diff --git a/tests/render/test_sun_shadow.cpp b/tests/render/test_sun_shadow.cpp new file mode 100644 index 0000000000..ccddaa9d9e --- /dev/null +++ b/tests/render/test_sun_shadow.cpp @@ -0,0 +1,153 @@ +#include "Render/Lighting/SunShadow.h" + +#include +#include + +#include +#include + +namespace +{ +using Render::Lighting::BuildSunShadowView; +using Render::Lighting::SunDirection; + +// A camera like the game's: high above the ground, looking down at the hero at `target`. +glm::mat4 SceneViewProjection(const glm::vec3& target) +{ + const glm::mat4 projection = glm::perspectiveRH_ZO(glm::radians(35.0f), 16.0f / 9.0f, 20.0f, 5000.0f); + const glm::mat4 view = glm::lookAtRH(target + glm::vec3(0.0f, -900.0f, 1300.0f), target, glm::vec3(0, 0, 1)); + return projection * view; +} + +glm::vec3 Ndc(const glm::mat4& viewProjection, const glm::vec3& world) +{ + const glm::vec4 clip = viewProjection * glm::vec4(world, 1.0f); + return glm::vec3(clip) / clip.w; +} +} // namespace + +TEST_CASE("the sun stands opposite where the shadows fall, as high as their length says [render][sun]") +{ + // Shadows towards -x (Classic), half as long as the caster is tall. + const glm::vec3 toSun = SunDirection(180.0f, 0.5f); + CHECK(glm::length(toSun) == doctest::Approx(1.0f)); + CHECK(toSun.x > 0.0f); + CHECK(toSun.y == doctest::Approx(0.0f).epsilon(1e-6)); + CHECK(toSun.x / toSun.z == doctest::Approx(0.5f)); + + const glm::vec3 east = SunDirection(90.0f, 0.5f); + CHECK(east.y < 0.0f); + CHECK(east.x == doctest::Approx(0.0f).epsilon(1e-6)); +} + +TEST_CASE("the shadow map covers the ground the camera sees [render][sun]") +{ + const glm::vec3 hero(12800.0f, 12800.0f, 200.0f); + const glm::mat4 scene = SceneViewProjection(hero); + const auto view = BuildSunShadowView(SunDirection(180.0f, 0.5f), scene, 0.0f, 600.0f, 2048u); + + // Every ground point at the screen's corners and centre lands inside the map's depth and area. + const glm::mat4 sceneFromClip = glm::inverse(scene); + for (const float x : {-1.0f, 0.0f, 1.0f}) + { + for (const float y : {-1.0f, 0.0f, 1.0f}) + { + const glm::vec4 nearPoint = sceneFromClip * glm::vec4(x, y, 0.0f, 1.0f); + const glm::vec4 farPoint = sceneFromClip * glm::vec4(x, y, 1.0f, 1.0f); + const glm::vec3 a = glm::vec3(nearPoint) / nearPoint.w; + const glm::vec3 b = glm::vec3(farPoint) / farPoint.w; + const glm::vec3 ground = a + (b - a) * ((hero.z - a.z) / (b.z - a.z)); + const glm::vec3 shadow = Ndc(view.viewProjection, ground); + CHECK(std::abs(shadow.x) < 1.0f); + CHECK(std::abs(shadow.y) < 1.0f); + CHECK(shadow.z > 0.0f); + CHECK(shadow.z < 1.0f); + } + } + // A caster high above the ground still lies in front of the map's near plane. + CHECK(Ndc(view.viewProjection, hero + glm::vec3(0.0f, 0.0f, 2000.0f)).z > 0.0f); + // Clip w is 2, so the vertex shaders' near-plane clip (w - 1) keeps every vertex. + CHECK((view.viewProjection * glm::vec4(hero, 1.0f)).w == doctest::Approx(2.0f)); +} + +TEST_CASE("a recorded scene matrix turns into the sun's [render][sun]") +{ + const glm::mat4 scene = SceneViewProjection({12800.0f, 12800.0f, 200.0f}); + const auto view = BuildSunShadowView(SunDirection(135.0f, 0.5f), scene, 0.0f, 600.0f, 2048u); + // A model's draw records scene * model; the sun pass draws it with sunFromScene * that. + const glm::mat4 model = glm::rotate(glm::translate(glm::mat4(1.0f), glm::vec3(12900.0f, 12750.0f, 180.0f)), 0.7f, + glm::vec3(0.0f, 0.0f, 1.0f)); + for (const glm::vec3 vertex : {glm::vec3(0.0f), glm::vec3(40.0f, -30.0f, 150.0f), glm::vec3(-60.0f, 10.0f, 5.0f)}) + { + const glm::vec3 expected = Ndc(view.viewProjection * model, vertex); + const glm::vec3 converted = Ndc(view.sunFromScene * (scene * model), vertex); + CHECK(converted.x == doctest::Approx(expected.x).epsilon(1e-4)); + CHECK(converted.y == doctest::Approx(expected.y).epsilon(1e-4)); + CHECK(converted.z == doctest::Approx(expected.z).epsilon(1e-4)); + } +} + +TEST_CASE("a camera moving less than a texel keeps the shadow map where it is [render][sun]") +{ + const glm::vec3 toSun = SunDirection(180.0f, 0.5f); + const glm::vec3 hero(12800.0f, 12800.0f, 200.0f); + const auto view = BuildSunShadowView(toSun, SceneViewProjection(hero), 0.0f, 600.0f, 2048u); + const float texel = view.box.size / 2048.0f; + const auto nudged = BuildSunShadowView(toSun, SceneViewProjection(hero + glm::vec3(texel * 0.01f, 0.0f, 0.0f)), + 0.0f, 600.0f, 2048u); + CHECK(nudged.box == view.box); + + // Further away, the map follows, by whole texels. + const auto moved = + BuildSunShadowView(toSun, SceneViewProjection(hero + glm::vec3(300.0f, 200.0f, 0.0f)), 0.0f, 600.0f, 2048u); + CHECK_FALSE(moved.box == view.box); + const glm::vec2 steps = moved.box.origin / (moved.box.size / 2048.0f); + CHECK(steps.x == doctest::Approx(std::round(steps.x)).epsilon(1e-3)); + CHECK(steps.y == doctest::Approx(std::round(steps.y)).epsilon(1e-3)); +} + +TEST_CASE("a baked light vector follows the sun's turn and rise, and is the same at the baked sun [render][sun]") +{ + using Render::Lighting::FollowSun; + const glm::vec3 bakedSun = SunDirection(Render::Lighting::kBakedSunShadowAngle, 0.5f); + const glm::vec3 terrain(0.5f, -0.5f, 0.5f); + const glm::vec3 model(0.0f, -1.5f, 0.0f); + + // At the baked sun: exactly the old vectors. + CHECK(FollowSun(terrain, bakedSun, bakedSun) == terrain); + CHECK(FollowSun(model, bakedSun, bakedSun) == model); + + // The sun a quarter turn round (shadows towards 225 degrees instead of 135): so is the vector, as long. + const glm::vec3 turned = FollowSun(terrain, bakedSun, SunDirection(225.0f, 0.5f)); + CHECK(glm::length(turned) == doctest::Approx(glm::length(terrain))); + CHECK(turned.x == doctest::Approx(0.5f)); + CHECK(turned.y == doctest::Approx(0.5f)); + CHECK(turned.z == doctest::Approx(0.5f)); + + // A higher sun (shorter shadows) raises a level vector by as much. + const glm::vec3 higherSun = SunDirection(Render::Lighting::kBakedSunShadowAngle, 0.25f); + const float rise = std::atan2(higherSun.z, std::hypot(higherSun.x, higherSun.y)) - + std::atan2(bakedSun.z, std::hypot(bakedSun.x, bakedSun.y)); + const glm::vec3 raised = FollowSun(model, bakedSun, higherSun); + CHECK(std::atan2(raised.z, std::hypot(raised.x, raised.y)) == doctest::Approx(rise)); + CHECK(glm::length(raised) == doctest::Approx(1.5f)); + + // Never past straight up. + const glm::vec3 steep = FollowSun(glm::vec3(0.0f, 0.0f, 1.0f) + glm::vec3(0.01f, 0.0f, 0.0f), bakedSun, + SunDirection(Render::Lighting::kBakedSunShadowAngle, 0.01f)); + CHECK(std::atan2(steep.z, std::hypot(steep.x, steep.y)) <= glm::radians(89.0f) + 1e-5f); +} + +TEST_CASE("a flat shadow falls away from the sun, as long as its slant [render][sun]") +{ + using Render::Lighting::FlatShadowFromSun; + // The baked sun: shadows towards 135 degrees, half a unit per unit of height. + const Render::Lighting::FlatShadowCast baked = FlatShadowFromSun(Render::Lighting::SunDirection(135.0f, 0.5f), 3.0f); + CHECK(baked.fallPerHeight == doctest::Approx(0.5f)); + CHECK(std::cos(baked.axisAngle) == doctest::Approx(std::cos(glm::radians(315.0f))).epsilon(1e-4)); + CHECK(std::sin(baked.axisAngle) == doctest::Approx(std::sin(glm::radians(315.0f))).epsilon(1e-4)); + // A low sun: long, but bounded. + CHECK(FlatShadowFromSun(Render::Lighting::SunDirection(90.0f, 10.0f), 3.0f).fallPerHeight == doctest::Approx(3.0f)); + // Straight overhead: no slant. + CHECK(FlatShadowFromSun(glm::vec3(0.0f, 0.0f, 1.0f), 3.0f).fallPerHeight == 0.0f); +} diff --git a/tests/render/test_tuning_controls.cpp b/tests/render/test_tuning_controls.cpp index 8504d076f1..620945530b 100644 --- a/tests/render/test_tuning_controls.cpp +++ b/tests/render/test_tuning_controls.cpp @@ -63,12 +63,18 @@ const SpecRow Spec[] = { TuningUnit::Seconds, TuningZero::Immediate}, {TuningControlId::EffectCap, TuningGroup::DynamicLights, false, LookValue::DynamicEffectCap, 0, 8, 0.1, TuningUnit::None, TuningZero::NoCap}, + {TuningControlId::ShadowOpacity, TuningGroup::DynamicLights, false, LookValue::GroundShadowOpacity, 0, 1, 0.05, + TuningUnit::Percent, TuningZero::Plain}, + {TuningControlId::ShadowLights, TuningGroup::DynamicLights, false, LookValue::GroundShadowLights, 0, 4, 1, + TuningUnit::None, TuningZero::Plain}, {TuningControlId::Wrap, TuningGroup::DynamicLights, true, LookValue::DynamicWrap, 0, 0.5, 0.05, TuningUnit::None, TuningZero::Plain}, {TuningControlId::MapSmoothing, TuningGroup::DynamicLights, true, LookValue::DynamicMapSmoothing, 0, 2, 0.05, TuningUnit::Seconds, TuningZero::Immediate}, {TuningControlId::EffectRangeMax, TuningGroup::DynamicLights, true, LookValue::DynamicEffectRangeMax, 0, 16, 1, TuningUnit::Cells, TuningZero::NoCap}, + {TuningControlId::ShadowAngle, TuningGroup::DynamicLights, true, LookValue::GroundShadowAngle, 0, 360, 5, + TuningUnit::Degrees, TuningZero::Plain}, {TuningControlId::MoodStrength, TuningGroup::LightMood, false, std::nullopt, 0, 100, 1, TuningUnit::Percent, TuningZero::Plain}, {TuningControlId::BloomStrength, TuningGroup::PostProcessing, false, LookValue::BloomStrength, 0, 2, 0.05, @@ -77,6 +83,30 @@ const SpecRow Spec[] = { 0.05, TuningUnit::None, TuningZero::Plain}, {TuningControlId::GradingStrength, TuningGroup::PostProcessing, false, LookValue::GradingStrength, 0, 1, 0.01, TuningUnit::Percent, TuningZero::Plain}, + {TuningControlId::AmbientOcclusionStrength, TuningGroup::PostProcessing, false, LookValue::AmbientOcclusionStrength, + 0, 2, 0.05, TuningUnit::None, TuningZero::Plain}, + {TuningControlId::AmbientOcclusionRadius, TuningGroup::PostProcessing, false, LookValue::AmbientOcclusionRadius, 10, + 300, 5, TuningUnit::None, TuningZero::Plain}, + {TuningControlId::SunShadowStrength, TuningGroup::DynamicLights, false, LookValue::SunShadowStrength, 0, 1, 0.05, + TuningUnit::Percent, TuningZero::Plain}, + {TuningControlId::SunShadowSoftness, TuningGroup::DynamicLights, true, LookValue::SunShadowSoftness, 0, 2, 0.1, + TuningUnit::None, TuningZero::Plain}, + {TuningControlId::SunShadowResolution, TuningGroup::DynamicLights, true, LookValue::SunShadowResolution, 1024, 4096, + 1024, TuningUnit::None, TuningZero::Plain}, + {TuningControlId::FlatSunShadow, TuningGroup::DynamicLights, true, LookValue::FlatSunShadow, 0, 1, 0.05, + TuningUnit::Percent, TuningZero::Plain}, + {TuningControlId::CloudStrength, TuningGroup::DynamicLights, false, LookValue::CloudStrength, 0, 1, 0.05, + TuningUnit::Percent, TuningZero::Plain}, + {TuningControlId::CloudScale, TuningGroup::DynamicLights, true, LookValue::CloudScale, 500, 10000, 250, + TuningUnit::None, TuningZero::Plain}, + {TuningControlId::CloudSpeed, TuningGroup::DynamicLights, true, LookValue::CloudSpeed, 0, 300, 5, TuningUnit::None, + TuningZero::Plain}, + {TuningControlId::CloudCover, TuningGroup::DynamicLights, true, LookValue::CloudCover, 0, 1, 0.05, + TuningUnit::Percent, TuningZero::Plain}, + {TuningControlId::SkyFill, TuningGroup::DynamicLights, false, LookValue::SkyFill, 0, 1, 0.05, TuningUnit::Percent, + TuningZero::Plain}, + {TuningControlId::RimSunFollow, TuningGroup::DynamicLights, true, LookValue::RimSunFollow, 0, 1, 0.05, + TuningUnit::Percent, TuningZero::Plain}, }; Data::Maps::LookProfileData ShippedLikeProfile() @@ -92,9 +122,9 @@ Data::Maps::LookProfileData ShippedLikeProfile() } } // namespace -TEST_CASE("the 19 tuning controls have the specified bounds, steps, units and placement [render][look][tuning]") +TEST_CASE("the 34 tuning controls have the specified bounds, steps, units and placement [render][look][tuning]") { - REQUIRE(Render::Look::TuningControlCount == 19); + REQUIRE(Render::Look::TuningControlCount == 34); REQUIRE(std::size(Spec) == Render::Look::TuningControlCount); std::set covered; for (const SpecRow& row : Spec)