From 39ed3da017ed56fcc5c4f8f920789396dd2c073b Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 22 Nov 2026 19:58:01 +0000 Subject: [PATCH 01/13] feat: dynamic sun and moon shadows, screen space ambient occlusion and a Shadows option (PC) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Gothic's lit shaders (world, VOBs, plants, NPCs, items) cast shadows (ShadowCaster passes with the same wind, alpha cut and fatness as the main pass) and receive them. The shadow darkens only the sun's light, GD3D11-like: Gothic's baked light of sun-facing outdoor surfaces and the sun part of objects; lightmaps, ambient and fires stay. - A "Sun" directional light (SkyService) is URP's main light: it rises at 6, is highest at 12 (60 degrees, the path tilted), sets at 18; at night the moon takes its place with a weaker shadow, faded out at the horizon. It moves every game second, so the shadows glide. _SunDirection was Euler angles, not a direction - N·L of objects was a switch on the normal's x. - DepthOnly/DepthNormals passes: URP's SSAO (HighFidelity renderer) finally sees the world; it darkens the baked/ambient light, less the sun and fires. - Immersion option Shadows: off / hard / medium / soft (default), 8 languages. - SunUpdateInterval defaults to every game second; InitSky no longer adds a sun listener per world load. Quest: the Performant asset has no shadows and no SSAO - nothing changes there. --- .../DeveloperConfigs/Production.asset | 2 +- Assets/Gothic-Core/Scripts/Const/Constants.cs | 4 + .../Scripts/Models/Config/DeveloperConfig.cs | 3 +- .../Scripts/Services/World/SkyService.cs | 109 +++++++++++++- .../Shaders/GothicDepthPasses.hlsl | 81 +++++++++++ .../Shaders/GothicDepthPasses.hlsl.meta | 7 + .../Gothic-Core/Shaders/GothicIncludes.hlsl | 7 + .../Shaders/GothicShadowCaster.hlsl | 77 ++++++++++ .../Shaders/GothicShadowCaster.hlsl.meta | 7 + Assets/Gothic-Core/Shaders/GothicShadows.hlsl | 71 ++++++++++ .../Shaders/GothicShadows.hlsl.meta | 7 + .../Shaders/Lit-AlphaToCoverage.shader | 133 +++++++++++++++++- .../Gothic-Core/Shaders/Lit-SingleMesh.shader | 100 ++++++++++++- Assets/Gothic-Core/Shaders/Lit-World.shader | 117 ++++++++++++++- .../Services/Context/VRContextMenuService.cs | 14 +- 15 files changed, 722 insertions(+), 17 deletions(-) create mode 100644 Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl create mode 100644 Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl.meta create mode 100644 Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl create mode 100644 Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl.meta create mode 100644 Assets/Gothic-Core/Shaders/GothicShadows.hlsl create mode 100644 Assets/Gothic-Core/Shaders/GothicShadows.hlsl.meta diff --git a/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset b/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset index dfc440af2..a84664623 100644 --- a/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset +++ b/Assets/Gothic-Core/Resources/DeveloperConfigs/Production.asset @@ -69,7 +69,7 @@ MonoBehaviour: EnableGameSounds: 1 SunLightColor: {r: 0.69, g: 0.69, b: 0.69, a: 1} SunLightIntensity: 1 - SunUpdateInterval: 1 + SunUpdateInterval: 0 AmbientLightColor: {r: 0.1, g: 0.1, b: 0.1, a: 1} EnableWorldLightmaps: 1 StartTimeHour: 8 diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index be0547dfb..0b09a1e69 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -15,6 +15,10 @@ public static class IniNames { // Choice 0 Low / 1 Medium / 2 High: how often moving lights (torch, Light spell) update the world shader. public const string LightRefresh = "lightRefresh"; + // Choice 0 Off / 1 Hard / 2 Medium / 3 Soft (default): the dynamic shadows of the sun, moon and lights. + // Only where the quality level draws shadows at all (PC; Quest has none). + public const string Shadows = "shadows"; + public const int ShadowsDefaultValue = 3; // 1 = "-X HP" numbers over NPC heads and next to the hero's bar, 0 = off (default). public const string HitNumbers = "hitNumbers"; // 1 = "HP/MAX" on health bars (and "MANA/MAX" on the hero's mana bar), 0 = off (default). diff --git a/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs b/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs index c47400a2d..2f5083c2c 100644 --- a/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs +++ b/Assets/Gothic-Core/Scripts/Models/Config/DeveloperConfig.cs @@ -253,7 +253,8 @@ public class DebugChannelTypesCollection : CollectionWrapper _isRaining; @@ -114,10 +132,12 @@ public void InitWorld() // Remove old world events if necessary. GlobalEventDispatcher.GameTimeSecondChangeCallback.RemoveListener(Interpolate); GlobalEventDispatcher.GameTimeHourChangeCallback.RemoveListener(UpdateRainTime); + GlobalEventDispatcher.PlayerPrefUpdated.RemoveListener(OnPlayerPrefUpdated); // And now re-add the events. GlobalEventDispatcher.GameTimeSecondChangeCallback.AddListener(Interpolate); GlobalEventDispatcher.GameTimeHourChangeCallback.AddListener(UpdateRainTime); + GlobalEventDispatcher.PlayerPrefUpdated.AddListener(OnPlayerPrefUpdated); _isIndoorWorld = _saveGameService.CurrentWorldData?.BspTree?.Type == ZenKit.BspTreeType.Indoor; Logger.Log($"[Sky] Indoor world: {_isIndoorWorld} - day/night light is " + @@ -140,6 +160,12 @@ public void InitWorld() private void InitSky() { RotateSun(_gameTimeService.GetCurrentDateTime()); + // Once per world: a second world load added a second listener. + GlobalEventDispatcher.GameTimeSecondChangeCallback.RemoveListener(RotateSun); + GlobalEventDispatcher.GameTimeMinuteChangeCallback.RemoveListener(RotateSun); + GlobalEventDispatcher.GameTimeHourChangeCallback.RemoveListener(RotateSun); + // Every game second (14 times a second, a 240th of a degree) the sun's shadows move smoothly; once per game + // minute they jumped. switch (_configService.Dev.SunUpdateInterval) { case GameTimeService.GameTimeInterval.EveryGameSecond: @@ -359,6 +385,8 @@ private void SetDayLight(Color polyColor) Shader.SetGlobalColor(_sunColorShaderId, _isIndoorWorld ? Color.black : _configService.Dev.SunLightColor * dayLight); Shader.SetGlobalColor(_ambientShaderId, _configService.Dev.AmbientLightColor * dayLight); + if (_sunLight != null) + _sunLight.color = _configService.Dev.SunLightColor * dayLight; } private void SetShaderProperties() @@ -497,10 +525,85 @@ private SkyState CreatePresetState(SkyState skyState, Action applyPres /// Calculation: 270f is the starting midnight value /// Calculation: One full DateTime == 360°. --> e.g. 15° * 24h + 0min + 0sec == 360° /// + /// + /// The sun rises at 6:00, stands highest at 12:00 and sets at 18:00 (one turn per day); at night the moon takes + /// the opposite place on the same path. _SunDirection was these angles themselves (not a direction) - the + /// shaders' N·L was a switch on the normal's x then. + /// private void RotateSun(DateTime time) { - var xRotation = 270f + 15f * (time.Hour + time.Minute / 60f + time.Second / 3600f); - _sunDirection = new Vector3(xRotation % 360, 0, 0); + var hours = time.Hour + time.Minute / 60f + time.Second / 3600f; + var sunDirection = GetSunPathDirection(270f + 15f * hours); + var isDay = sunDirection.y < 0f; + _sunDirection = isDay ? sunDirection : -sunDirection; + + var elevation = Mathf.Asin(Mathf.Clamp(-_sunDirection.y, -1f, 1f)) * Mathf.Rad2Deg; + _sunShadowFade = Mathf.Clamp01(elevation / _sunHorizonFadeDegrees); + + UpdateSunLight(isDay); + } + + private void OnPlayerPrefUpdated(string key, object value) + { + if (key == Constants.IniNames.Shadows) + ApplyShadowOption(); + } + + /// + /// Option "Shadows": off, hard (cheapest), medium or soft (wider filter, default) - the sun's/moon's shadow. + /// + private void ApplyShadowOption() + { + if (_sunLight == null) + return; + + var option = _configService.Gothic.GetInt(Constants.IniNames.Shadows, Constants.IniNames.ShadowsDefaultValue); + _sunLight.shadows = option switch + { + 0 => LightShadows.None, + 1 => LightShadows.Hard, + _ => LightShadows.Soft + }; + var lightData = _sunLight.GetUniversalAdditionalLightData(); + lightData.softShadowQuality = option == 2 ? SoftShadowQuality.Low : SoftShadowQuality.High; + Logger.Log($"[Sky] Shadows option {option}: sun {_sunLight.shadows}, soft quality " + + $"{lightData.softShadowQuality}.", LogCat.Loading); + } + + /// + /// Light direction for the angle on the sun's path (0 = sunrise, 90 = noon, from above), tilted by _sunPathTilt. + /// + private static Vector3 GetSunPathDirection(float pathAngle) + { + return Quaternion.AngleAxis(_sunPathTilt, Vector3.forward) * Quaternion.Euler(pathAngle, 0f, 0f) * + Vector3.forward; + } + + /// + /// The "Sun": a directional light along _sunDirection, URP's main light. Its shadow map gives the dynamic + /// shadows; its strength fades out at the horizon and is weaker under the moon. Indoor worlds have none. + /// The URP asset decides whether shadows are drawn at all (PC: on, Quest: off). + /// + private void UpdateSunLight(bool isDay) + { + if (_sunLight == null) + { + var sunGo = new GameObject("Sun"); + _sunLight = sunGo.AddComponent(); + _sunLight.type = LightType.Directional; + _sunLight.shadows = LightShadows.Soft; + _sunLight.intensity = 1f; + RenderSettings.sun = _sunLight; + Logger.Log("[Sky] Sun light created - dynamic sun/moon shadows where the quality level has them.", + LogCat.Loading); + ApplyShadowOption(); + } + + _sunLight.enabled = !_isIndoorWorld; + _sunLight.transform.rotation = Quaternion.LookRotation(_sunDirection); + Shader.SetGlobalVector(_sunDirectionShaderId, _sunDirection); + _sunLight.shadowStrength = (isDay ? _sunShadowStrength : _moonShadowStrength) * _sunShadowFade; + _sunLight.color = _configService.Dev.SunLightColor * _polyColor; } } } diff --git a/Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl b/Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl new file mode 100644 index 000000000..f9a6bfddb --- /dev/null +++ b/Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl @@ -0,0 +1,81 @@ +// DepthOnly and DepthNormals passes of Gothic's lit shaders: the world, VOBs, NPCs and plants draw into URP's depth +// and normals textures - screen space ambient occlusion (the renderer's SSAO feature) needs them, without them it saw +// an empty world. Both eyes in one draw (single-pass instanced). +// Included inside the pass after the shader's own UnityPerMaterial buffer and textures. Options like +// GothicShadowCaster.hlsl: GOTHIC_SHADOW_ALPHA_CLIP (texture array alpha cut at _Cutoff), GOTHIC_SHADOW_FATNESS, +// the _WIND keyword. +#ifndef GOTHIC_DEPTH_PASSES_INCLUDED +#define GOTHIC_DEPTH_PASSES_INCLUDED + +struct GothicDepthAttributes +{ + float4 vertex : POSITION; + float3 normal : NORMAL; + float4 uv : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; + +struct GothicDepthVaryings +{ + float4 positionCS : SV_POSITION; + half3 normalWS : TEXCOORD0; +#if defined(GOTHIC_SHADOW_ALPHA_CLIP) + float4 uv : TEXCOORD1; +#endif + UNITY_VERTEX_OUTPUT_STEREO +}; + +GothicDepthVaryings GothicDepthVert(GothicDepthAttributes v) +{ + GothicDepthVaryings o = (GothicDepthVaryings)0; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + + float3 position = v.vertex.xyz; +#if defined(GOTHIC_SHADOW_FATNESS) + position += v.normal * _Fatness; +#endif + float3 positionWS = TransformObjectToWorld(position); +#if defined(_WIND) + positionWS = ApplyWind(positionWS); +#endif + o.positionCS = TransformWorldToHClip(positionWS); + o.normalWS = TransformObjectToWorldNormal(v.normal); +#if defined(GOTHIC_SHADOW_ALPHA_CLIP) + o.uv = float4(v.uv.xy * REFERENCE_TEX_ARRAY_SIZE * _MainTex_TexelSize.xy, v.uv.zw); +#endif + return o; +} + +void GothicDepthClip(GothicDepthVaryings i) +{ +#if defined(GOTHIC_SHADOW_ALPHA_CLIP) + float mipLevel = CalcMipLevel(i.uv.xy * _MainTex_TexelSize.zw); + half alpha = SAMPLE_TEXTURE2D_ARRAY_LOD(_MainTex, sampler_MainTex, i.uv.xy, i.uv.z, clamp(mipLevel, 0, i.uv.w)).a; + clip(alpha - _Cutoff); +#endif +} + +half GothicDepthFrag(GothicDepthVaryings i) : SV_Target +{ + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i); + GothicDepthClip(i); + return i.positionCS.z; +} + +half4 GothicDepthNormalsFrag(GothicDepthVaryings i) : SV_Target +{ + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i); + GothicDepthClip(i); + + float3 normalWS = normalize(i.normalWS); +#if defined(_GBUFFER_NORMALS_OCT) + float2 octNormalWS = PackNormalOctQuadEncode(normalWS); + float2 remappedOctNormalWS = saturate(octNormalWS * 0.5 + 0.5); + return half4(PackFloat2To888(remappedOctNormalWS), 0.0); +#else + return half4(normalWS, 0.0); +#endif +} + +#endif diff --git a/Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl.meta b/Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl.meta new file mode 100644 index 000000000..76d182c3a --- /dev/null +++ b/Assets/Gothic-Core/Shaders/GothicDepthPasses.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 6c53f5fa949160b4d90ba1a3982b516b +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Gothic-Core/Shaders/GothicIncludes.hlsl b/Assets/Gothic-Core/Shaders/GothicIncludes.hlsl index 9c93c0a7a..0c31309cd 100644 --- a/Assets/Gothic-Core/Shaders/GothicIncludes.hlsl +++ b/Assets/Gothic-Core/Shaders/GothicIncludes.hlsl @@ -84,6 +84,13 @@ half3 SunAndAmbientDiffuse(float3 normal, half3 vertexShadowmap) return saturate(diffuseDot * _SunColor * vertexShadowmap + _AmbientColor); } +// The sun's part of SunAndAmbientDiffuse - per vertex; the fragment adds the ambient after the sun's shadow +// (GothicSunAndAmbient in GothicShadows.hlsl). +half3 SunDiffuse(float3 normal, half3 vertexShadowmap) +{ + return saturate(dot(normal, -_SunDirection)) * _SunColor * vertexShadowmap; +} + // Apply underwater color tinting when flag is enabled half3 ApplyUnderWaterEffect(half3 diffuse) { diff --git a/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl b/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl new file mode 100644 index 000000000..f3dd4e78d --- /dev/null +++ b/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl @@ -0,0 +1,77 @@ +// ShadowCaster pass of Gothic's lit shaders: the world, VOBs, NPCs and plants draw into URP's shadow maps (the sun's +// cascades), so they cast dynamic shadows (GothicShadows.hlsl receives them). +// Included inside the pass after the shader's own UnityPerMaterial buffer and textures (same layout in every pass, else +// the SRP batcher breaks). Options, defined before the include: +// - GOTHIC_SHADOW_ALPHA_CLIP: _MainTex is a texture array with alpha (plants, fences), cut at _Cutoff like the main pass. +// - GOTHIC_SHADOW_FATNESS: the vertex is pushed out by _Fatness (NPCs' Mdl_SetModelFatness). +// - _WIND (material keyword): the same sway as the main pass (GothicWind.hlsl), or the shadow stays behind the tree. +#ifndef GOTHIC_SHADOW_CASTER_INCLUDED +#define GOTHIC_SHADOW_CASTER_INCLUDED + +#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl" + +// Set by URP for the light whose shadow map is drawn. +float3 _LightDirection; +float3 _LightPosition; + +struct GothicShadowAttributes +{ + float4 vertex : POSITION; + float3 normal : NORMAL; + float4 uv : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID +}; + +struct GothicShadowVaryings +{ + float4 positionCS : SV_POSITION; +#if defined(GOTHIC_SHADOW_ALPHA_CLIP) + float4 uv : TEXCOORD0; +#endif +}; + +GothicShadowVaryings GothicShadowVert(GothicShadowAttributes v) +{ + GothicShadowVaryings o = (GothicShadowVaryings)0; + UNITY_SETUP_INSTANCE_ID(v); + + float3 position = v.vertex.xyz; +#if defined(GOTHIC_SHADOW_FATNESS) + position += v.normal * _Fatness; +#endif + float3 positionWS = TransformObjectToWorld(position); +#if defined(_WIND) + positionWS = ApplyWind(positionWS); +#endif + float3 normalWS = TransformObjectToWorldNormal(v.normal); + +#if defined(_CASTING_PUNCTUAL_LIGHT_SHADOW) + float3 lightDirectionWS = normalize(_LightPosition - positionWS); +#else + float3 lightDirectionWS = _LightDirection; +#endif + float4 positionCS = TransformWorldToHClip(ApplyShadowBias(positionWS, normalWS, lightDirectionWS)); +#if UNITY_REVERSED_Z + positionCS.z = min(positionCS.z, UNITY_NEAR_CLIP_VALUE); +#else + positionCS.z = max(positionCS.z, UNITY_NEAR_CLIP_VALUE); +#endif + o.positionCS = positionCS; + +#if defined(GOTHIC_SHADOW_ALPHA_CLIP) + o.uv = float4(v.uv.xy * REFERENCE_TEX_ARRAY_SIZE * _MainTex_TexelSize.xy, v.uv.zw); +#endif + return o; +} + +half4 GothicShadowFrag(GothicShadowVaryings i) : SV_Target +{ +#if defined(GOTHIC_SHADOW_ALPHA_CLIP) + // A low mip: the shadow map is coarse anyway, and leaves keep their holes instead of turning into blobs. + half alpha = SAMPLE_TEXTURE2D_ARRAY_LOD(_MainTex, sampler_MainTex, i.uv.xy, i.uv.z, min(1, i.uv.w)).a; + clip(alpha - _Cutoff); +#endif + return 0; +} + +#endif diff --git a/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl.meta b/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl.meta new file mode 100644 index 000000000..ad0be5743 --- /dev/null +++ b/Assets/Gothic-Core/Shaders/GothicShadowCaster.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 96df4c82260f1094d9647db27fa5321f +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Gothic-Core/Shaders/GothicShadows.hlsl b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl new file mode 100644 index 000000000..938846534 --- /dev/null +++ b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl @@ -0,0 +1,71 @@ +// Dynamic sun/moon shadows on Gothic's light (GD3D11-like): the shadow only darkens the light that comes from the sun - +// Gothic's baked vertex light on outdoor polygons, the sun part of objects and NPCs. Ambient light, lightmaps and +// fires/torches stay. Surfaces facing away from the sun get no extra shadow: Gothic's vertex light already has it. +// The shadow map is URP's main light (the "Sun" light of SkyService); its shadowStrength follows the time of day. +// Without the shadow keywords (Quest, shadows off) GothicSunShadow is 1 and compiles away. +#ifndef GOTHIC_SHADOWS_INCLUDED +#define GOTHIC_SHADOWS_INCLUDED + +#if defined(_MAIN_LIGHT_SHADOWS) || defined(_MAIN_LIGHT_SHADOWS_CASCADE) || defined(_MAIN_LIGHT_SHADOWS_SCREEN) + #define GOTHIC_RECEIVE_SUN_SHADOWS +#endif + +// 1 = lit, down to 1 - shadowStrength in the sun's shadow. Faded out towards the shadow distance. +half GothicSunShadow(float3 worldPos) +{ +#if defined(GOTHIC_RECEIVE_SUN_SHADOWS) + float4 shadowCoord = TransformWorldToShadowCoord(worldPos); + half shadow = MainLightRealtimeShadow(shadowCoord); + return lerp(shadow, 1, GetMainLightShadowFade(worldPos)); +#else + return 1; +#endif +} + +// How much of a surface's light comes from the sun's direction: 0 facing away, 1 facing it (a soft edge, so the +// terminator doesn't show the shadow map's bias). _SunDirection points from the sun to the ground. +half GothicSunFacing(half3 normalWS) +{ + return saturate(dot(normalWS, -_SunDirection) * 4); +} + +// Screen space ambient occlusion (URP's SSAO feature, PC): indirect darkens Gothic's baked light and the ambient, +// direct (weaker, the feature's "direct lighting strength") the sun and the fires. 1 without SSAO. +struct GothicOcclusion +{ + half indirect; + half direct; +}; + +GothicOcclusion GothicGetOcclusion(float4 positionCS) +{ + GothicOcclusion occlusion; +#if defined(_SCREEN_SPACE_OCCLUSION) + AmbientOcclusionFactor ao = GetScreenSpaceAmbientOcclusion(GetNormalizedScreenSpaceUV(positionCS)); + occlusion.indirect = ao.indirectAmbientOcclusion; + occlusion.direct = ao.directAmbientOcclusion; +#else + occlusion.indirect = 1; + occlusion.direct = 1; +#endif + return occlusion; +} + +// Objects and plants: sun (shadowed) + ambient, both occluded - SunAndAmbientDiffuse per pixel. +half3 GothicSunAndAmbient(half3 sunDiffuse, float3 worldPos, GothicOcclusion occlusion) +{ + return saturate(sunDiffuse * GothicSunShadow(worldPos) * occlusion.direct + _AmbientColor * occlusion.indirect); +} + +// The baked light of a sun-facing surface, darkened by the shadow at worldPos. +half3 GothicApplySunShadow(half3 bakedLight, half3 normalWS, float3 worldPos) +{ +#if defined(GOTHIC_RECEIVE_SUN_SHADOWS) + half facing = GothicSunFacing(normalWS); + return bakedLight * lerp(1, GothicSunShadow(worldPos), facing); +#else + return bakedLight; +#endif +} + +#endif diff --git a/Assets/Gothic-Core/Shaders/GothicShadows.hlsl.meta b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl.meta new file mode 100644 index 000000000..6d9d9c430 --- /dev/null +++ b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: c875df6a4009fd646b06ed8ac85f2200 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader b/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader index 368dc2a65..4514731bd 100644 --- a/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader +++ b/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader @@ -25,6 +25,9 @@ Shader "Lit/AlphaToCoverage" #pragma multi_compile_fog #pragma multi_compile_instancing #pragma multi_compile_local _ _WIND + #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" @@ -45,6 +48,8 @@ Shader "Lit/AlphaToCoverage" float4 uv : TEXCOORD0; float distance : TEXCOORD1; float3 worldPos : TEXCOORD2; + // The sun's part (shadowed per pixel); diffuse: fires/torches. + half3 sunDiffuse : TEXCOORD3; half3 diffuse : COLOR; UNITY_VERTEX_OUTPUT_STEREO @@ -66,10 +71,12 @@ Shader "Lit/AlphaToCoverage" #include "GothicIncludes.hlsl" #include "StationaryLighting.hlsl" #include "GothicWind.hlsl" + #include "GothicShadows.hlsl" - half3 DiffuseLighting(half3 normal, float3 worldPos, half3 color) + // Fires/torches - the sun and the ambient come per pixel (SunAndAmbientShadowed). + half3 DiffuseLighting(half3 normal, float3 worldPos) { - half3 diffuse = SunAndAmbientDiffuse(normal, color); + half3 diffuse = 0; //for (int j = 0; j < min(MAX_VISIBLE_LIGHTS, unity_LightData.y); j++) //{ @@ -103,7 +110,9 @@ Shader "Lit/AlphaToCoverage" float3 toCamera = o.worldPos - _WorldSpaceCameraPos; o.distance = length(toCamera); o.uv = float4(v.uv.xy * REFERENCE_TEX_ARRAY_SIZE * _MainTex_TexelSize.xy, v.uv.zw); - o.diffuse = DiffuseLighting(TransformObjectToWorldNormal(v.normal), o.worldPos, v.color); + half3 normalWS = TransformObjectToWorldNormal(v.normal); + o.sunDiffuse = SunDiffuse(normalWS, v.color); + o.diffuse = DiffuseLighting(normalWS, o.worldPos); return o; } @@ -120,7 +129,9 @@ Shader "Lit/AlphaToCoverage" albedo.a = lerp((albedo.a - _Cutoff) / max(fwidth(albedo.a), 0.0001) + 0.5, albedo.a, saturate(max(i.distance, 0.0001) / _DistanceFade)); - half3 diffuse = albedo.rgb * i.diffuse; + GothicOcclusion occlusion = GothicGetOcclusion(i.vertex); + half3 light = GothicSunAndAmbient(i.sunDiffuse, i.worldPos, occlusion) + i.diffuse * occlusion.direct; + half3 diffuse = albedo.rgb * light; diffuse = ApplyUnderWaterEffect(diffuse); @@ -131,5 +142,119 @@ Shader "Lit/AlphaToCoverage" } ENDHLSL } + + Pass + { + Name "ShadowCaster" + Tags { "LightMode" = "ShadowCaster" } + ZWrite On + ZTest LEqual + ColorMask 0 + AlphaToMask Off + // Gothic's polygons are one-sided: a wall facing away from the light still casts its shadow. + Cull Off + + HLSLPROGRAM + #pragma vertex GothicShadowVert + #pragma fragment GothicShadowFrag + #pragma multi_compile_instancing + #pragma multi_compile_local _ _WIND + #pragma multi_compile_vertex _ _CASTING_PUNCTUAL_LIGHT_SHADOW + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + TEXTURE2D_ARRAY(_MainTex); + SAMPLER(sampler_MainTex); + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_TexelSize; + half _Cutoff; + half _MipScale; + float _DistanceFade; + int _StationaryLightCount; + float4x4 _StationaryLightIndices; + float _WindStrength; + CBUFFER_END + + #define GOTHIC_SHADOW_ALPHA_CLIP + #include "GothicIncludes.hlsl" + #include "GothicWind.hlsl" + #include "GothicShadowCaster.hlsl" + ENDHLSL + } + Pass + { + Name "DepthOnly" + Tags { "LightMode" = "DepthOnly" } + ZWrite On + ZTest LEqual + ColorMask R + AlphaToMask Off + + HLSLPROGRAM + #pragma vertex GothicDepthVert + #pragma fragment GothicDepthFrag + #pragma multi_compile_instancing + #pragma multi_compile_local _ _WIND + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + TEXTURE2D_ARRAY(_MainTex); + SAMPLER(sampler_MainTex); + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_TexelSize; + half _Cutoff; + half _MipScale; + float _DistanceFade; + int _StationaryLightCount; + float4x4 _StationaryLightIndices; + float _WindStrength; + CBUFFER_END + + #define GOTHIC_SHADOW_ALPHA_CLIP + #include "GothicIncludes.hlsl" + #include "GothicWind.hlsl" + #include "GothicDepthPasses.hlsl" + ENDHLSL + } + Pass + { + Name "DepthNormals" + Tags { "LightMode" = "DepthNormals" } + ZWrite On + ZTest LEqual + AlphaToMask Off + + HLSLPROGRAM + #pragma vertex GothicDepthVert + #pragma fragment GothicDepthNormalsFrag + #pragma multi_compile_instancing + #pragma multi_compile_local _ _WIND + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + TEXTURE2D_ARRAY(_MainTex); + SAMPLER(sampler_MainTex); + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_TexelSize; + half _Cutoff; + half _MipScale; + float _DistanceFade; + int _StationaryLightCount; + float4x4 _StationaryLightIndices; + float _WindStrength; + CBUFFER_END + + #define GOTHIC_SHADOW_ALPHA_CLIP + #include "GothicIncludes.hlsl" + #include "GothicWind.hlsl" + #include "GothicDepthPasses.hlsl" + ENDHLSL + } } } diff --git a/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader b/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader index c1d5d2dd5..ba1819f7c 100644 --- a/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader +++ b/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader @@ -22,6 +22,9 @@ Shader "Lit/SingleMesh" #pragma fragment frag #pragma multi_compile_fog #pragma multi_compile_instancing + #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" @@ -41,6 +44,8 @@ Shader "Lit/SingleMesh" float4 vertex : SV_POSITION; half2 uv : TEXCOORD0; float3 worldPos : TEXCOORD1; + // The sun's part (shadowed per pixel); diffuse: lights. + half3 sunDiffuse : TEXCOORD2; half3 diffuse : COLOR; UNITY_VERTEX_OUTPUT_STEREO @@ -57,10 +62,12 @@ Shader "Lit/SingleMesh" CBUFFER_END #include "GothicIncludes.hlsl" + #include "GothicShadows.hlsl" - half3 DiffuseLighting(half3 normal, float3 worldPos, half3 color) + // Lights - the sun and the ambient come per pixel (SunAndAmbientShadowed). + half3 DiffuseLighting(half3 normal, float3 worldPos) { - half3 diffuse = SunAndAmbientDiffuse(normal, color); + half3 diffuse = 0; for (int j = 0; j < min(MAX_VISIBLE_LIGHTS, unity_LightData.y); j++) { @@ -84,14 +91,18 @@ Shader "Lit/SingleMesh" o.worldPos = TransformObjectToWorld(position); o.vertex = TransformObjectToHClip(position); o.uv = TRANSFORM_TEX(v.uv, _MainTex); - o.diffuse = DiffuseLighting(TransformObjectToWorldNormal(v.normal), o.worldPos, v.color); + half3 normalWS = TransformObjectToWorldNormal(v.normal); + o.sunDiffuse = SunDiffuse(normalWS, v.color); + o.diffuse = DiffuseLighting(normalWS, o.worldPos); return o; } half4 frag(v2f i) : SV_Target { half4 albedo = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv); - half3 diffuse = albedo.rgb * i.diffuse; + GothicOcclusion occlusion = GothicGetOcclusion(i.vertex); + half3 light = GothicSunAndAmbient(i.sunDiffuse, i.worldPos, occlusion) + i.diffuse * occlusion.direct; + half3 diffuse = albedo.rgb * light; diffuse = ApplyUnderWaterEffect(diffuse); @@ -102,5 +113,86 @@ Shader "Lit/SingleMesh" } ENDHLSL } + + Pass + { + Name "ShadowCaster" + Tags { "LightMode" = "ShadowCaster" } + ZWrite On + ZTest LEqual + ColorMask 0 + // Gothic's polygons are one-sided: a wall facing away from the light still casts its shadow. + Cull Off + + HLSLPROGRAM + #pragma vertex GothicShadowVert + #pragma fragment GothicShadowFrag + #pragma multi_compile_instancing + #pragma multi_compile_vertex _ _CASTING_PUNCTUAL_LIGHT_SHADOW + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_ST; + float _Fatness; + CBUFFER_END + + #define GOTHIC_SHADOW_FATNESS + #include "GothicIncludes.hlsl" + #include "GothicShadowCaster.hlsl" + ENDHLSL + } + Pass + { + Name "DepthOnly" + Tags { "LightMode" = "DepthOnly" } + ZWrite On + ZTest LEqual + ColorMask R + + HLSLPROGRAM + #pragma vertex GothicDepthVert + #pragma fragment GothicDepthFrag + #pragma multi_compile_instancing + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_ST; + float _Fatness; + CBUFFER_END + + #define GOTHIC_SHADOW_FATNESS + #include "GothicIncludes.hlsl" + #include "GothicDepthPasses.hlsl" + ENDHLSL + } + Pass + { + Name "DepthNormals" + Tags { "LightMode" = "DepthNormals" } + ZWrite On + ZTest LEqual + + HLSLPROGRAM + #pragma vertex GothicDepthVert + #pragma fragment GothicDepthNormalsFrag + #pragma multi_compile_instancing + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_ST; + float _Fatness; + CBUFFER_END + + #define GOTHIC_SHADOW_FATNESS + #include "GothicIncludes.hlsl" + #include "GothicDepthPasses.hlsl" + ENDHLSL + } } } diff --git a/Assets/Gothic-Core/Shaders/Lit-World.shader b/Assets/Gothic-Core/Shaders/Lit-World.shader index 1a0f2d4f2..8b7130ed8 100644 --- a/Assets/Gothic-Core/Shaders/Lit-World.shader +++ b/Assets/Gothic-Core/Shaders/Lit-World.shader @@ -27,6 +27,10 @@ Shader "Lit/World" #pragma multi_compile_fog #pragma multi_compile_instancing #pragma multi_compile_local _ _WIND + // Dynamic sun/moon shadows (GothicShadows.hlsl) - only where the URP asset has main light shadows. + #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN + #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH + #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" @@ -53,7 +57,8 @@ Shader "Lit/World" float4 uv : TEXCOORD0; float3 worldPos : TEXCOORD1; float4 lightmapUv : TEXCOORD2; - half3 normal : TEXCOORD3; + // w = 1 where the sun reaches: outdoor (vertex lit) polygons and VOBs outside of light mapped areas. + half4 normal : TEXCOORD3; half3 baseLight : COLOR; UNITY_VERTEX_OUTPUT_STEREO @@ -80,6 +85,7 @@ Shader "Lit/World" #include "GothicIncludes.hlsl" #include "StationaryLighting.hlsl" #include "GothicWind.hlsl" + #include "GothicShadows.hlsl" // Per pixel: per vertex a torch in the middle of a big cave wall lit nothing (its corners are far away). half3 StationaryLighting(half3 normal, float3 worldPos) @@ -117,7 +123,7 @@ Shader "Lit/World" #endif o.uv = float4(v.uv.xy * REFERENCE_TEX_ARRAY_SIZE * _MainTex_TexelSize.xy, v.uv.zw); o.lightmapUv = v.lightmapUv; - o.normal = TransformObjectToWorldNormal(v.normal.xyz); + o.normal = half4(TransformObjectToWorldNormal(v.normal.xyz), v.normal.w * (1 - _VobLightTint.a)); // Gothic's baked vertex light; outdoor polygons follow the time of day. o.baseLight = v.color * lerp(half3(1, 1, 1), _DayLightColor, v.normal.w); // A VOB standing in a cave/house takes the light of the floor below it, like the engine's VOB lighting. @@ -139,7 +145,16 @@ Shader "Lit/World" i.lightmapUv.z).rgb * _WorldLightmapBrightness; } - half3 light = baseLight + StationaryLighting(normalize(i.normal), i.worldPos); + half3 normal = normalize(i.normal.xyz); + // The sun's shadow darkens Gothic's baked (sun) light outdoors - not lightmaps, not the fires. + if (i.normal.w > 0.5) + { + baseLight = GothicApplySunShadow(baseLight, normal, i.worldPos); + } + + GothicOcclusion occlusion = GothicGetOcclusion(i.vertex); + half3 light = baseLight * occlusion.indirect + + StationaryLighting(normal, i.worldPos) * occlusion.direct; half3 diffuse = albedo.rgb * light * _FocusBrightness; diffuse = ApplyUnderWaterEffect(diffuse); @@ -151,5 +166,101 @@ Shader "Lit/World" } ENDHLSL } + + Pass + { + Name "ShadowCaster" + Tags { "LightMode" = "ShadowCaster" } + ZWrite On + ZTest LEqual + ColorMask 0 + // Gothic's polygons are one-sided: a wall facing away from the sun still casts its shadow. + Cull Off + + HLSLPROGRAM + #pragma vertex GothicShadowVert + #pragma fragment GothicShadowFrag + #pragma multi_compile_instancing + #pragma multi_compile_local _ _WIND + #pragma multi_compile_vertex _ _CASTING_PUNCTUAL_LIGHT_SHADOW + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_TexelSize; + int _StationaryLightCount; + float4x4 _StationaryLightIndices; + float4x4 _StationaryLightIndices2; + float _WindStrength; + float4 _VobLightTint; + CBUFFER_END + + #include "GothicIncludes.hlsl" + #include "GothicWind.hlsl" + #include "GothicShadowCaster.hlsl" + ENDHLSL + } + Pass + { + Name "DepthOnly" + Tags { "LightMode" = "DepthOnly" } + ZWrite On + ZTest LEqual + ColorMask R + + HLSLPROGRAM + #pragma vertex GothicDepthVert + #pragma fragment GothicDepthFrag + #pragma multi_compile_instancing + #pragma multi_compile_local _ _WIND + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_TexelSize; + int _StationaryLightCount; + float4x4 _StationaryLightIndices; + float4x4 _StationaryLightIndices2; + float _WindStrength; + float4 _VobLightTint; + CBUFFER_END + + #include "GothicIncludes.hlsl" + #include "GothicWind.hlsl" + #include "GothicDepthPasses.hlsl" + ENDHLSL + } + Pass + { + Name "DepthNormals" + Tags { "LightMode" = "DepthNormals" } + ZWrite On + ZTest LEqual + + HLSLPROGRAM + #pragma vertex GothicDepthVert + #pragma fragment GothicDepthNormalsFrag + #pragma multi_compile_instancing + #pragma multi_compile_local _ _WIND + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_TexelSize; + int _StationaryLightCount; + float4x4 _StationaryLightIndices; + float4x4 _StationaryLightIndices2; + float _WindStrength; + float4 _VobLightTint; + CBUFFER_END + + #include "GothicIncludes.hlsl" + #include "GothicWind.hlsl" + #include "GothicDepthPasses.hlsl" + ENDHLSL + } } } diff --git a/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs b/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs index 519fa7535..c46c41bb4 100644 --- a/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs +++ b/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs @@ -140,7 +140,8 @@ public void UpdateMainMenu(AbstractMenuInstance mainMenu) CreateToggleChoice(gameMenu, "HEALTH_NUMBERS", Constants.IniNames.HealthNumbers)), (CreateToggleLabel(gameMenu, "DIALOG_FREE_MOVEMENT", "dialogFreeMovement"), CreateToggleChoice(gameMenu, "DIALOG_FREE_MOVEMENT", Constants.IniNames.DialogFreeMovement)), - (CreateToggleLabel(gameMenu, "LIGHT_REFRESH", "lightRefresh"), CreateLightRefreshChoice(gameMenu)) + (CreateToggleLabel(gameMenu, "LIGHT_REFRESH", "lightRefresh"), CreateLightRefreshChoice(gameMenu)), + (CreateToggleLabel(gameMenu, "SHADOWS", "shadows"), CreateShadowsChoice(gameMenu)) }; // DeveloperConfig.EnableHeroHands: the hero's own fists instead of the VR hand models (needs the hero body). if (_configService.Dev.EnableHeroHands && _configService.Dev.EnableVrHeroBody) @@ -274,6 +275,17 @@ private MutableMenuItemInstance CreateLightRefreshChoice(AbstractMenuInstance ga return item; } + /// + /// Dynamic shadows (Core, SkyService): off, hard, medium, soft - slower PCs pick hard or off. + /// + private MutableMenuItemInstance CreateShadowsChoice(AbstractMenuInstance gameMenu) + { + var item = CreateToggleChoice(gameMenu, "SHADOWS", Constants.IniNames.Shadows, + Constants.IniNames.ShadowsDefaultValue); + item.SetText(0, _localizationService.GetText("menuitem.shadows.value")); + return item; + } + private AbstractMenuItemInstance CreateHitNumbersSizeSlider(AbstractMenuInstance gameMenu) { var mouseSlider = gameMenu.FindMenuItem("MENUITEM_MSENSITIVITY_SLIDER", out _); From 691f4935deadc6667990b6f66a92e675367b827d Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 22 Nov 2026 20:29:10 +0000 Subject: [PATCH 02/13] feat: lamps and fires cast dynamic shadows (their cages pattern the ground), darker nights, rain darkens the world MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The 6 lights closest to the camera (lamps, fires; not the lightmap-baked ones) become shadow casting URP point lights (StationaryLightsService, Shadows option). The shaders light them through URP with their cube shadow - a lamp's iron cage throws its ornament onto the street. GothicShadowLightsFeature tells the shaders their index among URP's additional lights every frame: URP's 8 per-object lights cut a lamp's light off at a world chunk's edge. - Only Unity lights within 40 m stay enabled: the city has ~770, URP takes 256 visible ones - turning the head pushed a lamp out and its light vanished. The pool still lights the world beyond. - Renderers sort their stationary lights: shadow casting first, then the closest (slot order left the market's lamps out). - Lamps/fires a bit stronger with a 1-(d/R)² falloff; the light sum stops at 1 like Gothic's 8 bit vertex light, pools next to each other no longer burn out orange. - Nights are darker (the world gets half of the night sky's light), indoor worlds (mines) darker, rain/thunderstorms darken the world and weaken the sun's shadow. --- .../Scripts/Adapters/Rendering.meta | 8 + .../Rendering/GothicShadowLightsFeature.cs | 74 ++++++++ .../GothicShadowLightsFeature.cs.meta | 2 + .../Scripts/Adapters/Vob/StationaryLight.cs | 14 ++ .../Scripts/Services/World/SkyService.cs | 23 ++- .../Services/World/StationaryLightsService.cs | 178 +++++++++++++++++- .../Settings/URP-HighFidelity-Renderer.asset | 62 +++--- .../Gothic-Core/Shaders/GothicIncludes.hlsl | 10 + Assets/Gothic-Core/Shaders/GothicShadows.hlsl | 61 ++++++ .../Shaders/Lit-AlphaToCoverage.shader | 11 +- .../Gothic-Core/Shaders/Lit-SingleMesh.shader | 11 +- Assets/Gothic-Core/Shaders/Lit-World.shader | 15 +- .../Shaders/StationaryLighting.hlsl | 12 +- 13 files changed, 434 insertions(+), 47 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Rendering.meta create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs.meta diff --git a/Assets/Gothic-Core/Scripts/Adapters/Rendering.meta b/Assets/Gothic-Core/Scripts/Adapters/Rendering.meta new file mode 100644 index 000000000..f20824315 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Rendering.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d921c222fadc2314eb0119c184af0b35 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs new file mode 100644 index 000000000..e6c58b301 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs @@ -0,0 +1,74 @@ +using Gothic.Core.Services.World; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.RenderGraphModule; +using UnityEngine.Rendering.Universal; + +namespace Gothic.Core.Adapters.Rendering +{ + /// + /// Tells the shaders where URP keeps this frame's shadow casting lamps/fires (StationaryLightsService picks them): + /// their index among URP's additional lights. GothicShadowedLights (GothicShadows.hlsl) lights every object in their + /// range with it - URP's per-object list holds 8 lights, a big world chunk near candles and oil lamps didn't get the + /// lamp, its light ended at the chunk's edge. + /// On the renderers with shadows (URP-HighFidelity-Renderer). Costs one loop over the visible lights per camera. + /// + public class GothicShadowLightsFeature : ScriptableRendererFeature + { + private const int _maxShadowLights = 8; + + private static readonly int _indicesShaderId = Shader.PropertyToID("_GothicShadowLightIndices"); + private static readonly int _countShaderId = Shader.PropertyToID("_GothicShadowLightCount"); + + private ShadowLightsPass _pass; + + public override void Create() + { + _pass = new ShadowLightsPass { renderPassEvent = RenderPassEvent.BeforeRenderingShadows }; + } + + public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData) + { + renderer.EnqueuePass(_pass); + } + + private class ShadowLightsPass : ScriptableRenderPass + { + private readonly Vector4[] _indices = new Vector4[_maxShadowLights / 4]; + private StationaryLightsService _lightsService; + + public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) + { + _lightsService ??= ReflexProjectInstaller.DIContainer?.Resolve(); + var lightData = frameData.Get(); + var visibleLights = lightData.visibleLights; + var count = 0; + + if (_lightsService != null && _lightsService.HasShadowLights) + { + // URP's additional light index: the visible lights in order, without the main light, up to its cap + // (ForwardLights.SetupAdditionalLightConstants). + var additionalIndex = 0; + var maxAdditional = UniversalRenderPipeline.maxVisibleAdditionalLights; + for (var i = 0; i < visibleLights.Length && additionalIndex < maxAdditional; i++) + { + if (i == lightData.mainLightIndex) + continue; + var light = visibleLights[i].light; + if (count < _maxShadowLights && light != null && _lightsService.IsShadowLight(light)) + { + var index = _indices[count / 4]; + index[count % 4] = additionalIndex; + _indices[count / 4] = index; + count++; + } + additionalIndex++; + } + } + + Shader.SetGlobalVectorArray(_indicesShaderId, _indices); + Shader.SetGlobalFloat(_countShaderId, count); + } + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs.meta new file mode 100644 index 000000000..1bb5d928e --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d964ebd92a12dd1428d2e982025fd22a \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs index 606cb7b8f..36ecc9c6a 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs @@ -143,6 +143,20 @@ public float SpotAngle public int AffectedRendererCount => _affectedRenderers.Count; + public IReadOnlyList AffectedRenderers => _affectedRenderers; + + /// + /// The Unity light (objects/NPCs, shadows) - off for lights far from the camera (StationaryLightsService). + /// The pool's slot lights the world either way. + /// + public void SetUnityLightEnabled(bool isEnabled) + { + if (!_unityLight) + _unityLight = GetComponent(); + if (_unityLight.enabled != isEnabled) + _unityLight.enabled = isEnabled; + } + /// /// Color the pool writes into the shader slot it hands out (linear space). /// diff --git a/Assets/Gothic-Core/Scripts/Services/World/SkyService.cs b/Assets/Gothic-Core/Scripts/Services/World/SkyService.cs index e1cefe706..2c975bab5 100644 --- a/Assets/Gothic-Core/Scripts/Services/World/SkyService.cs +++ b/Assets/Gothic-Core/Scripts/Services/World/SkyService.cs @@ -28,8 +28,9 @@ public class SkyService [Inject] private readonly TextureService _textureService; [Inject] private readonly SaveGameService _saveGameService; - // The light of indoor worlds (no sun, no fog) - like the night. - private static readonly Color _indoorLight = new(0.25f, 0.25f, 0.3f); + // The light of indoor worlds (no sun, no fog): dark - mines are lit by their lamps (lightmaps), fires and the + // hero's torch/Light spell, not by a sky (0.25 lit the Old Mine's rock like a cloudy day). + private static readonly Color _indoorLight = new(0.12f, 0.12f, 0.15f); // The sun's path is tilted by this much towards the south: at noon it's 60 degrees high, shadows never vanish // under the objects. Gothic's own sun stands still - its shadows are baked into the vertex light. @@ -40,6 +41,15 @@ public class SkyService private const float _sunShadowStrength = 0.6f; private const float _moonShadowStrength = 0.35f; + // Darker nights, so lamps and fires stand out (GD3D11-like): the sky's polyColor (Gothic's day light) at night + // (brightness ~0.43) lights the world at _nightLightFactor of it; day and dusk (from ~0.85) stay as they are. + private const float _nightLightFactor = 0.5f; + private const float _nightBrightness = 0.45f; + private const float _duskBrightness = 0.85f; + // Rain and thunderstorms: the world's light at full rain (clouds), and the sun's shadow weaker under them. + private const float _rainLightFactor = 0.7f; + private const float _rainShadowFactor = 0.35f; + // The direction the light travels (from the sun - at night the moon - to the ground): the shaders' _SunDirection // and the "Sun" light's forward. private Vector3 _sunDirection = Vector3.down; @@ -379,7 +389,11 @@ private void SetDayLight(Color polyColor) _polyColor = polyColor; // Indoor worlds (e.g. G1's Old Mine, Orc Temple) have no day/night - like in Gothic. // Indoors no sun - the engine's indoor sky lit the mines like the night. - var dayLight = _isIndoorWorld ? _indoorLight : polyColor; + var nightFactor = Mathf.Lerp(_nightLightFactor, 1f, + Mathf.InverseLerp(_nightBrightness, _duskBrightness, polyColor.grayscale)); + var rainFactor = Mathf.Lerp(1f, _rainLightFactor, _rainWeightAndVolume); + var dayLight = _isIndoorWorld ? _indoorLight : polyColor * (nightFactor * rainFactor); + dayLight.a = 1f; Shader.SetGlobalColor(_dayLightColorShaderId, dayLight); Shader.SetGlobalColor(_sunColorShaderId, @@ -602,7 +616,8 @@ private void UpdateSunLight(bool isDay) _sunLight.enabled = !_isIndoorWorld; _sunLight.transform.rotation = Quaternion.LookRotation(_sunDirection); Shader.SetGlobalVector(_sunDirectionShaderId, _sunDirection); - _sunLight.shadowStrength = (isDay ? _sunShadowStrength : _moonShadowStrength) * _sunShadowFade; + _sunLight.shadowStrength = (isDay ? _sunShadowStrength : _moonShadowStrength) * _sunShadowFade * + Mathf.Lerp(1f, _rainShadowFactor, _rainWeightAndVolume); _sunLight.color = _configService.Dev.SunLightColor * _polyColor; } } diff --git a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs index c3d4fcc2b..2abfdf073 100644 --- a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs +++ b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs @@ -8,6 +8,7 @@ using JetBrains.Annotations; using Reflex.Attributes; using UnityEngine; +using UnityEngine.Rendering.Universal; using Logger = Gothic.Core.Logging.Logger; namespace Gothic.Core.Services.World @@ -67,6 +68,35 @@ public class StationaryLightsService /// private const float _poolMaxDistance = 80f; + /// + /// Dynamic point light shadows (GD3D11-like): the lights closest to the camera (lamps, fires with a runtime slot) + /// become shadow casting URP lights; the shaders light them through URP with their cube shadow and the pool skips + /// them (w < 0 in the slot). URP reaches every object in their range - the pool only the renderers a light + /// gathered, Khorinis' market stayed dark under its lamps. Every one renders its surroundings 6 times, so only + /// a few; baked lights (in the lightmaps) never - the walls would get them twice. + /// + private const int _maxShadowLights = 6; + private const float _shadowLightMaxDistance = 30f; + // Geometry closer to the light than this casts no shadow: the lamp's cage casts its bars, not the flame's own + // mesh around the light. + private const float _shadowLightNearPlane = 0.05f; + private readonly HashSet _shadowLights = new(); + // Their Unity lights - GothicShadowLightsFeature finds them among URP's visible lights every frame. + private readonly HashSet _shadowUnityLights = new(); + + public bool HasShadowLights => _shadowUnityLights.Count > 0; + + public bool IsShadowLight(Light light) => _shadowUnityLights.Contains(light); + + /// + /// Only lights this close (m, minus their range) keep their Unity light enabled - URP takes 256 visible lights, + /// the city has ~770: turning the head pushed a lamp out of them, its light and shadow vanished. The Unity + /// light only lights objects/NPCs (and casts the shadow); the pool lights the world, also beyond this. + /// + private const float _unityLightMaxDistance = 40f; + private readonly HashSet _wantedShadowLights = new(); + private readonly List<(float Distance, StationaryLight Light)> _shadowCandidates = new(); + private HashSet _lightMappedCells = new(); private readonly Stack _freeRuntimeSlots = new(); // Who drives the hero light now - the last ClaimHeroLight wins, only it may update or release the slot. @@ -150,6 +180,9 @@ public void RemoveLightOnRenderer(StationaryLight light, MeshRenderer renderer) } } + // Lights a renderer's material gets: 16 in _StationaryLightIndices (plants), 16 more in _StationaryLightIndices2. + private const int MaxAffectingLights = 16; + private void UpdateRenderer(MeshRenderer renderer) { if (!renderer) @@ -158,6 +191,19 @@ private void UpdateRenderer(MeshRenderer renderer) } var rendererLights = _lightsPerRenderer[renderer]; + // The shader takes 32 lights (16 on plants): the shadow casting ones first, then the closest. In slot order + // a big world chunk (Khorinis' market) didn't get the lamps right above it. + if (rendererLights.Count > MaxAffectingLights) + { + var center = renderer.bounds.center; + rendererLights.Sort((a, b) => + { + var aShadow = _shadowLights.Contains(a); + if (aShadow != _shadowLights.Contains(b)) + return aShadow ? -1 : 1; + return (a.CachedPosition - center).sqrMagnitude.CompareTo((b.CachedPosition - center).sqrMagnitude); + }); + } var nonAllocMaterials = _rendererMaterials; var indicesMatrix = Matrix4x4.identity; @@ -220,6 +266,11 @@ public StationaryLightsService() { GlobalEventDispatcher.LoadingSceneLoaded.AddListener(ClearWorldLightmaps); GlobalEventDispatcher.MainMenuSceneLoaded.AddListener(ClearWorldLightmaps); + GlobalEventDispatcher.PlayerPrefUpdated.AddListener((key, _) => + { + if (key == Constants.IniNames.Shadows) + RefreshShadowLights(); + }); } /// @@ -495,6 +546,8 @@ public void InitStationaryLights() if (light != null && light.Index >= 0) light.DetachSlot(); _pooledLights.Clear(); + _shadowLights.Clear(); + _shadowUnityLights.Clear(); _poolPeak = 0; _isPoolDirty = true; @@ -611,9 +664,7 @@ public void UpdatePooledLight(StationaryLight light) return; } - var position = light.CachedPosition; - _lightPositionsAndAttenuation[light.Index] = new Vector4(position.x, position.y, position.z, - 1f / Mathf.Max(0.01f, light.CachedRange * light.CachedRange)); + _lightPositionsAndAttenuation[light.Index] = GetSlotPositionAndAttenuation(light); _lightColors[light.Index] = light.RuntimeLinearColor; _isUploadDirty = true; } @@ -687,14 +738,15 @@ private void RebalancePool() continue; var slot = _freeRuntimeSlots.Pop(); - var position = light.CachedPosition; - _lightPositionsAndAttenuation[slot] = new Vector4(position.x, position.y, position.z, - 1f / (light.CachedRange * light.CachedRange)); - _lightColors[slot] = light.RuntimeLinearColor; light.AttachSlot(slot); + _lightPositionsAndAttenuation[slot] = GetSlotPositionAndAttenuation(light); + _lightColors[slot] = light.RuntimeLinearColor; _isUploadDirty = true; } + UpdateUnityLights(camPos); + UpdateShadowLights(camPos); + if (_wantedLights.Count > _poolPeak) { _poolPeak = _wantedLights.Count; @@ -706,6 +758,8 @@ private void RebalancePool() private void FreeSlot(StationaryLight light) { + if (_shadowLights.Remove(light)) + SetLightShadow(light, false); var slot = light.Index; light.DetachSlot(); if (slot <= HeroLightIndex || slot >= _lightPositionsAndAttenuation.Length) @@ -717,6 +771,116 @@ private void FreeSlot(StationaryLight light) _isUploadDirty = true; } + private void UpdateUnityLights(Vector3 cameraPosition) + { + foreach (var light in _pooledLights) + { + if (light == null) + continue; + var isNear = Vector3.Distance(light.CachedPosition, cameraPosition) - light.CachedRange <= + _unityLightMaxDistance; + light.SetUnityLightEnabled(isNear); + } + } + + /// + /// Position and 1/range² of a slot - negative for a shadow casting light (the shaders look up its shadow). + /// + private Vector4 GetSlotPositionAndAttenuation(StationaryLight light) + { + var position = light.CachedPosition; + var attenuation = 1f / Mathf.Max(0.01f, light.CachedRange * light.CachedRange); + return new Vector4(position.x, position.y, position.z, + _shadowLights.Contains(light) ? -attenuation : attenuation); + } + + /// + /// The _maxShadowLights pooled lights closest to the camera cast shadows (option "Shadows" not off), the rest + /// not. Runs with the pool's rebalance (camera moved 2 m or every 2 s). + /// + private void UpdateShadowLights(Vector3 cameraPosition) + { + _shadowCandidates.Clear(); + _wantedShadowLights.Clear(); + if (_configService.Gothic.GetInt(Constants.IniNames.Shadows, Constants.IniNames.ShadowsDefaultValue) > 0) + { + foreach (var light in _pooledLights) + { + if (light == null || light.Index <= HeroLightIndex || light.IsBakedIntoWorld || + !light.isActiveAndEnabled) + continue; + var distance = Vector3.Distance(light.CachedPosition, cameraPosition); + if (distance - light.CachedRange <= _shadowLightMaxDistance) + _shadowCandidates.Add((distance, light)); + } + _shadowCandidates.Sort((a, b) => a.Distance.CompareTo(b.Distance)); + for (var i = 0; i < _shadowCandidates.Count && i < _maxShadowLights; i++) + _wantedShadowLights.Add(_shadowCandidates[i].Light); + } + + _shadowCandidates.Clear(); + foreach (var light in _shadowLights) + if (light == null || !_wantedShadowLights.Contains(light)) + _shadowCandidates.Add((0f, light)); + foreach (var (_, light) in _shadowCandidates) + { + _shadowLights.Remove(light); + if (light != null) + SetLightShadow(light, false); + } + + foreach (var light in _wantedShadowLights) + if (_shadowLights.Add(light)) + SetLightShadow(light, true); + } + + /// + /// Option "Shadows" changed: the shadow lights follow at once (off: none). + /// + public void RefreshShadowLights() + { + var cam = Camera.main; + if (cam == null || _lightPositionsAndAttenuation == null) + return; + foreach (var light in _shadowLights) + if (light != null) + SetLightShadow(light, true); + UpdateShadowLights(cam.transform.position); + } + + private void SetLightShadow(StationaryLight light, bool isOn) + { + var unityLight = light.GetComponent(); + if (unityLight == null) + return; + + var option = _configService.Gothic.GetInt(Constants.IniNames.Shadows, + Constants.IniNames.ShadowsDefaultValue); + unityLight.shadows = !isOn ? LightShadows.None : option == 1 ? LightShadows.Hard : LightShadows.Soft; + if (isOn) + _shadowUnityLights.Add(unityLight); + else + _shadowUnityLights.Remove(unityLight); + // URP's 8 lights per object: the shadow casting ones first. + unityLight.renderMode = isOn ? LightRenderMode.ForcePixel : LightRenderMode.Auto; + unityLight.shadowNearPlane = _shadowLightNearPlane; + if (isOn) + { + var lightData = unityLight.GetUniversalAdditionalLightData(); + lightData.softShadowQuality = option == 2 ? SoftShadowQuality.Low : SoftShadowQuality.High; + } + + if (light.Index > HeroLightIndex && light.Index < _lightPositionsAndAttenuation.Length) + { + _lightPositionsAndAttenuation[light.Index] = GetSlotPositionAndAttenuation(light); + _isUploadDirty = true; + } + // Its renderers re-sort their lights (UpdateRenderer: shadow casting ones first). + foreach (var renderer in light.AffectedRenderers) + if (renderer != null) + _dirtiedMeshes.Add(renderer); + } + private void UploadGlobalLightArrays() { // Unity exception: Zero sized arrays aren't allowed for Shader values. diff --git a/Assets/Gothic-Core/Settings/URP-HighFidelity-Renderer.asset b/Assets/Gothic-Core/Settings/URP-HighFidelity-Renderer.asset index f2a24f0f7..572cbc61c 100644 --- a/Assets/Gothic-Core/Settings/URP-HighFidelity-Renderer.asset +++ b/Assets/Gothic-Core/Settings/URP-HighFidelity-Renderer.asset @@ -1,5 +1,18 @@ %YAML 1.1 %TAG !u! tag:unity3d.com,2011: +--- !u!114 &-4152970174121565736 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: d964ebd92a12dd1428d2e982025fd22a, type: 3} + m_Name: GothicShadowLights + m_EditorClassIdentifier: Gothic.Core::Gothic.Core.Adapters.Rendering.GothicShadowLightsFeature + m_Active: 1 --- !u!114 &-1878332245247344467 MonoBehaviour: m_ObjectHideFlags: 0 @@ -13,8 +26,8 @@ MonoBehaviour: m_Name: SSAO m_EditorClassIdentifier: m_Active: 1 - m_Shader: {fileID: 4800000, guid: 0849e84e3d62649e8882e9d6f056a017, type: 3} m_Settings: + AOMethod: 1 Downsample: 0 AfterOpaque: 0 Source: 1 @@ -22,7 +35,10 @@ MonoBehaviour: Intensity: 0.5 DirectLightingStrength: 0.25 Radius: 0.25 - SampleCount: 12 + Samples: 0 + BlurQuality: 0 + Falloff: 100 + SampleCount: -1 --- !u!114 &11400000 MonoBehaviour: m_ObjectHideFlags: 0 @@ -36,30 +52,28 @@ MonoBehaviour: m_Name: URP-HighFidelity-Renderer m_EditorClassIdentifier: debugShaders: - debugReplacementPS: {fileID: 4800000, guid: cf852408f2e174538bcd9b7fda1c5ae7, - type: 3} + debugReplacementPS: {fileID: 4800000, guid: cf852408f2e174538bcd9b7fda1c5ae7, type: 3} + hdrDebugViewPS: {fileID: 4800000, guid: 573620ae32aec764abd4d728906d2587, type: 3} + probeVolumeSamplingDebugComputeShader: {fileID: 7200000, guid: 53626a513ea68ce47b59dc1299fe3959, type: 3} + probeVolumeResources: + probeVolumeDebugShader: {fileID: 0} + probeVolumeFragmentationDebugShader: {fileID: 0} + probeVolumeOffsetDebugShader: {fileID: 0} + probeVolumeSamplingDebugShader: {fileID: 0} + probeSamplingDebugMesh: {fileID: 0} + probeSamplingDebugTexture: {fileID: 0} + probeVolumeBlendStatesCS: {fileID: 0} m_RendererFeatures: - {fileID: -1878332245247344467} - m_RendererFeatureMap: adc0de57c6d2eee5 + - {fileID: -4152970174121565736} + m_RendererFeatureMap: adc0de57c6d2eee5d821b148a1af5dc6 m_UseNativeRenderPass: 0 + xrSystemData: {fileID: 0} postProcessData: {fileID: 11400000, guid: 41439944d30ece34e96484bdb6645b55, type: 2} - xrSystemData: {fileID: 11400000, guid: 60e1133243b97e347b653163a8c01b64, type: 2} - shaders: - blitPS: {fileID: 4800000, guid: c17132b1f77d20942aa75f8429c0f8bc, type: 3} - copyDepthPS: {fileID: 4800000, guid: d6dae50ee9e1bfa4db75f19f99355220, type: 3} - screenSpaceShadowPS: {fileID: 0} - samplingPS: {fileID: 4800000, guid: 04c410c9937594faa893a11dceb85f7e, type: 3} - stencilDeferredPS: {fileID: 4800000, guid: e9155b26e1bc55942a41e518703fe304, type: 3} - fallbackErrorPS: {fileID: 4800000, guid: e6e9a19c3678ded42a3bc431ebef7dbd, type: 3} - materialErrorPS: {fileID: 4800000, guid: 5fd9a8feb75a4b5894c241777f519d4e, type: 3} - coreBlitPS: {fileID: 4800000, guid: 93446b5c5339d4f00b85c159e1159b7c, type: 3} - coreBlitColorAndDepthPS: {fileID: 4800000, guid: d104b2fc1ca6445babb8e90b0758136b, - type: 3} - cameraMotionVector: {fileID: 4800000, guid: c56b7e0d4c7cb484e959caeeedae9bbf, - type: 3} - objectMotionVector: {fileID: 4800000, guid: 7b3ede40266cd49a395def176e1bc486, - type: 3} - m_AssetVersion: 2 + m_AssetVersion: 3 + m_PrepassLayerMask: + serializedVersion: 2 + m_Bits: 4294967295 m_OpaqueLayerMask: serializedVersion: 2 m_Bits: 4294967295 @@ -77,7 +91,7 @@ MonoBehaviour: m_RenderingMode: 0 m_DepthPrimingMode: 0 m_CopyDepthMode: 0 + m_DepthAttachmentFormat: 0 + m_DepthTextureFormat: 0 m_AccurateGbufferNormals: 0 - m_ClusteredRendering: 0 - m_TileSize: 32 m_IntermediateTextureMode: 1 diff --git a/Assets/Gothic-Core/Shaders/GothicIncludes.hlsl b/Assets/Gothic-Core/Shaders/GothicIncludes.hlsl index 0c31309cd..78f07c859 100644 --- a/Assets/Gothic-Core/Shaders/GothicIncludes.hlsl +++ b/Assets/Gothic-Core/Shaders/GothicIncludes.hlsl @@ -29,6 +29,16 @@ float CalcMipLevel(float2 uv) return max(0.0, 0.5 * log2(delta_max_sqr)); } +// Lamps and fires: a bit stronger than their Gothic color - the light sum stops at 1 (GothicClampLight), so pools +// next to each other don't burn out. +#define STATIONARY_LIGHT_STRENGTH 1.4 + +// 1 at the light, 0 at its range: 1 - (d/R)² keeps the pool's middle bright (linear 1 - d/R faded at once). +float StationaryLightFalloff(float distanceSqr, float oneOverRangeSqr) +{ + return saturate(1.0 - distanceSqr * oneOverRangeSqr) * STATIONARY_LIGHT_STRENGTH; +} + float CustomDistanceAttenuation(float distanceSqr, float rcpSqrRange) { return 1 - saturate(distanceSqr * rcpSqrRange); diff --git a/Assets/Gothic-Core/Shaders/GothicShadows.hlsl b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl index 938846534..29368eef7 100644 --- a/Assets/Gothic-Core/Shaders/GothicShadows.hlsl +++ b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl @@ -51,12 +51,73 @@ GothicOcclusion GothicGetOcclusion(float4 positionCS) return occlusion; } +// Gothic's light is 0...1 per channel (8 bit vertex light): a lamp's pool next to another's and the baked light +// burnt the colors out (bright orange) - the sum stops at 1, like in the engine. +half3 GothicClampLight(half3 light) +{ + return min(light, 1.0); +} + // Objects and plants: sun (shadowed) + ambient, both occluded - SunAndAmbientDiffuse per pixel. half3 GothicSunAndAmbient(half3 sunDiffuse, float3 worldPos, GothicOcclusion occlusion) { return saturate(sunDiffuse * GothicSunShadow(worldPos) * occlusion.direct + _AmbientColor * occlusion.indirect); } +// The few closest lamps, fires and torches are shadow casting URP lights (StationaryLightsService). True for such a +// light of the object's per-object lights. +bool GothicIsShadowedLight(int lightIndex) +{ +#if defined(_ADDITIONAL_LIGHT_SHADOWS) + return GetAdditionalLightShadowParams(lightIndex).w >= 0; +#else + return false; +#endif +} + +// This frame's shadow casting lights: their index among URP's additional lights (GothicShadowLightsFeature) - not +// the object's per-object list (8 lights, a big world chunk near candles didn't get the lamp). +float4 _GothicShadowLightIndices[2]; +float _GothicShadowLightCount; + +// The shadow casting lights, per pixel with their cube shadow. World and plants (isStationaryFalloff): like a +// stationary light (StationaryLightFalloff, no N·L, StationaryLighting.hlsl - which skips them). Objects and NPCs: like their +// other lights (AdditionalUnityLightDiffuse). +half3 GothicShadowedLights(float3 worldPos, half3 normalWS, bool isStationaryFalloff) +{ + half3 diffuse = 0; +#if defined(_ADDITIONAL_LIGHT_SHADOWS) + int count = min(8, (int)_GothicShadowLightCount); + for (int k = 0; k < count; k++) + { + int lightIndex = (int)_GothicShadowLightIndices[k / 4][k % 4]; + + #if USE_STRUCTURED_BUFFER_FOR_LIGHT_DATA + float4 lightPositionWS = _AdditionalLightsBuffer[lightIndex].position; + half3 color = _AdditionalLightsBuffer[lightIndex].color.rgb; + half4 distanceAndSpotAttenuation = _AdditionalLightsBuffer[lightIndex].attenuation; + #else + float4 lightPositionWS = _AdditionalLightsPosition[lightIndex]; + half3 color = _AdditionalLightsColor[lightIndex].rgb; + half4 distanceAndSpotAttenuation = _AdditionalLightsAttenuation[lightIndex]; + #endif + float3 lightVector = lightPositionWS.xyz - worldPos * lightPositionWS.w; + float distanceSqr = max(dot(lightVector, lightVector), HALF_MIN); + half3 lightDirection = half3(lightVector * rsqrt(distanceSqr)); + half attenuation = isStationaryFalloff + ? StationaryLightFalloff(distanceSqr, distanceAndSpotAttenuation.x) + : CustomDistanceAttenuation(distanceSqr, distanceAndSpotAttenuation.x) * + saturate(dot(lightDirection, normalWS)); + if (attenuation <= 0) + continue; + + half shadow = AdditionalLightRealtimeShadow(lightIndex, worldPos, lightDirection); + diffuse += color * attenuation * shadow * _PointLightIntensity; + } +#endif + return diffuse; +} + // The baked light of a sun-facing surface, darkened by the shadow at worldPos. half3 GothicApplySunShadow(half3 bakedLight, half3 normalWS, float3 worldPos) { diff --git a/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader b/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader index 4514731bd..cda86ed24 100644 --- a/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader +++ b/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage.shader @@ -28,6 +28,7 @@ Shader "Lit/AlphaToCoverage" #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION + #pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" @@ -87,7 +88,10 @@ Shader "Lit/AlphaToCoverage" for (uint k = 0; k < min(_StationaryLightCount, MAX_AFFECTING_STATIONARY_LIGHTS); k++) { - diffuse += AdditionalStationaryDiffuse(_StationaryLightIndices[k / 4][k % 4], worldPos, normal); + uint lightIndex = _StationaryLightIndices[k / 4][k % 4]; + // Shadow casting lights come per pixel through URP (GothicShadowedLights). + if (!IsStationaryLightShadowed(lightIndex)) + diffuse += AdditionalStationaryDiffuse(lightIndex, worldPos, normal); } return diffuse; @@ -130,8 +134,9 @@ Shader "Lit/AlphaToCoverage" saturate(max(i.distance, 0.0001) / _DistanceFade)); GothicOcclusion occlusion = GothicGetOcclusion(i.vertex); - half3 light = GothicSunAndAmbient(i.sunDiffuse, i.worldPos, occlusion) + i.diffuse * occlusion.direct; - half3 diffuse = albedo.rgb * light; + half3 light = GothicSunAndAmbient(i.sunDiffuse, i.worldPos, occlusion) + + (i.diffuse + GothicShadowedLights(i.worldPos, half3(0, 1, 0), true)) * occlusion.direct; + half3 diffuse = albedo.rgb * GothicClampLight(light); diffuse = ApplyUnderWaterEffect(diffuse); diff --git a/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader b/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader index ba1819f7c..ec2755634 100644 --- a/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader +++ b/Assets/Gothic-Core/Shaders/Lit-SingleMesh.shader @@ -25,6 +25,7 @@ Shader "Lit/SingleMesh" #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION + #pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" @@ -46,6 +47,7 @@ Shader "Lit/SingleMesh" float3 worldPos : TEXCOORD1; // The sun's part (shadowed per pixel); diffuse: lights. half3 sunDiffuse : TEXCOORD2; + half3 normalWS : TEXCOORD3; half3 diffuse : COLOR; UNITY_VERTEX_OUTPUT_STEREO @@ -72,6 +74,9 @@ Shader "Lit/SingleMesh" for (int j = 0; j < min(MAX_VISIBLE_LIGHTS, unity_LightData.y); j++) { int lightIndex = GetPerObjectLightIndex(j); + // Shadow casting lights come per pixel (GothicShadowedLights). + if (GothicIsShadowedLight(lightIndex)) + continue; Light light = CustomGetAdditionalPerObjectLight(lightIndex, worldPos); diffuse += AdditionalUnityLightDiffuse(light, normal); } @@ -93,6 +98,7 @@ Shader "Lit/SingleMesh" o.uv = TRANSFORM_TEX(v.uv, _MainTex); half3 normalWS = TransformObjectToWorldNormal(v.normal); o.sunDiffuse = SunDiffuse(normalWS, v.color); + o.normalWS = normalWS; o.diffuse = DiffuseLighting(normalWS, o.worldPos); return o; } @@ -101,8 +107,9 @@ Shader "Lit/SingleMesh" { half4 albedo = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.uv); GothicOcclusion occlusion = GothicGetOcclusion(i.vertex); - half3 light = GothicSunAndAmbient(i.sunDiffuse, i.worldPos, occlusion) + i.diffuse * occlusion.direct; - half3 diffuse = albedo.rgb * light; + half3 light = GothicSunAndAmbient(i.sunDiffuse, i.worldPos, occlusion) + + (i.diffuse + GothicShadowedLights(i.worldPos, normalize(i.normalWS), false)) * occlusion.direct; + half3 diffuse = albedo.rgb * GothicClampLight(light); diffuse = ApplyUnderWaterEffect(diffuse); diff --git a/Assets/Gothic-Core/Shaders/Lit-World.shader b/Assets/Gothic-Core/Shaders/Lit-World.shader index 8b7130ed8..8e51af56a 100644 --- a/Assets/Gothic-Core/Shaders/Lit-World.shader +++ b/Assets/Gothic-Core/Shaders/Lit-World.shader @@ -31,6 +31,7 @@ Shader "Lit/World" #pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN #pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH #pragma multi_compile_fragment _ _SCREEN_SPACE_OCCLUSION + #pragma multi_compile _ _ADDITIONAL_LIGHT_SHADOWS #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" @@ -93,15 +94,18 @@ Shader "Lit/World" half3 diffuse = 0; for (uint k = 0; k < min(_StationaryLightCount, MAX_AFFECTING_STATIONARY_LIGHTS); k++) { - diffuse += AdditionalStationaryDiffuse(_StationaryLightIndices[k / 4][k % 4], worldPos, normal); + uint lightIndex = _StationaryLightIndices[k / 4][k % 4]; + if (!IsStationaryLightShadowed(lightIndex)) + diffuse += AdditionalStationaryDiffuse(lightIndex, worldPos, normal); } if (_StationaryLightCount >= MAX_AFFECTING_STATIONARY_LIGHTS) { for (uint l = 0; l < min(_StationaryLightCount - MAX_AFFECTING_STATIONARY_LIGHTS, MAX_AFFECTING_STATIONARY_LIGHTS); l++) { - diffuse += AdditionalStationaryDiffuse(_StationaryLightIndices2[l / 4][l % 4], worldPos, - normal); + uint lightIndex2 = _StationaryLightIndices2[l / 4][l % 4]; + if (!IsStationaryLightShadowed(lightIndex2)) + diffuse += AdditionalStationaryDiffuse(lightIndex2, worldPos, normal); } } return diffuse; @@ -154,8 +158,9 @@ Shader "Lit/World" GothicOcclusion occlusion = GothicGetOcclusion(i.vertex); half3 light = baseLight * occlusion.indirect + - StationaryLighting(normal, i.worldPos) * occlusion.direct; - half3 diffuse = albedo.rgb * light * _FocusBrightness; + (StationaryLighting(normal, i.worldPos) + GothicShadowedLights(i.worldPos, normal, true)) * + occlusion.direct; + half3 diffuse = albedo.rgb * GothicClampLight(light) * _FocusBrightness; diffuse = ApplyUnderWaterEffect(diffuse); diff --git a/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl b/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl index ab17a16f0..51138c542 100644 --- a/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl +++ b/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl @@ -13,14 +13,22 @@ float4 _GlobalStationaryLightPositionsAndAttenuation[MAX_TOTAL_STATIONARY_LIGHTS]; real3 _GlobalStationaryLightColors[MAX_TOTAL_STATIONARY_LIGHTS]; +// A pooled light with w < 0 casts a shadow (StationaryLightsService): the shaders light it through its URP light with +// the cube shadow (GothicShadowedLights) and skip it here - URP reaches every object in its range, the pool only the +// renderers the light gathered. +bool IsStationaryLightShadowed(uint lightIndex) +{ + return _GlobalStationaryLightPositionsAndAttenuation[lightIndex].w < 0; +} + half3 AdditionalStationaryDiffuse(uint lightIndex, real3 worldPos, real3 normal) { float4 lightPosAndAttenuation = _GlobalStationaryLightPositionsAndAttenuation[lightIndex]; float3 lightVector = lightPosAndAttenuation.xyz - worldPos; float distanceSqr = max(dot(lightVector, lightVector), HALF_MIN); - // Linear distance falloff (1 - d/R) - float attenuation = saturate(1.0 - sqrt(distanceSqr * lightPosAndAttenuation.w)); + // w = 1/R², negative for a shadow casting light. + float attenuation = StationaryLightFalloff(distanceSqr, abs(lightPosAndAttenuation.w)); return _GlobalStationaryLightColors[lightIndex] * attenuation * _PointLightIntensity; } From faf63e22aeada3d76ec91fd3dd9bfe52ce74a347 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 22 Nov 2026 20:36:39 +0000 Subject: [PATCH 03/13] fix: outdoor lamps and fires dim by day - a lamp no longer glows red on shaded walls at noon Gothic's lights burn all day, but its bright vertex light hid them. Ours are stronger and the sun's shadow leaves 40%, so lamps glowed on shaded walls at noon. Lights outside of houses and caves (no light mapped polygons within 3 m) follow the day light: full at night, 20% at noon - their pool slot and Unity light (objects, NPCs, lamp shadows). Fireplaces inside, mines and the hero's torch stay. --- .../Scripts/Adapters/Vob/StationaryLight.cs | 5 ++ .../Domain/Vobs/VobInitializerDomain.cs | 4 ++ .../Scripts/Services/World/SkyService.cs | 3 ++ .../Services/World/StationaryLightsService.cs | 46 ++++++++++++++++++- 4 files changed, 56 insertions(+), 2 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs index 36ecc9c6a..54a006465 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs @@ -141,6 +141,11 @@ public float SpotAngle /// public bool IsBakedIntoWorld { get; set; } + /// + /// Not in a house or cave (no light mapped polygons around): its light dims by day (StationaryLightsService). + /// + public bool IsOutdoor { get; set; } + public int AffectedRendererCount => _affectedRenderers.Count; public IReadOnlyList AffectedRenderers => _affectedRenderers; diff --git a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs index beb1ff979..2ef450dfb 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs @@ -653,6 +653,10 @@ private GameObject CreateLight(Light vob, GameObject parent, Vector3 worldPositi // A static light is in the world's lightmaps (EnableWorldLightmaps) - it lights VOBs and NPCs only. lightComp.IsBakedIntoWorld = vob.LightStatic && _stationaryLightsService.HasWorldLightmaps; + // Street lamps and camp fires dim by day (StationaryLightsService.SetDaylight) - not the fireplaces in + // houses and caves (light mapped polygons around). + lightComp.IsOutdoor = !_stationaryLightsService.IsNearLightMappedPolygons(worldPosition, + Constants.Fires.IndoorRadius); // All world lights share the shader slots - the ones closest to the camera get them. lightComp.RuntimeLinearColor = lightComp.Color.linear; diff --git a/Assets/Gothic-Core/Scripts/Services/World/SkyService.cs b/Assets/Gothic-Core/Scripts/Services/World/SkyService.cs index 2c975bab5..d58498d91 100644 --- a/Assets/Gothic-Core/Scripts/Services/World/SkyService.cs +++ b/Assets/Gothic-Core/Scripts/Services/World/SkyService.cs @@ -27,6 +27,7 @@ public class SkyService [Inject] private readonly TextureCacheService _textureCacheService; [Inject] private readonly TextureService _textureService; [Inject] private readonly SaveGameService _saveGameService; + [Inject] private readonly StationaryLightsService _stationaryLightsService; // The light of indoor worlds (no sun, no fog): dark - mines are lit by their lamps (lightmaps), fires and the // hero's torch/Light spell, not by a sky (0.25 lit the Old Mine's rock like a cloudy day). @@ -394,6 +395,8 @@ private void SetDayLight(Color polyColor) var rainFactor = Mathf.Lerp(1f, _rainLightFactor, _rainWeightAndVolume); var dayLight = _isIndoorWorld ? _indoorLight : polyColor * (nightFactor * rainFactor); dayLight.a = 1f; + // Outdoor lamps and fires dim by day. + _stationaryLightsService.SetDaylight(dayLight.grayscale); Shader.SetGlobalColor(_dayLightColorShaderId, dayLight); Shader.SetGlobalColor(_sunColorShaderId, diff --git a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs index 2abfdf073..1a56a1ad3 100644 --- a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs +++ b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs @@ -646,6 +646,8 @@ public bool IsNearLightMappedPolygons(Vector3 position, float rangeMeters) /// public void RegisterPooledLight(StationaryLight light) { + if (light.IsOutdoor) + light.Intensity = _outdoorLightFactor; if (_pooledLights.Add(light)) _isPoolDirty = true; } @@ -665,7 +667,7 @@ public void UpdatePooledLight(StationaryLight light) } _lightPositionsAndAttenuation[light.Index] = GetSlotPositionAndAttenuation(light); - _lightColors[light.Index] = light.RuntimeLinearColor; + _lightColors[light.Index] = GetSlotColor(light); _isUploadDirty = true; } @@ -740,7 +742,7 @@ private void RebalancePool() var slot = _freeRuntimeSlots.Pop(); light.AttachSlot(slot); _lightPositionsAndAttenuation[slot] = GetSlotPositionAndAttenuation(light); - _lightColors[slot] = light.RuntimeLinearColor; + _lightColors[slot] = GetSlotColor(light); _isUploadDirty = true; } @@ -783,6 +785,46 @@ private void UpdateUnityLights(Vector3 cameraPosition) } } + /// + /// Outdoor lamps and fires by day: Gothic's lights burn all day, but its bright vertex light hid them. Ours are + /// stronger (StationaryLightFalloff) and the sun's shadow leaves 40% - lamps glowed red on shaded walls at noon. + /// Night (sky brightness up to _lampFullBrightness) full, noon _lampDayFactor. + /// + private const float _lampDayFactor = 0.2f; + private const float _lampFullBrightness = 0.35f; + private float _outdoorLightFactor = 1f; + + /// + /// SkyService: the world's day light changed (its brightness 0..1, indoor worlds dark). Outdoor lights follow. + /// + public void SetDaylight(float brightness) + { + var factor = Mathf.Lerp(1f, _lampDayFactor, Mathf.InverseLerp(_lampFullBrightness, 1f, brightness)); + if (Mathf.Abs(factor - _outdoorLightFactor) < 0.02f) + return; + + _outdoorLightFactor = factor; + if (_lightColors == null) + return; + foreach (var light in _pooledLights) + { + if (light == null || !light.IsOutdoor) + continue; + // The Unity light lights objects/NPCs and the shadow casting lamps' pools. + light.Intensity = factor; + if (light.Index > HeroLightIndex && light.Index < _lightColors.Length) + { + _lightColors[light.Index] = GetSlotColor(light); + _isUploadDirty = true; + } + } + } + + private Color GetSlotColor(StationaryLight light) + { + return light.IsOutdoor ? light.RuntimeLinearColor * _outdoorLightFactor : light.RuntimeLinearColor; + } + /// /// Position and 1/range² of a slot - negative for a shadow casting light (the shaders look up its shadow). /// From 718f7d9695fa846efeb26f8138189e6cbd56e54f Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 22 Nov 2026 20:42:51 +0000 Subject: [PATCH 04/13] fix: a light counts as indoors only under a light mapped ceiling - Khorinis' street lamps next to light mapped walls dim by day too Light mapped polygons within 3 m made a light indoors: the market's street lamps stand next to light mapped walls and stairs (and the sewers run below), they kept glowing at noon. Now a light mapped polygon 2-8 m right above the light (roof, cave or sewer ceiling) makes it indoors. --- .../Scripts/Domain/Vobs/VobInitializerDomain.cs | 7 +++---- .../Services/World/StationaryLightsService.cs | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs index 2ef450dfb..58ef05aec 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs @@ -653,10 +653,9 @@ private GameObject CreateLight(Light vob, GameObject parent, Vector3 worldPositi // A static light is in the world's lightmaps (EnableWorldLightmaps) - it lights VOBs and NPCs only. lightComp.IsBakedIntoWorld = vob.LightStatic && _stationaryLightsService.HasWorldLightmaps; - // Street lamps and camp fires dim by day (StationaryLightsService.SetDaylight) - not the fireplaces in - // houses and caves (light mapped polygons around). - lightComp.IsOutdoor = !_stationaryLightsService.IsNearLightMappedPolygons(worldPosition, - Constants.Fires.IndoorRadius); + // Street lamps and camp fires dim by day (StationaryLightsService.SetDaylight) - not the lights under a + // light mapped ceiling (houses, caves, Khorinis' sewers below the market). + lightComp.IsOutdoor = !_stationaryLightsService.HasLightMappedCeiling(worldPosition); // All world lights share the shader slots - the ones closest to the camera get them. lightComp.RuntimeLinearColor = lightComp.Color.linear; diff --git a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs index 1a56a1ad3..52322c909 100644 --- a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs +++ b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs @@ -626,6 +626,21 @@ public void SetLightMappedCells(HashSet cells) /// Gothic bakes a static light into the world's vertex light outdoors (we render that already) and into /// lightmaps indoors (caves, houses - we don't). Only lights next to light mapped polygons are worth a slot. /// + /// + /// Light mapped polygons in the 2 m column right above (2 to 8 m up): a roof or a ceiling - the position is + /// indoors (house, cave, sewer). Walls next to it don't count (Khorinis' street lamps stand next to light mapped + /// walls, the sewers' lamps below the open market). + /// + public bool HasLightMappedCeiling(Vector3 position) + { + for (var up = 1; up <= 4; up++) + { + if (_lightMappedCells.Contains(ToCell(position + Vector3.up * (up * _cellSize)))) + return true; + } + return false; + } + public bool IsNearLightMappedPolygons(Vector3 position, float rangeMeters) { if (_lightMappedCells.Count == 0) From 97cee68ec54689d87c85b21a97a4351bffbf1e43 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 22 Nov 2026 20:43:26 +0000 Subject: [PATCH 05/13] docs: shadows and darkness - decision record and the lighting doc's new section --- Docs/adr/2026-11-22-pcvr-shadows-lighting.md | 23 ++++++++++++++++++++ Docs/world-lighting.md | 21 ++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 Docs/adr/2026-11-22-pcvr-shadows-lighting.md diff --git a/Docs/adr/2026-11-22-pcvr-shadows-lighting.md b/Docs/adr/2026-11-22-pcvr-shadows-lighting.md new file mode 100644 index 000000000..16afb911d --- /dev/null +++ b/Docs/adr/2026-11-22-pcvr-shadows-lighting.md @@ -0,0 +1,23 @@ +# ADR: Dynamic shadows and lighting on PC (GD3D11-like) + +- Date: 2026-11-22 +- Technical details: Docs/world-lighting.md (section "Shadows and darkness") + +## Context + +Gothic bakes its lighting: the sun's shadows are in the world's vertex light, the light of lamps and fires is in the lightmaps or added flat. Nothing casts a shadow at runtime, and at night the world stays fairly bright. GD3D11, the well-known D3D11 renderer mod for the original games, adds dynamic sun shadows, shadows of lamps and fires, ambient occlusion and darker nights, while keeping Gothic's look. In VR these shadows make a big difference to immersion. Our shaders could neither cast nor receive shadows, and the world had no sun light. The shaders' "sun direction" was a set of angles, not a direction. + +## Decisions + +1. **The sun and moon cast dynamic shadows on PC.** The sun rises at 6, is highest at 12 (60 degrees, so shadows never vanish under objects) and sets at 18. At night the moon takes its place with a weaker shadow, and the shadows fade out at the horizon. The shadow darkens only the sun's part of the light, so lightmaps, ambient light and fires stay as they are. That is how GD3D11 does it, and it keeps the baked Gothic look. Not chosen: replacing Gothic's baked light with Unity's lighting, which would be a different game. +2. **The few lights closest to the player cast shadows too.** Up to 6 lamps and fires (not lights baked into lightmaps) get a real shadow: a street lamp throws its iron cage onto the ground. Every such light renders its surroundings six times, so all lights casting shadows would be far too expensive. Not chosen: shadows for every light. +3. **Ambient occlusion on PC.** It gives soft contact shadows in corners and under objects, and darkens the baked and ambient light more than the sun and fires (like GD3D11). +4. **Gothic's light stops at full brightness.** Lamps next to each other no longer burn the colors out. The engine's 8-bit vertex light worked the same way. +5. **Nights, mines and rain are darker; lamps and fires outdoors dim by day.** Lights stand out at night, mines are lit by their lamps and the hero's torch, and a street lamp doesn't glow on a shaded wall at noon. Lights under a roof (houses, caves, sewers) stay as they are. Gothic's lamps burn all day too, but its bright vertex light hid them. Ours are stronger, so we dim them, which is a deliberate difference from the original. +6. **A "Shadows" option in the VR Immersion menu: off, hard, medium, soft (default soft).** Not every PC is fast. Quest stays without shadows and ambient occlusion: its quality level has them off. + +## Consequences + +- PC costs GPU time for the shadow maps (the sun's cascades plus up to 6 point lights) and ambient occlusion. Players with slower PCs pick hard shadows or switch them off. +- The hero's torch and spells don't cast shadows yet (follow-up). Neither do lights baked into lightmaps. +- Not done in this step: height fog, god rays, bloom and tonemapping, water reflections. diff --git a/Docs/world-lighting.md b/Docs/world-lighting.md index 4e720ef16..e958fb6f1 100644 --- a/Docs/world-lighting.md +++ b/Docs/world-lighting.md @@ -58,3 +58,24 @@ Core code is in `Assets/Gothic-Core/Scripts/`. | Rule | Lives in | |------|----------| | A world whose BSP tree is indoor (mines, temples) has no sun and no fog, the time of day doesn't darken it | `Services/World/SkyService.cs` | + +## Shadows and darkness + +Why: Docs/adr/2026-11-22-pcvr-shadows-lighting.md. PC only - the Quest quality level (URP-Performant) draws no shadows +and no SSAO, the shaders compile those parts away there. + +| Rule | Lives in | +|------|----------| +| The "Sun" directional light is URP's main light (shadow map only, Gothic's shaders take `_SunColor`): rises 6:00, highest 12:00 (60°, path tilted), sets 18:00; at night the moon on the same path with a weaker shadow, faded out at the horizon. Moves every game second | `Services/World/SkyService.cs` (`RotateSun`, `UpdateSunLight`), `DeveloperConfig.SunUpdateInterval` | +| `_SunDirection` is the light's direction (sun/moon to the ground) - it used to be Euler angles | `SkyService`, `Shaders/GothicIncludes.hlsl` | +| Gothic's lit shaders cast shadows with the main pass' wind, alpha cut (plants) and fatness (NPCs); depth/normals passes feed SSAO | `Shaders/GothicShadowCaster.hlsl`, `Shaders/GothicDepthPasses.hlsl` | +| The sun's shadow darkens only the sun's part: baked light of sun-facing outdoor polygons and VOBs (not light mapped ones), the sun term of objects/NPCs | `Shaders/GothicShadows.hlsl`, `Lit-World`, `Lit-AlphaToCoverage`, `Lit-SingleMesh` | +| SSAO (HighFidelity renderer): darkens baked/ambient light, less the sun and lights | `GothicShadows.hlsl` (`GothicGetOcclusion`) | +| The 6 pooled lights closest to the camera within 30 m (not baked into lightmaps) cast cube shadows; the pool marks them (slot w < 0) and skips them, the shaders light them through URP | `Services/World/StationaryLightsService.cs` (`UpdateShadowLights`), `StationaryLighting.hlsl`, `GothicShadowedLights` | +| Their index among URP's additional lights, every frame - URP's 8 per-object lights cut a lamp off at a world chunk's edge | `Adapters/Rendering/GothicShadowLightsFeature.cs` (on `URP-HighFidelity-Renderer`) | +| Only Unity lights within 40 m stay enabled: URP takes 256 visible lights, the city has ~770 | `StationaryLightsService.UpdateUnityLights` | +| Renderers list their lights shadow casting first, then closest | `StationaryLightsService.UpdateRenderer` | +| Lamps/fires: falloff 1 - (d/R)², strength 1.4; the light sum stops at 1 like Gothic's 8 bit vertex light | `GothicIncludes.hlsl` (`StationaryLightFalloff`), `GothicShadows.hlsl` (`GothicClampLight`) | +| Nights: the world gets 50% of the night sky's light; rain 70% and a 35% sun shadow; indoor worlds (mines) 0.12 | `SkyService` (`SetDayLight`) | +| Outdoor lamps/fires (no light mapped ceiling 2-8 m above) dim by day: 100% at night, 20% at noon | `StationaryLightsService.SetDaylight`, `HasLightMappedCeiling`, `VobInitializerDomain.CreateLight` | +| Option "Shadows" (Immersion, Gothic.ini `shadows`): 0 off, 1 hard, 2 medium, 3 soft (default) - sun and point lights | `Constants.IniNames.Shadows`, `VRContextMenuService.CreateShadowsChoice` | From c64a13fafadbf93a4796b11162ae516dad4b4058 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 22 Nov 2026 20:44:32 +0000 Subject: [PATCH 06/13] feat: Shadows option texts in 8 languages (off / hard / medium / soft) --- .../Localizations/Gothic-UI Shared Data.asset | 12 ++++++++++++ .../Gothic-Core/Localizations/Gothic-UI_cs.asset | 13 +++++++++++++ .../Gothic-Core/Localizations/Gothic-UI_de.asset | 13 +++++++++++++ .../Gothic-Core/Localizations/Gothic-UI_en.asset | 13 +++++++++++++ .../Gothic-Core/Localizations/Gothic-UI_es.asset | 13 +++++++++++++ .../Gothic-Core/Localizations/Gothic-UI_fr.asset | 13 +++++++++++++ .../Gothic-Core/Localizations/Gothic-UI_it.asset | 13 +++++++++++++ .../Gothic-Core/Localizations/Gothic-UI_pl.asset | 13 +++++++++++++ .../Gothic-Core/Localizations/Gothic-UI_ru.asset | 16 ++++++++++++++++ 9 files changed, 119 insertions(+) diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset b/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset index 13af945fc..e554f3be9 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset @@ -567,6 +567,18 @@ MonoBehaviour: m_Key: vr.help.ring.text m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Key: menuitem.shadows.label + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Key: menuitem.shadows.description + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Key: menuitem.shadows.value + m_Metadata: + m_Items: [] m_Metadata: m_Items: [] m_KeyGenerator: diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset index 86544ba3a..1c80fa710 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset @@ -469,6 +469,19 @@ MonoBehaviour: m_Localized: "s t\u011Blem|prolnut\xED" m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: "St\xEDny" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "Dynamick\xE9 st\xEDny slunce, m\u011Bs\xEDce a sv\u011Btel. Ostr\xE9 + nebo vypnut\xE9 pro slab\u0161\xED PC" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: "Vyp.|Ostr\xE9|St\u0159edn\xED|M\u011Bkk\xE9" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset index 8daf4c595..abae47fa0 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset @@ -595,6 +595,19 @@ MonoBehaviour: \"Favoriten-Ring\"." m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: Schatten + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "Dynamische Schatten von Sonne, Mond und Lichtern. Hart oder aus + f\xFCr langsamere PCs" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: Aus|Hart|Mittel|Weich + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset index 418df7bd8..34bdc98d5 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset @@ -607,6 +607,19 @@ MonoBehaviour: it off in Immersion: "Favorites ring".' m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: Shadows + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: Dynamic shadows of the sun, moon and lights. Hard or off for slower + PCs + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: Off|Hard|Medium|Soft + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset index 57e8ee258..0cbb8256a 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset @@ -458,6 +458,19 @@ MonoBehaviour: m_Localized: con el cuerpo|fundido m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: Sombras + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "Sombras din\xE1micas del sol, la luna y las luces. Duras o desactivadas + para PC m\xE1s lentos" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: No|Duras|Medias|Suaves + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset index a111644b4..1d3197a14 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset @@ -463,6 +463,19 @@ MonoBehaviour: m_Localized: avec le corps|fondu m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: Ombres + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "Ombres dynamiques du soleil, de la lune et des lumi\xE8res. Dures + ou d\xE9sactiv\xE9es pour les PC plus lents" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: Non|Dures|Moyennes|Douces + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset index 45f797f75..dd23c47a8 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset @@ -459,6 +459,19 @@ MonoBehaviour: m_Localized: col corpo|dissolvenza m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: Ombre + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "Ombre dinamiche di sole, luna e luci. Nette o disattivate per PC + pi\xF9 lenti" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: No|Nette|Medie|Morbide + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset index 9bd41a227..b085b769e 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset @@ -465,6 +465,19 @@ MonoBehaviour: dr\u0105\u017Cek, gdy jest otwarty)" m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: Cienie + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "Dynamiczne cienie s\u0142o\u0144ca, ksi\u0119\u017Cyca i \u015Bwiate\u0142. + Twarde lub wy\u0142\u0105czone na s\u0142absze komputery" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: "Wy\u0142.|Twarde|\u015Arednie|Mi\u0119kkie" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset index c4fd61883..b97f83b1c 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset @@ -549,6 +549,22 @@ MonoBehaviour: m_Localized: "\u0441 \u0442\u0435\u043B\u043E\u043C|\u0437\u0430\u0442\u0435\u043C\u043D\u0435\u043D\u0438\u0435" m_Metadata: m_Items: [] + - m_Id: 196594145456431104 + m_Localized: "\u0422\u0435\u043D\u0438" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957056 + m_Localized: "\u0414\u0438\u043D\u0430\u043C\u0438\u0447\u0435\u0441\u043A\u0438\u0435 + \u0442\u0435\u043D\u0438 \u0441\u043E\u043B\u043D\u0446\u0430, \u043B\u0443\u043D\u044B + \u0438 \u043E\u0433\u043D\u0435\u0439. \u0416\u0451\u0441\u0442\u043A\u0438\u0435 + \u0438\u043B\u0438 \u0432\u044B\u043A\u043B. \u0434\u043B\u044F \u0441\u043B\u0430\u0431\u044B\u0445 + \u041F\u041A" + m_Metadata: + m_Items: [] + - m_Id: 196594145510957057 + m_Localized: "\u0412\u044B\u043A\u043B.|\u0416\u0451\u0441\u0442\u043A\u0438\u0435|\u0421\u0440\u0435\u0434\u043D\u0438\u0435|\u041C\u044F\u0433\u043A\u0438\u0435" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] From 6693cdbada1bb9fa5b54645e99858a7c23bb1b49 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 22 Nov 2026 21:11:12 +0000 Subject: [PATCH 07/13] feat: the hero's torch, the Light spell and spell projectiles cast shadows; highlighted NPCs and objects keep theirs - ClaimHeroLight takes the hero light's Unity light (torch, Light spell): it casts a cube shadow (near plane 0.2 m, so the torch's stick doesn't hide its flame), its slot is marked (w < 0) and the shaders light it through URP like the lamps. - Spell projectiles (VRSpellThrow) register their light as a dynamic shadow light: a flying fireball now lights the walls it passes (before only NPCs and objects) and throws shadows. Up to 4 dynamic shadow lights; destroyed ones drop out. - Spell effect lights (VisualFxLight: summoning, fire rain) come before the lamps among the pooled shadow lights. - 12 shadow lights at most (feature and shader). - Lit/SingleMesh-Dynamic and Lit/AlphaToCoverage-Dynamic (highlight on hover, fading) got a ShadowCaster pass - a highlighted NPC lost its shadow. - The Shadows option switches them too. --- .../Rendering/GothicShadowLightsFeature.cs | 3 +- .../Scripts/Adapters/Vob/StationaryLight.cs | 5 + .../Scripts/Adapters/Vob/VisualFxLight.cs | 1 + .../Services/World/StationaryLightsService.cs | 94 ++++++++++++++++++- Assets/Gothic-Core/Shaders/GothicShadows.hlsl | 4 +- .../Lit-AlphaToCoverage-Dynamic.shader | 41 ++++++++ .../Shaders/Lit-SingleMesh-Dynamic.shader | 35 +++++++ .../Scripts/Adapters/Vob/VobItem/VRSpellFx.cs | 3 +- .../Adapters/Vob/VobItem/VRSpellThrow.cs | 5 + .../Scripts/Adapters/Vob/VobItem/VRTorch.cs | 3 +- 10 files changed, 185 insertions(+), 9 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs index e6c58b301..1dfc75e70 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs @@ -15,7 +15,8 @@ namespace Gothic.Core.Adapters.Rendering /// public class GothicShadowLightsFeature : ScriptableRendererFeature { - private const int _maxShadowLights = 8; + // 6 lamps/fires + hero light + spell projectiles (StationaryLightsService). Same as GothicShadows.hlsl. + private const int _maxShadowLights = 12; private static readonly int _indicesShaderId = Shader.PropertyToID("_GothicShadowLightIndices"); private static readonly int _countShaderId = Shader.PropertyToID("_GothicShadowLightCount"); diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs index 54a006465..0b6581aef 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs @@ -146,6 +146,11 @@ public float SpotAngle /// public bool IsOutdoor { get; set; } + /// + /// A spell's light (VisualFxLight): it casts a shadow before the lamps (StationaryLightsService). + /// + public bool IsSpellLight { get; set; } + public int AffectedRendererCount => _affectedRenderers.Count; public IReadOnlyList AffectedRenderers => _affectedRenderers; diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/VisualFxLight.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/VisualFxLight.cs index 957a7b95c..4fbc6e01a 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/VisualFxLight.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/VisualFxLight.cs @@ -51,6 +51,7 @@ private void Init(LightPresetLoader.LightPreset preset, float rangeMeters) _light.Color = preset.Color; _light.Range = Mathf.Max(0.01f, _baseRange); _light.RuntimeLinearColor = preset.Color.linear; + _light.IsSpellLight = true; _light.Init(); _gatheredAt = transform.position; Apply(); diff --git a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs index 52322c909..931c81af4 100644 --- a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs +++ b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs @@ -101,6 +101,8 @@ public class StationaryLightsService private readonly Stack _freeRuntimeSlots = new(); // Who drives the hero light now - the last ClaimHeroLight wins, only it may update or release the slot. private object _heroLightOwner; + // The hero light's Unity light (torch, Light spell) - a dynamic shadow light while the option is on. + private Light _heroUnityLight; private readonly HashSet _pooledLights = new(); // Pooled lights in reach with their reach (distance to the camera minus range), sorted closest first. private readonly List<(float Reach, StationaryLight Light)> _pooledSorted = new(); @@ -548,6 +550,9 @@ public void InitStationaryLights() _pooledLights.Clear(); _shadowLights.Clear(); _shadowUnityLights.Clear(); + _dynamicShadowLights.Clear(); + _dynamicShadowNearPlanes.Clear(); + _heroUnityLight = null; _poolPeak = 0; _isPoolDirty = true; @@ -561,8 +566,14 @@ public void InitStationaryLights() /// The owner (a burning torch, a Light spell) takes the hero light - there's one slot, so the previous owner's /// light goes dark (its updates are ignored from now on, IsHeroLightOwner tells it). /// - public void ClaimHeroLight(object owner) + public void ClaimHeroLight(object owner, Light unityLight = null) { + if (_heroUnityLight != null && _heroUnityLight != unityLight) + RemoveDynamicShadowLight(_heroUnityLight); + _heroUnityLight = unityLight; + // The torch's own stick and the hand would hide the flame - geometry closer than this casts nothing. + if (unityLight != null) + AddDynamicShadowLight(unityLight, _heroShadowNearPlane); if (_heroLightOwner != null && !ReferenceEquals(_heroLightOwner, owner)) Logger.Log($"[StationaryLights] Hero light taken over by {owner} from {_heroLightOwner}", LogCat.Vob); _heroLightOwner = owner; @@ -582,8 +593,11 @@ public bool UpdateHeroLight(object owner, Vector3 worldPosition, float rangeMete if (HeroLightIndex < 0 || _lightPositionsAndAttenuation == null) return true; // world not loaded yet + // w < 0: a shadow casting light, the shaders light it through URP (GothicShadowedLights). + var attenuation = 1f / (rangeMeters * rangeMeters); + var isShadowed = _heroUnityLight != null && _shadowUnityLights.Contains(_heroUnityLight); _lightPositionsAndAttenuation[HeroLightIndex] = new Vector4( - worldPosition.x, worldPosition.y, worldPosition.z, 1f / (rangeMeters * rangeMeters)); + worldPosition.x, worldPosition.y, worldPosition.z, isShadowed ? -attenuation : attenuation); _lightColors[HeroLightIndex] = linearColor; UploadGlobalLightArrays(); return true; @@ -598,6 +612,9 @@ public void ReleaseHeroLight(object owner) if (!IsHeroLightOwner(owner)) return; _heroLightOwner = null; + if (_heroUnityLight != null) + RemoveDynamicShadowLight(_heroUnityLight); + _heroUnityLight = null; if (HeroLightIndex < 0 || _lightPositionsAndAttenuation == null) return; @@ -857,6 +874,8 @@ private Vector4 GetSlotPositionAndAttenuation(StationaryLight light) /// private void UpdateShadowLights(Vector3 cameraPosition) { + _shadowUnityLights.RemoveWhere(light => light == null); + _dynamicShadowLights.RemoveAll(light => light == null); _shadowCandidates.Clear(); _wantedShadowLights.Clear(); if (_configService.Gothic.GetInt(Constants.IniNames.Shadows, Constants.IniNames.ShadowsDefaultValue) > 0) @@ -867,8 +886,10 @@ private void UpdateShadowLights(Vector3 cameraPosition) !light.isActiveAndEnabled) continue; var distance = Vector3.Distance(light.CachedPosition, cameraPosition); - if (distance - light.CachedRange <= _shadowLightMaxDistance) - _shadowCandidates.Add((distance, light)); + if (distance - light.CachedRange > _shadowLightMaxDistance) + continue; + // Spell effects (summoning, fire rain) before lamps - they're short and right next to the hero. + _shadowCandidates.Add((light.IsSpellLight ? distance - _shadowLightMaxDistance : distance, light)); } _shadowCandidates.Sort((a, b) => a.Distance.CompareTo(b.Distance)); for (var i = 0; i < _shadowCandidates.Count && i < _maxShadowLights; i++) @@ -896,6 +917,7 @@ private void UpdateShadowLights(Vector3 cameraPosition) /// public void RefreshShadowLights() { + RefreshDynamicShadowLights(); var cam = Camera.main; if (cam == null || _lightPositionsAndAttenuation == null) return; @@ -905,6 +927,70 @@ public void RefreshShadowLights() UpdateShadowLights(cam.transform.position); } + /// + /// Moving lights that cast shadows: the hero's torch / Light spell (ClaimHeroLight) and spell projectiles + /// (VRSpellThrow). URP renders their cube shadow every frame; the shaders light the world with them through + /// URP (GothicShadowLightsFeature) - before, a projectile's light only reached NPCs and objects. + /// Up to _maxDynamicShadowLights at once, more stay plain lights. + /// + private const int _maxDynamicShadowLights = 4; + private const float _heroShadowNearPlane = 0.2f; + private const float _dynamicShadowNearPlane = 0.15f; + private readonly List _dynamicShadowLights = new(); + private readonly Dictionary _dynamicShadowNearPlanes = new(); + + public void AddDynamicShadowLight(Light light, float nearPlane = _dynamicShadowNearPlane) + { + if (light == null || _dynamicShadowLights.Contains(light)) + return; + _dynamicShadowLights.RemoveAll(other => other == null); + if (_dynamicShadowLights.Count >= _maxDynamicShadowLights) + return; + + _dynamicShadowLights.Add(light); + _dynamicShadowNearPlanes[light] = nearPlane; + ApplyDynamicShadow(light); + } + + public void RemoveDynamicShadowLight(Light light) + { + if (light == null || !_dynamicShadowLights.Remove(light)) + return; + _dynamicShadowNearPlanes.Remove(light); + _shadowUnityLights.Remove(light); + light.shadows = LightShadows.None; + light.renderMode = LightRenderMode.Auto; + } + + private void RefreshDynamicShadowLights() + { + _dynamicShadowLights.RemoveAll(light => light == null); + foreach (var light in _dynamicShadowLights) + ApplyDynamicShadow(light); + } + + private void ApplyDynamicShadow(Light light) + { + var option = _configService.Gothic.GetInt(Constants.IniNames.Shadows, + Constants.IniNames.ShadowsDefaultValue); + var isOn = option > 0; + light.shadows = !isOn ? LightShadows.None : option == 1 ? LightShadows.Hard : LightShadows.Soft; + light.renderMode = isOn ? LightRenderMode.ForcePixel : LightRenderMode.Auto; + light.shadowNearPlane = _dynamicShadowNearPlanes.TryGetValue(light, out var nearPlane) + ? nearPlane + : _dynamicShadowNearPlane; + if (isOn) + { + light.GetUniversalAdditionalLightData().softShadowQuality = + option == 2 ? SoftShadowQuality.Low : SoftShadowQuality.High; + _shadowUnityLights.Add(light); + } + else + { + _shadowUnityLights.Remove(light); + } + } + private void SetLightShadow(StationaryLight light, bool isOn) { var unityLight = light.GetComponent(); diff --git a/Assets/Gothic-Core/Shaders/GothicShadows.hlsl b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl index 29368eef7..f7a198e41 100644 --- a/Assets/Gothic-Core/Shaders/GothicShadows.hlsl +++ b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl @@ -77,7 +77,7 @@ bool GothicIsShadowedLight(int lightIndex) // This frame's shadow casting lights: their index among URP's additional lights (GothicShadowLightsFeature) - not // the object's per-object list (8 lights, a big world chunk near candles didn't get the lamp). -float4 _GothicShadowLightIndices[2]; +float4 _GothicShadowLightIndices[3]; float _GothicShadowLightCount; // The shadow casting lights, per pixel with their cube shadow. World and plants (isStationaryFalloff): like a @@ -87,7 +87,7 @@ half3 GothicShadowedLights(float3 worldPos, half3 normalWS, bool isStationaryFal { half3 diffuse = 0; #if defined(_ADDITIONAL_LIGHT_SHADOWS) - int count = min(8, (int)_GothicShadowLightCount); + int count = min(12, (int)_GothicShadowLightCount); for (int k = 0; k < count; k++) { int lightIndex = (int)_GothicShadowLightIndices[k / 4][k % 4]; diff --git a/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage-Dynamic.shader b/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage-Dynamic.shader index d1fa3b28c..f6352d3a1 100644 --- a/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage-Dynamic.shader +++ b/Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage-Dynamic.shader @@ -127,5 +127,46 @@ Shader "Lit/AlphaToCoverage-Dynamic" } ENDHLSL } + + // Highlighted (hovered by the hand) or faded objects keep their shadow - the swap to this shader dropped it. + Pass + { + Name "ShadowCaster" + Tags { "LightMode" = "ShadowCaster" } + ZWrite On + ZTest LEqual + ColorMask 0 + AlphaToMask Off + Blend Off + Cull Off + + HLSLPROGRAM + #pragma vertex GothicShadowVert + #pragma fragment GothicShadowFrag + #pragma multi_compile_instancing + #pragma multi_compile_vertex _ _CASTING_PUNCTUAL_LIGHT_SHADOW + #pragma editor_sync_compilation + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + TEXTURE2D_ARRAY(_MainTex); + SAMPLER(sampler_MainTex); + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_TexelSize; + half _Cutoff; + half _MipScale; + float _DistanceFade; + int _StationaryLightCount; + float4x4 _StationaryLightIndices; + float _FocusBrightness; + CBUFFER_END + + #define GOTHIC_SHADOW_ALPHA_CLIP + #include "GothicIncludes.hlsl" + #include "GothicShadowCaster.hlsl" + ENDHLSL + } } } diff --git a/Assets/Gothic-Core/Shaders/Lit-SingleMesh-Dynamic.shader b/Assets/Gothic-Core/Shaders/Lit-SingleMesh-Dynamic.shader index 5512339ab..6f7a33a1e 100644 --- a/Assets/Gothic-Core/Shaders/Lit-SingleMesh-Dynamic.shader +++ b/Assets/Gothic-Core/Shaders/Lit-SingleMesh-Dynamic.shader @@ -110,5 +110,40 @@ Shader "Lit/SingleMesh-Dynamic" } ENDHLSL } + + // Highlighted (hovered by the hand) or faded objects keep their shadow - the swap to this shader dropped it. + Pass + { + Name "ShadowCaster" + Tags { "LightMode" = "ShadowCaster" } + ZWrite On + ZTest LEqual + ColorMask 0 + AlphaToMask Off + Blend Off + Cull Off + + HLSLPROGRAM + #pragma vertex GothicShadowVert + #pragma fragment GothicShadowFrag + #pragma multi_compile_instancing + #pragma multi_compile_vertex _ _CASTING_PUNCTUAL_LIGHT_SHADOW + #pragma editor_sync_compilation + + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_ST; + float _FocusBrightness; + float _Alpha; + float _Fatness; + CBUFFER_END + + #define GOTHIC_SHADOW_FATNESS + #include "GothicIncludes.hlsl" + #include "GothicShadowCaster.hlsl" + ENDHLSL + } } } diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs index ba14a048c..f1c74288c 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs @@ -519,7 +519,8 @@ public void ToggleLightSpell() stationaryLight.Range = _lightRange; stationaryLight.Intensity = _lightIntensity; stationaryLight.Index = _stationaryLightsService.HeroLightIndex; - _stationaryLightsService.ClaimHeroLight(lightGo); + // Its Unity light casts the Light spell's shadow (Shadows option). + _stationaryLightsService.ClaimHeroLight(lightGo, stationaryLight.GetComponent()); stationaryLight.Init(); _meshService.CreateVobPfx("MFX_LIGHT_INIT", parent: lightGo); diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellThrow.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellThrow.cs index 8122ce638..b52a77e2c 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellThrow.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellThrow.cs @@ -11,6 +11,7 @@ using Gothic.Core.Services.Npc; using Gothic.VR.Interaction.Models; using Gothic.VR.Services; +using Gothic.Core.Services.World; using Reflex.Attributes; using UnityEngine; using ZenKit.Daedalus; @@ -30,6 +31,7 @@ public class VRSpellThrow [Inject] private readonly MeshService _meshService; [Inject] private readonly VmCacheService _vmCacheService; [Inject] private readonly MultiTypeCacheService _multiTypeCacheService; + [Inject] private readonly StationaryLightsService _stationaryLightsService; private readonly ParticleEffectEmitKeyInstance _castKey; private readonly string _mfxName; @@ -197,6 +199,9 @@ public void Throw(Vector3 origin, Vector3 direction, int level, int investLevel, light.range = 3f; light.intensity = 2f; light.color = GetSpellLightColor(mfxName); + // A flying fireball lights the walls it passes and throws shadows (Shadows option) - gone with the + // projectile (the service drops destroyed lights). + _stationaryLightsService.AddDynamicShadowLight(light); var homingTarget = lockedTarget?.Go != null ? lockedTarget diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs index 156535c15..52ae749a7 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs @@ -94,7 +94,8 @@ private void Light() _light.Range = visual.LightRange; _light.Intensity = 1f; _light.Index = _stationaryLightsService.HeroLightIndex; - _stationaryLightsService.ClaimHeroLight(this); + // Its Unity light casts the torch's shadow (Shadows option). + _stationaryLightsService.ClaimHeroLight(this, _light.GetComponent()); _light.Init(); StartCoroutine(DriveLight(visual)); From 6b652d29e9960e4325c0b64f9421c748d43b7c5e Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Mon, 23 Nov 2026 02:09:36 +0000 Subject: [PATCH 08/13] perf: the world and its VOBs are SRP batched - Lit/World's _FocusBrightness was outside UnityPerMaterial and ~1900 VOBs had a MaterialPropertyBlock Co-Authored-By: Claude Opus 5.5 --- .../Services/World/StationaryLightsService.cs | 12 +++++++----- Assets/Gothic-Core/Shaders/Lit-World.shader | 5 +++-- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs index c3d4fcc2b..ea89703d8 100644 --- a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs +++ b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs @@ -307,7 +307,6 @@ public void ClearWorldChunks() public bool IsWorldLit(Renderer renderer) => _worldLitRenderers.Contains(renderer); // Lightmap light per cell (ToCell) of the light mapped world polygons, sampled at their centers by WorldMeshBuilder. private readonly Dictionary _lightmapCells = new(); - private MaterialPropertyBlock _vobLightBlock; /// /// The lightmap light of the world's light mapped polygons per cell (rgb summed, w = polygon count). @@ -378,15 +377,18 @@ public void ApplyWorldLight(GameObject vobGo) if (!light.HasValue) return; - _vobLightBlock ??= new MaterialPropertyBlock(); var tint = new Vector4(light.Value.r, light.Value.g, light.Value.b, 1f); foreach (var renderer in renderers) { if (renderer is MeshRenderer meshRenderer && IsWorldChunk(meshRenderer)) continue; - renderer.GetPropertyBlock(_vobLightBlock); - _vobLightBlock.SetVector(_vobLightTintShaderId, tint); - renderer.SetPropertyBlock(_vobLightBlock); + // Into the renderer's own materials (each has its own - UpdateRenderer writes its light indices there + // too), not a MaterialPropertyBlock: the SRP batcher skips renderers with one, ~1900 VOBs in Khorinis + // were drawn one by one. + renderer.GetSharedMaterials(_rendererMaterials); + foreach (var material in _rendererMaterials) + if (material != null) + material.SetVector(_vobLightTintShaderId, tint); _worldLitRenderers.Add(renderer); } } diff --git a/Assets/Gothic-Core/Shaders/Lit-World.shader b/Assets/Gothic-Core/Shaders/Lit-World.shader index 1a0f2d4f2..5cdd9b9ec 100644 --- a/Assets/Gothic-Core/Shaders/Lit-World.shader +++ b/Assets/Gothic-Core/Shaders/Lit-World.shader @@ -31,8 +31,6 @@ Shader "Lit/World" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl" - float _FocusBrightness; - struct appdata { float4 vertex : POSITION; @@ -68,6 +66,8 @@ Shader "Lit/World" SAMPLER(sampler_WorldLightmaps); float _WorldLightmapBrightness; + // Every material property in here, the same in every pass - else the SRP batcher skips the world and + // draws it chunk by chunk. CBUFFER_START(UnityPerMaterial) float4 _MainTex_TexelSize; int _StationaryLightCount; @@ -75,6 +75,7 @@ Shader "Lit/World" float4x4 _StationaryLightIndices2; float _WindStrength; float4 _VobLightTint; + float _FocusBrightness; CBUFFER_END #include "GothicIncludes.hlsl" From d959036353bc3bcca9a0da041159b03256c70dbd Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Mon, 23 Nov 2026 00:16:25 +0000 Subject: [PATCH 09/13] feat: the VR hero body casts its shadow (sun, moon, lamps, torch) --- Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs | 3 ++- Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroSleeves.cs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs index b713ff5bf..e595917b9 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs @@ -411,7 +411,8 @@ private void EnsureBody(NpcContainer hero) _renderers.AddRange(_body.GetComponentsInChildren(true)); foreach (var r in _renderers) { - r.shadowCastingMode = ShadowCastingMode.Off; + // The hero's own shadow (sun, lamps, torch) - immersion; the body is lit, its shadow was missing. + r.shadowCastingMode = ShadowCastingMode.On; if (_bodyRenderer == null && r is SkinnedMeshRenderer skinnedRenderer) _bodyRenderer = skinnedRenderer; } diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroSleeves.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroSleeves.cs index 6593fb4b5..c844ff8eb 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroSleeves.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroSleeves.cs @@ -156,7 +156,7 @@ public void Build(GameObject body, NpcProperties props, string mdhName, armorBones.TryGetValue(nakedRenderer.rootBone.name.ToUpperInvariant(), out var rootBone)) forearm.rootBone = rootBone; forearm.updateWhenOffscreen = true; - forearm.shadowCastingMode = ShadowCastingMode.Off; + forearm.shadowCastingMode = ShadowCastingMode.On; forearm.enabled = false; _bareForearms.Add(forearm); _bareForearmMeshes[forearm] = (forearmMesh, From 40cde6a90b89555291134d8ce36116c1794064df Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Mon, 23 Nov 2026 00:16:33 +0000 Subject: [PATCH 10/13] fix: lights inside houses no longer glow on the outside walls; 10 lamps/fires within 40 m cast shadows Lights beyond the shadow casting ones have no shadow: a candle in a house lit the house's outside walls like a spotlight. A light under a light mapped ceiling (house, cave, sewer) is indoor (slot color alpha 1) and skips outdoor surfaces (vertex lit polygons, VOBs outside light mapped areas). 10 instead of 6 lamps/fires within 40 m cast shadows (16 shadow lights at most incl. the hero light and projectiles). --- .../Adapters/Rendering/GothicShadowLightsFeature.cs | 4 ++-- .../Scripts/Adapters/Vob/StationaryLight.cs | 6 ++++++ .../Scripts/Domain/Vobs/VobInitializerDomain.cs | 5 ++++- .../Services/World/StationaryLightsService.cs | 13 ++++++++++--- Assets/Gothic-Core/Shaders/GothicShadows.hlsl | 4 ++-- Assets/Gothic-Core/Shaders/Lit-World.shader | 12 ++++++++---- Assets/Gothic-Core/Shaders/StationaryLighting.hlsl | 12 ++++++++++-- 7 files changed, 42 insertions(+), 14 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs index 1dfc75e70..13e389637 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs @@ -15,8 +15,8 @@ namespace Gothic.Core.Adapters.Rendering /// public class GothicShadowLightsFeature : ScriptableRendererFeature { - // 6 lamps/fires + hero light + spell projectiles (StationaryLightsService). Same as GothicShadows.hlsl. - private const int _maxShadowLights = 12; + // 10 lamps/fires + hero light + spell projectiles (StationaryLightsService). Same as GothicShadows.hlsl. + private const int _maxShadowLights = 16; private static readonly int _indicesShaderId = Shader.PropertyToID("_GothicShadowLightIndices"); private static readonly int _countShaderId = Shader.PropertyToID("_GothicShadowLightCount"); diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs index 0b6581aef..f72b648d5 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs @@ -146,6 +146,12 @@ public float SpotAngle /// public bool IsOutdoor { get; set; } + /// + /// Under a light mapped ceiling (house, cave, sewer): it doesn't light outdoor surfaces - the candles in a house + /// glowed on its outside walls, the walls had no shadow for them. + /// + public bool IsIndoor { get; set; } + /// /// A spell's light (VisualFxLight): it casts a shadow before the lamps (StationaryLightsService). /// diff --git a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs index 58ef05aec..716611168 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs @@ -655,7 +655,10 @@ private GameObject CreateLight(Light vob, GameObject parent, Vector3 worldPositi lightComp.IsBakedIntoWorld = vob.LightStatic && _stationaryLightsService.HasWorldLightmaps; // Street lamps and camp fires dim by day (StationaryLightsService.SetDaylight) - not the lights under a // light mapped ceiling (houses, caves, Khorinis' sewers below the market). - lightComp.IsOutdoor = !_stationaryLightsService.HasLightMappedCeiling(worldPosition); + var isUnderCeiling = _stationaryLightsService.HasLightMappedCeiling(worldPosition); + lightComp.IsOutdoor = !isUnderCeiling; + // A light under a roof doesn't light the outside walls through the house (StationaryLighting.hlsl). + lightComp.IsIndoor = isUnderCeiling; // All world lights share the shader slots - the ones closest to the camera get them. lightComp.RuntimeLinearColor = lightComp.Color.linear; diff --git a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs index 931c81af4..f49259526 100644 --- a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs +++ b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs @@ -75,8 +75,8 @@ public class StationaryLightsService /// gathered, Khorinis' market stayed dark under its lamps. Every one renders its surroundings 6 times, so only /// a few; baked lights (in the lightmaps) never - the walls would get them twice. /// - private const int _maxShadowLights = 6; - private const float _shadowLightMaxDistance = 30f; + private const int _maxShadowLights = 10; + private const float _shadowLightMaxDistance = 40f; // Geometry closer to the light than this casts no shadow: the lamp's cage casts its bars, not the flame's own // mesh around the light. private const float _shadowLightNearPlane = 0.05f; @@ -598,6 +598,8 @@ public bool UpdateHeroLight(object owner, Vector3 worldPosition, float rangeMete var isShadowed = _heroUnityLight != null && _shadowUnityLights.Contains(_heroUnityLight); _lightPositionsAndAttenuation[HeroLightIndex] = new Vector4( worldPosition.x, worldPosition.y, worldPosition.z, isShadowed ? -attenuation : attenuation); + // Alpha 0: the hero's light reaches indoor and outdoor surfaces. + linearColor.a = 0f; _lightColors[HeroLightIndex] = linearColor; UploadGlobalLightArrays(); return true; @@ -852,9 +854,14 @@ public void SetDaylight(float brightness) } } + /// + /// The slot's color; its alpha marks an indoor light (StationaryLighting.hlsl: no light on outdoor surfaces). + /// private Color GetSlotColor(StationaryLight light) { - return light.IsOutdoor ? light.RuntimeLinearColor * _outdoorLightFactor : light.RuntimeLinearColor; + var color = light.IsOutdoor ? light.RuntimeLinearColor * _outdoorLightFactor : light.RuntimeLinearColor; + color.a = light.IsIndoor ? 1f : 0f; + return color; } /// diff --git a/Assets/Gothic-Core/Shaders/GothicShadows.hlsl b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl index f7a198e41..5cb62a36c 100644 --- a/Assets/Gothic-Core/Shaders/GothicShadows.hlsl +++ b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl @@ -77,7 +77,7 @@ bool GothicIsShadowedLight(int lightIndex) // This frame's shadow casting lights: their index among URP's additional lights (GothicShadowLightsFeature) - not // the object's per-object list (8 lights, a big world chunk near candles didn't get the lamp). -float4 _GothicShadowLightIndices[3]; +float4 _GothicShadowLightIndices[4]; float _GothicShadowLightCount; // The shadow casting lights, per pixel with their cube shadow. World and plants (isStationaryFalloff): like a @@ -87,7 +87,7 @@ half3 GothicShadowedLights(float3 worldPos, half3 normalWS, bool isStationaryFal { half3 diffuse = 0; #if defined(_ADDITIONAL_LIGHT_SHADOWS) - int count = min(12, (int)_GothicShadowLightCount); + int count = min(16, (int)_GothicShadowLightCount); for (int k = 0; k < count; k++) { int lightIndex = (int)_GothicShadowLightIndices[k / 4][k % 4]; diff --git a/Assets/Gothic-Core/Shaders/Lit-World.shader b/Assets/Gothic-Core/Shaders/Lit-World.shader index 8e51af56a..6fbe26963 100644 --- a/Assets/Gothic-Core/Shaders/Lit-World.shader +++ b/Assets/Gothic-Core/Shaders/Lit-World.shader @@ -89,13 +89,15 @@ Shader "Lit/World" #include "GothicShadows.hlsl" // Per pixel: per vertex a torch in the middle of a big cave wall lit nothing (its corners are far away). - half3 StationaryLighting(half3 normal, float3 worldPos) + // isOutdoorSurface: vertex lit polygons and VOBs outside light mapped areas - indoor lights skip them. + half3 StationaryLighting(half3 normal, float3 worldPos, bool isOutdoorSurface) { half3 diffuse = 0; for (uint k = 0; k < min(_StationaryLightCount, MAX_AFFECTING_STATIONARY_LIGHTS); k++) { uint lightIndex = _StationaryLightIndices[k / 4][k % 4]; - if (!IsStationaryLightShadowed(lightIndex)) + if (!IsStationaryLightShadowed(lightIndex) && + !(isOutdoorSurface && IsStationaryLightIndoor(lightIndex))) diffuse += AdditionalStationaryDiffuse(lightIndex, worldPos, normal); } if (_StationaryLightCount >= MAX_AFFECTING_STATIONARY_LIGHTS) @@ -104,7 +106,8 @@ Shader "Lit/World" MAX_AFFECTING_STATIONARY_LIGHTS); l++) { uint lightIndex2 = _StationaryLightIndices2[l / 4][l % 4]; - if (!IsStationaryLightShadowed(lightIndex2)) + if (!IsStationaryLightShadowed(lightIndex2) && + !(isOutdoorSurface && IsStationaryLightIndoor(lightIndex2))) diffuse += AdditionalStationaryDiffuse(lightIndex2, worldPos, normal); } } @@ -158,7 +161,8 @@ Shader "Lit/World" GothicOcclusion occlusion = GothicGetOcclusion(i.vertex); half3 light = baseLight * occlusion.indirect + - (StationaryLighting(normal, i.worldPos) + GothicShadowedLights(i.worldPos, normal, true)) * + (StationaryLighting(normal, i.worldPos, i.normal.w > 0.5) + + GothicShadowedLights(i.worldPos, normal, true)) * occlusion.direct; half3 diffuse = albedo.rgb * GothicClampLight(light) * _FocusBrightness; diff --git a/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl b/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl index 51138c542..255c7588c 100644 --- a/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl +++ b/Assets/Gothic-Core/Shaders/StationaryLighting.hlsl @@ -11,11 +11,19 @@ #define MAX_AFFECTING_STATIONARY_LIGHTS 16 float4 _GlobalStationaryLightPositionsAndAttenuation[MAX_TOTAL_STATIONARY_LIGHTS]; -real3 _GlobalStationaryLightColors[MAX_TOTAL_STATIONARY_LIGHTS]; +// rgb: color, a: 1 = indoor light (under a light mapped ceiling, IsStationaryLightIndoor). Same 16 byte stride as +// the former real3. +real4 _GlobalStationaryLightColors[MAX_TOTAL_STATIONARY_LIGHTS]; // A pooled light with w < 0 casts a shadow (StationaryLightsService): the shaders light it through its URP light with // the cube shadow (GothicShadowedLights) and skip it here - URP reaches every object in its range, the pool only the // renderers the light gathered. +// A candle in a house doesn't light the house's outside walls (no shadow for it from the walls). +bool IsStationaryLightIndoor(uint lightIndex) +{ + return _GlobalStationaryLightColors[lightIndex].a > 0.5; +} + bool IsStationaryLightShadowed(uint lightIndex) { return _GlobalStationaryLightPositionsAndAttenuation[lightIndex].w < 0; @@ -30,7 +38,7 @@ half3 AdditionalStationaryDiffuse(uint lightIndex, real3 worldPos, real3 normal) // w = 1/R², negative for a shadow casting light. float attenuation = StationaryLightFalloff(distanceSqr, abs(lightPosAndAttenuation.w)); - return _GlobalStationaryLightColors[lightIndex] * attenuation * _PointLightIntensity; + return _GlobalStationaryLightColors[lightIndex].rgb * attenuation * _PointLightIntensity; } #endif From 4ef3cfe810803c9c40211308331b8bc94748c581 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Mon, 23 Nov 2026 00:56:15 +0000 Subject: [PATCH 11/13] feat: "Shadow range" option (10 lamps within 40 m up to 40 within 200 m); the hero's head casts a shadow the camera never sees Co-Authored-By: Claude Opus 5.5 --- .../Localizations/Gothic-UI Shared Data.asset | 8 +++ .../Localizations/Gothic-UI_cs.asset | 9 ++++ .../Localizations/Gothic-UI_de.asset | 9 ++++ .../Localizations/Gothic-UI_en.asset | 9 ++++ .../Localizations/Gothic-UI_es.asset | 9 ++++ .../Localizations/Gothic-UI_fr.asset | 9 ++++ .../Localizations/Gothic-UI_it.asset | 9 ++++ .../Localizations/Gothic-UI_pl.asset | 9 ++++ .../Localizations/Gothic-UI_ru.asset | 12 +++++ .../Rendering/GothicShadowLightsFeature.cs | 29 +++++++++-- Assets/Gothic-Core/Scripts/Const/Constants.cs | 4 ++ .../Meshes/Builder/NpcHeadMeshBuilder.cs | 15 +++--- .../Services/World/StationaryLightsService.cs | 27 +++++++--- .../Settings/URP-HighFidelity.asset | 4 +- Assets/Gothic-Core/Shaders/GothicShadows.hlsl | 4 +- .../Scripts/Adapters/Player/VRHeroBody.cs | 49 +++++++++++++++++++ .../Services/Context/VRContextMenuService.cs | 20 +++++++- 17 files changed, 211 insertions(+), 24 deletions(-) diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset b/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset index e554f3be9..a5ae85db6 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI Shared Data.asset @@ -579,6 +579,14 @@ MonoBehaviour: m_Key: menuitem.shadows.value m_Metadata: m_Items: [] + - m_Id: 196653647115460608 + m_Key: menuitem.shadowRange.label + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Key: menuitem.shadowRange.description + m_Metadata: + m_Items: [] m_Metadata: m_Items: [] m_KeyGenerator: diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset index 1c80fa710..cac4bfd0f 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_cs.asset @@ -482,6 +482,15 @@ MonoBehaviour: m_Localized: "Vyp.|Ostr\xE9|St\u0159edn\xED|M\u011Bkk\xE9" m_Metadata: m_Items: [] + - m_Id: 196653647115460608 + m_Localized: "Dosah st\xEDn\u016F" + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: "Kolik lamp a oh\u0148\u016F vrh\xE1 st\xEDny a jak daleko. Na slab\u0161\xEDch + PC sni\u017Ete" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset index abae47fa0..bb872baa0 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_de.asset @@ -608,6 +608,15 @@ MonoBehaviour: m_Localized: Aus|Hart|Mittel|Weich m_Metadata: m_Items: [] + - m_Id: 196653647115460608 + m_Localized: Schattenreichweite + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: Wie viele Lampen und Feuer Schatten werfen und wie weit. Auf langsameren + PCs verringern + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset index 34bdc98d5..f4299457c 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_en.asset @@ -620,6 +620,15 @@ MonoBehaviour: m_Localized: Off|Hard|Medium|Soft m_Metadata: m_Items: [] + - m_Id: 196653647115460608 + m_Localized: Shadow range + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: How many lamps and fires cast shadows, and how far. Lower it on + slower PCs + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset index 0cbb8256a..036054e3a 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_es.asset @@ -471,6 +471,15 @@ MonoBehaviour: m_Localized: No|Duras|Medias|Suaves m_Metadata: m_Items: [] + - m_Id: 196653647115460608 + m_Localized: Alcance de sombras + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: "Cu\xE1ntas l\xE1mparas y fuegos proyectan sombras y hasta d\xF3nde. + Red\xFAcelo en PC m\xE1s lentos" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset index 1d3197a14..1e83c32b2 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_fr.asset @@ -476,6 +476,15 @@ MonoBehaviour: m_Localized: Non|Dures|Moyennes|Douces m_Metadata: m_Items: [] + - m_Id: 196653647115460608 + m_Localized: "Port\xE9e des ombres" + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: "Combien de lampes et de feux projettent des ombres, et jusqu'o\xF9. + \xC0 r\xE9duire sur les PC plus lents" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset index dd23c47a8..8b7253e30 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_it.asset @@ -472,6 +472,15 @@ MonoBehaviour: m_Localized: No|Nette|Medie|Morbide m_Metadata: m_Items: [] + - m_Id: 196653647115460608 + m_Localized: Portata ombre + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: "Quante lampade e fuochi proiettano ombre e fin dove. Riducila sui + PC pi\xF9 lenti" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset index b085b769e..b10874969 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_pl.asset @@ -478,6 +478,15 @@ MonoBehaviour: m_Localized: "Wy\u0142.|Twarde|\u015Arednie|Mi\u0119kkie" m_Metadata: m_Items: [] + - m_Id: 196653647115460608 + m_Localized: "Zasi\u0119g cieni" + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: "Ile lamp i ognisk rzuca cienie i jak daleko. Zmniejsz na s\u0142abszych + komputerach" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset b/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset index b97f83b1c..5ad60190f 100644 --- a/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset +++ b/Assets/Gothic-Core/Localizations/Gothic-UI_ru.asset @@ -565,6 +565,18 @@ MonoBehaviour: m_Localized: "\u0412\u044B\u043A\u043B.|\u0416\u0451\u0441\u0442\u043A\u0438\u0435|\u0421\u0440\u0435\u0434\u043D\u0438\u0435|\u041C\u044F\u0433\u043A\u0438\u0435" m_Metadata: m_Items: [] + - m_Id: 196653647115460608 + m_Localized: "\u0414\u0430\u043B\u044C\u043D\u043E\u0441\u0442\u044C \u0442\u0435\u043D\u0435\u0439" + m_Metadata: + m_Items: [] + - m_Id: 196653647161597952 + m_Localized: "\u0421\u043A\u043E\u043B\u044C\u043A\u043E \u043B\u0430\u043C\u043F + \u0438 \u043A\u043E\u0441\u0442\u0440\u043E\u0432 \u043E\u0442\u0431\u0440\u0430\u0441\u044B\u0432\u0430\u044E\u0442 + \u0442\u0435\u043D\u0438 \u0438 \u043A\u0430\u043A \u0434\u0430\u043B\u0435\u043A\u043E. + \u0423\u043C\u0435\u043D\u044C\u0448\u0438\u0442\u0435 \u043D\u0430 \u0441\u043B\u0430\u0431\u044B\u0445 + \u041F\u041A" + m_Metadata: + m_Items: [] references: version: 2 RefIds: [] diff --git a/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs index 13e389637..bddab681c 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs @@ -15,8 +15,9 @@ namespace Gothic.Core.Adapters.Rendering /// public class GothicShadowLightsFeature : ScriptableRendererFeature { - // 10 lamps/fires + hero light + spell projectiles (StationaryLightsService). Same as GothicShadows.hlsl. - private const int _maxShadowLights = 16; + // Up to 40 lamps/fires (Shadow range option) + hero light + spell projectiles (StationaryLightsService). + // Same as GothicShadows.hlsl. + private const int _maxShadowLights = 64; private static readonly int _indicesShaderId = Shader.PropertyToID("_GothicShadowLightIndices"); private static readonly int _countShaderId = Shader.PropertyToID("_GothicShadowLightCount"); @@ -37,10 +38,32 @@ private class ShadowLightsPass : ScriptableRenderPass { private readonly Vector4[] _indices = new Vector4[_maxShadowLights / 4]; private StationaryLightsService _lightsService; + private float _nextResolveTime; + + /// + /// The service only exists while the game runs (not for the Editor's scene view, not before the boot) - + /// asked again once a second until then. + /// + private StationaryLightsService TryResolveLightsService() + { + if (!Application.isPlaying || Time.unscaledTime < _nextResolveTime || + ReflexProjectInstaller.DIContainer == null) + return null; + + _nextResolveTime = Time.unscaledTime + 1f; + try + { + return ReflexProjectInstaller.DIContainer.Resolve(); + } + catch (System.Exception) + { + return null; + } + } public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { - _lightsService ??= ReflexProjectInstaller.DIContainer?.Resolve(); + _lightsService ??= TryResolveLightsService(); var lightData = frameData.Get(); var visibleLights = lightData.visibleLights; var count = 0; diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index 0b09a1e69..1ad5cf7ed 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -19,6 +19,10 @@ public static class IniNames // Only where the quality level draws shadows at all (PC; Quest has none). public const string Shadows = "shadows"; public const int ShadowsDefaultValue = 3; + // Slider 0...1: how many lamps/fires cast shadows and how far - 0 = 10 within 40 m, 1 = 40 within 200 m + // (StationaryLightsService). Lights beyond have no shadow (a candle in a house lit its outside walls). + public const string ShadowRange = "shadowRange"; + public const float ShadowRangeDefaultValue = 0.75f; // 1 = "-X HP" numbers over NPC heads and next to the hero's bar, 0 = off (default). public const string HitNumbers = "hitNumbers"; // 1 = "HP/MAX" on health bars (and "MANA/MAX" on the hero's mana bar), 0 = off (default). diff --git a/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/NpcHeadMeshBuilder.cs b/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/NpcHeadMeshBuilder.cs index 920fe944e..9dbdcc042 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/NpcHeadMeshBuilder.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/NpcHeadMeshBuilder.cs @@ -20,17 +20,16 @@ public override GameObject Build() return RootGo; } + // Without an NPC (the VR hero body) the head mesh is built anyway - its shadow (VRHeroBody) - only the + // face animation setup is skipped. var npcContainer = RootGo.GetComponentInParent()?.Npc?.GetUserData(); - if (npcContainer == null) + if (npcContainer != null) { - Logger.LogWarning($"NpcContainer not available during head build for {RootGo.name} — skipping head component setup.", LogCat.Mesh); - return RootGo; + // Cache it for faster use during runtime + npcContainer.PrefabProps.Head = headGo.transform; + npcContainer.PrefabProps.HeadMorph = headGo.AddComponent().Inject(); + npcContainer.PrefabProps.HeadMorph.HeadName = npcContainer.Props.BodyData.Head; } - - // Cache it for faster use during runtime - npcContainer.PrefabProps.Head = headGo.transform; - npcContainer.PrefabProps.HeadMorph = headGo.AddComponent().Inject(); - npcContainer.PrefabProps.HeadMorph.HeadName = npcContainer.Props.BodyData.Head; // Fix for G1: Damlurker if (Mmb == null) diff --git a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs index f49259526..76db64a6e 100644 --- a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs +++ b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs @@ -75,8 +75,16 @@ public class StationaryLightsService /// gathered, Khorinis' market stayed dark under its lamps. Every one renders its surroundings 6 times, so only /// a few; baked lights (in the lightmaps) never - the walls would get them twice. /// - private const int _maxShadowLights = 10; - private const float _shadowLightMaxDistance = 40f; + // Option "Shadow range" (slider): from 10 lights within 40 m to 40 within 200 m (URP: 256 shadow slices, + // 6 per point light; the asset's shadow distance is 200 m). + private const int _minShadowLights = 10; + private const int _maxShadowLights = 40; + private const float _minShadowLightDistance = 40f; + private const float _maxShadowLightDistance = 200f; + private float ShadowRange => Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.ShadowRange, + Constants.IniNames.ShadowRangeDefaultValue)); + private int ShadowLightCount => Mathf.RoundToInt(Mathf.Lerp(_minShadowLights, _maxShadowLights, ShadowRange)); + private float ShadowLightMaxDistance => Mathf.Lerp(_minShadowLightDistance, _maxShadowLightDistance, ShadowRange); // Geometry closer to the light than this casts no shadow: the lamp's cage casts its bars, not the flame's own // mesh around the light. private const float _shadowLightNearPlane = 0.05f; @@ -270,7 +278,7 @@ public StationaryLightsService() GlobalEventDispatcher.MainMenuSceneLoaded.AddListener(ClearWorldLightmaps); GlobalEventDispatcher.PlayerPrefUpdated.AddListener((key, _) => { - if (key == Constants.IniNames.Shadows) + if (key == Constants.IniNames.Shadows || key == Constants.IniNames.ShadowRange) RefreshShadowLights(); }); } @@ -780,8 +788,8 @@ private void RebalancePool() _isUploadDirty = true; } - UpdateUnityLights(camPos); UpdateShadowLights(camPos); + UpdateUnityLights(camPos); if (_wantedLights.Count > _poolPeak) { @@ -815,7 +823,8 @@ private void UpdateUnityLights(Vector3 cameraPosition) continue; var isNear = Vector3.Distance(light.CachedPosition, cameraPosition) - light.CachedRange <= _unityLightMaxDistance; - light.SetUnityLightEnabled(isNear); + // A shadow casting light farther away needs its Unity light for the shadow. + light.SetUnityLightEnabled(isNear || _shadowLights.Contains(light)); } } @@ -885,6 +894,8 @@ private void UpdateShadowLights(Vector3 cameraPosition) _dynamicShadowLights.RemoveAll(light => light == null); _shadowCandidates.Clear(); _wantedShadowLights.Clear(); + var maxDistance = ShadowLightMaxDistance; + var maxCount = ShadowLightCount; if (_configService.Gothic.GetInt(Constants.IniNames.Shadows, Constants.IniNames.ShadowsDefaultValue) > 0) { foreach (var light in _pooledLights) @@ -893,13 +904,13 @@ private void UpdateShadowLights(Vector3 cameraPosition) !light.isActiveAndEnabled) continue; var distance = Vector3.Distance(light.CachedPosition, cameraPosition); - if (distance - light.CachedRange > _shadowLightMaxDistance) + if (distance - light.CachedRange > maxDistance) continue; // Spell effects (summoning, fire rain) before lamps - they're short and right next to the hero. - _shadowCandidates.Add((light.IsSpellLight ? distance - _shadowLightMaxDistance : distance, light)); + _shadowCandidates.Add((light.IsSpellLight ? distance - maxDistance : distance, light)); } _shadowCandidates.Sort((a, b) => a.Distance.CompareTo(b.Distance)); - for (var i = 0; i < _shadowCandidates.Count && i < _maxShadowLights; i++) + for (var i = 0; i < _shadowCandidates.Count && i < maxCount; i++) _wantedShadowLights.Add(_shadowCandidates[i].Light); } diff --git a/Assets/Gothic-Core/Settings/URP-HighFidelity.asset b/Assets/Gothic-Core/Settings/URP-HighFidelity.asset index c71875690..4206810a0 100644 --- a/Assets/Gothic-Core/Settings/URP-HighFidelity.asset +++ b/Assets/Gothic-Core/Settings/URP-HighFidelity.asset @@ -47,14 +47,14 @@ MonoBehaviour: m_AdditionalLightsRenderingMode: 1 m_AdditionalLightsPerObjectLimit: 8 m_AdditionalLightShadowsSupported: 1 - m_AdditionalLightsShadowmapResolution: 4096 + m_AdditionalLightsShadowmapResolution: 8192 m_AdditionalLightsShadowResolutionTierLow: 128 m_AdditionalLightsShadowResolutionTierMedium: 256 m_AdditionalLightsShadowResolutionTierHigh: 512 m_ReflectionProbeBlending: 1 m_ReflectionProbeBoxProjection: 1 m_ReflectionProbeAtlas: 1 - m_ShadowDistance: 150 + m_ShadowDistance: 200 m_ShadowCascadeCount: 4 m_Cascade2Split: 0.25 m_Cascade3Split: {x: 0.1, y: 0.3} diff --git a/Assets/Gothic-Core/Shaders/GothicShadows.hlsl b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl index 5cb62a36c..c372368e3 100644 --- a/Assets/Gothic-Core/Shaders/GothicShadows.hlsl +++ b/Assets/Gothic-Core/Shaders/GothicShadows.hlsl @@ -77,7 +77,7 @@ bool GothicIsShadowedLight(int lightIndex) // This frame's shadow casting lights: their index among URP's additional lights (GothicShadowLightsFeature) - not // the object's per-object list (8 lights, a big world chunk near candles didn't get the lamp). -float4 _GothicShadowLightIndices[4]; +float4 _GothicShadowLightIndices[16]; float _GothicShadowLightCount; // The shadow casting lights, per pixel with their cube shadow. World and plants (isStationaryFalloff): like a @@ -87,7 +87,7 @@ half3 GothicShadowedLights(float3 worldPos, half3 normalWS, bool isStationaryFal { half3 diffuse = 0; #if defined(_ADDITIONAL_LIGHT_SHADOWS) - int count = min(16, (int)_GothicShadowLightCount); + int count = min(64, (int)_GothicShadowLightCount); for (int k = 0; k < count; k++) { int lightIndex = (int)_GothicShadowLightIndices[k / 4][k % 4]; diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs index e595917b9..8dffec994 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroBody.cs @@ -56,6 +56,9 @@ public class VRHeroBody : MonoBehaviour private const float _torsoBackOffset = 0.15f; private const float _hiddenBoneScale = 0.001f; + // A copy of the head (and what sits on it - helmet, hood) that only casts the shadow: the head bone is scaled + // away so the camera never sees inside it, the shadow had no head. Follows the head bone every frame. + private Transform _shadowHead; private const string _headBoneName = "BIP01 HEAD"; private const float _minScale = 0.5f; private const float _maxScale = 1.3f; @@ -230,7 +233,10 @@ private void LateUpdate() var feetY = rig.Root.position.y; if (_downPose.UpdateDown(head, feetY, _standingScale, rig)) + { + UpdateShadowHead(); return; + } // Crouching (sneaking) lowers the head, not the body size - keep the standing scale then. The crouch // button's camera offset doesn't count: standing up the camera rises slowly, the body shrank and grew // with it. @@ -258,6 +264,7 @@ private void LateUpdate() } SolveArms(); + UpdateShadowHead(); } /// @@ -291,6 +298,47 @@ private void UpdateCrouchHeight(IVrRig rig, float scale) rig.CrouchHeightOverride = height; } + /// + /// Shadow-only copies of the renderers on the head bone (before it's scaled away), under an anchor that follows + /// the bone (UpdateShadowHead). The camera never draws them, the lights do. + /// + private void CreateShadowHead() + { + var headRenderers = _headBone.GetComponentsInChildren(true); + if (headRenderers.Length == 0) + return; + + _shadowHead = new GameObject("_ShadowHead").transform; + _shadowHead.SetParent(_body.transform, false); + _shadowHead.SetPositionAndRotation(_headBone.position, _headBone.rotation); + foreach (var headRenderer in headRenderers) + { + var meshFilter = headRenderer.GetComponent(); + if (meshFilter == null || meshFilter.sharedMesh == null) + continue; + + var copy = new GameObject(headRenderer.name); + copy.transform.SetParent(_shadowHead, false); + copy.transform.SetPositionAndRotation(headRenderer.transform.position, headRenderer.transform.rotation); + copy.transform.localScale = headRenderer.transform.lossyScale; + copy.AddComponent().sharedMesh = meshFilter.sharedMesh; + var copyRenderer = copy.AddComponent(); + copyRenderer.sharedMaterials = headRenderer.sharedMaterials; + copyRenderer.shadowCastingMode = ShadowCastingMode.ShadowsOnly; + copyRenderer.allowOcclusionWhenDynamic = false; + // The original sits on the scaled-away bone: off, also when the body's visibility switches back. + headRenderer.enabled = false; + _renderers.Remove(headRenderer); + _renderers.Add(copyRenderer); + } + } + + private void UpdateShadowHead() + { + if (_shadowHead != null && _headBone != null) + _shadowHead.SetPositionAndRotation(_headBone.position, _headBone.rotation); + } + private void SolveArms() { GetSecondHandGripPoses(out var leftGrip, out var rightGrip); @@ -448,6 +496,7 @@ private void EnsureBody(NpcContainer hero) foreach (var bone in bones.Values) lowestY = Mathf.Min(lowestY, bone.position.y); _modelHeadHeight = Mathf.Max(0.5f, _headBone.position.y - lowestY + _neckBelowEyes); + CreateShadowHead(); _headBone.localScale = Vector3.one * _hiddenBoneScale; } diff --git a/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs b/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs index c46c41bb4..f746ed1e6 100644 --- a/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs +++ b/Assets/Gothic-VR/Scripts/Services/Context/VRContextMenuService.cs @@ -141,7 +141,8 @@ public void UpdateMainMenu(AbstractMenuInstance mainMenu) (CreateToggleLabel(gameMenu, "DIALOG_FREE_MOVEMENT", "dialogFreeMovement"), CreateToggleChoice(gameMenu, "DIALOG_FREE_MOVEMENT", Constants.IniNames.DialogFreeMovement)), (CreateToggleLabel(gameMenu, "LIGHT_REFRESH", "lightRefresh"), CreateLightRefreshChoice(gameMenu)), - (CreateToggleLabel(gameMenu, "SHADOWS", "shadows"), CreateShadowsChoice(gameMenu)) + (CreateToggleLabel(gameMenu, "SHADOWS", "shadows"), CreateShadowsChoice(gameMenu)), + (CreateToggleLabel(gameMenu, "SHADOW_RANGE", "shadowRange"), CreateShadowRangeSlider(gameMenu)) }; // DeveloperConfig.EnableHeroHands: the hero's own fists instead of the VR hand models (needs the hero body). if (_configService.Dev.EnableHeroHands && _configService.Dev.EnableVrHeroBody) @@ -286,6 +287,23 @@ private MutableMenuItemInstance CreateShadowsChoice(AbstractMenuInstance gameMen return item; } + /// + /// How many lamps/fires cast shadows and how far (Core, StationaryLightsService) - slower PCs slide it down. + /// + private AbstractMenuItemInstance CreateShadowRangeSlider(AbstractMenuInstance gameMenu) + { + var mouseSlider = gameMenu.FindMenuItem("MENUITEM_MSENSITIVITY_SLIDER", out _); + var slider = new MutableMenuItemInstance("MENUITEM_GOTHIC_OPT_VR_IMMERSION_SHADOW_RANGE_SLIDER", + mouseSlider); + + slider.SetUserFloat(0, VRConstants.SmoothRotationSettingAmount); // Steps. + slider.SetUserFloat(3, Constants.IniNames.ShadowRangeDefaultValue); + slider.OnChgSetOption = Constants.IniNames.ShadowRange; + slider.OnChgSetOptionSection = VRConstants.IniSectionImmersion; + + return slider; + } + private AbstractMenuItemInstance CreateHitNumbersSizeSlider(AbstractMenuInstance gameMenu) { var mouseSlider = gameMenu.FindMenuItem("MENUITEM_MSENSITIVITY_SLIDER", out _); From 2cbaa621660a14746e8d96573b9747b42b4aafa0 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Mon, 23 Nov 2026 02:11:08 +0000 Subject: [PATCH 12/13] perf: fewer per-frame lamp shadows (4 within 20 m up to 12 within 50 m), additional shadow atlas 4096, sun shadows 150 m; every Lit/World pass SRP batched Co-Authored-By: Claude Opus 5.5 --- .../Rendering/GothicShadowLightsFeature.cs | 2 +- Assets/Gothic-Core/Scripts/Const/Constants.cs | 5 +++-- .../Services/World/StationaryLightsService.cs | 14 +++++++------- Assets/Gothic-Core/Settings/URP-HighFidelity.asset | 4 ++-- Assets/Gothic-Core/Shaders/Lit-World.shader | 5 ++++- 5 files changed, 17 insertions(+), 13 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs index bddab681c..94b59af11 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Rendering/GothicShadowLightsFeature.cs @@ -15,7 +15,7 @@ namespace Gothic.Core.Adapters.Rendering /// public class GothicShadowLightsFeature : ScriptableRendererFeature { - // Up to 40 lamps/fires (Shadow range option) + hero light + spell projectiles (StationaryLightsService). + // Up to 12 lamps/fires (Shadow range option) + hero light + spell projectiles (StationaryLightsService). // Same as GothicShadows.hlsl. private const int _maxShadowLights = 64; diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index 1ad5cf7ed..6388ca9dd 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -19,8 +19,9 @@ public static class IniNames // Only where the quality level draws shadows at all (PC; Quest has none). public const string Shadows = "shadows"; public const int ShadowsDefaultValue = 3; - // Slider 0...1: how many lamps/fires cast shadows and how far - 0 = 10 within 40 m, 1 = 40 within 200 m - // (StationaryLightsService). Lights beyond have no shadow (a candle in a house lit its outside walls). + // Slider 0...1: how many lamps/fires near the hero get URP's per-frame shadow (NPCs and the hero cast in + // it) - 0 = 4 within 20 m, 1 = 12 within 50 m (StationaryLightsService). Lights beyond have no shadow; + // an indoor light skips outdoor surfaces instead. public const string ShadowRange = "shadowRange"; public const float ShadowRangeDefaultValue = 0.75f; // 1 = "-X HP" numbers over NPC heads and next to the hero's bar, 0 = off (default). diff --git a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs index dd6656fe9..849fc7cfd 100644 --- a/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs +++ b/Assets/Gothic-Core/Scripts/Services/World/StationaryLightsService.cs @@ -75,12 +75,12 @@ public class StationaryLightsService /// gathered, Khorinis' market stayed dark under its lamps. Every one renders its surroundings 6 times, so only /// a few; baked lights (in the lightmaps) never - the walls would get them twice. /// - // Option "Shadow range" (slider): from 10 lights within 40 m to 40 within 200 m (URP: 256 shadow slices, - // 6 per point light; the asset's shadow distance is 200 m). - private const int _minShadowLights = 10; - private const int _maxShadowLights = 40; - private const float _minShadowLightDistance = 40f; - private const float _maxShadowLightDistance = 200f; + // Option "Shadow range" (slider): from 4 lights within 20 m to 12 within 50 m. Every one draws its surroundings + // 6 times per frame - with 40 the frame rate tanked. + private const int _minShadowLights = 4; + private const int _maxShadowLights = 12; + private const float _minShadowLightDistance = 20f; + private const float _maxShadowLightDistance = 50f; private float ShadowRange => Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.ShadowRange, Constants.IniNames.ShadowRangeDefaultValue)); private int ShadowLightCount => Mathf.RoundToInt(Mathf.Lerp(_minShadowLights, _maxShadowLights, ShadowRange)); @@ -445,7 +445,7 @@ public void ApplyWorldLight(GameObject vobGo) continue; // Into the renderer's own materials (each has its own - UpdateRenderer writes its light indices there // too), not a MaterialPropertyBlock: the SRP batcher skips renderers with one, ~1900 VOBs in Khorinis - // were drawn one by one. + // were drawn one by one in every pass (with the shadows: sun cascades, lamp cubes). renderer.GetSharedMaterials(_rendererMaterials); foreach (var material in _rendererMaterials) if (material != null) diff --git a/Assets/Gothic-Core/Settings/URP-HighFidelity.asset b/Assets/Gothic-Core/Settings/URP-HighFidelity.asset index 4206810a0..c71875690 100644 --- a/Assets/Gothic-Core/Settings/URP-HighFidelity.asset +++ b/Assets/Gothic-Core/Settings/URP-HighFidelity.asset @@ -47,14 +47,14 @@ MonoBehaviour: m_AdditionalLightsRenderingMode: 1 m_AdditionalLightsPerObjectLimit: 8 m_AdditionalLightShadowsSupported: 1 - m_AdditionalLightsShadowmapResolution: 8192 + m_AdditionalLightsShadowmapResolution: 4096 m_AdditionalLightsShadowResolutionTierLow: 128 m_AdditionalLightsShadowResolutionTierMedium: 256 m_AdditionalLightsShadowResolutionTierHigh: 512 m_ReflectionProbeBlending: 1 m_ReflectionProbeBoxProjection: 1 m_ReflectionProbeAtlas: 1 - m_ShadowDistance: 200 + m_ShadowDistance: 150 m_ShadowCascadeCount: 4 m_Cascade2Split: 0.25 m_Cascade3Split: {x: 0.1, y: 0.3} diff --git a/Assets/Gothic-Core/Shaders/Lit-World.shader b/Assets/Gothic-Core/Shaders/Lit-World.shader index d6baa65a4..5505271e5 100644 --- a/Assets/Gothic-Core/Shaders/Lit-World.shader +++ b/Assets/Gothic-Core/Shaders/Lit-World.shader @@ -73,7 +73,7 @@ Shader "Lit/World" float _WorldLightmapBrightness; // Every material property in here, the same in every pass - else the SRP batcher skips the world and - // draws it chunk by chunk. + // every pass (sun cascades, lamp cube shadows, depth for SSAO) draws chunk by chunk. CBUFFER_START(UnityPerMaterial) float4 _MainTex_TexelSize; int _StationaryLightCount; @@ -204,6 +204,7 @@ Shader "Lit/World" float4x4 _StationaryLightIndices2; float _WindStrength; float4 _VobLightTint; + float _FocusBrightness; CBUFFER_END #include "GothicIncludes.hlsl" @@ -235,6 +236,7 @@ Shader "Lit/World" float4x4 _StationaryLightIndices2; float _WindStrength; float4 _VobLightTint; + float _FocusBrightness; CBUFFER_END #include "GothicIncludes.hlsl" @@ -265,6 +267,7 @@ Shader "Lit/World" float4x4 _StationaryLightIndices2; float _WindStrength; float4 _VobLightTint; + float _FocusBrightness; CBUFFER_END #include "GothicIncludes.hlsl" From b9f9a2e83ab7e399de2a39c8bf013e864ebd40ee Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Mon, 23 Nov 2026 02:11:50 +0000 Subject: [PATCH 13/13] docs: shadows ADR and lighting doc - torch/spell shadows, roof rule, hero body shadow, Shadow range option, SRP batcher rule Co-Authored-By: Claude Opus 5.5 --- Docs/adr/2026-11-22-pcvr-shadows-lighting.md | 18 +++++++++++------- Docs/world-lighting.md | 7 ++++++- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/Docs/adr/2026-11-22-pcvr-shadows-lighting.md b/Docs/adr/2026-11-22-pcvr-shadows-lighting.md index 16afb911d..19033e401 100644 --- a/Docs/adr/2026-11-22-pcvr-shadows-lighting.md +++ b/Docs/adr/2026-11-22-pcvr-shadows-lighting.md @@ -10,14 +10,18 @@ Gothic bakes its lighting: the sun's shadows are in the world's vertex light, th ## Decisions 1. **The sun and moon cast dynamic shadows on PC.** The sun rises at 6, is highest at 12 (60 degrees, so shadows never vanish under objects) and sets at 18. At night the moon takes its place with a weaker shadow, and the shadows fade out at the horizon. The shadow darkens only the sun's part of the light, so lightmaps, ambient light and fires stay as they are. That is how GD3D11 does it, and it keeps the baked Gothic look. Not chosen: replacing Gothic's baked light with Unity's lighting, which would be a different game. -2. **The few lights closest to the player cast shadows too.** Up to 6 lamps and fires (not lights baked into lightmaps) get a real shadow: a street lamp throws its iron cage onto the ground. Every such light renders its surroundings six times, so all lights casting shadows would be far too expensive. Not chosen: shadows for every light. -3. **Ambient occlusion on PC.** It gives soft contact shadows in corners and under objects, and darkens the baked and ambient light more than the sun and fires (like GD3D11). -4. **Gothic's light stops at full brightness.** Lamps next to each other no longer burn the colors out. The engine's 8-bit vertex light worked the same way. -5. **Nights, mines and rain are darker; lamps and fires outdoors dim by day.** Lights stand out at night, mines are lit by their lamps and the hero's torch, and a street lamp doesn't glow on a shaded wall at noon. Lights under a roof (houses, caves, sewers) stay as they are. Gothic's lamps burn all day too, but its bright vertex light hid them. Ours are stronger, so we dim them, which is a deliberate difference from the original. -6. **A "Shadows" option in the VR Immersion menu: off, hard, medium, soft (default soft).** Not every PC is fast. Quest stays without shadows and ambient occlusion: its quality level has them off. +2. **The few lights closest to the player cast shadows too.** 4 to 12 lamps and fires within 20 to 50 m (not lights baked into lightmaps; the "Shadow range" option) get a real shadow: a street lamp throws its iron cage onto the ground, NPCs and the hero cast shadows in it. The hero's torch, the Light spell and spell projectiles cast shadows as well. Every such light renders its surroundings six times per frame - with 40 of them the frame rate tanked - so all lights casting shadows this way would be far too expensive. Not chosen: shadows for every light. +3. **A light under a roof doesn't light outdoor surfaces.** A light whose position has a light mapped ceiling above (house, cave, sewer) skips vertex lit polygons and VOBs outside light mapped areas: the candles in a house no longer glow on its outside walls and the street. A stand-in for a real shadow where the light has none. +4. **The VR hero's body casts its shadow.** The head is scaled away so the camera doesn't see into it; a shadow-only copy of it casts the head's shadow, the camera never draws it. +5. **Ambient occlusion on PC.** It gives soft contact shadows in corners and under objects, and darkens the baked and ambient light more than the sun and fires (like GD3D11). +6. **Gothic's light stops at full brightness.** Lamps next to each other no longer burn the colors out. The engine's 8-bit vertex light worked the same way. +7. **Nights, mines and rain are darker; lamps and fires outdoors dim by day.** Lights stand out at night, mines are lit by their lamps and the hero's torch, and a street lamp doesn't glow on a shaded wall at noon. Lights under a roof (houses, caves, sewers) stay as they are. Gothic's lamps burn all day too, but its bright vertex light hid them. Ours are stronger, so we dim them, which is a deliberate difference from the original. +8. **Options in the VR Immersion menu: "Shadows" (off, hard, medium, soft; default soft) and "Shadow range" (how many lamps get a shadow).** Not every PC is fast. Quest stays without shadows and ambient occlusion: its quality level has them off. +9. **Gothic's world shader stays SRP batcher compatible.** Every pass of Lit/World has the same material buffer with every material property, and VOBs get their lightmap tint in their own material, not in a property block. Without it every shadow pass drew the world chunk by chunk (3100 SetPass calls in Khorinis, 190 with it). ## Consequences -- PC costs GPU time for the shadow maps (the sun's cascades plus up to 6 point lights) and ambient occlusion. Players with slower PCs pick hard shadows or switch them off. -- The hero's torch and spells don't cast shadows yet (follow-up). Neither do lights baked into lightmaps. +- PC costs GPU time for the shadow maps (the sun's cascades plus up to 12 point lights) and ambient occlusion. Players with slower PCs pick hard shadows, a shorter shadow range or switch them off. +- Lamps beyond the shadow range have no shadow; walls between them and the player don't stop their light (only the roof rule of decision 3). Lights baked into lightmaps cast none. +- New Gothic shader passes must keep the material buffer identical, or the SRP batcher drops the world again. - Not done in this step: height fog, god rays, bloom and tonemapping, water reflections. diff --git a/Docs/world-lighting.md b/Docs/world-lighting.md index e958fb6f1..5c7f27914 100644 --- a/Docs/world-lighting.md +++ b/Docs/world-lighting.md @@ -71,7 +71,10 @@ and no SSAO, the shaders compile those parts away there. | Gothic's lit shaders cast shadows with the main pass' wind, alpha cut (plants) and fatness (NPCs); depth/normals passes feed SSAO | `Shaders/GothicShadowCaster.hlsl`, `Shaders/GothicDepthPasses.hlsl` | | The sun's shadow darkens only the sun's part: baked light of sun-facing outdoor polygons and VOBs (not light mapped ones), the sun term of objects/NPCs | `Shaders/GothicShadows.hlsl`, `Lit-World`, `Lit-AlphaToCoverage`, `Lit-SingleMesh` | | SSAO (HighFidelity renderer): darkens baked/ambient light, less the sun and lights | `GothicShadows.hlsl` (`GothicGetOcclusion`) | -| The 6 pooled lights closest to the camera within 30 m (not baked into lightmaps) cast cube shadows; the pool marks them (slot w < 0) and skips them, the shaders light them through URP | `Services/World/StationaryLightsService.cs` (`UpdateShadowLights`), `StationaryLighting.hlsl`, `GothicShadowedLights` | +| The pooled lights closest to the camera (option "Shadow range": 4 within 20 m up to 12 within 50 m, spell lights first; not baked into lightmaps) cast cube shadows; the pool marks them (slot w < 0) and skips them, the shaders light them through URP | `Services/World/StationaryLightsService.cs` (`UpdateShadowLights`, `ShadowLightCount`), `StationaryLighting.hlsl`, `GothicShadowedLights` | +| The hero's torch / Light spell (`ClaimHeroLight`) and spell projectiles (`AddDynamicShadowLight`, max 4) cast shadows too; near plane keeps the stick and hand out | `StationaryLightsService`, `VRTorch`, `VRSpellFx`, `VRSpellThrow` | +| A light under a light mapped ceiling (`IsIndoor`) skips outdoor surfaces - slot color alpha 1, `normal.w` marks outdoor surfaces | `VobInitializerDomain.CreateLight`, `StationaryLightsService.GetSlotColor`, `Lit-World` (`StationaryLighting`) | +| The VR hero body casts shadows; its head (scaled away for the camera) has a `ShadowsOnly` copy following the head bone | `Gothic-VR/.../VRHeroBody.cs` (`CreateShadowHead`), `NpcHeadMeshBuilder` (head without NpcContainer) | | Their index among URP's additional lights, every frame - URP's 8 per-object lights cut a lamp off at a world chunk's edge | `Adapters/Rendering/GothicShadowLightsFeature.cs` (on `URP-HighFidelity-Renderer`) | | Only Unity lights within 40 m stay enabled: URP takes 256 visible lights, the city has ~770 | `StationaryLightsService.UpdateUnityLights` | | Renderers list their lights shadow casting first, then closest | `StationaryLightsService.UpdateRenderer` | @@ -79,3 +82,5 @@ and no SSAO, the shaders compile those parts away there. | Nights: the world gets 50% of the night sky's light; rain 70% and a 35% sun shadow; indoor worlds (mines) 0.12 | `SkyService` (`SetDayLight`) | | Outdoor lamps/fires (no light mapped ceiling 2-8 m above) dim by day: 100% at night, 20% at noon | `StationaryLightsService.SetDaylight`, `HasLightMappedCeiling`, `VobInitializerDomain.CreateLight` | | Option "Shadows" (Immersion, Gothic.ini `shadows`): 0 off, 1 hard, 2 medium, 3 soft (default) - sun and point lights | `Constants.IniNames.Shadows`, `VRContextMenuService.CreateShadowsChoice` | +| Option "Shadow range" (Immersion, Gothic.ini `shadowRange`, slider 0..1, default 0.75) | `Constants.IniNames.ShadowRange`, `VRContextMenuService.CreateShadowRangeSlider` | +| Lit/World is SRP batcher compatible: every pass has the same `UnityPerMaterial` with every material property (`_FocusBrightness` too); the VOB lightmap tint goes into the renderer's own material, no MaterialPropertyBlock. Check: `ShaderUtil.GetSRPBatcherCompatibilityCode` | `Shaders/Lit-World.shader`, `StationaryLightsService.ApplyWorldLight` |