Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ namespace Gothic.Core.Adapters.Rendering
/// </summary>
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");
Expand Down
5 changes: 5 additions & 0 deletions Assets/Gothic-Core/Scripts/Adapters/Vob/StationaryLight.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,11 @@ public float SpotAngle
/// </summary>
public bool IsOutdoor { get; set; }

/// <summary>
/// A spell's light (VisualFxLight): it casts a shadow before the lamps (StationaryLightsService).
/// </summary>
public bool IsSpellLight { get; set; }

public int AffectedRendererCount => _affectedRenderers.Count;

public IReadOnlyList<MeshRenderer> AffectedRenderers => _affectedRenderers;
Expand Down
1 change: 1 addition & 0 deletions Assets/Gothic-Core/Scripts/Adapters/Vob/VisualFxLight.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ public class StationaryLightsService
private readonly Stack<int> _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<StationaryLight> _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();
Expand Down Expand Up @@ -548,6 +550,9 @@ public void InitStationaryLights()
_pooledLights.Clear();
_shadowLights.Clear();
_shadowUnityLights.Clear();
_dynamicShadowLights.Clear();
_dynamicShadowNearPlanes.Clear();
_heroUnityLight = null;
_poolPeak = 0;
_isPoolDirty = true;

Expand All @@ -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).
/// </summary>
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;
Expand All @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -857,6 +874,8 @@ private Vector4 GetSlotPositionAndAttenuation(StationaryLight light)
/// </summary>
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)
Expand All @@ -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++)
Expand Down Expand Up @@ -896,6 +917,7 @@ private void UpdateShadowLights(Vector3 cameraPosition)
/// </summary>
public void RefreshShadowLights()
{
RefreshDynamicShadowLights();
var cam = Camera.main;
if (cam == null || _lightPositionsAndAttenuation == null)
return;
Expand All @@ -905,6 +927,70 @@ public void RefreshShadowLights()
UpdateShadowLights(cam.transform.position);
}

/// <summary>
/// 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.
/// </summary>
private const int _maxDynamicShadowLights = 4;
private const float _heroShadowNearPlane = 0.2f;
private const float _dynamicShadowNearPlane = 0.15f;
private readonly List<Light> _dynamicShadowLights = new();
private readonly Dictionary<Light, float> _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<Light>();
Expand Down
4 changes: 2 additions & 2 deletions Assets/Gothic-Core/Shaders/GothicShadows.hlsl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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];
Expand Down
41 changes: 41 additions & 0 deletions Assets/Gothic-Core/Shaders/Lit-AlphaToCoverage-Dynamic.shader
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}
35 changes: 35 additions & 0 deletions Assets/Gothic-Core/Shaders/Lit-SingleMesh-Dynamic.shader
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}
3 changes: 2 additions & 1 deletion Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellFx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Light>());
stationaryLight.Init();

_meshService.CreateVobPfx("MFX_LIGHT_INIT", parent: lightGo);
Expand Down
5 changes: 5 additions & 0 deletions Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRSpellThrow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRTorch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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>());
_light.Init();
StartCoroutine(DriveLight(visual));

Expand Down