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 @@ -856,22 +856,22 @@ private Material GetDefaultMaterial(TextureCacheService.TextureArrayTypes textur

/// <summary>
/// The SingleMesh shader only samples _MainTex. A 1x1 texture with the material's color gives the same look.
/// Cached per color, as every VOB using it shares the very same material.
/// The texture is cached per color; the material is per renderer, as the light services write each renderer's
/// lights and world-light tint into it (a shared one lit every X mark like the last one). Same shader variant,
/// so they still batch.
/// </summary>
private Material GetUntexturedMaterial(System.Drawing.Color color)
{
var unityColor = new Color32(color.R, color.G, color.B, color.A);
if (_multiTypeCacheService.UntexturedMaterials.TryGetValue(unityColor, out var material))
return material;

var texture = new Texture2D(1, 1);
texture.SetPixel(0, 0, unityColor);
texture.Apply();

material = new Material(Constants.ShaderSingleMeshLit) { mainTexture = texture };
_multiTypeCacheService.UntexturedMaterials[unityColor] = material;
if (!_multiTypeCacheService.UntexturedTextures.TryGetValue(unityColor, out var texture))
{
texture = new Texture2D(1, 1);
texture.SetPixel(0, 0, unityColor);
texture.Apply();
_multiTypeCacheService.UntexturedTextures[unityColor] = texture;
}

return material;
return new Material(Constants.ShaderSingleMeshLit) { mainTexture = texture };
}

protected Material GetWaterMaterial()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ public class MultiTypeCacheService
public Dictionary<string, AudioClip> AudioClips = new();

/// <summary>
/// Materials of texture-less, color-only meshes (e.g. G2's treasure X marks) - shared by all VOBs with the same
/// color.
/// 1x1 textures of texture-less, color-only meshes (e.g. G2's treasure X marks) - shared by all VOBs with the
/// same color. Each renderer gets its own material with it: per-renderer light values are written there.
/// </summary>
public Dictionary<Color32, Material> UntexturedMaterials = new();
public Dictionary<Color32, Texture2D> UntexturedTextures = new();

/// <summary>
/// Colliders of items without pre-cached ones, calculated from their mesh once per mesh name
Expand All @@ -65,7 +65,7 @@ public void Dispose()
FontCache.Clear();
Meshes.Clear();
AudioClips.Clear();
UntexturedMaterials.Clear();
UntexturedTextures.Clear();
ItemColliders.Clear();
NpcCache.Clear();
VobCache.Clear();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ private class CacheEntry
{ Constants.ShaderLitAlphaToCoverageName, new (Constants.ShaderLitAlphaToCoverageDynamic, (int)RenderQueue.AlphaTest) }
};

private static readonly int _fatnessShaderId = Shader.PropertyToID("_Fatness");

// Some objects (like NPCs) have multiple meshes. We therefore add all self+children renderers/materials.
private Dictionary<GameObject, CacheEntry> _cache = new();
Expand Down Expand Up @@ -109,7 +108,8 @@ private static bool IsOutdated(GameObject go, CacheEntry entry)
}

/// <summary>
/// Only our own dynamic material copies are changed - the default materials are shared with other objects.
/// Only our own dynamic material copies are changed - the default materials stay as they are (some are
/// shared with other objects, e.g. Constants.LoadingMaterial; VOB world materials are per renderer).
/// </summary>
private static void SetValue(CacheEntry entry, int shaderProperty, float shaderValue)
{
Expand Down Expand Up @@ -147,14 +147,13 @@ private void CacheGameObject(GameObject go)
continue;
}

var newMaterial = new Material(shaderMapEntry.dynamicShader)
// A copy of the original keeps every per-renderer value (texture, fatness, the world-light tint
// _VobLightTint, the stationary light indices): a chest in the Old Mine stays dark while focused.
var newMaterial = new Material(mat)
{
mainTexture = mat.mainTexture,
shader = shaderMapEntry.dynamicShader,
renderQueue = shaderMapEntry.shaderType
};
// A fat NPC stays fat while it is highlighted or see-through.
if (mat.HasProperty(_fatnessShaderId) && newMaterial.HasProperty(_fatnessShaderId))
newMaterial.SetFloat(_fatnessShaderId, mat.GetFloat(_fatnessShaderId));
dynamicSlots[i] = newMaterial;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ private void UpdateRenderer(MeshRenderer renderer)

var nonAllocMaterials = _rendererMaterials;
var indicesMatrix = Matrix4x4.identity;
renderer.GetSharedMaterials(nonAllocMaterials);
GetOwnedMaterials(renderer, nonAllocMaterials);
for (var i = 0; i < Mathf.Min(16, rendererLights.Count); i++)
{
indicesMatrix[i / 4, i % 4] = rendererLights[i].Index;
Expand Down Expand Up @@ -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<long, Color> _lightmapCells = new();
private MaterialPropertyBlock _vobLightBlock;

/// <summary>
/// The lightmap light of the world's light mapped polygons per cell (rgb summed, w = polygon count).
Expand Down Expand Up @@ -387,19 +386,38 @@ 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 (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.
GetOwnedMaterials(renderer, _rendererMaterials);
foreach (var material in _rendererMaterials)
if (material.HasProperty(_vobLightTintShaderId))
material.SetVector(_vobLightTintShaderId, tint);
_worldLitRenderers.Add(renderer);
}
}

/// <summary>
/// The renderer's materials this service writes per-renderer values into (light indices, world-light tint).
/// Every VOB and chunk renderer has its own (mesh builders); the loading material is the one shared exception,
/// left in place when a mesh failed to build - writing there would light every renderer still using it.
/// </summary>
private static void GetOwnedMaterials(Renderer renderer, List<Material> materials)
{
renderer.GetSharedMaterials(materials);
// Backwards and without a lambda: called for hundreds of renderers at once (GC spikes on Quest).
for (var i = materials.Count - 1; i >= 0; i--)
{
if (materials[i] == null || materials[i] == Constants.LoadingMaterial)
materials.RemoveAt(i);
}
}

// Diagnostics: how many VOBs got the world light, with a few examples (VOBs in the Old Mine stayed bright).
private int _vobLightApplied;
private int _vobLightMissed;
Expand Down
5 changes: 3 additions & 2 deletions Assets/Gothic-Core/Shaders/Lit-World.shader
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -68,13 +66,16 @@ 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;
float4x4 _StationaryLightIndices;
float4x4 _StationaryLightIndices2;
float _WindStrength;
float4 _VobLightTint;
float _FocusBrightness;
CBUFFER_END

#include "GothicIncludes.hlsl"
Expand Down
6 changes: 4 additions & 2 deletions Docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -376,8 +376,10 @@ player's view, which in VR causes nausea.
### P4. Rendering has a budget

**Rule:** A feature that adds draw calls, materials, realtime lights, shadows, transparency, post-processing or
shader variants says what it costs on Quest in its PR, and has a quality setting if it's optional. Meshes share
materials and texture arrays so they batch.
shader variants says what it costs on Quest in its PR, and has a quality setting if it's optional. World and VOB
shaders stay SRP batcher compatible: every `Properties` entry sits in `UnityPerMaterial`, the same in every pass, and
world/VOB renderers get no `MaterialPropertyBlock`. A per-renderer value goes into the renderer's own material (the
mesh builders give each one its own); meshes share texture arrays.

**Why:** On a mobile GPU the frame is usually lost in rendering, not in C#. Each eye renders the scene, so every
draw call and every overdrawn pixel counts.
Expand Down
1 change: 1 addition & 0 deletions Docs/world-lighting.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Core code is in `Assets/Gothic-Core/Scripts/`.
|------|----------|
| A static VOB in a light mapped area takes the light of the floor below it (nearest lightmap cell, searched ring by ring) | `StationaryLightsService.ApplyWorldLight`, called by `VobInitializerDomain` |
| A VOB lit this way ignores the baked static lights, else it gets the light twice | `Adapters/Vob/StationaryLight.cs` |
| The tint is `_VobLightTint` in the VOB's own materials, never a MaterialPropertyBlock: VOBs stay SRP batched; the focus highlight copies the material, so the tint stays | `StationaryLightsService.ApplyWorldLight`, `DynamicMaterialService.CacheGameObject` |

## Fireplaces and torches

Expand Down