From a706b76c65367c86fd4ee23603cf7aded312dc6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 20:31:47 +0300 Subject: [PATCH 01/57] Fix GL pixel types for 16-bit and float textures --- Source.Bitmap/ImageLoader.cs | 12 ++++++++++++ Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 12 ++++++------ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/Source.Bitmap/ImageLoader.cs b/Source.Bitmap/ImageLoader.cs index d85a766c8..11637ec9f 100644 --- a/Source.Bitmap/ImageLoader.cs +++ b/Source.Bitmap/ImageLoader.cs @@ -283,6 +283,18 @@ public static int GetNumMipMapLevels(int width, int height, int depth) { ImageFormat.I8 => GL_RED, ImageFormat.IA88 => GL_RG, }; + const int GL_UNSIGNED_BYTE = 0x1401; + const int GL_UNSIGNED_SHORT = 0x1403; + const int GL_FLOAT = 0x1406; + const int GL_HALF_FLOAT = 0x140B; + public static int GetGLImageUploadType(ImageFormat format) => format switch { + ImageFormat.RGBA16161616 => GL_UNSIGNED_SHORT, + ImageFormat.RGBA16161616F => GL_HALF_FLOAT, + ImageFormat.R32F => GL_FLOAT, + ImageFormat.RGB323232F => GL_FLOAT, + ImageFormat.RGBA32323232F => GL_FLOAT, + _ => GL_UNSIGNED_BYTE, + }; public static int GetGLImageInternalFormat(ImageFormat format, bool srgb) => srgb ? GetGLImageInternalFormatSRGB(format) : GetGLImageInternalFormat(format); private static int GetGLImageInternalFormatSRGB(ImageFormat format) => format switch { diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index 515228760..86ee9f73a 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -1920,7 +1920,7 @@ private unsafe void LoadCubeTextureFromVTF(in TextureLoadInfo info, IVTFTexture else { ConvertDataToAcceptableGLFormat(info.SrcFormat, data, out ImageFormat uploadFormat, out Span convertedData); fixed (byte* bytes = convertedData) - glTextureSubImage3D((uint)info.Texture, mip, 0, 0, face, w, h, 1, ImageLoader.GetGLImageUploadFormat(uploadFormat), GL_UNSIGNED_BYTE, bytes); + glTextureSubImage3D((uint)info.Texture, mip, 0, 0, face, w, h, 1, ImageLoader.GetGLImageUploadFormat(uploadFormat), ImageLoader.GetGLImageUploadType(uploadFormat), bytes); } } } @@ -2308,7 +2308,7 @@ private unsafe void BlitSurfaceBits(ref TextureLoadInfo info, int xOffset, int y glPixelStorei(GL_UNPACK_ROW_LENGTH, srcStride / srcFormat.SizeInBytes()); ConvertDataToAcceptableGLFormat(srcFormat, imageData, out srcFormat, out Span convertedData); fixed (byte* data = convertedData) - glTextureSubImage2D((uint)info.Texture, mip, xOffset, yOffset, width >> mip, height >> mip, ImageLoader.GetGLImageUploadFormat(srcFormat), GL_UNSIGNED_BYTE, data); + glTextureSubImage2D((uint)info.Texture, mip, xOffset, yOffset, width >> mip, height >> mip, ImageLoader.GetGLImageUploadFormat(srcFormat), ImageLoader.GetGLImageUploadType(srcFormat), data); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); var err = glGetError(); // System.Diagnostics.Debug.Assert(err == 0); @@ -2332,7 +2332,7 @@ public unsafe void TexSubImage2D(int mip, int face, int x, int y, int z, int wid glPixelStorei(GL_UNPACK_ROW_LENGTH, srcStride / srcFormat.SizeInBytes()); ConvertDataToAcceptableGLFormat(srcFormat, imageData, out srcFormat, out Span convertedData); fixed (byte* data = convertedData) - glTextureSubImage2D(GetModifyTexture(), mip, x, y, width >> mip, height >> mip, ImageLoader.GetGLImageUploadFormat(srcFormat), GL_UNSIGNED_BYTE, data); + glTextureSubImage2D(GetModifyTexture(), mip, x, y, width >> mip, height >> mip, ImageLoader.GetGLImageUploadFormat(srcFormat), ImageLoader.GetGLImageUploadType(srcFormat), data); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); var err = glGetError(); // System.Diagnostics.Debug.Assert(err == 0); @@ -2768,7 +2768,7 @@ public unsafe bool TexLock(int level, int cubeFaceID, int xOffset, int yOffset, Memory buffer = GetTempLockBuffer(info.Format, width, height); fixed (byte* data = buffer.Span) { - glGetTextureSubImage(GetModifyTexture(), level, xOffset, yOffset, 0, width, height, 1, GL_RGBA, GL_UNSIGNED_BYTE, buffer.Span.Length, data); + glGetTextureSubImage(GetModifyTexture(), level, xOffset, yOffset, 0, width, height, 1, ImageLoader.GetGLImageUploadFormat(info.Format), ImageLoader.GetGLImageUploadType(info.Format), buffer.Span.Length, data); } writer.SetPixelMemory(info.Format, buffer.Span, width * ImageLoader.SizeInBytes(info.Format)); return true; @@ -2791,7 +2791,7 @@ public unsafe bool TexLock(int level, int cubeFaceID, int xOffset, int yOffset, Memory buffer = GetTempLockBuffer(info.Format, width, height); fixed (byte* data = buffer.Span) { - glGetTextureSubImage(GetModifyTexture(), level, xOffset, yOffset, 0, width, height, 1, GL_RGBA, GL_UNSIGNED_BYTE, buffer.Span.Length, data); + glGetTextureSubImage(GetModifyTexture(), level, xOffset, yOffset, 0, width, height, 1, ImageLoader.GetGLImageUploadFormat(info.Format), ImageLoader.GetGLImageUploadType(info.Format), buffer.Span.Length, data); } writer.SetPixelMemory(info.Format, buffer, width * ImageLoader.SizeInBytes(info.Format)); return true; @@ -2800,7 +2800,7 @@ public unsafe bool TexLock(int level, int cubeFaceID, int xOffset, int yOffset, public unsafe void TexUnlock() { glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); fixed (byte* data = lockdata) - glTextureSubImage2D(GetGL46Texture(Lock.Handle), Lock.Mip, Lock.X, Lock.Y, Lock.W, Lock.H, ImageLoader.GetGLImageUploadFormat(Lock.Format), GL_UNSIGNED_BYTE, data); + glTextureSubImage2D(GetGL46Texture(Lock.Handle), Lock.Mip, Lock.X, Lock.Y, Lock.W, Lock.H, ImageLoader.GetGLImageUploadFormat(Lock.Format), ImageLoader.GetGLImageUploadType(Lock.Format), data); Lock = default; } From 72ba55cc188eafd001e350e13c1b2fe780c546a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 20:44:13 +0300 Subject: [PATCH 02/57] Fix ViewSetup not defaulting DoBloomAndToneMapping to true --- Source.Common/ViewShared.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Source.Common/ViewShared.cs b/Source.Common/ViewShared.cs index b5f6ca32b..8d893e328 100644 --- a/Source.Common/ViewShared.cs +++ b/Source.Common/ViewShared.cs @@ -24,6 +24,10 @@ public enum StereoEye public struct ViewSetup { + public ViewSetup() { + DoBloomAndToneMapping = true; + } + public int X; public int UnscaledX; public int Y; From bea8d8fb452669108d29a564d615fbd27a15477b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 20:58:36 +0300 Subject: [PATCH 03/57] Port HDR enable state to HardwareConfig --- .../MaterialSystem/MaterialSystem_Config.cs | 1 + Source.MaterialSystem/MaterialSystem.cs | 10 ++++---- Source.ShaderAPI.Gl46/HardwareConfig.cs | 23 +++++++++++++++---- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/Source.Common/MaterialSystem/MaterialSystem_Config.cs b/Source.Common/MaterialSystem/MaterialSystem_Config.cs index 490c21cb9..e074cb635 100644 --- a/Source.Common/MaterialSystem/MaterialSystem_Config.cs +++ b/Source.Common/MaterialSystem/MaterialSystem_Config.cs @@ -116,6 +116,7 @@ public void SetFlag(MaterialSystem_Config_Flags flag, bool val) { public bool EnableParallaxMapping() => (Flags & (int)MaterialSystem_Config_Flags.EnableParallaxMapping) != 0; public bool UseZPrefill() => (Flags & (int)MaterialSystem_Config_Flags.UseZPrefill) != 0; public bool ReduceFillrate() => (Flags & (int)MaterialSystem_Config_Flags.ReduceFillrate) != 0; + public bool HDREnabled() => (Flags & (int)MaterialSystem_Config_Flags.ENABLE_HDR) != 0; public bool LimitWindowedSize() => (Flags & (int)MaterialSystem_Config_Flags.LimitedWindowSize) != 0; public bool ScaleToOutputResolution() => (Flags & (int)MaterialSystem_Config_Flags.ScaleToOutputResolution) != 0; public bool UsingMultipleWindows() => (Flags & (int)MaterialSystem_Config_Flags.UsingMultipleWindows) != 0; diff --git a/Source.MaterialSystem/MaterialSystem.cs b/Source.MaterialSystem/MaterialSystem.cs index 4d5e6be6a..ed497b2ea 100644 --- a/Source.MaterialSystem/MaterialSystem.cs +++ b/Source.MaterialSystem/MaterialSystem.cs @@ -185,10 +185,10 @@ public bool OverrideConfig(MaterialSystem_Config config, bool forceUpdate) { ShaderAPI.SetDefaultState(); - // if (config.HDREnabled() != Config.HDREnabled()) { - // forceUpdate = true; - // reloadMaterials = true; - // } + if (config.HDREnabled() != Config.HDREnabled()) { + forceUpdate = true; + reloadMaterials = true; + } if (config.ShadowDepthTexture != Config.ShadowDepthTexture) { forceUpdate = true; @@ -1572,7 +1572,7 @@ public bool SupportsFetch4() { } public bool SupportsHDRMode(HDRType hdrMode) { - throw new NotImplementedException("Incomplete port of IMaterialSystem"); + return HardwareConfig.SupportsHDRMode(hdrMode); } public bool SupportsMSAAMode(int nMSAAMode) { diff --git a/Source.ShaderAPI.Gl46/HardwareConfig.cs b/Source.ShaderAPI.Gl46/HardwareConfig.cs index f02a801e1..fa9a85af8 100644 --- a/Source.ShaderAPI.Gl46/HardwareConfig.cs +++ b/Source.ShaderAPI.Gl46/HardwareConfig.cs @@ -30,16 +30,21 @@ public int GetFrameBufferColorDepth() { throw new NotImplementedException(); } - // HDR todo fixme + public HDRType HDRTypeCap = HDRType.Integer; + public HDRType MaxHDRType = HDRType.Float; + bool HDREnabled; + public HDRType GetHardwareHDRType() { - return HDRType.None; + return HDRTypeCap; } public bool GetHDREnabled() { - return false; + return HDREnabled; } public HDRType GetHDRType() { + if (HDREnabled) + return HDRTypeCap; return HDRType.None; } @@ -203,7 +208,7 @@ public bool ReadPixelsFromFrontBuffer() { } public void SetHDREnabled(bool bEnable) { - throw new NotImplementedException(); + HDREnabled = bEnable; } public bool SpecifiesFogColorInLinearSpace() { @@ -252,7 +257,15 @@ public bool SupportsHDR() { } public bool SupportsHDRMode(HDRType nHDRMode) { - throw new NotImplementedException(); + switch (nHDRMode) { + case HDRType.None: + return true; + case HDRType.Integer: + return MaxHDRType == HDRType.Integer || MaxHDRType == HDRType.Float; + case HDRType.Float: + return MaxHDRType == HDRType.Float; + } + return false; } public bool SupportsMipmappedCubemaps() { From bbf259c0d779940f7198ec89bbd33c966d0886ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:19:52 +0300 Subject: [PATCH 04/57] Port MaterialSystem.ReloadMaterials --- Source.Common/MaterialSystem/IMaterial.cs | 3 ++ Source.MaterialSystem/Material.cs | 15 ++++++ Source.MaterialSystem/MaterialSystem.cs | 63 +++++++++++++++++++++-- 3 files changed, 77 insertions(+), 4 deletions(-) diff --git a/Source.Common/MaterialSystem/IMaterial.cs b/Source.Common/MaterialSystem/IMaterial.cs index f138b9413..101530532 100644 --- a/Source.Common/MaterialSystem/IMaterial.cs +++ b/Source.Common/MaterialSystem/IMaterial.cs @@ -496,6 +496,9 @@ public interface IMaterialInternal : IMaterial IMaterialInternal GetRealTimeVersion(); bool IsManuallyCreated(); bool IsPrecached(); + bool IsPrecachedVars(); + int GetReferenceCount(); + void ReloadTextures(); bool IsUsingVertexID(); void Precache(); bool PrecacheVars(KeyValues? inVmtKeyValues = null, KeyValues? inPatchKeyValues = null, List? includes = null, MaterialFindContext findContext = 0); diff --git a/Source.MaterialSystem/Material.cs b/Source.MaterialSystem/Material.cs index 487773f6a..2a3407b9c 100644 --- a/Source.MaterialSystem/Material.cs +++ b/Source.MaterialSystem/Material.cs @@ -1108,6 +1108,19 @@ public void Refresh() { } } + public void ReloadTextures() { + Precache(); + int paramCount = ShaderParamCount(); + IMaterialVar[]? vars = GetShaderParams(); + for (int i = 0; i < paramCount; i++) { + if (vars![i] != null && vars[i].IsTexture()) { + ITexture? texture = vars[i].GetTextureValue(); + if (!ITexture.IsError(texture)) + texture.Download(); + } + } + } + public void RefreshPreservingMaterialVars() { if (materials.ShaderDevice.IsUsingGraphics()) { Uncache(true); @@ -1194,6 +1207,8 @@ public void SetNeedsWhiteLightmap(bool value) { int RefCount; + public int GetReferenceCount() => RefCount; + public void IncrementReferenceCount() => ++RefCount; public void DecrementReferenceCount() => --RefCount; diff --git a/Source.MaterialSystem/MaterialSystem.cs b/Source.MaterialSystem/MaterialSystem.cs index ed497b2ea..7c2808e5b 100644 --- a/Source.MaterialSystem/MaterialSystem.cs +++ b/Source.MaterialSystem/MaterialSystem.cs @@ -952,6 +952,7 @@ public void CreateDebugMaterials() { void ReleaseShaderObjects() { // todo + ReleaseStandardTextures(); for (int i = 0; i < ReleaseFunc.Count; i++) ReleaseFunc[i](); } @@ -967,6 +968,7 @@ public void RestoreShaderObjects(IServiceProvider? services, int changeFlags) { } TextureSystem.RestoreRenderTargets(); + AllocateStandardTextures(); Restore?.Invoke(); for (int i = 0; i < RestoreFunc.Count; i++) RestoreFunc[i]((RestoreChangeFlags)changeFlags); @@ -1244,7 +1246,55 @@ public void ReloadTextures() { } public void ReloadMaterials(ReadOnlySpan subString = default) { - // todo + bool vertexFormatChanged = false; + if (subString.IsEmpty) { + vertexFormatChanged = true; + UncacheAllMaterials(); + CacheUsedMaterials(); + } + else { + const char multiDelim = '*'; + List searchItems = []; + if (subString.Contains(multiDelim)) + searchItems.AddRange(new string(subString).Split(multiDelim)); + + foreach (IMaterialInternal material in (IMaterialInternal[])[.. MaterialDict]) { + if (material.GetReferenceCount() <= 0) + continue; + + ReadOnlySpan matName = material.GetName(); + + if (searchItems.Count > 1) { + bool matched = false; + for (int k = 0; !matched && k < searchItems.Count; ++k) + if (matName.Contains(searchItems[k], StringComparison.OrdinalIgnoreCase)) + matched = true; + + if (!matched) + continue; + } + else if (!matName.Contains(subString, StringComparison.OrdinalIgnoreCase)) + continue; + + if (!material.IsPrecached()) { + if (material.IsPrecachedVars()) + material.Uncache(); + } + else { + VertexFormat oldVertexFormat = material.GetVertexFormat(); + material.Uncache(); + material.Precache(); + material.ReloadTextures(); + if (material.GetVertexFormat() != oldVertexFormat) + vertexFormatChanged = true; + } + } + } + + if (vertexFormatChanged) { + ReleaseShaderObjects(); + RestoreShaderObjects(null, (int)RestoreChangeFlags.VertexFormatChanged); + } } void RecomputeAllStateSnapshots() { @@ -1309,7 +1359,11 @@ public void AsyncFindTexture(ReadOnlySpan pFilename, ReadOnlySpan } public void CacheUsedMaterials() { - throw new NotImplementedException("Incomplete port of IMaterialSystem"); + foreach (IMaterialInternal material in (IMaterialInternal[])[.. MaterialDict]) { + Assert(material.GetReferenceCount() >= 0); + if (material.GetReferenceCount() > 0) + material.Precache(); + } } public void ClearBuffers(bool clearColor, bool clearDepth, bool clearStencil = false) { @@ -1492,11 +1546,12 @@ public void OverrideRenderTargetAllocation(bool rtAlloc) { } public void ReacquireResources() { - throw new NotImplementedException("Incomplete port of IMaterialSystem"); + ShaderDevice.ReacquireResources(); } public void ReleaseResources() { - throw new NotImplementedException("Incomplete port of IMaterialSystem"); + ShaderAPI.FlushBufferedPrimitives(); + ShaderDevice.ReleaseResources(); } public void ReloadFilesInList(IFileList filesToReload) { From 19c3ba816fd8b99fa5bb15870fa3af1f536cc424 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:37:08 +0300 Subject: [PATCH 05/57] Port Map_CheckForHDR and EnableHDR --- Source.Engine/CdllEngineInterface.cs | 2 +- Source.Engine/MatSysInterface.cs | 1 + Source.Engine/ModelLoader.cs | 34 +++++++++++++++++++++++++++- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/Source.Engine/CdllEngineInterface.cs b/Source.Engine/CdllEngineInterface.cs index 2730937ee..7f1918569 100644 --- a/Source.Engine/CdllEngineInterface.cs +++ b/Source.Engine/CdllEngineInterface.cs @@ -533,7 +533,7 @@ public bool IsHammerRunning() { } public bool MapHasHDRLighting() { - throw new NotImplementedException(); + return modelloader.LastLoadedMapHasHDRLighting(); } public int GetAppID() { diff --git a/Source.Engine/MatSysInterface.cs b/Source.Engine/MatSysInterface.cs index 11dc0e2e4..87ff8a3ba 100644 --- a/Source.Engine/MatSysInterface.cs +++ b/Source.Engine/MatSysInterface.cs @@ -47,6 +47,7 @@ public static class MatSysVars public static readonly ConVar r_waterforcereflectentities = new("r_waterforcereflectentities", "0"); public static readonly ConVar mat_depthbias_normal = new("mat_depthbias_normal", "0.0", FCvar.Cheat); public static readonly ConVar mat_show_ab_hdr = new("mat_show_ab_hdr", "0"); + public static readonly ConVar mat_hdr_level = new("mat_hdr_level", "2", FCvar.Archive, "Set to 0 for no HDR, 1 for LDR+bloom on HDR maps, and 2 for full HDR on HDR maps."); } public struct MaterialList diff --git a/Source.Engine/ModelLoader.cs b/Source.Engine/ModelLoader.cs index 852860592..35df6753e 100644 --- a/Source.Engine/ModelLoader.cs +++ b/Source.Engine/ModelLoader.cs @@ -774,6 +774,38 @@ private void Mod_LoadLump(Model loadmodel, LumpIndex lump, ReadOnlySpan data = lh.LoadLumpData(); } + bool MapHasHDRLighting; + public bool LastLoadedMapHasHDRLighting() => MapHasHDRLighting; + + void EnableHDR(bool enable) { + if (materialSystemHardwareConfig.GetHDREnabled() == enable) + return; + + materialSystemHardwareConfig.SetHDREnabled(enable); + + MatSysInterface.UpdateMaterialSystemConfig(); + + materialSystem.ReleaseResources(); + materialSystem.ReacquireResources(); + } + + bool Map_CheckForHDR(Model mod, ReadOnlySpan loadName) { + MapLoadHelper.Init(mod, loadName); + + bool hasHDR = MapLoadHelper.GetLumpSize(LumpIndex.LightingHDR) > 0 && + MapLoadHelper.GetLumpSize(LumpIndex.WorldLightsHDR) > 0; + if (MapLoadHelper.MapHeader.Version >= 20 && MapLoadHelper.GetLumpSize(LumpIndex.LeafAmbientLightingHDR) == 0) + hasHDR = false; + + bool enableHDR = hasHDR && mat_hdr_level.GetInt() >= 2; + + EnableHDR(enableHDR); + + MapLoadHelper.Shutdown(); + + return hasHDR; + } + private void Map_LoadModel(Model mod) { MapLoadCount++; @@ -790,7 +822,7 @@ private void Map_LoadModel(Model mod) { mod.Brush.RenderHandle = 0; Common.TimestampedLog(" Map_CheckForHDR"); - // todo + MapHasHDRLighting = Map_CheckForHDR(mod, LoadNameSliced()); Common.TimestampedLog(" CM_LoadMap"); CM.LoadMap(mod.StrName, false, out uint checksum); From d44840d019e83850864e5843cafedc689a1b865a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:46:29 +0300 Subject: [PATCH 06/57] Load the HDR face lump when HDR is enabled --- Source.Engine/CollisionModelSubsystem.cs | 5 ++++- Source.Engine/ModelLoader.cs | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Source.Engine/CollisionModelSubsystem.cs b/Source.Engine/CollisionModelSubsystem.cs index ed80e5409..e66fb78d6 100644 --- a/Source.Engine/CollisionModelSubsystem.cs +++ b/Source.Engine/CollisionModelSubsystem.cs @@ -557,7 +557,10 @@ internal void LoadDispInfo() { BSPDertex[] verts = new MapLoadHelper(LumpIndex.Vertexes).LoadLumpData(); BSPDEdge[] edges = new MapLoadHelper(LumpIndex.Edges).LoadLumpData(); int[] surfEdges = new MapLoadHelper(LumpIndex.SurfEdges).LoadLumpData(); - BSPDFace[] faces = new MapLoadHelper(LumpIndex.Faces).LoadLumpData(); + LumpIndex faceLumpToLoad = LumpIndex.Faces; + if (HardwareConfig.GetHDRType() != HDRType.None && MapLoadHelper.GetLumpSize(LumpIndex.FacesHDR) > 0) + faceLumpToLoad = LumpIndex.FacesHDR; + BSPDFace[] faces = new MapLoadHelper(faceLumpToLoad).LoadLumpData(); BSPDDispInfo[] dispInfos = new MapLoadHelper(LumpIndex.DispInfo).LoadLumpData(); DispVert[] dispVerts = new MapLoadHelper(LumpIndex.DispVerts).LoadLumpData(); DispTri[] dispTris = new MapLoadHelper(LumpIndex.DispTris).LoadLumpData(); diff --git a/Source.Engine/ModelLoader.cs b/Source.Engine/ModelLoader.cs index 35df6753e..298bfbc9b 100644 --- a/Source.Engine/ModelLoader.cs +++ b/Source.Engine/ModelLoader.cs @@ -1870,7 +1870,10 @@ private static void CalcSurfaceExtents(in MapLoadHelper lh, ref BSPMSurface2 sur } private void Mod_LoadFaces() { - MapLoadHelper lh = new MapLoadHelper(LumpIndex.Faces); + LumpIndex faceLumpToLoad = LumpIndex.Faces; + if (materialSystemHardwareConfig.GetHDRType() != HDRType.None && MapLoadHelper.GetLumpSize(LumpIndex.FacesHDR) > 0) + faceLumpToLoad = LumpIndex.FacesHDR; + MapLoadHelper lh = new MapLoadHelper(faceLumpToLoad); BSPDFace[] inFaces = lh.LoadLumpData(); int count = inFaces.Length; From f04d90fab1244045dc47c074e1988cab9e8016a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:03:41 +0300 Subject: [PATCH 07/57] Port integer HDR lightmap writers --- Source.MaterialSystem/ColorSpace.cs | 68 +++++++++++++++++++ Source.MaterialSystem/MatLightmaps.cs | 97 ++++++++++++++++++++++++++- 2 files changed, 163 insertions(+), 2 deletions(-) diff --git a/Source.MaterialSystem/ColorSpace.cs b/Source.MaterialSystem/ColorSpace.cs index f71691375..0b2d4328c 100644 --- a/Source.MaterialSystem/ColorSpace.cs +++ b/Source.MaterialSystem/ColorSpace.cs @@ -170,6 +170,74 @@ public static void LinearToBumpedLightmap( retBump3[2] = MathLib.RoundFloatToByte(correctedBumpColor3[2] * 255.0f); } + public static ushort LinearFloatToCorrectedShort(float input) { + input = MathF.Min(input * 4096.0f, 65535.0f); + return (ushort)MathF.Max(input, 0.0f); + } + + public static ushort LinearToUnsignedShort(float input, int fractionalBits) { + input = input * (1 << fractionalBits); + input = MathF.Min(input, 65535); + return (ushort)MathF.Max(input, 0.0f); + } + + public static void ClampToHDR(in Vector3 input, Span output) { + output[0] = LinearFloatToCorrectedShort(input.X); + output[1] = LinearFloatToCorrectedShort(input.Y); + output[2] = LinearFloatToCorrectedShort(input.Z); + } + + public static void LinearToBumpedLightmap( + ReadOnlySpan linearColor, ReadOnlySpan linearBumpColor1, + ReadOnlySpan linearBumpColor2, ReadOnlySpan linearBumpColor3, + out Vector3 ret, out Vector3 retBump1, + out Vector3 retBump2, out Vector3 retBump3) { + + Vector3 linearUnbumped = linearColor[..3].Cast()[0]; + Vector3 linearBump1 = linearBumpColor1[..3].Cast()[0]; + Vector3 linearBump2 = linearBumpColor2[..3].Cast()[0]; + Vector3 linearBump3 = linearBumpColor3[..3].Cast()[0]; + + Vector3 bumpAverage = linearBump1; + bumpAverage += linearBump2; + bumpAverage += linearBump3; + bumpAverage *= (1.0f / 3.0f); + + Vector3 correctionScale = default; + if (const_reinterpret(in bumpAverage.X) != 0 && const_reinterpret(in bumpAverage.Y) != 0 && const_reinterpret(in bumpAverage.Z) != 0) + MathLib.VectorDivide(linearUnbumped, bumpAverage, out correctionScale); + else { + correctionScale.Init(0.0f, 0.0f, 0.0f); + if (bumpAverage[0] != 0.0f) + correctionScale[0] = linearUnbumped[0] / bumpAverage[0]; + if (bumpAverage[1] != 0.0f) + correctionScale[1] = linearUnbumped[1] / bumpAverage[1]; + if (bumpAverage[2] != 0.0f) + correctionScale[2] = linearUnbumped[2] / bumpAverage[2]; + } + linearBump1 *= correctionScale; + linearBump2 *= correctionScale; + linearBump3 *= correctionScale; + + ret = linearUnbumped; + retBump1 = linearBump1; + retBump2 = linearBump2; + retBump3 = linearBump3; + } + + public static void LinearToBumpedLightmap( + ReadOnlySpan linearColor, ReadOnlySpan linearBumpColor1, + ReadOnlySpan linearBumpColor2, ReadOnlySpan linearBumpColor3, + Span ret, Span retBump1, + Span retBump2, Span retBump3) { + LinearToBumpedLightmap(linearColor, linearBumpColor1, linearBumpColor2, linearBumpColor3, out Vector3 linearUnbumped, out Vector3 linearBump1, out Vector3 linearBump2, out Vector3 linearBump3); + + ClampToHDR(in linearUnbumped, ret); + ClampToHDR(in linearBump1, retBump1); + ClampToHDR(in linearBump2, retBump2); + ClampToHDR(in linearBump3, retBump3); + } + internal static void SetGamma(float screenGamma, float texGamma, float overbright, bool allowCheats, bool linearFrameBuffer) { int i, inf; float g1, g3; diff --git a/Source.MaterialSystem/MatLightmaps.cs b/Source.MaterialSystem/MatLightmaps.cs index fca8696ba..3b7fe7b83 100644 --- a/Source.MaterialSystem/MatLightmaps.cs +++ b/Source.MaterialSystem/MatLightmaps.cs @@ -593,7 +593,72 @@ void BumpedLightmapBitsToPixelWriter_HDRF(Span floatImage, Span fl } void BumpedLightmapBitsToPixelWriter_HDRI(Span floatImage, Span floatImageBump1, Span floatImageBump2, Span floatImageBump3, Span lightmapSize, Span offsetIntoLightmapPage) { - throw new NotImplementedException(); + int lightmapSize0 = lightmapSize[0]; + int lightmap0WriterSizeBytes = lightmapSize0 * LightmapPixelWriter.GetPixelSize(); + int rewindToNextPixel = -((lightmap0WriterSizeBytes * 3) - LightmapPixelWriter.GetPixelSize()); + + Span color0 = stackalloc ushort[4]; + Span color1 = stackalloc ushort[4]; + Span color2 = stackalloc ushort[4]; + Span color3 = stackalloc ushort[4]; + + if (LightmapPixelWriter.IsUsingFloatFormat()) { + for (int t = 0; t < lightmapSize[1]; t++) { + int srcTexelOffset = 4 * (0 + t * lightmapSize0); + LightmapPixelWriter.Seek(offsetIntoLightmapPage[0], offsetIntoLightmapPage[1] + t); + + for (int s = 0; s < lightmapSize0; + s++, LightmapPixelWriter.SkipBytes(rewindToNextPixel), srcTexelOffset += 4) { + ColorSpace.LinearToBumpedLightmap(floatImage[srcTexelOffset..], + floatImageBump1[srcTexelOffset..], floatImageBump2[srcTexelOffset..], + floatImageBump3[srcTexelOffset..], + color0, color1, color2, color3); + float alpha = floatImage[srcTexelOffset + 3]; + Assert(alpha >= 0.0f && alpha <= 1.0f); + color0[3] = color1[3] = color2[3] = color3[3] = (ushort)alpha; + + float toFloat = 1.0f / (float)(1 << 16); + + LightmapPixelWriter.WritePixelNoAdvanceF(toFloat * color0[0], toFloat * color0[1], toFloat * color0[2], toFloat * color0[3]); + + LightmapPixelWriter.SkipBytes(lightmap0WriterSizeBytes); + LightmapPixelWriter.WritePixelNoAdvanceF(toFloat * color1[0], toFloat * color1[1], toFloat * color1[2], toFloat * color1[3]); + + LightmapPixelWriter.SkipBytes(lightmap0WriterSizeBytes); + LightmapPixelWriter.WritePixelNoAdvanceF(toFloat * color2[0], toFloat * color2[1], toFloat * color2[2], toFloat * color2[3]); + + LightmapPixelWriter.SkipBytes(lightmap0WriterSizeBytes); + LightmapPixelWriter.WritePixelNoAdvanceF(toFloat * color3[0], toFloat * color3[1], toFloat * color3[2], toFloat * color3[3]); + } + } + } + else { + for (int t = 0; t < lightmapSize[1]; t++) { + int srcTexelOffset = 4 * (0 + t * lightmapSize0); + LightmapPixelWriter.Seek(offsetIntoLightmapPage[0], offsetIntoLightmapPage[1] + t); + + for (int s = 0; s < lightmapSize0; + s++, LightmapPixelWriter.SkipBytes(rewindToNextPixel), srcTexelOffset += 4) { + ColorSpace.LinearToBumpedLightmap(floatImage[srcTexelOffset..], + floatImageBump1[srcTexelOffset..], floatImageBump2[srcTexelOffset..], + floatImageBump3[srcTexelOffset..], + color0, color1, color2, color3); + ushort alpha = ColorSpace.LinearToUnsignedShort(floatImage[srcTexelOffset + 3], 16); + color0[3] = color1[3] = color2[3] = color3[3] = alpha; + + LightmapPixelWriter.WritePixelNoAdvance(color0[0], color0[1], color0[2], color0[3]); + + LightmapPixelWriter.SkipBytes(lightmap0WriterSizeBytes); + LightmapPixelWriter.WritePixelNoAdvance(color1[0], color1[1], color1[2], color1[3]); + + LightmapPixelWriter.SkipBytes(lightmap0WriterSizeBytes); + LightmapPixelWriter.WritePixelNoAdvance(color2[0], color2[1], color2[2], color2[3]); + + LightmapPixelWriter.SkipBytes(lightmap0WriterSizeBytes); + LightmapPixelWriter.WritePixelNoAdvance(color3[0], color3[1], color3[2], color3[3]); + } + } + } } void LightmapBitsToPixelWriter_LDR(Span floatImage, Span lightmapSize, Span offsetIntoLightmapPage) { @@ -615,7 +680,35 @@ void LightmapBitsToPixelWriter_HDRF(Span floatImage, Span lightmapSi } void LightmapBitsToPixelWriter_HDRI(Span floatImage, Span lightmapSize, Span offsetIntoLightmapPage) { - throw new NotImplementedException(); + Span src = floatImage; + if (LightmapPixelWriter.IsUsingFloatFormat()) { + for (int t = 0; t < lightmapSize[1]; ++t) { + LightmapPixelWriter.Seek(offsetIntoLightmapPage[0], offsetIntoLightmapPage[1] + t); + for (int s = 0; s < lightmapSize[0]; ++s, src = src[4..]) { + int r = ColorSpace.LinearFloatToCorrectedShort(src[0]); + int g = ColorSpace.LinearFloatToCorrectedShort(src[1]); + int b = ColorSpace.LinearFloatToCorrectedShort(src[2]); + + float toFloat = 1.0f / (float)(1 << 16); + + Assert(src[3] >= 0.0f && src[3] <= 1.0f); + LightmapPixelWriter.WritePixelF(r * toFloat, g * toFloat, b * toFloat, src[3]); + } + } + } + else { + for (int t = 0; t < lightmapSize[1]; ++t) { + LightmapPixelWriter.Seek(offsetIntoLightmapPage[0], offsetIntoLightmapPage[1] + t); + for (int s = 0; s < lightmapSize[0]; ++s, src = src[4..]) { + int r = ColorSpace.LinearFloatToCorrectedShort(src[0]); + int g = ColorSpace.LinearFloatToCorrectedShort(src[1]); + int b = ColorSpace.LinearFloatToCorrectedShort(src[2]); + int a = ColorSpace.LinearToUnsignedShort(src[3], 16); + + LightmapPixelWriter.WritePixel(r, g, b, a); + } + } + } } // For computing sort info From 5f1f94fe874c044c63ec349720f3ba0719d670e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:15:57 +0300 Subject: [PATCH 08/57] Port RGBA16161616 and RGBA16161616F conversions --- Source.Bitmap/ImageLoader.cs | 37 ++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/Source.Bitmap/ImageLoader.cs b/Source.Bitmap/ImageLoader.cs index 11637ec9f..a738b8a4a 100644 --- a/Source.Bitmap/ImageLoader.cs +++ b/Source.Bitmap/ImageLoader.cs @@ -380,12 +380,49 @@ public static bool ConvertImageFormat(Span srcData, ImageFormat srcFormat, return true; } break; + case ImageFormat.RGBA16161616: + switch (dstFormat) { + case ImageFormat.RGBA16161616F: + ConvertImageFormat_RGBA16161616_To_RGBA16161616F(MemoryMarshal.Cast(srcData), MemoryMarshal.Cast(dstData), width, height); + return true; + } + break; + case ImageFormat.RGBA16161616F: + switch (dstFormat) { + case ImageFormat.RGBA16161616: + ConvertImageFormat_RGBA16161616F_To_RGBA16161616(MemoryMarshal.Cast(srcData), MemoryMarshal.Cast(dstData), width, height); + return true; + } + break; } AssertMsg(false, $"No good way to convert {srcFormat} to {dstFormat}, expect issues\n"); return false; } + static void ConvertImageFormat_RGBA16161616_To_RGBA16161616F(ReadOnlySpan srcImage, Span dstImage, int width, int height) { + int srcSize = width * height * 4; + for (int i = 0; i < srcSize; i += 4) { + dstImage[i + 0] = (Half)(srcImage[i + 0] * (1.0f / (float)(1 << 16))); + dstImage[i + 1] = (Half)(srcImage[i + 1] * (1.0f / (float)(1 << 16))); + dstImage[i + 2] = (Half)(srcImage[i + 2] * (1.0f / (float)(1 << 16))); + dstImage[i + 3] = (Half)(srcImage[i + 3] * (1.0f / (float)(1 << 16))); + } + } + + static void ConvertImageFormat_RGBA16161616F_To_RGBA16161616(ReadOnlySpan srcImage, Span dstImage, int width, int height) { + int srcSize = width * height * 4; + for (int i = 0; i < srcSize; i += 4) { + for (int j = 0; j < 4; j++) { + float val = (float)srcImage[i + j]; + val *= (float)(1 << 12); + val = Math.Max(val, 0); + val = Math.Min(val, 65535.0f); + dstImage[i + j] = (ushort)val; + } + } + } + private static void ConvertFromDXT5(Span srcData, Span span, int width, int height) { int realWidth = 0; int realHeight = 0; From 669b07e58f803cef22dedde3414e9f83bb6ab37c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:38:24 +0300 Subject: [PATCH 09/57] Port Sky_DX9 and Sky_HDR_DX9 shaders --- Game.Assets/hl2/shaders/sky_gl460.fs | 24 ++ Game.Assets/hl2/shaders/sky_gl460.vs | 53 ++++ .../hl2/shaders/sky_hdr_compressed_gl460.fs | 25 ++ .../shaders/sky_hdr_compressed_rgbs_gl460.fs | 43 ++++ Source.StdShader.Gl46/Sky.cs | 114 +-------- Source.StdShader.Gl46/Sky_DX9.cs | 81 ++++++ Source.StdShader.Gl46/Sky_HDR_DX9.cs | 235 ++++++++++++++++++ 7 files changed, 462 insertions(+), 113 deletions(-) create mode 100644 Game.Assets/hl2/shaders/sky_gl460.fs create mode 100644 Game.Assets/hl2/shaders/sky_gl460.vs create mode 100644 Game.Assets/hl2/shaders/sky_hdr_compressed_gl460.fs create mode 100644 Game.Assets/hl2/shaders/sky_hdr_compressed_rgbs_gl460.fs create mode 100644 Source.StdShader.Gl46/Sky_DX9.cs create mode 100644 Source.StdShader.Gl46/Sky_HDR_DX9.cs diff --git a/Game.Assets/hl2/shaders/sky_gl460.fs b/Game.Assets/hl2/shaders/sky_gl460.fs new file mode 100644 index 000000000..29a1cda31 --- /dev/null +++ b/Game.Assets/hl2/shaders/sky_gl460.fs @@ -0,0 +1,24 @@ +#version 460 +// DYNAMIC: "WRITE_DEPTH_TO_DESTALPHA" "0..1" + +in vec2 vs_BaseTexCoord00; + +layout(std140, binding = 6) uniform source_ps_constants { + vec4 ps_const[256]; +}; + +out vec4 fragColor; + +#include "common_gl460.fs" + +layout(binding = 0) uniform sampler2D BaseTextureSampler; + +#define InputScale ps_const[0] + +void main() +{ + vec4 color = texture(BaseTextureSampler, vs_BaseTexCoord00); + color.rgb *= InputScale.rgb; + + fragColor = FinalOutput(color, 0.0, PIXEL_FOG_TYPE_NONE, TONEMAP_SCALE_LINEAR, WRITE_DEPTH_TO_DESTALPHA != 0, 1e20); +} diff --git a/Game.Assets/hl2/shaders/sky_gl460.vs b/Game.Assets/hl2/shaders/sky_gl460.vs new file mode 100644 index 000000000..8dfe2d1bb --- /dev/null +++ b/Game.Assets/hl2/shaders/sky_gl460.vs @@ -0,0 +1,53 @@ +#version 460 + +layout(location = 0) in vec3 v_Position; +layout(location = 10) in vec2 v_TexCoord0; + +layout(std140, binding = 0) uniform source_matrices { + mat4 viewMatrix; + mat4 projectionMatrix; + mat4 modelMatrix; +}; + +layout(std140, binding = 5) uniform source_vs_constants { + vec4 vs_const[256]; +}; + +#define g_vTextureSizeInfo vs_const[48] +#define g_mBaseTexCoordTransform0 vs_const[49] +#define g_mBaseTexCoordTransform1 vs_const[50] + +#define TEXEL_XINCR (g_vTextureSizeInfo.x) +#define TEXEL_YINCR (g_vTextureSizeInfo.y) +#define U_TO_PIXEL_COORD_SCALE (g_vTextureSizeInfo.z) +#define V_TO_PIXEL_COORD_SCALE (g_vTextureSizeInfo.w) + +out vec2 vs_BaseTexCoord00; +out vec2 vs_BaseTexCoord01; +out vec2 vs_BaseTexCoord10; +out vec2 vs_BaseTexCoord11; +out vec2 vs_BaseTexCoord_In_Pixels; + +void main() +{ + gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(v_Position, 1.0); + + vec4 vTexCoordInput = vec4(v_TexCoord0.x, v_TexCoord0.y, 0.0, 1.0); + vec2 vTexCoord; + vTexCoord.x = dot(vTexCoordInput, g_mBaseTexCoordTransform0); + vTexCoord.y = dot(vTexCoordInput, g_mBaseTexCoordTransform1); + + vs_BaseTexCoord00.x = vTexCoord.x - TEXEL_XINCR; + vs_BaseTexCoord00.y = vTexCoord.y - TEXEL_YINCR; + vs_BaseTexCoord10.x = vTexCoord.x + TEXEL_XINCR; + vs_BaseTexCoord10.y = vTexCoord.y - TEXEL_YINCR; + + vs_BaseTexCoord01.x = vTexCoord.x - TEXEL_XINCR; + vs_BaseTexCoord01.y = vTexCoord.y + TEXEL_YINCR; + vs_BaseTexCoord11.x = vTexCoord.x + TEXEL_XINCR; + vs_BaseTexCoord11.y = vTexCoord.y + TEXEL_YINCR; + + vs_BaseTexCoord_In_Pixels = vs_BaseTexCoord00; + vs_BaseTexCoord_In_Pixels.x *= U_TO_PIXEL_COORD_SCALE; + vs_BaseTexCoord_In_Pixels.y *= V_TO_PIXEL_COORD_SCALE; +} diff --git a/Game.Assets/hl2/shaders/sky_hdr_compressed_gl460.fs b/Game.Assets/hl2/shaders/sky_hdr_compressed_gl460.fs new file mode 100644 index 000000000..45452511f --- /dev/null +++ b/Game.Assets/hl2/shaders/sky_hdr_compressed_gl460.fs @@ -0,0 +1,25 @@ +#version 460 +// DYNAMIC: "WRITE_DEPTH_TO_DESTALPHA" "0..1" + +in vec2 vs_BaseTexCoord00; + +layout(std140, binding = 6) uniform source_ps_constants { + vec4 ps_const[256]; +}; + +out vec4 fragColor; + +#include "common_gl460.fs" + +layout(binding = 0) uniform sampler2D ExposureTextureSampler0; +layout(binding = 1) uniform sampler2D ExposureTextureSampler1; +layout(binding = 2) uniform sampler2D ExposureTextureSampler2; + +void main() +{ + vec3 color0 = 0.25 * texture(ExposureTextureSampler0, vs_BaseTexCoord00).rgb; + vec3 color1 = 2.0 * texture(ExposureTextureSampler1, vs_BaseTexCoord00).rgb; + vec3 color2 = 16.0 * texture(ExposureTextureSampler2, vs_BaseTexCoord00).rgb; + + fragColor = FinalOutput(vec4(1.0, 0.0, 0.0, 1.0), 0.0, PIXEL_FOG_TYPE_NONE, TONEMAP_SCALE_LINEAR, WRITE_DEPTH_TO_DESTALPHA != 0, 1e20); +} diff --git a/Game.Assets/hl2/shaders/sky_hdr_compressed_rgbs_gl460.fs b/Game.Assets/hl2/shaders/sky_hdr_compressed_rgbs_gl460.fs new file mode 100644 index 000000000..3b2a6f938 --- /dev/null +++ b/Game.Assets/hl2/shaders/sky_hdr_compressed_rgbs_gl460.fs @@ -0,0 +1,43 @@ +#version 460 +// DYNAMIC: "WRITE_DEPTH_TO_DESTALPHA" "0..1" + +in vec2 vs_BaseTexCoord00; +in vec2 vs_BaseTexCoord01; +in vec2 vs_BaseTexCoord10; +in vec2 vs_BaseTexCoord11; +in vec2 vs_BaseTexCoord_In_Pixels; + +layout(std140, binding = 6) uniform source_ps_constants { + vec4 ps_const[256]; +}; + +out vec4 fragColor; + +#include "common_gl460.fs" + +layout(binding = 0) uniform sampler2D RGBSTextureSampler; + +#define InputScale ps_const[0] + +void main() +{ + vec4 s00 = texture(RGBSTextureSampler, vs_BaseTexCoord00); + vec4 s10 = texture(RGBSTextureSampler, vs_BaseTexCoord10); + vec4 s01 = texture(RGBSTextureSampler, vs_BaseTexCoord01); + vec4 s11 = texture(RGBSTextureSampler, vs_BaseTexCoord11); + + vec2 fracCoord = fract(vs_BaseTexCoord_In_Pixels); + + s00.rgb *= s00.a; + s10.rgb *= s10.a; + + s00.xyz = mix(s00, s10, fracCoord.x).xyz; + + s01.rgb *= s01.a; + s11.rgb *= s11.a; + s01.xyz = mix(s01, s11, fracCoord.x).xyz; + + vec3 result = mix(s00, s01, fracCoord.y).xyz; + + fragColor = FinalOutput(vec4(InputScale.rgb * result, 1.0), 0.0, PIXEL_FOG_TYPE_NONE, TONEMAP_SCALE_LINEAR, WRITE_DEPTH_TO_DESTALPHA != 0, 1e20); +} diff --git a/Source.StdShader.Gl46/Sky.cs b/Source.StdShader.Gl46/Sky.cs index 21a4fb95a..dfdca8589 100644 --- a/Source.StdShader.Gl46/Sky.cs +++ b/Source.StdShader.Gl46/Sky.cs @@ -1,123 +1,11 @@ -#if GMOD_DLL using Source.Common.MaterialSystem; -using Source.Common.ShaderLib; namespace Source.StdShader.Gl46; public class Sky : BaseVSShader { - public static string HelpString = "Help for Sky"; public static int Flags = 0; - public static List ShaderParams = []; - public static ShaderParam[] ShaderParamOverrides = new ShaderParam[(int)ShaderMaterialVars.Count]; - - public class ShaderParam - { - public readonly ShaderParamInfo Info; - public readonly int Index; - public ShaderParam(ShaderMaterialVars var, ShaderParamType type, ReadOnlySpan defaultParam, ReadOnlySpan help, int flags) { - Info.Name = "override"; - Info.Type = type; - Info.DefaultValue = new(defaultParam); - Info.Help = new(help); - Info.Flags = (ShaderParamFlags)flags; - - if (ShaderParamOverrides[(int)var] == null) { - - } - else { - AssertMsg(false, "ShaderParamOverrides at var index had null value"); - } - - ShaderParamOverrides[(int)var] = this; - Index = (int)var; - } - public ShaderParam(string name, ShaderParamType type, ReadOnlySpan defaultParam, ReadOnlySpan help, int flags = 0) { - Info.Name = name; - Info.Type = type; - Info.DefaultValue = new(defaultParam); - Info.Help = new(help); - Info.Flags = (ShaderParamFlags)flags; - Index = (int)ShaderMaterialVars.Count + ShaderParams.Count; - ShaderParams.Add(this); - } - public static implicit operator int(ShaderParam param) => param.Index; - public ReadOnlySpan GetName() => Info.Name; - public ShaderParamType GetType() => Info.Type; - public ReadOnlySpan GetDefaultValue() => Info.DefaultValue; - public int GetFlags() => (int)Info.Flags; - public ReadOnlySpan GetHelp() => Info.Help; - } - - public static readonly ShaderParam DETAIL = new($"${nameof(DETAIL)}", ShaderParamType.Texture, "shadertest/detail", "detail texture"); - public static readonly ShaderParam DETAILSCALE = new($"${nameof(DETAILSCALE)}", ShaderParamType.Float, "4", "scale of the detail texture" ); - public static readonly ShaderParam ENVMAP = new($"${nameof(ENVMAP)}", ShaderParamType.Texture, "shadertest/shadertest_env", "envmap" ); - public static readonly ShaderParam ENVMAPFRAME = new($"${nameof(ENVMAPFRAME)}", ShaderParamType.Integer, "0", "" ); - public static readonly ShaderParam ENVMAPMASK = new($"${nameof(ENVMAPMASK)}", ShaderParamType.Texture, "shadertest/shadertest_envmask", "envmap mask" ); - public static readonly ShaderParam ENVMAPMASKFRAME = new($"${nameof(ENVMAPMASKFRAME)}", ShaderParamType.Integer, "0", "" ); - public static readonly ShaderParam ENVMAPMASKSCALE = new($"${nameof(ENVMAPMASKSCALE)}", ShaderParamType.Float, "1", "envmap mask scale" ); - public static readonly ShaderParam ENVMAPTINT = new($"${nameof(ENVMAPTINT)}", ShaderParamType.Color, "[1 1 1]", "envmap tint" ); - public static readonly ShaderParam ENVMAPOPTIONAL = new($"${nameof(ENVMAPOPTIONAL)}", ShaderParamType.Bool, "0", "Make the envmap only apply to dx9 and higher hardware" ); - public static readonly ShaderParam DETAILBLENDMODE = new($"${nameof(DETAILBLENDMODE)}", ShaderParamType.Integer, "0", "mode for combining detail texture with base. 0=normal, 1= additive, 2=alpha blend detail over base, 3=crossfade" ); - public static readonly ShaderParam ALPHATESTREFERENCE = new($"${nameof(ALPHATESTREFERENCE)}", ShaderParamType.Float, "0.7", "" ); - public static readonly ShaderParam OUTLINE = new($"${nameof(OUTLINE)}", ShaderParamType.Bool, "0", "Enable outline for distance coded textures."); - public static readonly ShaderParam OUTLINECOLOR = new($"${nameof(OUTLINECOLOR)}", ShaderParamType.Color, "[1 1 1]", "color of outline for distance coded images." ); - public static readonly ShaderParam OUTLINESTART0 = new($"${nameof(OUTLINESTART0)}", ShaderParamType.Float, "0.0", "outer start value for outline"); - public static readonly ShaderParam OUTLINESTART1 = new($"${nameof(OUTLINESTART1)}", ShaderParamType.Float, "0.0", "inner start value for outline"); - public static readonly ShaderParam OUTLINEEND0 = new($"${nameof(OUTLINEEND0)}", ShaderParamType.Float, "0.0", "inner end value for outline"); - public static readonly ShaderParam OUTLINEEND1 = new($"${nameof(OUTLINEEND1)}", ShaderParamType.Float, "0.0", "outer end value for outline"); - public static readonly ShaderParam SEPARATEDETAILUVS = new($"${nameof(SEPARATEDETAILUVS)}", ShaderParamType.Integer, "0", "" ); - - - protected override void OnInitShaderParams(IMaterialVar[] vars, ReadOnlySpan materialName) { - InitParamsUnlitGeneric((int)ShaderMaterialVars.BaseTexture, DETAILSCALE, ENVMAPOPTIONAL, ENVMAP, ENVMAPTINT, ENVMAPMASKSCALE, DETAILBLENDMODE); - } - public override string? GetFallbackShader(IMaterialVar[] vars) { - return null; - } - public override int GetFlags() => Flags; - public override int GetNumParams() => base.GetNumParams() + ShaderParams.Count; - public override ReadOnlySpan GetParamName(int paramIndex) { - int baseClassParamCount = base.GetNumParams(); - if (paramIndex < baseClassParamCount) - return base.GetParamName(paramIndex); - else - return ShaderParams[paramIndex - baseClassParamCount].GetName(); - } - public override ReadOnlySpan GetParamHelp(int paramIndex) { - int baseClassParamCount = base.GetNumParams(); - if (paramIndex < baseClassParamCount) - return base.GetParamHelp(paramIndex); - else - return ShaderParams[paramIndex - baseClassParamCount].GetHelp(); - } - public override ShaderParamType GetParamType(int paramIndex) { - int baseClassParamCount = base.GetNumParams(); - if (paramIndex < baseClassParamCount) - return base.GetParamType(paramIndex); - else - return ShaderParams[paramIndex - baseClassParamCount].GetType(); - } - public override ReadOnlySpan GetParamDefault(int paramIndex) { - int baseClassParamCount = base.GetNumParams(); - if (paramIndex < baseClassParamCount) - return base.GetParamDefault(paramIndex); - else - return ShaderParams[paramIndex - baseClassParamCount].GetDefaultValue(); - } - protected override void OnInitShaderInstance(IMaterialVar[] vars, ReadOnlySpan materialName) { - InitUnlitGeneric((int)ShaderMaterialVars.BaseTexture, DETAIL, ENVMAP, ENVMAPMASK); - } - protected override void OnDrawElements(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, VertexCompressionType vertexCompression) { - if (IsSnapshotting()) { - ShaderShadow.EnableDepthTest(false); - } - VertexShaderUnlitGenericPass((int)ShaderMaterialVars.BaseTexture, (int)ShaderMaterialVars.Frame, (int)ShaderMaterialVars.BaseTextureTransform, - DETAIL, DETAILSCALE, true, ENVMAP, ENVMAPFRAME, ENVMAPMASK, - ENVMAPMASKFRAME, ENVMAPMASKSCALE, ENVMAPTINT, ALPHATESTREFERENCE, - DETAILBLENDMODE, OUTLINE, OUTLINECOLOR, OUTLINESTART0, OUTLINEEND1, SEPARATEDETAILUVS, "unlitgeneric"); - } + public override string? GetFallbackShader(IMaterialVar[] vars) => "Sky_HDR_DX9"; } -#endif diff --git a/Source.StdShader.Gl46/Sky_DX9.cs b/Source.StdShader.Gl46/Sky_DX9.cs new file mode 100644 index 000000000..ae7831124 --- /dev/null +++ b/Source.StdShader.Gl46/Sky_DX9.cs @@ -0,0 +1,81 @@ +using Source.Common; +using Source.Common.Bitmap; +using Source.Common.MaterialSystem; +using Source.Common.ShaderAPI; +using Source.Common.ShaderLib; + +namespace Source.StdShader.Gl46; + +public class Sky_DX9 : BaseVSShader +{ + public static string HelpString = "Help for Sky_DX9 shader"; + public static int Flags = 0; + + public override string? GetFallbackShader(IMaterialVar[] vars) => null; + + protected override void OnInitShaderParams(IMaterialVar[] vars, ReadOnlySpan materialName) { + SetFlags(vars, MaterialVarFlags.NoFog); + SetFlags(vars, MaterialVarFlags.IgnoreZ); + } + + protected override void OnInitShaderInstance(IMaterialVar[] vars, ReadOnlySpan materialName) { + if (vars[(int)ShaderMaterialVars.BaseTexture].IsDefined()) { + ImageFormat fmt = vars[(int)ShaderMaterialVars.BaseTexture].GetTextureValue()!.GetImageFormat(); + LoadTexture((int)ShaderMaterialVars.BaseTexture, (fmt == ImageFormat.RGBA16161616F) || (fmt == ImageFormat.RGBA16161616) ? 0 : (int)TextureFlags.SRGB); + } + } + + protected override void OnDrawElements(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, VertexCompressionType vertexCompression) { + if (IsSnapshotting()) { + SetInitialShadowState(); + + ShaderShadow.EnableTexture(Sampler.Sampler0, true); + ITexture txtr = vars[(int)ShaderMaterialVars.BaseTexture].GetTextureValue()!; + ImageFormat fmt = txtr.GetImageFormat(); + if ((fmt == ImageFormat.RGBA16161616F) || (fmt == ImageFormat.RGBA16161616)) + ShaderShadow.EnableSRGBRead(Sampler.Sampler0, false); + else + ShaderShadow.EnableSRGBRead(Sampler.Sampler0, true); + + ShaderShadow.VertexShaderVertexFormat(VertexFormat.Position, 1, null, 0); + + StaticShaderIndex vshIndex = new(ShaderShadow, ShaderType.Vertex, "sky"); + ShaderShadow.SetVertexShader("sky", vshIndex.GetIndex()); + + StaticShaderIndex pshIndex = new(ShaderShadow, ShaderType.Pixel, "sky"); + ShaderShadow.SetPixelShader("sky", pshIndex.GetIndex()); + + ShaderShadow.EnableSRGBWrite(true); + + ShaderShadow.EnableAlphaWrites(true); + } + else { + BindTexture(Sampler.Sampler0, (int)ShaderMaterialVars.BaseTexture, (int)ShaderMaterialVars.Frame); + Span c1 = [0, 0, 0, 0]; + shaderAPI.SetVertexShaderConstant(VertexShaderConst.ShaderSpecificConst0, c1); + + Span c0 = [1, 1, 1, 1]; + if (vars[(int)ShaderMaterialVars.Color].IsDefined()) + vars[(int)ShaderMaterialVars.Color].GetVecValue(c0[..3]); + ITexture txtr = vars[(int)ShaderMaterialVars.BaseTexture].GetTextureValue()!; + ImageFormat fmt = txtr.GetImageFormat(); + if ((fmt == ImageFormat.RGBA16161616) || + ((fmt == ImageFormat.RGBA16161616F) && + (HardwareConfig.GetHDRType() == HDRType.Integer))) { + c0[0] *= 16.0f; + c0[1] *= 16.0f; + c0[2] *= 16.0f; + } + shaderAPI.SetPixelShaderConstant(0, c0, 1); + DynamicShaderIndex vshIndex = new(shaderAPI, ShaderType.Vertex); + shaderAPI.SetVertexShaderIndex(vshIndex.GetIndex()); + + SetVertexShaderTextureTransform(VertexShaderConst.ShaderSpecificConst1, (int)ShaderMaterialVars.BaseTextureTransform); + + DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); + pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", shaderAPI.ShouldWriteDepthToDestAlpha()); + shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); + } + Draw(); + } +} diff --git a/Source.StdShader.Gl46/Sky_HDR_DX9.cs b/Source.StdShader.Gl46/Sky_HDR_DX9.cs new file mode 100644 index 000000000..402245b17 --- /dev/null +++ b/Source.StdShader.Gl46/Sky_HDR_DX9.cs @@ -0,0 +1,235 @@ +using Source.Common; +using Source.Common.Bitmap; +using Source.Common.Commands; +using Source.Common.MaterialSystem; +using Source.Common.ShaderAPI; +using Source.Common.ShaderLib; + +namespace Source.StdShader.Gl46; + +public class Sky_HDR_DX9 : BaseVSShader +{ + public static string HelpString = "Help for Sky_HDR_DX9 shader"; + public static int Flags = 0; + public static List ShaderParams = []; + + public class ShaderParam + { + public readonly ShaderParamInfo Info; + public readonly int Index; + public ShaderParam(string name, ShaderParamType type, ReadOnlySpan defaultParam, ReadOnlySpan help, int flags = 0) { + Info.Name = name; + Info.Type = type; + Info.DefaultValue = new(defaultParam); + Info.Help = new(help); + Info.Flags = (ShaderParamFlags)flags; + Index = (int)ShaderMaterialVars.Count + ShaderParams.Count; + ShaderParams.Add(this); + } + public static implicit operator int(ShaderParam param) => param.Index; + public ReadOnlySpan GetName() => Info.Name; + public ShaderParamType GetType() => Info.Type; + public ReadOnlySpan GetDefaultValue() => Info.DefaultValue; + public int GetFlags() => (int)Info.Flags; + public ReadOnlySpan GetHelp() => Info.Help; + } + + public static readonly ShaderParam HDRBASETEXTURE = new($"${nameof(HDRBASETEXTURE)}", ShaderParamType.Texture, "", "base texture when running with HDR enabled"); + public static readonly ShaderParam HDRCOMPRESSEDTEXTURE = new($"${nameof(HDRCOMPRESSEDTEXTURE)}", ShaderParamType.Texture, "", "base texture (compressed) for hdr compression method A"); + public static readonly ShaderParam HDRCOMPRESSEDTEXTURE0 = new($"${nameof(HDRCOMPRESSEDTEXTURE0)}", ShaderParamType.Texture, "", "compressed base texture0 for hdr compression method B"); + public static readonly ShaderParam HDRCOMPRESSEDTEXTURE1 = new($"${nameof(HDRCOMPRESSEDTEXTURE1)}", ShaderParamType.Texture, "", "compressed base texture1 for hdr compression method B"); + public static readonly ShaderParam HDRCOMPRESSEDTEXTURE2 = new($"${nameof(HDRCOMPRESSEDTEXTURE2)}", ShaderParamType.Texture, "", "compressed base texture2 for hdr compression method B"); + + static readonly ConVar mat_use_compressed_hdr_textures = new("mat_use_compressed_hdr_textures", "1"); + + public override string? GetFallbackShader(IMaterialVar[] vars) { + if (HardwareConfig.GetHDRType() == HDRType.None) + return "Sky_DX9"; + return null; + } + public override int GetFlags() => Flags; + public override int GetNumParams() => base.GetNumParams() + ShaderParams.Count; + public override ReadOnlySpan GetParamName(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamName(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetName(); + } + public override ReadOnlySpan GetParamHelp(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamHelp(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetHelp(); + } + public override ShaderParamType GetParamType(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamType(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetType(); + } + public override ReadOnlySpan GetParamDefault(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamDefault(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetDefaultValue(); + } + + protected override void OnInitShaderParams(IMaterialVar[] vars, ReadOnlySpan materialName) { + SetFlags(vars, MaterialVarFlags.NoFog); + SetFlags(vars, MaterialVarFlags.IgnoreZ); + } + + protected override void OnInitShaderInstance(IMaterialVar[] vars, ReadOnlySpan materialName) { + int samplerZeroFlags = 0; + if (vars[HDRCOMPRESSEDTEXTURE].IsDefined() && mat_use_compressed_hdr_textures.GetBool()) { + samplerZeroFlags = 0; + } + else { + if (vars[HDRCOMPRESSEDTEXTURE0].IsDefined()) { + samplerZeroFlags = 0; + } + else { + samplerZeroFlags = (int)TextureFlags.SRGB; + + if (vars[HDRBASETEXTURE].IsDefined() && vars[HDRBASETEXTURE].IsTexture()) { + ITexture txtr = vars[HDRBASETEXTURE].GetTextureValue()!; + ImageFormat fmt = txtr.GetImageFormat(); + if ((fmt == ImageFormat.RGBA16161616F) || (fmt == ImageFormat.RGBA16161616)) + samplerZeroFlags = 0; + } + } + } + + int sampler0 = HDRCOMPRESSEDTEXTURE; + if (vars[HDRCOMPRESSEDTEXTURE].IsDefined() && mat_use_compressed_hdr_textures.GetBool()) { + sampler0 = HDRCOMPRESSEDTEXTURE; + } + else { + if (vars[HDRCOMPRESSEDTEXTURE0].IsDefined()) + sampler0 = HDRCOMPRESSEDTEXTURE0; + else + sampler0 = HDRBASETEXTURE; + } + + if (vars[HDRCOMPRESSEDTEXTURE].IsDefined() && mat_use_compressed_hdr_textures.GetBool()) { + LoadTexture(HDRCOMPRESSEDTEXTURE, HDRCOMPRESSEDTEXTURE == sampler0 ? samplerZeroFlags : 0); + } + else { + if (vars[HDRCOMPRESSEDTEXTURE0].IsDefined()) { + LoadTexture(HDRCOMPRESSEDTEXTURE0, HDRCOMPRESSEDTEXTURE0 == sampler0 ? samplerZeroFlags : 0); + if (vars[HDRCOMPRESSEDTEXTURE1].IsDefined()) + LoadTexture(HDRCOMPRESSEDTEXTURE1, HDRCOMPRESSEDTEXTURE1 == sampler0 ? samplerZeroFlags : 0); + if (vars[HDRCOMPRESSEDTEXTURE2].IsDefined()) + LoadTexture(HDRCOMPRESSEDTEXTURE2, HDRCOMPRESSEDTEXTURE2 == sampler0 ? samplerZeroFlags : 0); + } + else { + if (vars[HDRBASETEXTURE].IsDefined()) + LoadTexture(HDRBASETEXTURE, HDRBASETEXTURE == sampler0 ? samplerZeroFlags : 0); + } + } + } + + protected override void OnDrawElements(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, VertexCompressionType vertexCompression) { + if (IsSnapshotting()) { + SetInitialShadowState(); + + ShaderShadow.EnableTexture(Sampler.Sampler0, true); + ShaderShadow.VertexShaderVertexFormat(VertexFormat.Position, 1, null, 0); + + StaticShaderIndex vshIndex = new(ShaderShadow, ShaderType.Vertex, "sky"); + ShaderShadow.SetVertexShader("sky", vshIndex.GetIndex()); + + if (vars[HDRCOMPRESSEDTEXTURE].IsDefined() && mat_use_compressed_hdr_textures.GetBool()) { + ShaderShadow.EnableSRGBRead(Sampler.Sampler0, false); + StaticShaderIndex pshIndex = new(ShaderShadow, ShaderType.Pixel, "sky_hdr_compressed_rgbs"); + ShaderShadow.SetPixelShader("sky_hdr_compressed_rgbs", pshIndex.GetIndex()); + } + else { + if (vars[HDRCOMPRESSEDTEXTURE0].IsDefined()) { + ShaderShadow.EnableTexture(Sampler.Sampler1, true); + ShaderShadow.EnableTexture(Sampler.Sampler2, true); + + ShaderShadow.EnableSRGBRead(Sampler.Sampler0, false); + ShaderShadow.EnableSRGBRead(Sampler.Sampler1, false); + ShaderShadow.EnableSRGBRead(Sampler.Sampler2, false); + StaticShaderIndex pshIndex = new(ShaderShadow, ShaderType.Pixel, "sky_hdr_compressed"); + ShaderShadow.SetPixelShader("sky_hdr_compressed", pshIndex.GetIndex()); + } + else { + ITexture txtr = vars[HDRBASETEXTURE].GetTextureValue()!; + ImageFormat fmt = txtr.GetImageFormat(); + if ((fmt == ImageFormat.RGBA16161616F) || (fmt == ImageFormat.RGBA16161616)) + ShaderShadow.EnableSRGBRead(Sampler.Sampler0, false); + else + ShaderShadow.EnableSRGBRead(Sampler.Sampler0, true); + + StaticShaderIndex pshIndex = new(ShaderShadow, ShaderType.Pixel, "sky"); + ShaderShadow.SetPixelShader("sky", pshIndex.GetIndex()); + } + } + ShaderShadow.EnableSRGBWrite(true); + + ShaderShadow.EnableAlphaWrites(true); + } + else { + DynamicShaderIndex vshIndex = new(shaderAPI, ShaderType.Vertex); + shaderAPI.SetVertexShaderIndex(vshIndex.GetIndex()); + + SetVertexShaderTextureTransform(VertexShaderConst.ShaderSpecificConst1, (int)ShaderMaterialVars.BaseTextureTransform); + + Span c0 = [1, 1, 1, 1]; + if (vars[(int)ShaderMaterialVars.Color].IsDefined()) + vars[(int)ShaderMaterialVars.Color].GetVecValue(c0[..3]); + if (vars[HDRCOMPRESSEDTEXTURE].IsDefined() && mat_use_compressed_hdr_textures.GetBool()) { + ITexture txtr = vars[HDRCOMPRESSEDTEXTURE].GetTextureValue()!; + float w = txtr.GetActualWidth(); + float h = txtr.GetActualHeight(); + float FUDGE = 0.01f / Math.Max(w, h); + Span c1 = [0.5f / w - FUDGE, 0.5f / h - FUDGE, w, h]; + shaderAPI.SetVertexShaderConstant(VertexShaderConst.ShaderSpecificConst0, c1); + + BindTexture(Sampler.Sampler0, HDRCOMPRESSEDTEXTURE, (int)ShaderMaterialVars.Frame); + c0[0] *= 8.0f; + c0[1] *= 8.0f; + c0[2] *= 8.0f; + DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); + pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", shaderAPI.ShouldWriteDepthToDestAlpha()); + shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); + } + else { + Span c1 = [0, 0, 0, 0]; + shaderAPI.SetVertexShaderConstant(VertexShaderConst.ShaderSpecificConst0, c1); + + if (vars[HDRCOMPRESSEDTEXTURE0].IsDefined()) { + BindTexture(Sampler.Sampler0, HDRCOMPRESSEDTEXTURE0, (int)ShaderMaterialVars.Frame); + BindTexture(Sampler.Sampler1, HDRCOMPRESSEDTEXTURE1, (int)ShaderMaterialVars.Frame); + BindTexture(Sampler.Sampler2, HDRCOMPRESSEDTEXTURE2, (int)ShaderMaterialVars.Frame); + DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); + pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", shaderAPI.ShouldWriteDepthToDestAlpha()); + shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); + } + else { + BindTexture(Sampler.Sampler0, HDRBASETEXTURE, (int)ShaderMaterialVars.Frame); + ITexture txtr = vars[HDRBASETEXTURE].GetTextureValue()!; + ImageFormat fmt = txtr.GetImageFormat(); + if ((fmt == ImageFormat.RGBA16161616) || + ((fmt == ImageFormat.RGBA16161616F) && + (HardwareConfig.GetHDRType() == HDRType.Integer))) { + c0[0] *= 16.0f; + c0[1] *= 16.0f; + c0[2] *= 16.0f; + } + DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); + pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", shaderAPI.ShouldWriteDepthToDestAlpha()); + shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); + } + } + shaderAPI.SetPixelShaderConstant(0, c0, 1); + } + Draw(); + } +} From ae2ac7e93037448e99b30d9da12c9f06959b6c51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:47:18 +0300 Subject: [PATCH 10/57] Port ModelInfo.IsModelVertexLit --- Source.Engine/ModelInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source.Engine/ModelInfo.cs b/Source.Engine/ModelInfo.cs index 10154f4eb..39ea85545 100644 --- a/Source.Engine/ModelInfo.cs +++ b/Source.Engine/ModelInfo.cs @@ -281,7 +281,7 @@ public void GetModelMaterials(Model? model, Span material) { } public bool IsModelVertexLit(Model? model) { - throw new NotImplementedException(); + return model != null && (model.Flags & ModelFlag.VertexLit) != 0; } public ReadOnlySpan GetModelKeyValueText(Model? model) { From fbab607231a7376341d211ba1a2416c39b18ff91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:05:33 +0300 Subject: [PATCH 11/57] Port occlusion queries --- Source.Common/ShaderAPI/IShaderAPI.cs | 5 + Source.MaterialSystem/MatRenderContext.cs | 25 ++-- Source.MaterialSystem/MaterialSystem.cs | 4 + Source.MaterialSystem/OcclusionQueryMgr.cs | 149 +++++++++++++++++++++ Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 33 +++-- 5 files changed, 192 insertions(+), 24 deletions(-) create mode 100644 Source.MaterialSystem/OcclusionQueryMgr.cs diff --git a/Source.Common/ShaderAPI/IShaderAPI.cs b/Source.Common/ShaderAPI/IShaderAPI.cs index bee438604..48e5362ab 100644 --- a/Source.Common/ShaderAPI/IShaderAPI.cs +++ b/Source.Common/ShaderAPI/IShaderAPI.cs @@ -301,6 +301,11 @@ void SetRenderTarget(ShaderAPITextureHandle_t colorTextureHandle = (ShaderAPITex // Occlusion query support // + public const ShaderAPIOcclusionQuery_t INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE = 0; + public const int OCCLUSION_QUERY_RESULT_PENDING = -1; + public const int OCCLUSION_QUERY_RESULT_ERROR = -2; + public static bool OCCLUSION_QUERY_FINISHED(int queryResult) => queryResult != OCCLUSION_QUERY_RESULT_PENDING; + // Allocate and delete query objects. ShaderAPIOcclusionQuery_t CreateOcclusionQueryObject(); void DestroyOcclusionQueryObject(ShaderAPIOcclusionQuery_t query); diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index e67f71a1c..924ef8cfb 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -354,6 +354,7 @@ public void SetFrameTime(double frameTime) { } public void SwapBuffers() { + materials.OcclusionQueryMgr.AdvanceFrame(); materials.ShaderDevice.Present(); } @@ -802,9 +803,7 @@ public void BeginMorphAccumulation() { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void BeginOcclusionQueryDrawing(OcclusionQueryObjectHandle_t handle) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void BeginOcclusionQueryDrawing(OcclusionQueryObjectHandle_t handle) => materials.OcclusionQueryMgr.BeginOcclusionQueryDrawing(handle); public void BeginPIXEvent(Color color, ReadOnlySpan name) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); @@ -847,7 +846,9 @@ public IMorph CreateMorph(MorphFormatFlags format, ReadOnlySpan debugName) } public OcclusionQueryObjectHandle_t CreateOcclusionQueryObject() { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); + OcclusionQueryObjectHandle_t h = materials.OcclusionQueryMgr.CreateOcclusionQueryObject(); + materials.OcclusionQueryMgr.OnCreateOcclusionQueryObject(h); + return h; } public void CullMode(MaterialCullMode cullMode) { @@ -858,9 +859,7 @@ public void DestroyMorph(IMorph morph) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void DestroyOcclusionQueryObject(OcclusionQueryObjectHandle_t handle) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void DestroyOcclusionQueryObject(OcclusionQueryObjectHandle_t handle) => materials.OcclusionQueryMgr.DestroyOcclusionQueryObject(handle); public void DrawScreenSpaceQuad(IMaterial? material) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); @@ -886,9 +885,7 @@ public void EndMorphAccumulation() { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void EndOcclusionQueryDrawing(OcclusionQueryObjectHandle_t handle) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void EndOcclusionQueryDrawing(OcclusionQueryObjectHandle_t handle) => materials.OcclusionQueryMgr.EndOcclusionQueryDrawing(handle); public void EndPIXEvent() { throw new NotImplementedException("Incomplete port of IMatRenderContext"); @@ -1010,9 +1007,7 @@ public void MultMatrixLocal(in Matrix3x4 matrix) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public int OcclusionQuery_GetNumPixelsRendered(OcclusionQueryObjectHandle_t handle) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public int OcclusionQuery_GetNumPixelsRendered(OcclusionQueryObjectHandle_t handle) => materials.OcclusionQueryMgr.OcclusionQuery_GetNumPixelsRendered(handle, true); public void OverrideAlphaWriteEnable(bool enable, bool alphaWriteEnable) => shaderAPI.OverrideAlphaWriteEnable(enable, alphaWriteEnable); @@ -1096,9 +1091,7 @@ public void ResetLookupWeights() { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void ResetOcclusionQueryObject(OcclusionQueryObjectHandle_t handle) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void ResetOcclusionQueryObject(OcclusionQueryObjectHandle_t handle) => materials.OcclusionQueryMgr.ResetOcclusionQueryObject(handle); public void ResetToneMappingScale(float monoscale) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); diff --git a/Source.MaterialSystem/MaterialSystem.cs b/Source.MaterialSystem/MaterialSystem.cs index 7c2808e5b..a55cbb0ea 100644 --- a/Source.MaterialSystem/MaterialSystem.cs +++ b/Source.MaterialSystem/MaterialSystem.cs @@ -135,6 +135,7 @@ public MaterialSystem(IServiceProvider services) { ShaderSystem.Init(); CreateDebugMaterials(); MatLightmaps = new(this); + OcclusionQueryMgr = new(this); } ILauncherManager launcherMgr; @@ -952,6 +953,7 @@ public void CreateDebugMaterials() { void ReleaseShaderObjects() { // todo + OcclusionQueryMgr.FreeOcclusionQueryObjects(); ReleaseStandardTextures(); for (int i = 0; i < ReleaseFunc.Count; i++) ReleaseFunc[i](); @@ -969,6 +971,7 @@ public void RestoreShaderObjects(IServiceProvider? services, int changeFlags) { TextureSystem.RestoreRenderTargets(); AllocateStandardTextures(); + OcclusionQueryMgr.AllocOcclusionQueryObjects(); Restore?.Invoke(); for (int i = 0; i < RestoreFunc.Count; i++) RestoreFunc[i]((RestoreChangeFlags)changeFlags); @@ -1337,6 +1340,7 @@ public void RemoveRestoreFunc(MaterialBufferRestoreFunc func) { public IMaterialInternal errorMaterial; public readonly MatLightmaps MatLightmaps; + public readonly OcclusionQueryMgr OcclusionQueryMgr; public bool AddTextureCompositorTemplate(ReadOnlySpan name, KeyValues tmplDesc, int texCompositeTemplateFlags = 0) { throw new NotImplementedException("Incomplete port of IMaterialSystem"); diff --git a/Source.MaterialSystem/OcclusionQueryMgr.cs b/Source.MaterialSystem/OcclusionQueryMgr.cs new file mode 100644 index 000000000..11d23589e --- /dev/null +++ b/Source.MaterialSystem/OcclusionQueryMgr.cs @@ -0,0 +1,149 @@ +using Source.Common.ShaderAPI; + +namespace Source.MaterialSystem; + +public class OcclusionQueryMgr(MaterialSystem materials) +{ + public const int COUNT_OCCLUSION_QUERY_STACK = 4; + + class OcclusionQueryObject + { + public readonly ShaderAPIOcclusionQuery_t[] QueryHandle = new ShaderAPIOcclusionQuery_t[COUNT_OCCLUSION_QUERY_STACK]; + public int LastResult = -1; + public int FrameIssued = -1; + public int CurrentIssue = 0; + public readonly bool[] HasBeenIssued = new bool[COUNT_OCCLUSION_QUERY_STACK]; + } + + readonly Dictionary OcclusionQueryObjects = []; + OcclusionQueryObjectHandle_t NextHandle = 1; + int FrameCount = 0; + + IShaderAPI ShaderAPI => materials.ShaderAPI; + + public OcclusionQueryObjectHandle_t CreateOcclusionQueryObject() { + OcclusionQueryObjectHandle_t h = NextHandle++; + OcclusionQueryObjects.Add(h, new()); + return h; + } + + public void OnCreateOcclusionQueryObject(OcclusionQueryObjectHandle_t h) { + OcclusionQueryObject obj = OcclusionQueryObjects[h]; + for (int i = 0; i < COUNT_OCCLUSION_QUERY_STACK; i++) + obj.QueryHandle[i] = ShaderAPI.CreateOcclusionQueryObject(); + } + + public void DestroyOcclusionQueryObject(OcclusionQueryObjectHandle_t occlusionQuery) { + Assert(OcclusionQueryObjects.ContainsKey(occlusionQuery)); + if (OcclusionQueryObjects.TryGetValue(occlusionQuery, out OcclusionQueryObject? obj)) { + for (int i = 0; i < COUNT_OCCLUSION_QUERY_STACK; i++) { + if (obj.QueryHandle[i] != IShaderAPI.INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE) + ShaderAPI.DestroyOcclusionQueryObject(obj.QueryHandle[i]); + } + OcclusionQueryObjects.Remove(occlusionQuery); + } + } + + public void AdvanceFrame() { + ++FrameCount; + } + + public void AllocOcclusionQueryObjects() { + foreach (OcclusionQueryObject obj in OcclusionQueryObjects.Values) { + for (int i = 0; i < COUNT_OCCLUSION_QUERY_STACK; i++) { + obj.QueryHandle[i] = ShaderAPI.CreateOcclusionQueryObject(); + obj.HasBeenIssued[i] = false; + } + } + } + + public void FreeOcclusionQueryObjects() { + foreach (OcclusionQueryObject obj in OcclusionQueryObjects.Values) { + for (int i = 0; i < COUNT_OCCLUSION_QUERY_STACK; i++) { + if (obj.QueryHandle[i] != IShaderAPI.INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE) { + ShaderAPI.DestroyOcclusionQueryObject(obj.QueryHandle[i]); + obj.QueryHandle[i] = IShaderAPI.INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE; + obj.HasBeenIssued[i] = false; + } + } + } + } + + public void ResetOcclusionQueryObject(OcclusionQueryObjectHandle_t occlusionQuery) { + Assert(OcclusionQueryObjects.ContainsKey(occlusionQuery)); + if (OcclusionQueryObjects.TryGetValue(occlusionQuery, out OcclusionQueryObject? obj)) { + for (int i = 0; i < COUNT_OCCLUSION_QUERY_STACK; i++) + obj.HasBeenIssued[i] = false; + + obj.LastResult = -1; + obj.FrameIssued = -1; + } + } + + public void BeginOcclusionQueryDrawing(OcclusionQueryObjectHandle_t occlusionQuery) { + Assert(OcclusionQueryObjects.ContainsKey(occlusionQuery)); + if (OcclusionQueryObjects.TryGetValue(occlusionQuery, out OcclusionQueryObject? obj)) { + int current = obj.CurrentIssue; + ShaderAPIOcclusionQuery_t query = obj.QueryHandle[current]; + if (query != IShaderAPI.INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE) { + if (obj.HasBeenIssued[current]) { + int pixels = ShaderAPI.OcclusionQuery_GetNumPixelsRendered(query, false); + if ((pixels == IShaderAPI.OCCLUSION_QUERY_RESULT_PENDING) && (obj.FrameIssued == FrameCount)) { + if (s_WarnCount++ < 5) + DevWarning("blocking issue in occlusion queries! Grab brian!\n"); + } + while (!IShaderAPI.OCCLUSION_QUERY_FINISHED(pixels)) + pixels = ShaderAPI.OcclusionQuery_GetNumPixelsRendered(query, true); + if (pixels >= 0) + obj.LastResult = pixels; + obj.HasBeenIssued[current] = false; + } + ShaderAPI.BeginOcclusionQueryDrawing(query); + } + } + } + static int s_WarnCount = 0; + + public void EndOcclusionQueryDrawing(OcclusionQueryObjectHandle_t occlusionQuery) { + Assert(OcclusionQueryObjects.ContainsKey(occlusionQuery)); + if (OcclusionQueryObjects.TryGetValue(occlusionQuery, out OcclusionQueryObject? obj)) { + int current = obj.CurrentIssue; + ShaderAPIOcclusionQuery_t query = obj.QueryHandle[current]; + if (query != IShaderAPI.INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE) { + ShaderAPI.EndOcclusionQueryDrawing(query); + + obj.HasBeenIssued[current] = true; + obj.FrameIssued = FrameCount; + + current = (current + 1) % COUNT_OCCLUSION_QUERY_STACK; + obj.CurrentIssue = current; + } + } + } + + public void OcclusionQuery_IssueNumPixelsRenderedQuery(OcclusionQueryObjectHandle_t occlusionQuery) { + Assert(OcclusionQueryObjects.ContainsKey(occlusionQuery)); + if (OcclusionQueryObjects.TryGetValue(occlusionQuery, out OcclusionQueryObject? obj)) { + for (int i = 0; i < COUNT_OCCLUSION_QUERY_STACK; i++) { + int index = (obj.CurrentIssue + i) % COUNT_OCCLUSION_QUERY_STACK; + ShaderAPIOcclusionQuery_t query = obj.QueryHandle[index]; + if (query != IShaderAPI.INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE && obj.HasBeenIssued[index]) { + int pixels = ShaderAPI.OcclusionQuery_GetNumPixelsRendered(query); + if (pixels == IShaderAPI.OCCLUSION_QUERY_RESULT_ERROR) + obj.HasBeenIssued[index] = false; + else if (pixels >= 0) { + obj.LastResult = pixels; + obj.HasBeenIssued[index] = false; + } + } + } + } + } + + public int OcclusionQuery_GetNumPixelsRendered(OcclusionQueryObjectHandle_t h, bool doQuery) { + if (doQuery) + OcclusionQuery_IssueNumPixelsRenderedQuery(h); + + return OcclusionQueryObjects[h].LastResult; + } +} diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index 86ee9f73a..26f0af03b 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -3035,7 +3035,8 @@ public void AcquireThreadOwnership() { } public void BeginOcclusionQueryDrawing(ShaderAPIOcclusionQuery_t query) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + FlushBufferedPrimitives(); + glBeginQuery(GL_SAMPLES_PASSED, (uint)query); } public void BeginPIXEvent(Color color, ReadOnlySpan name) { @@ -3082,8 +3083,10 @@ public void CopyTextureToRenderTargetEx(int renderTargetID, ShaderAPITextureHand throw new NotImplementedException("Incomplete port of IShaderAPI"); } - public ShaderAPIOcclusionQuery_t CreateOcclusionQueryObject() { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + public unsafe ShaderAPIOcclusionQuery_t CreateOcclusionQueryObject() { + uint query; + glCreateQueries(GL_SAMPLES_PASSED, 1, &query); + return (ShaderAPIOcclusionQuery_t)query; } public void CullMode(MaterialCullMode cullMode) { @@ -3094,8 +3097,9 @@ public void DXSupportLevelChanged() { throw new NotImplementedException("Incomplete port of IShaderAPI"); } - public void DestroyOcclusionQueryObject(ShaderAPIOcclusionQuery_t query) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + public unsafe void DestroyOcclusionQueryObject(ShaderAPIOcclusionQuery_t query) { + uint id = (uint)query; + glDeleteQueries(1, &id); } public void DestroyVertexBuffers(bool exitingLevel = false) { @@ -3131,7 +3135,8 @@ public void EnableUserClipTransformOverride(bool enable) { } public void EndOcclusionQueryDrawing(ShaderAPIOcclusionQuery_t query) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + FlushBufferedPrimitives(); + glEndQuery(GL_SAMPLES_PASSED); } public void EndPIXEvent() { @@ -3202,8 +3207,20 @@ public void LoadSelectionName(int name) { throw new NotImplementedException("Incomplete port of IShaderAPI"); } - public int OcclusionQuery_GetNumPixelsRendered(ShaderAPIOcclusionQuery_t query, bool flush = false) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + public unsafe int OcclusionQuery_GetNumPixelsRendered(ShaderAPIOcclusionQuery_t query, bool flush = false) { + int available; + glGetQueryObjectiv((uint)query, GL_QUERY_RESULT_AVAILABLE, &available); + if (available == 0) { + if (flush) + glFlush(); + return IShaderAPI.OCCLUSION_QUERY_RESULT_PENDING; + } + + uint pixels; + glGetQueryObjectuiv((uint)query, GL_QUERY_RESULT, &pixels); + if ((pixels & 0x80000000) != 0) + pixels = 0; + return (int)pixels; } bool OverrideAlphaWrite; From 46d3b518f34502fc52f8e92a71f49654482d3551 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:17:46 +0300 Subject: [PATCH 12/57] Port tone mapping scale blending --- Source.MaterialSystem/MatRenderContext.cs | 59 +++++++++++++++++++++-- 1 file changed, 54 insertions(+), 5 deletions(-) diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index 924ef8cfb..544701d8d 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -1,5 +1,6 @@ using Source.Common; using Source.Common.Bitmap; +using Source.Common.Commands; using Source.Common.MaterialSystem; using Source.Common.Mathematics; using Source.Common.ShaderAPI; @@ -336,9 +337,49 @@ public bool InFlashlightMode() { return FlashlightEnable; } + Vector3 LastSetToneMapScale = new(1, 1, 1); float CurToneMapScale = 1.0f; + float GoalToneMapScale = 1.0f; + TimeUnit_t FrameTime; - public void TurnOnToneMapping() => SetToneMappingScaleLinear(new(CurToneMapScale, CurToneMapScale, CurToneMapScale)); + static readonly ConVar mat_accelerate_adjust_exposure_down = new("mat_accelerate_adjust_exposure_down", "3.0", FCvar.Cheat); + static readonly ConVar mat_hdr_manual_tonemap_rate = new("mat_hdr_manual_tonemap_rate", "1.0"); + static readonly ConVar mat_tonemap_algorithm = new("mat_tonemap_algorithm", "1", FCvar.Cheat, "0 = Original Algorithm 1 = New Algorithm"); + + public void TurnOnToneMapping() { + if ((materials.HardwareConfig.GetHDRType() != HDRType.None) && (FrameTime > 0.0)) { + TimeUnit_t elapsedTime = FrameTime; + float goalScale = GoalToneMapScale; + float rate = mat_hdr_manual_tonemap_rate.GetFloat(); + + if (mat_tonemap_algorithm.GetInt() == 1) + rate *= 2.0f; + + if (rate == 0.0f) + CurToneMapScale = goalScale; + else { + if (goalScale < CurToneMapScale) { + float accExposureAdjust = mat_accelerate_adjust_exposure_down.GetFloat(); + rate = Math.Min(accExposureAdjust * rate, MathLib.Lerp(rate, accExposureAdjust * rate, 0.0f, 1.5f, CurToneMapScale - goalScale)); + } + + float rateTimesTime = (float)(rate * elapsedTime); + if (mat_tonemap_algorithm.GetInt() == 1) + rateTimesTime = Math.Min(rateTimesTime, (1.0f / 16.0f) * 0.25f); + + float alpha = Math.Max(0.0f, Math.Min(1.0f, rateTimesTime)); + CurToneMapScale = (goalScale * alpha) + (CurToneMapScale * (1.0f - alpha)); + + if (!float.IsFinite(CurToneMapScale)) { + Assert(false); + CurToneMapScale = goalScale; + } + } + + SetToneMappingScaleLinear(new(CurToneMapScale, CurToneMapScale, CurToneMapScale)); + LastSetToneMapScale = new(CurToneMapScale, CurToneMapScale, CurToneMapScale); + } + } public void SetToneMappingScaleLinear(in Vector3 scale) => shaderAPI.SetToneMappingScaleLinear(in scale); @@ -350,7 +391,7 @@ public void MarkRenderDataUnused(bool v) { } public void SetFrameTime(double frameTime) { - + FrameTime = frameTime; } public void SwapBuffers() { @@ -960,7 +1001,10 @@ public int GetNumActiveDeformations() { } public Vector3 GetToneMappingScaleLinear() { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); + if (materials.HardwareConfig.GetHDRType() == HDRType.None) + return new(1, 1, 1); + else + return LastSetToneMapScale; } public void GetWorldSpaceCameraVectors(out Vector3 forward, out Vector3 right, out Vector3 up) { @@ -1094,7 +1138,10 @@ public void ResetLookupWeights() { public void ResetOcclusionQueryObject(OcclusionQueryObjectHandle_t handle) => materials.OcclusionQueryMgr.ResetOcclusionQueryObject(handle); public void ResetToneMappingScale(float monoscale) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); + CurToneMapScale = monoscale; + SetToneMappingScaleLinear(new(CurToneMapScale, CurToneMapScale, CurToneMapScale)); + LastSetToneMapScale = new(CurToneMapScale, CurToneMapScale, CurToneMapScale); + GoalToneMapScale = 1; } public void Rotate(float angle, float x, float y, float z) { @@ -1124,7 +1171,9 @@ public void SetFullScreenDepthTextureValidityFlag(bool isValid) { } public void SetGoalToneMappingScale(float monoscale) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); + Assert(float.IsFinite(monoscale)); + if (float.IsFinite(monoscale)) + GoalToneMapScale = monoscale; } public void SetHeightClipZ(float z) { From 1fe9cacf6bf7acdbd88689901f8a05092ce5cb8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:24:09 +0300 Subject: [PATCH 13/57] Port MatRenderContext.PushRenderTargetAndViewport --- Source.MaterialSystem/MatRenderContext.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index 544701d8d..50e54d4ed 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -1106,7 +1106,9 @@ public void PushDeformation(ref readonly DeformationBase deformation) { } public void PushRenderTargetAndViewport() { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); + RenderTargetStackElement top = RenderTargetStack.Top(); + RenderTargetStack.Push(top); + CommitRenderTargetAndViewport(); } public void PushSelectionName(int name) { From c94aa12ed50462eba78ec46a26e911ed5a3bb9b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:39:52 +0300 Subject: [PATCH 14/57] Port bloom and luminance compare shaders --- Game.Assets/hl2/shaders/bloomadd_gl460.fs | 33 +++ Game.Assets/hl2/shaders/blurfilter_gl460.fs | 61 +++++ Game.Assets/hl2/shaders/blurfilter_gl460.vs | 38 +++ .../hl2/shaders/constant_color_gl460.fs | 36 +++ Game.Assets/hl2/shaders/downsample_gl460.vs | 33 +++ .../hl2/shaders/downsample_nohdr_gl460.fs | 59 +++++ .../hl2/shaders/luminance_compare_gl460.fs | 47 ++++ Source.StdShader.Gl46/BlurFilterX.cs | 76 ++++++ Source.StdShader.Gl46/BlurFilterY.cs | 140 +++++++++++ Source.StdShader.Gl46/Downsample_nohdr.cs | 139 +++++++++++ Source.StdShader.Gl46/screenspace_general.cs | 11 + .../screenspace_general_dx9.cs | 217 ++++++++++++++++++ 12 files changed, 890 insertions(+) create mode 100644 Game.Assets/hl2/shaders/bloomadd_gl460.fs create mode 100644 Game.Assets/hl2/shaders/blurfilter_gl460.fs create mode 100644 Game.Assets/hl2/shaders/blurfilter_gl460.vs create mode 100644 Game.Assets/hl2/shaders/constant_color_gl460.fs create mode 100644 Game.Assets/hl2/shaders/downsample_gl460.vs create mode 100644 Game.Assets/hl2/shaders/downsample_nohdr_gl460.fs create mode 100644 Game.Assets/hl2/shaders/luminance_compare_gl460.fs create mode 100644 Source.StdShader.Gl46/BlurFilterX.cs create mode 100644 Source.StdShader.Gl46/BlurFilterY.cs create mode 100644 Source.StdShader.Gl46/Downsample_nohdr.cs create mode 100644 Source.StdShader.Gl46/screenspace_general.cs create mode 100644 Source.StdShader.Gl46/screenspace_general_dx9.cs diff --git a/Game.Assets/hl2/shaders/bloomadd_gl460.fs b/Game.Assets/hl2/shaders/bloomadd_gl460.fs new file mode 100644 index 000000000..f90ea2ef0 --- /dev/null +++ b/Game.Assets/hl2/shaders/bloomadd_gl460.fs @@ -0,0 +1,33 @@ +#version 460 + +in vec2 vs_BaseTexCoord; + +layout(std140, binding = 3) uniform source_pixel_sharedUBO { + bool isAlphaTesting; + int alphaTestFunc; + float alphaTestRef; +}; + +out vec4 fragColor; + +layout(binding = 0) uniform sampler2D TexSampler; + +void main() +{ + vec4 result = texture(TexSampler, vs_BaseTexCoord); + result.a = 1.0; + + if(isAlphaTesting){ + switch(alphaTestFunc){ + case 0: discard; break; + case 1: if(result.a >= alphaTestRef){ discard; } break; + case 2: if(result.a != alphaTestRef){ discard; } break; + case 3: if(result.a > alphaTestRef){ discard; } break; + case 4: if(result.a <= alphaTestRef){ discard; } break; + case 5: if(result.a == alphaTestRef){ discard; } break; + case 6: if(result.a < alphaTestRef){ discard; } break; + } + } + + fragColor = result; +} diff --git a/Game.Assets/hl2/shaders/blurfilter_gl460.fs b/Game.Assets/hl2/shaders/blurfilter_gl460.fs new file mode 100644 index 000000000..00b0d6fca --- /dev/null +++ b/Game.Assets/hl2/shaders/blurfilter_gl460.fs @@ -0,0 +1,61 @@ +#version 460 + +in vec2 vs_CoordTap0; +in vec2 vs_CoordTap1; +in vec2 vs_CoordTap2; +in vec2 vs_CoordTap3; +in vec2 vs_CoordTap1Neg; +in vec2 vs_CoordTap2Neg; +in vec2 vs_CoordTap3Neg; + +layout(std140, binding = 6) uniform source_ps_constants { + vec4 ps_const[256]; +}; + +out vec4 fragColor; + +layout(binding = 0) uniform sampler2D TexSampler; + +#define psTapOffs0 ps_const[0].xy +#define psTapOffs1 ps_const[1].xy +#define psTapOffs2 ps_const[2].xy +#define scale_factor ps_const[3].xyz + +void main() +{ + vec4 s0, s1, s2, s3, s4, s5, s6, color; + + s0 = texture(TexSampler, vs_CoordTap0); + s1 = texture(TexSampler, vs_CoordTap1); + s2 = texture(TexSampler, vs_CoordTap2); + s3 = texture(TexSampler, vs_CoordTap3); + s4 = texture(TexSampler, vs_CoordTap1Neg); + s5 = texture(TexSampler, vs_CoordTap2Neg); + s6 = texture(TexSampler, vs_CoordTap3Neg); + + color = s0 * 0.2013; + color += (s1 + s4) * 0.2185; + color += (s2 + s5) * 0.0821; + color += (s3 + s6) * 0.0461; + + vec2 coordTap4 = vs_CoordTap0 + psTapOffs0; + vec2 coordTap5 = vs_CoordTap0 + psTapOffs1; + vec2 coordTap6 = vs_CoordTap0 + psTapOffs2; + vec2 coordTap4Neg = vs_CoordTap0 - psTapOffs0; + vec2 coordTap5Neg = vs_CoordTap0 - psTapOffs1; + vec2 coordTap6Neg = vs_CoordTap0 - psTapOffs2; + + s1 = texture(TexSampler, coordTap4); + s2 = texture(TexSampler, coordTap5); + s3 = texture(TexSampler, coordTap6); + s4 = texture(TexSampler, coordTap4Neg); + s5 = texture(TexSampler, coordTap5Neg); + s6 = texture(TexSampler, coordTap6Neg); + + color += (s1 + s4) * 0.0262; + color += (s2 + s5) * 0.0162; + color += (s3 + s6) * 0.0102; + color.xyz *= scale_factor.xyz; + + fragColor = color; +} diff --git a/Game.Assets/hl2/shaders/blurfilter_gl460.vs b/Game.Assets/hl2/shaders/blurfilter_gl460.vs new file mode 100644 index 000000000..8c915a90c --- /dev/null +++ b/Game.Assets/hl2/shaders/blurfilter_gl460.vs @@ -0,0 +1,38 @@ +#version 460 + +layout(location = 0) in vec3 v_Position; +layout(location = 10) in vec2 v_TexCoord; + +layout(std140, binding = 5) uniform source_vs_constants { + vec4 vs_const[256]; +}; + +#define vsTapOffs0 vs_const[48].xy +#define vsTapOffs1 vs_const[49].xy +#define vsTapOffs2 vs_const[50].xy + +out vec2 vs_CoordTap0; +out vec2 vs_CoordTap1; +out vec2 vs_CoordTap2; +out vec2 vs_CoordTap3; +out vec2 vs_CoordTap1Neg; +out vec2 vs_CoordTap2Neg; +out vec2 vs_CoordTap3Neg; + +vec2 FlipV(vec2 uv) +{ + return vec2(uv.x, 1.0 - uv.y); +} + +void main() +{ + gl_Position = vec4(v_Position, 1.0); + + vs_CoordTap0 = FlipV(v_TexCoord); + vs_CoordTap1 = FlipV(v_TexCoord + vsTapOffs0); + vs_CoordTap2 = FlipV(v_TexCoord + vsTapOffs1); + vs_CoordTap3 = FlipV(v_TexCoord + vsTapOffs2); + vs_CoordTap1Neg = FlipV(v_TexCoord - vsTapOffs0); + vs_CoordTap2Neg = FlipV(v_TexCoord - vsTapOffs1); + vs_CoordTap3Neg = FlipV(v_TexCoord - vsTapOffs2); +} diff --git a/Game.Assets/hl2/shaders/constant_color_gl460.fs b/Game.Assets/hl2/shaders/constant_color_gl460.fs new file mode 100644 index 000000000..35a201505 --- /dev/null +++ b/Game.Assets/hl2/shaders/constant_color_gl460.fs @@ -0,0 +1,36 @@ +#version 460 + +in vec2 vs_BaseTexCoord; + +layout(std140, binding = 3) uniform source_pixel_sharedUBO { + bool isAlphaTesting; + int alphaTestFunc; + float alphaTestRef; +}; + +layout(std140, binding = 6) uniform source_ps_constants { + vec4 ps_const[256]; +}; + +out vec4 fragColor; + +#include "common_gl460.fs" + +void main() +{ + vec4 result = FinalOutput(vec4(0.0, 1.0, 0.0, 1.0), 0.0, PIXEL_FOG_TYPE_NONE, TONEMAP_SCALE_NONE); + + if(isAlphaTesting){ + switch(alphaTestFunc){ + case 0: discard; break; + case 1: if(result.a >= alphaTestRef){ discard; } break; + case 2: if(result.a != alphaTestRef){ discard; } break; + case 3: if(result.a > alphaTestRef){ discard; } break; + case 4: if(result.a <= alphaTestRef){ discard; } break; + case 5: if(result.a == alphaTestRef){ discard; } break; + case 6: if(result.a < alphaTestRef){ discard; } break; + } + } + + fragColor = result; +} diff --git a/Game.Assets/hl2/shaders/downsample_gl460.vs b/Game.Assets/hl2/shaders/downsample_gl460.vs new file mode 100644 index 000000000..b74445d1f --- /dev/null +++ b/Game.Assets/hl2/shaders/downsample_gl460.vs @@ -0,0 +1,33 @@ +#version 460 + +layout(location = 0) in vec3 v_Position; +layout(location = 10) in vec2 v_TexCoord; + +layout(std140, binding = 5) uniform source_vs_constants { + vec4 vs_const[256]; +}; + +#define vsTapOffs0 vs_const[48].xy +#define vsTapOffs1 vs_const[49].xy +#define vsTapOffs2 vs_const[50].xy +#define vsTapOffs3 vs_const[51].xy + +out vec2 vs_CoordTap0; +out vec2 vs_CoordTap1; +out vec2 vs_CoordTap2; +out vec2 vs_CoordTap3; + +vec2 FlipV(vec2 uv) +{ + return vec2(uv.x, 1.0 - uv.y); +} + +void main() +{ + gl_Position = vec4(v_Position, 1.0); + + vs_CoordTap0 = FlipV(v_TexCoord + vsTapOffs0); + vs_CoordTap1 = FlipV(v_TexCoord + vsTapOffs1); + vs_CoordTap2 = FlipV(v_TexCoord + vsTapOffs2); + vs_CoordTap3 = FlipV(v_TexCoord + vsTapOffs3); +} diff --git a/Game.Assets/hl2/shaders/downsample_nohdr_gl460.fs b/Game.Assets/hl2/shaders/downsample_nohdr_gl460.fs new file mode 100644 index 000000000..18e4d3bb3 --- /dev/null +++ b/Game.Assets/hl2/shaders/downsample_nohdr_gl460.fs @@ -0,0 +1,59 @@ +#version 460 +// STATIC: "CSTRIKE" "0..1" + +in vec2 vs_CoordTap0; +in vec2 vs_CoordTap1; +in vec2 vs_CoordTap2; +in vec2 vs_CoordTap3; + +layout(std140, binding = 6) uniform source_ps_constants { + vec4 ps_const[256]; +}; + +out vec4 fragColor; + +#include "common_gl460.fs" + +layout(binding = 0) uniform sampler2D TexSampler; + +#define params ps_const[0] + +#if CSTRIKE == 0 +vec4 Shape(vec2 uv) +{ + vec4 pixel = texture(TexSampler, uv); + + float lum = dot(pixel.xyz, params.xyz); + pixel.xyz = pow(pixel.xyz, vec3(params.w)) * lum; + + return pixel; +} + +void main() +{ + vec4 s0 = Shape(vs_CoordTap0); + vec4 s1 = Shape(vs_CoordTap1); + vec4 s2 = Shape(vs_CoordTap2); + vec4 s3 = Shape(vs_CoordTap3); + + vec4 avgColor = (s0 + s1 + s2 + s3) * 0.25; + fragColor = FinalOutput(avgColor, 0.0, PIXEL_FOG_TYPE_NONE, TONEMAP_SCALE_NONE); +} +#else +vec3 Shape(vec3 s) +{ + float lum = (0.3 * s.x) + (0.59 * s.y) + (0.11 * s.z); + return lum * s; +} + +void main() +{ + vec3 s0 = Shape(GammaToLinear(texture(TexSampler, vs_CoordTap0).rgb)); + vec3 s1 = Shape(GammaToLinear(texture(TexSampler, vs_CoordTap1).rgb)); + vec3 s2 = Shape(GammaToLinear(texture(TexSampler, vs_CoordTap2).rgb)); + vec3 s3 = Shape(GammaToLinear(texture(TexSampler, vs_CoordTap3).rgb)); + + vec3 avgColor = (s0 + s1 + s2 + s3) * 0.25; + fragColor = vec4(avgColor, 1.0); +} +#endif diff --git a/Game.Assets/hl2/shaders/luminance_compare_gl460.fs b/Game.Assets/hl2/shaders/luminance_compare_gl460.fs new file mode 100644 index 000000000..b41febbdc --- /dev/null +++ b/Game.Assets/hl2/shaders/luminance_compare_gl460.fs @@ -0,0 +1,47 @@ +#version 460 + +in vec2 vs_BaseTexCoord; + +layout(std140, binding = 3) uniform source_pixel_sharedUBO { + bool isAlphaTesting; + int alphaTestFunc; + float alphaTestRef; +}; + +layout(std140, binding = 6) uniform source_ps_constants { + vec4 ps_const[256]; +}; + +out vec4 fragColor; + +layout(binding = 0) uniform sampler2D TexSampler; + +#define g_vComparisonMinMaxScale ps_const[0] +#define g_flComparisonMin g_vComparisonMinMaxScale.x +#define g_flComparisonMax g_vComparisonMinMaxScale.y +#define g_flComparisonScale g_vComparisonMinMaxScale.z + +void main() +{ + vec3 color = texture(TexSampler, vs_BaseTexCoord).rgb * g_flComparisonScale; + + vec3 tmpv = vec3(0.2125, 0.7154, 0.0721); + float flLuminance = dot(color.rgb, tmpv.rgb); + + vec4 result = vec4(step(g_flComparisonMin, flLuminance) * step(flLuminance, g_flComparisonMax)); + + if(isAlphaTesting){ + switch(alphaTestFunc){ + case 0: discard; break; + case 1: if(result.a >= alphaTestRef){ discard; } break; + case 2: if(result.a != alphaTestRef){ discard; } break; + case 3: if(result.a > alphaTestRef){ discard; } break; + case 4: if(result.a <= alphaTestRef){ discard; } break; + case 5: if(result.a == alphaTestRef){ discard; } break; + case 6: if(result.a < alphaTestRef){ discard; } break; + } + } + + fragColor = result; + gl_FragDepth = 0.0; +} diff --git a/Source.StdShader.Gl46/BlurFilterX.cs b/Source.StdShader.Gl46/BlurFilterX.cs new file mode 100644 index 000000000..dca61cc78 --- /dev/null +++ b/Source.StdShader.Gl46/BlurFilterX.cs @@ -0,0 +1,76 @@ +using Source.Common.MaterialSystem; +using Source.Common.ShaderAPI; +using Source.Common.ShaderLib; + +namespace Source.StdShader.Gl46; + +public class BlurFilterX : BaseVSShader +{ + public static string HelpString = "Help for BlurFilterX"; + public static int Flags = (int)ShaderParamFlags.NotEditable; + + public override string? GetFallbackShader(IMaterialVar[] vars) => null; + public override int GetFlags() => Flags; + + protected override void OnInitShaderInstance(IMaterialVar[] vars, ReadOnlySpan materialName) { + if (vars[(int)ShaderMaterialVars.BaseTexture].IsDefined()) + LoadTexture((int)ShaderMaterialVars.BaseTexture); + } + + protected override void OnDrawElements(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, VertexCompressionType vertexCompression) { + if (IsSnapshotting()) { + ShaderShadow.EnableDepthWrites(false); + ShaderShadow.EnableAlphaWrites(true); + ShaderShadow.EnableTexture(Sampler.Sampler0, true); + ShaderShadow.VertexShaderVertexFormat(VertexFormat.Position, 1, null, 0); + + ShaderShadow.EnableSRGBRead(Sampler.Sampler0, false); + ShaderShadow.EnableSRGBWrite(false); + + ShaderShadow.SetVertexShader("blurfilter", 0); + + StaticShaderIndex pshIndex = new(ShaderShadow, ShaderType.Pixel, "blurfilter"); + ShaderShadow.SetPixelShader("blurfilter", pshIndex.GetIndex()); + + if (IsFlagSet(vars, MaterialVarFlags.Additive)) + EnableAlphaBlending(ShaderBlendFactor.One, ShaderBlendFactor.One); + } + else { + BindTexture(Sampler.Sampler0, (int)ShaderMaterialVars.BaseTexture, -1); + + Span v = [0, 0, 0, 0]; + + ITexture srcTexture = vars[(int)ShaderMaterialVars.BaseTexture].GetTextureValue()!; + int width = srcTexture.GetActualWidth(); + float dX = 1.0f / width; + + v[0] = 1.3366f * dX; + v[1] = 0.0f; + shaderAPI.SetVertexShaderConstant(VertexShaderConst.ShaderSpecificConst0, v, 1); + v[0] = 3.4295f * dX; + v[1] = 0.0f; + shaderAPI.SetVertexShaderConstant(VertexShaderConst.ShaderSpecificConst1, v, 1); + v[0] = 5.4264f * dX; + v[1] = 0.0f; + shaderAPI.SetVertexShaderConstant(VertexShaderConst.ShaderSpecificConst2, v, 1); + + v[0] = 7.4359f * dX; + v[1] = 0.0f; + shaderAPI.SetPixelShaderConstant(0, v, 1); + v[0] = 9.4436f * dX; + v[1] = 0.0f; + shaderAPI.SetPixelShaderConstant(1, v, 1); + v[0] = 11.4401f * dX; + v[1] = 0.0f; + shaderAPI.SetPixelShaderConstant(2, v, 1); + v[0] = v[1] = v[2] = v[3] = 1.0f; + shaderAPI.SetPixelShaderConstant(3, v, 1); + + shaderAPI.SetVertexShaderIndex(0); + + DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); + shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); + } + Draw(); + } +} diff --git a/Source.StdShader.Gl46/BlurFilterY.cs b/Source.StdShader.Gl46/BlurFilterY.cs new file mode 100644 index 000000000..f17a9cf98 --- /dev/null +++ b/Source.StdShader.Gl46/BlurFilterY.cs @@ -0,0 +1,140 @@ +using Source.Common.MaterialSystem; +using Source.Common.ShaderAPI; +using Source.Common.ShaderLib; + +namespace Source.StdShader.Gl46; + +public class BlurFilterY : BaseVSShader +{ + public static string HelpString = "Help for BlurFilterY"; + public static int Flags = (int)ShaderParamFlags.NotEditable; + public static List ShaderParams = []; + + public class ShaderParam + { + public readonly ShaderParamInfo Info; + public readonly int Index; + public ShaderParam(string name, ShaderParamType type, ReadOnlySpan defaultParam, ReadOnlySpan help, int flags = 0) { + Info.Name = name; + Info.Type = type; + Info.DefaultValue = new(defaultParam); + Info.Help = new(help); + Info.Flags = (ShaderParamFlags)flags; + Index = (int)ShaderMaterialVars.Count + ShaderParams.Count; + ShaderParams.Add(this); + } + public static implicit operator int(ShaderParam param) => param.Index; + public ReadOnlySpan GetName() => Info.Name; + public ShaderParamType GetType() => Info.Type; + public ReadOnlySpan GetDefaultValue() => Info.DefaultValue; + public int GetFlags() => (int)Info.Flags; + public ReadOnlySpan GetHelp() => Info.Help; + } + + public static readonly ShaderParam BLOOMAMOUNT = new($"${nameof(BLOOMAMOUNT)}", ShaderParamType.Float, "1.0", ""); + public static readonly ShaderParam FRAMETEXTURE = new($"${nameof(FRAMETEXTURE)}", ShaderParamType.Texture, "_rt_SmallHDR0", ""); + + public override string? GetFallbackShader(IMaterialVar[] vars) => null; + public override int GetFlags() => Flags; + public override int GetNumParams() => base.GetNumParams() + ShaderParams.Count; + public override ReadOnlySpan GetParamName(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamName(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetName(); + } + public override ReadOnlySpan GetParamHelp(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamHelp(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetHelp(); + } + public override ShaderParamType GetParamType(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamType(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetType(); + } + public override ReadOnlySpan GetParamDefault(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamDefault(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetDefaultValue(); + } + + protected override void OnInitShaderParams(IMaterialVar[] vars, ReadOnlySpan materialName) { + if (!vars[BLOOMAMOUNT].IsDefined()) + vars[BLOOMAMOUNT].SetFloatValue(1.0f); + } + + protected override void OnInitShaderInstance(IMaterialVar[] vars, ReadOnlySpan materialName) { + if (vars[(int)ShaderMaterialVars.BaseTexture].IsDefined()) + LoadTexture((int)ShaderMaterialVars.BaseTexture); + } + + protected override void OnDrawElements(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, VertexCompressionType vertexCompression) { + if (IsSnapshotting()) { + ShaderShadow.EnableDepthWrites(false); + ShaderShadow.EnableAlphaWrites(true); + ShaderShadow.EnableTexture(Sampler.Sampler0, true); + ShaderShadow.VertexShaderVertexFormat(VertexFormat.Position, 1, null, 0); + + ShaderShadow.EnableSRGBRead(Sampler.Sampler0, false); + ShaderShadow.EnableSRGBWrite(false); + + StaticShaderIndex vshIndex = new(ShaderShadow, ShaderType.Vertex, "blurfilter"); + ShaderShadow.SetVertexShader("blurfilter", vshIndex.GetIndex()); + + StaticShaderIndex pshIndex = new(ShaderShadow, ShaderType.Pixel, "blurfilter"); + ShaderShadow.SetPixelShader("blurfilter", pshIndex.GetIndex()); + + if (IsFlagSet(vars, MaterialVarFlags.Additive)) + EnableAlphaBlending(ShaderBlendFactor.One, ShaderBlendFactor.One); + } + else { + BindTexture(Sampler.Sampler0, (int)ShaderMaterialVars.BaseTexture, -1); + + ITexture srcTexture = vars[(int)ShaderMaterialVars.BaseTexture].GetTextureValue()!; + int height = srcTexture.GetActualWidth(); + float dY = 1.0f / height; + Span v = [0, 0, 0, 0]; + + v[0] = 0.0f; + v[1] = 1.3366f * dY; + v[2] = 0; + v[3] = 0; + shaderAPI.SetVertexShaderConstant(VertexShaderConst.ShaderSpecificConst0, v, 1); + v[0] = 0.0f; + v[1] = 3.4295f * dY; + shaderAPI.SetVertexShaderConstant(VertexShaderConst.ShaderSpecificConst1, v, 1); + v[0] = 0.0f; + v[1] = 5.4264f * dY; + shaderAPI.SetVertexShaderConstant(VertexShaderConst.ShaderSpecificConst2, v, 1); + + v[0] = 0.0f; + v[1] = 7.4359f * dY; + shaderAPI.SetPixelShaderConstant(0, v, 1); + v[0] = 0.0f; + v[1] = 9.4436f * dY; + shaderAPI.SetPixelShaderConstant(1, v, 1); + v[0] = 0.0f; + v[1] = 11.4401f * dY; + shaderAPI.SetPixelShaderConstant(2, v, 1); + + v[0] = v[1] = v[2] = vars[BLOOMAMOUNT].GetFloatValue(); + + shaderAPI.SetPixelShaderConstant(3, v, 1); + + DynamicShaderIndex vshIndex = new(shaderAPI, ShaderType.Vertex); + shaderAPI.SetVertexShaderIndex(vshIndex.GetIndex()); + + DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); + shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); + } + Draw(); + } +} diff --git a/Source.StdShader.Gl46/Downsample_nohdr.cs b/Source.StdShader.Gl46/Downsample_nohdr.cs new file mode 100644 index 000000000..897663264 --- /dev/null +++ b/Source.StdShader.Gl46/Downsample_nohdr.cs @@ -0,0 +1,139 @@ +using Source.Common.Commands; +using Source.Common.MaterialSystem; +using Source.Common.ShaderAPI; +using Source.Common.ShaderLib; + +namespace Source.StdShader.Gl46; + +public class Downsample_nohdr : BaseVSShader +{ + public static string HelpString = "Help for Downsample_nohdr"; + public static int Flags = (int)ShaderParamFlags.NotEditable; + public static List ShaderParams = []; + + public class ShaderParam + { + public readonly ShaderParamInfo Info; + public readonly int Index; + public ShaderParam(string name, ShaderParamType type, ReadOnlySpan defaultParam, ReadOnlySpan help, int flags = 0) { + Info.Name = name; + Info.Type = type; + Info.DefaultValue = new(defaultParam); + Info.Help = new(help); + Info.Flags = (ShaderParamFlags)flags; + Index = (int)ShaderMaterialVars.Count + ShaderParams.Count; + ShaderParams.Add(this); + } + public static implicit operator int(ShaderParam param) => param.Index; + public ReadOnlySpan GetName() => Info.Name; + public ShaderParamType GetType() => Info.Type; + public ReadOnlySpan GetDefaultValue() => Info.DefaultValue; + public int GetFlags() => (int)Info.Flags; + public ReadOnlySpan GetHelp() => Info.Help; + } + + public static readonly ShaderParam BLOOMTINTENABLE = new($"${nameof(BLOOMTINTENABLE)}", ShaderParamType.Integer, "1", ""); + public static readonly ShaderParam CSTRIKE = new($"${nameof(CSTRIKE)}", ShaderParamType.Integer, "0", ""); + + static readonly ConVar r_bloomtintr = new("r_bloomtintr", "0.3"); + static readonly ConVar r_bloomtintg = new("r_bloomtintg", "0.59"); + static readonly ConVar r_bloomtintb = new("r_bloomtintb", "0.11"); + static readonly ConVar r_bloomtintexponent = new("r_bloomtintexponent", "2.2"); + + public override string? GetFallbackShader(IMaterialVar[] vars) => null; + public override int GetFlags() => Flags; + public override int GetNumParams() => base.GetNumParams() + ShaderParams.Count; + public override ReadOnlySpan GetParamName(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamName(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetName(); + } + public override ReadOnlySpan GetParamHelp(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamHelp(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetHelp(); + } + public override ShaderParamType GetParamType(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamType(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetType(); + } + public override ReadOnlySpan GetParamDefault(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamDefault(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetDefaultValue(); + } + + protected override void OnInitShaderParams(IMaterialVar[] vars, ReadOnlySpan materialName) { + if (!vars[BLOOMTINTENABLE].IsDefined()) + vars[BLOOMTINTENABLE].SetIntValue(1); + } + + protected override void OnInitShaderInstance(IMaterialVar[] vars, ReadOnlySpan materialName) { + LoadTexture((int)ShaderMaterialVars.BaseTexture); + } + + protected override void OnDrawElements(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, VertexCompressionType vertexCompression) { + if (IsSnapshotting()) { + ShaderShadow.EnableDepthWrites(false); + ShaderShadow.EnableAlphaWrites(true); + ShaderShadow.EnableTexture(Sampler.Sampler0, true); + + ShaderShadow.EnableSRGBRead(Sampler.Sampler0, false); + ShaderShadow.EnableSRGBWrite(false); + + ShaderShadow.VertexShaderVertexFormat(VertexFormat.Position, 1, null, 0); + + ShaderShadow.SetVertexShader("downsample", 0); + + StaticShaderIndex pshIndex = new(ShaderShadow, ShaderType.Pixel, "downsample_nohdr"); + pshIndex.Set("CSTRIKE", vars[CSTRIKE].GetIntValue() != 0 ? 1 : 0); + ShaderShadow.SetPixelShader("downsample_nohdr", pshIndex.GetIndex()); + } + else { + BindTexture(Sampler.Sampler0, (int)ShaderMaterialVars.BaseTexture, -1); + + shaderAPI.GetBackBufferDimensions(out int width, out int height); + + Span v = stackalloc float[16]; + float dX = 1.0f / width; + float dY = 1.0f / height; + + v[0] = .5f * dX; + v[1] = .5f * dY; + v[4] = 2.5f * dX; + v[5] = .5f * dY; + v[8] = .5f * dX; + v[9] = 2.5f * dY; + v[12] = 2.5f * dX; + v[13] = 2.5f * dY; + shaderAPI.SetVertexShaderConstant(VertexShaderConst.ShaderSpecificConst0, v, 4); + + shaderAPI.SetVertexShaderIndex(0); + + Span pixelShaderParams = [r_bloomtintr.GetFloat(), + r_bloomtintg.GetFloat(), + r_bloomtintb.GetFloat(), + r_bloomtintexponent.GetFloat()]; + if (vars[BLOOMTINTENABLE].GetIntValue() == 0) { + pixelShaderParams[0] = 0.333f; + pixelShaderParams[1] = 0.333f; + pixelShaderParams[2] = 0.333f; + pixelShaderParams[3] = 1.0f; + } + shaderAPI.SetPixelShaderConstant(0, pixelShaderParams, 1); + + DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); + shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); + } + Draw(); + } +} diff --git a/Source.StdShader.Gl46/screenspace_general.cs b/Source.StdShader.Gl46/screenspace_general.cs new file mode 100644 index 000000000..72b893356 --- /dev/null +++ b/Source.StdShader.Gl46/screenspace_general.cs @@ -0,0 +1,11 @@ +using Source.Common.MaterialSystem; + +namespace Source.StdShader.Gl46; + +public class screenspace_general : BaseVSShader +{ + public static string HelpString = "Help for screenspace_general"; + public static int Flags = 0; + + public override string? GetFallbackShader(IMaterialVar[] vars) => "screenspace_general_dx9"; +} diff --git a/Source.StdShader.Gl46/screenspace_general_dx9.cs b/Source.StdShader.Gl46/screenspace_general_dx9.cs new file mode 100644 index 000000000..92d72c8fc --- /dev/null +++ b/Source.StdShader.Gl46/screenspace_general_dx9.cs @@ -0,0 +1,217 @@ +using Source.Common.Bitmap; +using Source.Common.MaterialSystem; +using Source.Common.ShaderAPI; +using Source.Common.ShaderLib; + +namespace Source.StdShader.Gl46; + +public class screenspace_general_dx9 : BaseVSShader +{ + public static string HelpString = "Help for screenspace_general"; + public static int Flags = (int)ShaderParamFlags.NotEditable; + public static List ShaderParams = []; + + public class ShaderParam + { + public readonly ShaderParamInfo Info; + public readonly int Index; + public ShaderParam(string name, ShaderParamType type, ReadOnlySpan defaultParam, ReadOnlySpan help, int flags = 0) { + Info.Name = name; + Info.Type = type; + Info.DefaultValue = new(defaultParam); + Info.Help = new(help); + Info.Flags = (ShaderParamFlags)flags; + Index = (int)ShaderMaterialVars.Count + ShaderParams.Count; + ShaderParams.Add(this); + } + public static implicit operator int(ShaderParam param) => param.Index; + public ReadOnlySpan GetName() => Info.Name; + public ShaderParamType GetType() => Info.Type; + public ReadOnlySpan GetDefaultValue() => Info.DefaultValue; + public int GetFlags() => (int)Info.Flags; + public ReadOnlySpan GetHelp() => Info.Help; + } + + public static readonly ShaderParam C0_X = new($"${nameof(C0_X)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C0_Y = new($"${nameof(C0_Y)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C0_Z = new($"${nameof(C0_Z)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C0_W = new($"${nameof(C0_W)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C1_X = new($"${nameof(C1_X)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C1_Y = new($"${nameof(C1_Y)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C1_Z = new($"${nameof(C1_Z)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C1_W = new($"${nameof(C1_W)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C2_X = new($"${nameof(C2_X)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C2_Y = new($"${nameof(C2_Y)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C2_Z = new($"${nameof(C2_Z)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C2_W = new($"${nameof(C2_W)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C3_X = new($"${nameof(C3_X)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C3_Y = new($"${nameof(C3_Y)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C3_Z = new($"${nameof(C3_Z)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C3_W = new($"${nameof(C3_W)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam PIXSHADER = new($"${nameof(PIXSHADER)}", ShaderParamType.String, "", "Name of the pixel shader to use"); + public static readonly ShaderParam DISABLE_COLOR_WRITES = new($"${nameof(DISABLE_COLOR_WRITES)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam ALPHATESTED = new($"${nameof(ALPHATESTED)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam ALPHA_BLEND_COLOR_OVERLAY = new($"${nameof(ALPHA_BLEND_COLOR_OVERLAY)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam ALPHA_BLEND = new($"${nameof(ALPHA_BLEND)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam TEXTURE1 = new($"${nameof(TEXTURE1)}", ShaderParamType.Texture, "", ""); + public static readonly ShaderParam TEXTURE2 = new($"${nameof(TEXTURE2)}", ShaderParamType.Texture, "", ""); + public static readonly ShaderParam TEXTURE3 = new($"${nameof(TEXTURE3)}", ShaderParamType.Texture, "", ""); + public static readonly ShaderParam LINEARREAD_BASETEXTURE = new($"${nameof(LINEARREAD_BASETEXTURE)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam LINEARREAD_TEXTURE1 = new($"${nameof(LINEARREAD_TEXTURE1)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam LINEARREAD_TEXTURE2 = new($"${nameof(LINEARREAD_TEXTURE2)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam LINEARREAD_TEXTURE3 = new($"${nameof(LINEARREAD_TEXTURE3)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam LINEARWRITE = new($"${nameof(LINEARWRITE)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam COPYALPHA = new($"${nameof(COPYALPHA)}", ShaderParamType.Integer, "0", ""); + + public override string? GetFallbackShader(IMaterialVar[] vars) => null; + public override int GetFlags() => Flags; + public override int GetNumParams() => base.GetNumParams() + ShaderParams.Count; + public override ReadOnlySpan GetParamName(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamName(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetName(); + } + public override ReadOnlySpan GetParamHelp(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamHelp(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetHelp(); + } + public override ShaderParamType GetParamType(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamType(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetType(); + } + public override ReadOnlySpan GetParamDefault(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamDefault(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetDefaultValue(); + } + + protected override void OnInitShaderInstance(IMaterialVar[] vars, ReadOnlySpan materialName) { + if (vars[(int)ShaderMaterialVars.BaseTexture].IsDefined()) + LoadTexture((int)ShaderMaterialVars.BaseTexture); + if (vars[TEXTURE1].IsDefined()) + LoadTexture(TEXTURE1); + if (vars[TEXTURE2].IsDefined()) + LoadTexture(TEXTURE2); + if (vars[TEXTURE3].IsDefined()) + LoadTexture(TEXTURE3); + } + + void SetupSamplerSRGBRead(IMaterialVar[] vars, Sampler sampler, int textureVar, int linearReadVar) { + ShaderShadow!.EnableTexture(sampler, true); + ITexture txtr = vars[textureVar].GetTextureValue()!; + ImageFormat fmt = txtr.GetImageFormat(); + if ((fmt == ImageFormat.RGBA16161616F) || (fmt == ImageFormat.RGBA16161616)) + ShaderShadow.EnableSRGBRead(sampler, false); + else + ShaderShadow.EnableSRGBRead(sampler, !vars[linearReadVar].IsDefined() || vars[linearReadVar].GetIntValue() == 0); + } + + void BindTextureWithPixelSize(IShaderDynamicAPI shaderAPI, IMaterialVar[] vars, Sampler sampler, int textureVar, int constant) { + BindTexture(sampler, textureVar, -1); + + ITexture target = vars[textureVar].GetTextureValue()!; + Span pixelSize = [1.0f / target.GetActualWidth(), 1.0f / target.GetActualHeight(), 0.0f, 0.0f]; + shaderAPI.SetPixelShaderConstant(constant, pixelSize, 1); + } + + static ReadOnlySpan PixelShaderFileName(ReadOnlySpan pixelShader) { + if (pixelShader.EndsWith("_ps20b", StringComparison.OrdinalIgnoreCase)) + return pixelShader[..^6]; + if (pixelShader.EndsWith("_ps20", StringComparison.OrdinalIgnoreCase)) + return pixelShader[..^5]; + return pixelShader; + } + + protected override void OnDrawElements(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, VertexCompressionType vertexCompression) { + if (IsSnapshotting()) { + ShaderShadow.EnableDepthWrites(false); + + if (vars[(int)ShaderMaterialVars.BaseTexture].IsDefined()) + SetupSamplerSRGBRead(vars, Sampler.Sampler0, (int)ShaderMaterialVars.BaseTexture, LINEARREAD_BASETEXTURE); + if (vars[TEXTURE1].IsDefined()) + SetupSamplerSRGBRead(vars, Sampler.Sampler1, TEXTURE1, LINEARREAD_TEXTURE1); + if (vars[TEXTURE2].IsDefined()) + SetupSamplerSRGBRead(vars, Sampler.Sampler2, TEXTURE2, LINEARREAD_TEXTURE2); + if (vars[TEXTURE3].IsDefined()) + SetupSamplerSRGBRead(vars, Sampler.Sampler3, TEXTURE3, LINEARREAD_TEXTURE3); + + ShaderShadow.VertexShaderVertexFormat(VertexFormat.Position, 1, null, 0); + + bool srgbWrite = true; + if (vars[LINEARWRITE].GetFloatValue() != 0) + srgbWrite = false; + ShaderShadow.EnableSRGBWrite(srgbWrite); + + ShaderShadow.SetVertexShader("screenspaceeffect", 0); + + if (vars[DISABLE_COLOR_WRITES].GetIntValue() != 0) + ShaderShadow.EnableColorWrites(false); + + ShaderShadow.EnableAlphaTest(true); + ShaderShadow.AlphaFunc(ShaderAlphaFunc.Greater, 0.0f); + + if (IsFlagSet(vars, MaterialVarFlags.Additive)) + EnableAlphaBlending(ShaderBlendFactor.One, ShaderBlendFactor.One); + if (vars[ALPHA_BLEND_COLOR_OVERLAY].GetIntValue() != 0) + EnableAlphaBlending(ShaderBlendFactor.One, ShaderBlendFactor.OneMinusSrcAlpha); + if (vars[ALPHA_BLEND].GetIntValue() != 0) + EnableAlphaBlending(ShaderBlendFactor.SrcAlpha, ShaderBlendFactor.OneMinusSrcAlpha); + + if (vars[COPYALPHA].GetIntValue() != 0) { + ShaderShadow.EnableBlending(false); + ShaderShadow.AlphaFunc(ShaderAlphaFunc.Always, 0.0f); + } + + ShaderShadow.SetPixelShader(PixelShaderFileName(vars[PIXSHADER].GetStringValue()), 0); + } + else { + if (vars[(int)ShaderMaterialVars.BaseTexture].IsDefined()) + BindTextureWithPixelSize(shaderAPI, vars, Sampler.Sampler0, (int)ShaderMaterialVars.BaseTexture, 4); + if (vars[TEXTURE1].IsDefined()) + BindTextureWithPixelSize(shaderAPI, vars, Sampler.Sampler1, TEXTURE1, 5); + if (vars[TEXTURE2].IsDefined()) + BindTextureWithPixelSize(shaderAPI, vars, Sampler.Sampler2, TEXTURE2, 6); + if (vars[TEXTURE3].IsDefined()) + BindTextureWithPixelSize(shaderAPI, vars, Sampler.Sampler3, TEXTURE3, 7); + + Span c0 = [ + vars[C0_X].GetFloatValue(), + vars[C0_Y].GetFloatValue(), + vars[C0_Z].GetFloatValue(), + vars[C0_W].GetFloatValue(), + vars[C1_X].GetFloatValue(), + vars[C1_Y].GetFloatValue(), + vars[C1_Z].GetFloatValue(), + vars[C1_W].GetFloatValue(), + vars[C2_X].GetFloatValue(), + vars[C2_Y].GetFloatValue(), + vars[C2_Z].GetFloatValue(), + vars[C2_W].GetFloatValue(), + vars[C3_X].GetFloatValue(), + vars[C3_Y].GetFloatValue(), + vars[C3_Z].GetFloatValue(), + vars[C3_W].GetFloatValue() + ]; + + shaderAPI.SetPixelShaderConstant(0, c0, c0.Length / 4); + + Span eyePos = [0, 0, 0, 0]; + shaderAPI.GetWorldSpaceCameraPosition(eyePos); + shaderAPI.SetPixelShaderConstant(10, eyePos, 1); + + shaderAPI.SetVertexShaderIndex(0); + shaderAPI.SetPixelShaderIndex(0); + } + Draw(); + } +} From 5e9fbbaabfdf8ae0f86ef09827a76724b3b2de45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:51:27 +0300 Subject: [PATCH 15/57] Port HDR bloom and auto exposure post processing --- Game.Client/C_EnvTonemapController.cs | 25 + Game.Client/HLClient.cs | 1 + Game.Client/View.cs | 13 + Game.Client/ViewPostProcess.cs | 743 ++++++++++++++++++++++++++ 4 files changed, 782 insertions(+) create mode 100644 Game.Client/ViewPostProcess.cs diff --git a/Game.Client/C_EnvTonemapController.cs b/Game.Client/C_EnvTonemapController.cs index b07093b04..b65b5fe75 100644 --- a/Game.Client/C_EnvTonemapController.cs +++ b/Game.Client/C_EnvTonemapController.cs @@ -34,4 +34,29 @@ public class C_EnvTonemapController : C_BaseEntity public float CustomBloomScale; [NetworkName("m_flCustomBloomScaleMinimum")] public float CustomBloomScaleMinimum; + + static readonly EHANDLE g_hTonemapControllerInUse = new(); + + public override void UpdateOnRemove() { + if (g_hTonemapControllerInUse.Get() == this) { + g_bUseCustomAutoExposureMin = false; + g_bUseCustomAutoExposureMax = false; + g_bUseCustomBloomScale = false; + } + base.UpdateOnRemove(); + } + + public override void OnDataChanged(DataUpdateType updateType) { + base.OnDataChanged(updateType); + + g_bUseCustomAutoExposureMin = UseCustomAutoExposureMin; + g_bUseCustomAutoExposureMax = UseCustomAutoExposureMax; + g_bUseCustomBloomScale = UseCustomBloomScale; + g_flCustomAutoExposureMin = CustomAutoExposureMin; + g_flCustomAutoExposureMax = CustomAutoExposureMax; + g_flCustomBloomScale = CustomBloomScale; + g_flCustomBloomScaleMinimum = CustomBloomScaleMinimum; + + g_hTonemapControllerInUse.Set(this); + } } \ No newline at end of file diff --git a/Game.Client/HLClient.cs b/Game.Client/HLClient.cs index 62b53e9c4..838a35ed7 100644 --- a/Game.Client/HLClient.cs +++ b/Game.Client/HLClient.cs @@ -80,6 +80,7 @@ public void LevelInitPreEntity(ReadOnlySpan mapname) { vieweffects.LevelInit(); modemanager.LevelInit(mapname); + ResetToneMapping(1.0f); IGameSystem.LevelInitPreEntityAllSystems(mapname); #if GMOD_DLL garrysmod.LevelInit(mapname); diff --git a/Game.Client/View.cs b/Game.Client/View.cs index d96770301..c9cab4fdb 100644 --- a/Game.Client/View.cs +++ b/Game.Client/View.cs @@ -441,6 +441,19 @@ public void RenderView(in ViewSetup viewRender, ClearFlags clearFlags, RenderVie IMaterial? material = blend ? ModulateSingleColor.Get() : TranslucentSingleColor.Get(); render.ViewDrawFade(color, material); + if (viewRender.DoBloomAndToneMapping) { + bool flashlightIsOn = false; + C_BasePlayer? local = C_BasePlayer.GetLocalPlayer(); + if (local != null) + flashlightIsOn = local.IsEffectActive(EntityEffects.DimLight); + DoEnginePostProcessing(viewRender.X, viewRender.Y, viewRender.Width, viewRender.Height, flashlightIsOn); + } + + if (HardwareConfig.GetHDRType() == HDRType.Integer) { + using (renderContext = new MatRenderContextPtr(materials)) + renderContext.SetToneMappingScaleLinear(new(1, 1, 1)); + } + CleanupMain3DView(in viewRender); if ((whatToDraw & RenderViewInfo.DrawHUD) != 0) { diff --git a/Game.Client/ViewPostProcess.cs b/Game.Client/ViewPostProcess.cs new file mode 100644 index 000000000..c96f1b738 --- /dev/null +++ b/Game.Client/ViewPostProcess.cs @@ -0,0 +1,743 @@ +global using static Game.Client.ViewPostProcess; + +using Source; +using Source.Common; +using Source.Common.Commands; +using Source.Common.MaterialSystem; +using Source.Common.Mathematics; +using Source.Engine; + +using System.Numerics; + +namespace Game.Client; + +[EngineComponent] +public static class ViewPostProcess +{ + public static bool g_bUseCustomAutoExposureMin = false; + public static bool g_bUseCustomAutoExposureMax = false; + public static bool g_bUseCustomBloomScale = false; + public static float g_flCustomAutoExposureMin = 0; + public static float g_flCustomAutoExposureMax = 0; + public static float g_flCustomBloomScale = 0.0f; + public static float g_flCustomBloomScaleMinimum = 0.0f; + + public static bool g_bFlashlightIsOn = false; + + internal static IMaterialSystemHardwareConfig HardwareConfig => field ??= Singleton(); + + public static readonly ConVar mat_bloomscale = new("mat_bloomscale", "1"); + + public static readonly ConVar mat_bloomamount_rate = new("mat_bloomamount_rate", "0.05f", FCvar.Cheat); + static readonly ConVar debug_postproc = new("mat_debug_postprocessing_effects", "0", FCvar.None, "0 = off, 1 = show post-processing passes in quadrants of the screen, 2 = only apply post-processing to the centre of the screen"); + static readonly ConVar mat_postprocessing_combine = new("mat_postprocessing_combine", "1", FCvar.None, "Combine bloom, software anti-aliasing and color correction into one post-processing pass"); + static readonly ConVar mat_dynamic_tonemapping = new("mat_dynamic_tonemapping", "1", FCvar.Cheat); + static readonly ConVar mat_tonemapping_occlusion_use_stencil = new("mat_tonemapping_occlusion_use_stencil", "0"); + public static readonly ConVar mat_debug_autoexposure = new("mat_debug_autoexposure", "0", FCvar.Cheat); + static readonly ConVar mat_autoexposure_max = new("mat_autoexposure_max", "2"); + static readonly ConVar mat_autoexposure_min = new("mat_autoexposure_min", "0.5"); + public static readonly ConVar mat_hdr_tonemapscale = new("mat_hdr_tonemapscale", "1.0", FCvar.Cheat); + public static readonly ConVar mat_hdr_uncapexposure = new("mat_hdr_uncapexposure", "0", FCvar.Cheat); + public static readonly ConVar mat_force_bloom = new("mat_force_bloom", "0", FCvar.Cheat); + public static readonly ConVar mat_disable_bloom = new("mat_disable_bloom", "0"); + public static readonly ConVar mat_debug_bloom = new("mat_debug_bloom", "0", FCvar.Cheat); + + public static readonly ConVar mat_non_hdr_bloom_scalefactor = new("mat_non_hdr_bloom_scalefactor", ".3"); + static readonly ConVar mat_bloom_scalefactor_scalar = new("mat_bloom_scalefactor_scalar", "1.0"); + + public static readonly ConVar mat_exposure_center_region_x = new("mat_exposure_center_region_x", "0.9", FCvar.Cheat); + public static readonly ConVar mat_exposure_center_region_y = new("mat_exposure_center_region_y", "0.85", FCvar.Cheat); + public static readonly ConVar mat_exposure_center_region_x_flashlight = new("mat_exposure_center_region_x_flashlight", "0.9", FCvar.Cheat); + public static readonly ConVar mat_exposure_center_region_y_flashlight = new("mat_exposure_center_region_y_flashlight", "0.85", FCvar.Cheat); + + public static readonly ConVar mat_tonemap_algorithm = new("mat_tonemap_algorithm", "1", FCvar.Cheat, "0 = Original Algorithm 1 = New Algorithm"); + public static readonly ConVar mat_tonemap_percent_target = new("mat_tonemap_percent_target", "60.0", FCvar.Cheat); + public static readonly ConVar mat_tonemap_percent_bright_pixels = new("mat_tonemap_percent_bright_pixels", "2.0", FCvar.Cheat); + public static readonly ConVar mat_tonemap_min_avglum = new("mat_tonemap_min_avglum", "3.0", FCvar.Cheat); + + static readonly ConVar mat_force_tonemap_scale = new("mat_force_tonemap_scale", "0.0", FCvar.Cheat); + + static readonly ConVar mat_postprocess_x = new("mat_postprocess_x", "4"); + static readonly ConVar mat_postprocess_y = new("mat_postprocess_y", "1"); + + static void SetRenderTargetAndViewPort(ITexture rt) { + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetRenderTarget(rt); + renderContext.Viewport(0, 0, rt.GetActualWidth(), rt.GetActualHeight()); + } + + enum HistogramEntryState + { + Initial = 0, + FirstQueryInFlight, + QueryInFlight, + QueryDone, + } + + const int N_LUMINANCE_RANGES = 31; + const int N_LUMINANCE_RANGES_NEW = 17; + const int MAX_QUERIES_PER_FRAME = 1; + + class HistogramEntry + { + public HistogramEntryState State; + public OcclusionQueryObjectHandle_t OccHandle; + public int FrameQueued; + public int NPixels; + public int NPixelsInRange; + public float MinLum, MaxLum; + public float MinX, MinY, MaxX, MaxY; + + public bool ContainsValidData() => (State == HistogramEntryState.QueryDone) || (State == HistogramEntryState.QueryInFlight); + + public void IssueQuery(int frmNum) { + using MatRenderContextPtr renderContext = new(materials); + if (OccHandle == 0) + OccHandle = renderContext.CreateOcclusionQueryObject(); + + renderContext.GetViewport(out int xl, out int yl, out int destWidth, out int destHeight); + + float testRangeMin = MinLum; + float testRangeMax = (MaxLum == 1.0f) ? 10000.0f : MaxLum; + + IMaterial testMat = materials.FindMaterial("dev/lumcompare", MaterialDefines.TEXTURE_GROUP_OTHER, true)!; + IMaterialVar minVar = testMat.FindVar("$C0_X", out _); + minVar.SetFloatValue(testRangeMin); + IMaterialVar maxVar = testMat.FindVar("$C0_Y", out _); + maxVar.SetFloatValue(testRangeMax); + int scrxMin = (int)MathLib.Lerp(xl, (xl + destWidth - 1), 0, 1, MinX); + int scrxMax = (int)MathLib.Lerp(xl, (xl + destWidth - 1), 0, 1, MaxX); + int scryMin = (int)MathLib.Lerp(yl, (yl + destHeight - 1), 0, 1, MinY); + int scryMax = (int)MathLib.Lerp(yl, (yl + destHeight - 1), 0, 1, MaxY); + + float exposureWidthScale, exposureHeightScale; + + if (g_bFlashlightIsOn) { + exposureWidthScale = 0.5f * (1.0f - mat_exposure_center_region_x_flashlight.GetFloat()); + exposureHeightScale = 0.5f * (1.0f - mat_exposure_center_region_y_flashlight.GetFloat()); + } + else { + exposureWidthScale = 0.5f * (1.0f - mat_exposure_center_region_x.GetFloat()); + exposureHeightScale = 0.5f * (1.0f - mat_exposure_center_region_y.GetFloat()); + } + int skipEdgeX = (int)((1 + scrxMax - scrxMin) * exposureWidthScale); + int skipEdgeY = (int)((1 + scryMax - scryMin) * exposureHeightScale); + + float tscale = 1.0f; + if (HardwareConfig.GetHDRType() == HDRType.Float) + tscale = renderContext.GetToneMappingScaleLinear().X; + IMaterialVar useTScale = testMat.FindVar("$C0_Z", out _); + useTScale.SetFloatValue(tscale); + + NPixels = (1 + scrxMax - scrxMin) * (1 + scryMax - scryMin); + + if (mat_tonemapping_occlusion_use_stencil.GetInt() != 0) { + renderContext.SetStencilWriteMask(1); + + renderContext.SetStencilEnable(true); + renderContext.SetStencilPassOperation(StencilOperation.Replace); + renderContext.SetStencilCompareFunction(StencilComparisonFunction.Always); + renderContext.SetStencilFailOperation(StencilOperation.Keep); + renderContext.SetStencilZFailOperation(StencilOperation.Keep); + renderContext.SetStencilReferenceValue(1); + } + else + renderContext.BeginOcclusionQueryDrawing(OccHandle); + + scrxMin += skipEdgeX; + scryMin += skipEdgeY; + scrxMax -= skipEdgeX; + scryMax -= skipEdgeY; + Singleton().DrawScreenSpaceRectangle(testMat, + scrxMin, scryMin, + 1 + scrxMax - scrxMin, + 1 + scryMax - scryMin, + scrxMin, scryMin, + scrxMax, scryMax, + destWidth, destHeight, null, 1, 1, 0); + + if (mat_tonemapping_occlusion_use_stencil.GetInt() != 0) { + renderContext.BeginOcclusionQueryDrawing(OccHandle); + + renderContext.SetStencilEnable(true); + renderContext.SetStencilTestMask(1); + renderContext.SetStencilPassOperation(StencilOperation.Keep); + renderContext.SetStencilCompareFunction(StencilComparisonFunction.Equal); + renderContext.SetStencilFailOperation(StencilOperation.Keep); + renderContext.SetStencilZFailOperation(StencilOperation.Keep); + renderContext.SetStencilReferenceValue(1); + IMaterial stestMat = materials.FindMaterial("dev/no_pixel_write", MaterialDefines.TEXTURE_GROUP_OTHER, true)!; + Singleton().DrawScreenSpaceRectangle(stestMat, + scrxMin, scryMin, + 1 + scrxMax - scrxMin, + 1 + scryMax - scryMin, + scrxMin, scryMin, + scrxMax, scryMax, + destWidth, destHeight, null, 1, 1, 0); + renderContext.SetStencilEnable(false); + } + renderContext.EndOcclusionQueryDrawing(OccHandle); + if (State == HistogramEntryState.Initial) + State = HistogramEntryState.FirstQueryInFlight; + else + State = HistogramEntryState.QueryInFlight; + FrameQueued = frmNum; + } + } + + class LuminanceHistogramSystem + { + readonly HistogramEntry[] CurHistogram = new HistogramEntry[N_LUMINANCE_RANGES]; + int CurQueryFrame; + + public LuminanceHistogramSystem() { + for (int i = 0; i < CurHistogram.Length; i++) + CurHistogram[i] = new(); + UpdateLuminanceRanges(); + } + + public void Update() { + UpdateLuminanceRanges(); + + int nQueriesIssuedThisFrame = 0; + CurQueryFrame++; + + int numRanges = N_LUMINANCE_RANGES; + if (mat_tonemap_algorithm.GetInt() == 1) + numRanges = N_LUMINANCE_RANGES_NEW; + + for (int i = 0; i < numRanges; i++) { + switch (CurHistogram[i].State) { + case HistogramEntryState.Initial: + if (nQueriesIssuedThisFrame < MAX_QUERIES_PER_FRAME) { + CurHistogram[i].IssueQuery(CurQueryFrame); + nQueriesIssuedThisFrame++; + } + break; + + case HistogramEntryState.FirstQueryInFlight: + case HistogramEntryState.QueryInFlight: + if (CurQueryFrame > CurHistogram[i].FrameQueued + 2) { + using MatRenderContextPtr renderContext = new(materials); + int np = renderContext.OcclusionQuery_GetNumPixelsRendered(CurHistogram[i].OccHandle); + if (np != -1) { + CurHistogram[i].NPixelsInRange = np; + CurHistogram[i].State = HistogramEntryState.QueryDone; + } + } + break; + } + } + + while (nQueriesIssuedThisFrame < MAX_QUERIES_PER_FRAME) { + numRanges = N_LUMINANCE_RANGES; + if (mat_tonemap_algorithm.GetInt() == 1) + numRanges = N_LUMINANCE_RANGES_NEW; + + int oldestSoFar = -1; + for (int i = 0; i < numRanges; i++) + if ((CurHistogram[i].State == HistogramEntryState.QueryDone) && + ((oldestSoFar == -1) || + (CurHistogram[i].FrameQueued < + CurHistogram[oldestSoFar].FrameQueued))) + oldestSoFar = i; + if (oldestSoFar == -1) + break; + CurHistogram[oldestSoFar].IssueQuery(CurQueryFrame); + nQueriesIssuedThisFrame++; + } + } + + public float FindLocationOfPercentBrightPixels(float percentBrightPixels, float percentTargetToSnapToIfInSameBin = -1.0f) { + if (mat_tonemap_algorithm.GetInt() == 1) { + int totalValidPixels = 0; + for (int i = 0; i < N_LUMINANCE_RANGES_NEW - 1; i++) { + if (CurHistogram[i].ContainsValidData()) + totalValidPixels += CurHistogram[i].NPixelsInRange; + } + + if (totalValidPixels == 0) + return -1.0f; + + float totalPercentRangeTested = 0.0f; + float totalPercentPixelsTested = 0.0f; + for (int i = N_LUMINANCE_RANGES_NEW - 2; i >= 0; i--) { + if (!CurHistogram[i].ContainsValidData()) + return -1.0f; + + float pixelPercentNeeded = (percentBrightPixels / 100.0f) - totalPercentPixelsTested; + float thisBinPercentOfTotalPixels = (float)CurHistogram[i].NPixelsInRange / (float)totalValidPixels; + float thisBinLuminanceRange = CurHistogram[i].MaxLum - CurHistogram[i].MinLum; + if (thisBinPercentOfTotalPixels >= pixelPercentNeeded) { + if (percentTargetToSnapToIfInSameBin >= 0.0f) { + if ((CurHistogram[i].MinLum <= (percentTargetToSnapToIfInSameBin / 100.0f)) && (CurHistogram[i].MaxLum >= (percentTargetToSnapToIfInSameBin / 100.0f))) + return percentTargetToSnapToIfInSameBin / 100.0f; + } + + float percentOfThesePixelsNeeded = pixelPercentNeeded / thisBinPercentOfTotalPixels; + float percentLocationOfBorder = 1.0f - (totalPercentRangeTested + (thisBinLuminanceRange * percentOfThesePixelsNeeded)); + percentLocationOfBorder = Math.Max(CurHistogram[i].MinLum, Math.Min(CurHistogram[i].MaxLum, percentLocationOfBorder)); + return percentLocationOfBorder; + } + + totalPercentPixelsTested += thisBinPercentOfTotalPixels; + totalPercentRangeTested += thisBinLuminanceRange; + } + + return -1.0f; + } + else + return -1.0f; + } + + public float GetTargetTonemapScalar(bool getIdealTargetForDebugMode = false) { + if (mat_tonemap_algorithm.GetInt() == 1) { + float percentLocationOfTarget; + if (getIdealTargetForDebugMode == true) + percentLocationOfTarget = FindLocationOfPercentBrightPixels(mat_tonemap_percent_bright_pixels.GetFloat()); + else + percentLocationOfTarget = FindLocationOfPercentBrightPixels(mat_tonemap_percent_bright_pixels.GetFloat(), mat_tonemap_percent_target.GetFloat()); + if (percentLocationOfTarget < 0.0f) + percentLocationOfTarget = mat_tonemap_percent_target.GetFloat() / 100.0f; + + percentLocationOfTarget = Math.Max(0.0001f, percentLocationOfTarget); + + float targetScalar = (mat_tonemap_percent_target.GetFloat() / 100.0f) / percentLocationOfTarget; + + float averageLuminanceLocation = FindLocationOfPercentBrightPixels(50.0f); + if (averageLuminanceLocation > 0.0f) { + float targetScalar2 = (mat_tonemap_min_avglum.GetFloat() / 100.0f) / averageLuminanceLocation; + + if (targetScalar2 > targetScalar) + targetScalar = targetScalar2; + } + + using MatRenderContextPtr renderContext = new(materials); + float lastScale = renderContext.GetToneMappingScaleLinear().X; + targetScalar *= lastScale; + + targetScalar = Math.Max(0.001f, targetScalar); + return targetScalar; + } + else { + float averageLuminance = 0.5f; + + float total = 0; + int totalPixels = 0; + float scaleValue = 1.0f; + if (CurHistogram[N_LUMINANCE_RANGES - 1].ContainsValidData()) { + scaleValue = CurHistogram[N_LUMINANCE_RANGES - 1].NPixels * (1.0f / CurHistogram[N_LUMINANCE_RANGES - 1].NPixelsInRange); + + if (mat_debug_autoexposure.GetInt() != 0) + engine.Con_NPrintf(20, $"Scale value = {scaleValue:F6}"); + } + else + averageLuminance = 0.5f; + + if (!float.IsFinite(scaleValue)) + scaleValue = 1.0f; + + for (int i = 0; i < N_LUMINANCE_RANGES - 1; i++) { + if (CurHistogram[i].ContainsValidData()) { + total += scaleValue * CurHistogram[i].NPixelsInRange * ((CurHistogram[i].MinLum + CurHistogram[i].MaxLum) * 0.5f); + totalPixels += CurHistogram[i].NPixels; + } + else + averageLuminance = 0.5f; + } + if (totalPixels > 0) + averageLuminance = total * (1.0f / totalPixels); + else + averageLuminance = 0.5f; + + averageLuminance = Math.Max(0.0001f, averageLuminance); + + float targetScalar = 0.005f / averageLuminance; + + return targetScalar; + } + } + + static int s_nCurrentBucketAlgorithm = -1; + static bool s_bFirstTime = true; + static readonly string[] sModsForOriginalAlgorithm = ["dod", "cstrike", "lostcoast"]; + + public void UpdateLuminanceRanges() { + if (s_nCurrentBucketAlgorithm == mat_tonemap_algorithm.GetInt()) + return; + s_nCurrentBucketAlgorithm = mat_tonemap_algorithm.GetInt(); + + if (engine == null) + s_nCurrentBucketAlgorithm = -1; + else if (s_bFirstTime == true) { + s_bFirstTime = false; + + ReadOnlySpan gameDirectory = engine.GetGameDirectory(); + for (int i = 0; i < 3; i++) { + if (gameDirectory.EndsWith(sModsForOriginalAlgorithm[i], StringComparison.OrdinalIgnoreCase)) { + mat_tonemap_algorithm.SetValue(0); + s_nCurrentBucketAlgorithm = mat_tonemap_algorithm.GetInt(); + break; + } + } + } + + int numRanges = N_LUMINANCE_RANGES; + + if (mat_tonemap_algorithm.GetInt() == 1) + numRanges = N_LUMINANCE_RANGES_NEW; + + CurQueryFrame = 0; + for (int bucket = 0; bucket < numRanges; bucket++) { + HistogramEntry e = CurHistogram[bucket]; + e.State = HistogramEntryState.Initial; + e.MinX = 0; + e.MaxX = 1; + e.MinY = 0; + e.MaxY = 1; + if (bucket != numRanges - 1) { + if (mat_tonemap_algorithm.GetInt() == 0) { + e.MinLum = -0.01f + MathF.Exp(MathLib.Lerp(MathF.Log(.01f), MathF.Log(.01f + 1), 0, numRanges - 1, bucket)); + e.MaxLum = -0.01f + MathF.Exp(MathLib.Lerp(MathF.Log(.01f), MathF.Log(.01f + 1), 0, numRanges - 1, bucket + 1)); + } + else { + e.MinLum = (float)bucket / (float)(numRanges - 1); + e.MaxLum = (float)(bucket + 1) / (float)(numRanges - 1); + + e.MinLum = e.MinLum > 0.0f ? MathF.Pow(e.MinLum, 1.5f) : e.MinLum; + e.MaxLum = e.MaxLum > 0.0f ? MathF.Pow(e.MaxLum, 1.5f) : e.MaxLum; + } + } + else { + e.MinLum = 0; + e.MaxLum = 100000.0f; + } + } + } + } + + static float GetCurrentBloomScale() { + float currentBloomScale = 1.0f; + if (g_bUseCustomBloomScale) + currentBloomScale = g_flCustomBloomScale; + else + currentBloomScale = mat_bloomscale.GetFloat(); + return currentBloomScale; + } + + static void GetExposureRange(out float autoExposureMin, out float autoExposureMax) { + if (g_bUseCustomAutoExposureMin && (g_flCustomAutoExposureMin > 0.0f)) + autoExposureMin = g_flCustomAutoExposureMin; + else + autoExposureMin = mat_autoexposure_min.GetFloat(); + + if (g_bUseCustomAutoExposureMax && (g_flCustomAutoExposureMax > 0.0f)) + autoExposureMax = g_flCustomAutoExposureMax; + else + autoExposureMax = mat_autoexposure_max.GetFloat(); + + if (mat_hdr_uncapexposure.GetInt() != 0) { + autoExposureMax = 20.0f; + autoExposureMin = 0.0f; + } + + if (autoExposureMin > autoExposureMax) + autoExposureMax = autoExposureMin; + } + + static readonly LuminanceHistogramSystem g_HDR_HistogramSystem = new(); + + static readonly float[] s_MovingAverageToneMapScale = [1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f]; + static int s_nInAverage = 0; + + public static void ResetToneMapping(float value) { + using MatRenderContextPtr renderContext = new(materials); + s_nInAverage = 0; + renderContext.ResetToneMappingScale(value); + } + + static void SetToneMapScale(MatRenderContextPtr renderContext, float newvalue, float minvalue, float maxvalue) { + Assert(float.IsFinite(newvalue)); + if (!float.IsFinite(newvalue)) + return; + + float forcedTonemapScale = mat_force_tonemap_scale.GetFloat(); + + if (MatSysVars.mat_fullbright.GetInt() == 1) + forcedTonemapScale = 1.0f; + + if (forcedTonemapScale > 0.0f) { + mat_hdr_tonemapscale.SetValue(forcedTonemapScale); + renderContext.ResetToneMappingScale(forcedTonemapScale); + return; + } + + mat_hdr_tonemapscale.SetValue(newvalue); + renderContext.SetGoalToneMappingScale(newvalue); + + if (s_nInAverage < s_MovingAverageToneMapScale.Length) + s_MovingAverageToneMapScale[s_nInAverage++] = newvalue; + else { + for (int i = 0; i < s_MovingAverageToneMapScale.Length - 1; i++) + s_MovingAverageToneMapScale[i] = s_MovingAverageToneMapScale[i + 1]; + s_MovingAverageToneMapScale[^1] = newvalue; + } + + if (s_nInAverage == s_MovingAverageToneMapScale.Length) { + float avg = 0.0f; + float sumweights = 0; + int samplePt = s_MovingAverageToneMapScale.Length / 2; + for (int i = 0; i < s_MovingAverageToneMapScale.Length; i++) { + float weight = Math.Abs(i - samplePt) * (1.0f / (s_MovingAverageToneMapScale.Length / 2)); + sumweights += weight; + avg += weight * s_MovingAverageToneMapScale[i]; + } + avg *= 1.0f / sumweights; + avg = Math.Min(maxvalue, Math.Max(minvalue, avg)); + renderContext.SetGoalToneMappingScale(avg); + mat_hdr_tonemapscale.SetValue(avg); + } + } + + static void DrawBloomDebugBoxes(MatRenderContextPtr renderContext) { + renderContext.SetRenderTarget(null); + renderContext.GetRenderTargetDimensions(out int destWidth, out int destHeight); + + renderContext.Viewport(0, 0, destWidth, destHeight); + renderContext.ClearColor3ub(0, 0, 0); + renderContext.ClearBuffers(true, true); + + int inset = 64; + int size = 32; + + s_DebugBoxWx = (s_DebugBoxWx + 1) & 63; + + renderContext.Viewport(destWidth / 2 + s_DebugBoxWx, destHeight / 2, size, size); + renderContext.ClearColor3ub(255, 255, 255); + renderContext.ClearBuffers(true, true); + + renderContext.Viewport(inset, inset, size, size); + renderContext.ClearBuffers(true, true); + + renderContext.Viewport(destWidth - inset - size, inset, size, size); + renderContext.ClearBuffers(true, true); + + renderContext.Viewport(destWidth - inset - size, destHeight - inset - size, size, size); + renderContext.ClearBuffers(true, true); + + renderContext.Viewport(inset, destHeight - inset - size, size, size); + renderContext.ClearBuffers(true, true); + + renderContext.Viewport(0, 0, destWidth, destHeight); + } + static int s_DebugBoxWx = 0; + + static float s_CurrentBloomAmount = 1.0f; + + static float GetBloomAmount() { + HDRType hdrType = HardwareConfig.GetHDRType(); + + bool bloomEnabled = MatSysVars.mat_hdr_level.GetInt() >= 1; + + if (!engine.MapHasHDRLighting()) + bloomEnabled = false; + if (mat_force_bloom.GetInt() != 0) + bloomEnabled = true; + if (mat_disable_bloom.GetInt() != 0) + bloomEnabled = false; + if (MatSysVars.mat_fullbright.GetInt() == 1) + bloomEnabled = false; + +#if GMOD_DLL + if (bloomEnabled) { + ConVarRef pp_bloom = new("pp_bloom"); + if (pp_bloom.IsValid() && pp_bloom.GetBool()) + bloomEnabled = false; + } +#endif + + float bloomAmount = 0.0f; + + if (bloomEnabled) { + float rate = mat_bloomamount_rate.GetFloat(); + + s_CurrentBloomAmount = GetCurrentBloomScale() * rate + (1.0f - rate) * s_CurrentBloomAmount; + bloomAmount = s_CurrentBloomAmount; + } + + if (hdrType == HDRType.None) + bloomAmount *= mat_non_hdr_bloom_scalefactor.GetFloat(); + + bloomAmount *= mat_bloom_scalefactor_scalar.GetFloat(); + + return bloomAmount; + } + + static bool s_bScreenEffectTextureIsUpdated = false; + + static void Generate8BitBloomTexture(MatRenderContextPtr renderContext, float bloomScale, int x, int y, int w, int h) { + renderContext.PushRenderTargetAndViewport(); + ITexture src = materials.FindTexture("_rt_FullFrameFB", MaterialDefines.TEXTURE_GROUP_RENDER_TARGET)!; + int srcWidth = src.GetActualWidth(); + int srcHeight = src.GetActualHeight(); + + IMaterial downsampleMat = materials.FindMaterial("dev/downsample_non_hdr", MaterialDefines.TEXTURE_GROUP_OTHER, true)!; + + IMaterial xblurMat = materials.FindMaterial("dev/blurfilterx_nohdr", MaterialDefines.TEXTURE_GROUP_OTHER, true)!; + IMaterial yblurMat = materials.FindMaterial("dev/blurfiltery_nohdr", MaterialDefines.TEXTURE_GROUP_OTHER, true)!; + ITexture destRt0 = materials.FindTexture("_rt_SmallFB0", MaterialDefines.TEXTURE_GROUP_RENDER_TARGET)!; + ITexture destRt1 = materials.FindTexture("_rt_SmallFB1", MaterialDefines.TEXTURE_GROUP_RENDER_TARGET)!; + + Assert(destRt0.GetActualWidth() == src.GetActualWidth() / 4); + Assert(destRt0.GetActualHeight() == src.GetActualHeight() / 4); + Assert(destRt1.GetActualWidth() == src.GetActualWidth() / 4); + Assert(destRt1.GetActualHeight() == src.GetActualHeight() / 4); + + RenderUtils renderUtils = Singleton(); + + SetRenderTargetAndViewPort(destRt0); + renderUtils.DrawScreenSpaceRectangle(downsampleMat, 0, 0, srcWidth / 4, srcHeight / 4, + 0, 0, srcWidth - 2, srcHeight - 2, + srcWidth, srcHeight, null, 1, 1, 0); + + SetRenderTargetAndViewPort(destRt1); + renderUtils.DrawScreenSpaceRectangle(xblurMat, 0, 0, srcWidth / 4, srcHeight / 4, + 0, 0, srcWidth / 4 - 1, srcHeight / 4 - 1, + srcWidth / 4, srcHeight / 4, null, 1, 1, 0); + + SetRenderTargetAndViewPort(destRt0); + IMaterialVar bloomAmountVar = yblurMat.FindVar("$bloomamount", out _); + bloomAmountVar.SetFloatValue(bloomScale); + renderUtils.DrawScreenSpaceRectangle(yblurMat, 0, 0, srcWidth / 4, srcHeight / 4, + 0, 0, srcWidth / 4 - 1, srcHeight / 4 - 1, + srcWidth / 4, srcHeight / 4, null, 1, 1, 0); + + renderContext.PopRenderTargetAndViewport(); + } + + static void DoPreBloomTonemapping(MatRenderContextPtr renderContext, int x, int y, int width, int height, float autoExposureMin, float autoExposureMax) { + if (mat_dynamic_tonemapping.GetInt() != 0) { + if (s_bScreenEffectTextureIsUpdated == false) { + UpdateScreenEffectTexture(0, x, y, width, height, true); + s_bScreenEffectTextureIsUpdated = true; + } + + g_HDR_HistogramSystem.Update(); + + float targetScalar = g_HDR_HistogramSystem.GetTargetTonemapScalar(); + float targetScalarClamped = Math.Max(autoExposureMin, Math.Min(autoExposureMax, targetScalar)); + targetScalarClamped = Math.Max(0.001f, targetScalarClamped); + SetToneMapScale(renderContext, targetScalarClamped, autoExposureMin, autoExposureMax); + + if (mat_debug_autoexposure.GetInt() != 0) { + if (mat_tonemap_algorithm.GetInt() == 0) { + engine.Con_NPrintf(19, $"(Original algorithm) Target Scalar = {targetScalar:F2} Min/Max( {autoExposureMin:F2}, {autoExposureMax:F2} ) Final Scalar: {mat_hdr_tonemapscale.GetFloat():F2} Actual: {renderContext.GetToneMappingScaleLinear().X:F2}"); + } + else { + engine.Con_NPrintf(19, $"{mat_tonemap_percent_bright_pixels.GetFloat():F2}% of pixels above {mat_tonemap_percent_target.GetInt()}% target @ {g_HDR_HistogramSystem.FindLocationOfPercentBrightPixels(mat_tonemap_percent_bright_pixels.GetFloat(), mat_tonemap_percent_target.GetFloat()) * 100.0f:F2}% Target Scalar = {g_HDR_HistogramSystem.GetTargetTonemapScalar(true):F2} Min/Max( {autoExposureMin:F2}, {autoExposureMax:F2} ) Final Scalar: {mat_hdr_tonemapscale.GetFloat():F2} Actual: {renderContext.GetToneMappingScaleLinear().X:F2}"); + } + } + } + } + + static void CenterScaleQuadUVs(ref Vector4 quadUVs, in Vector2 uvScale) { + Vector2 uvMid = 0.5f * new Vector2(quadUVs.Z + quadUVs.X, quadUVs.W + quadUVs.Y); + Vector2 uvRange = 0.5f * new Vector2(quadUVs.Z - quadUVs.X, quadUVs.W - quadUVs.Y); + quadUVs.X = uvMid.X - uvScale.X * uvRange.X; + quadUVs.Y = uvMid.Y - uvScale.Y * uvRange.Y; + quadUVs.Z = uvMid.X + uvScale.X * uvRange.X; + quadUVs.W = uvMid.Y + uvScale.Y * uvRange.Y; + } + + public static void DoEnginePostProcessing(int x, int y, int w, int h, bool flashlightIsOn, bool postVGui = false) { + using MatRenderContextPtr renderContext = new(materials); + + float bloomScale = GetBloomAmount(); + + HDRType hdrType = HardwareConfig.GetHDRType(); + + g_bFlashlightIsOn = flashlightIsOn; + + GetExposureRange(out float autoExposureMin, out float autoExposureMax); + + if (mat_debug_bloom.GetInt() == 1) + DrawBloomDebugBoxes(renderContext); + + switch (hdrType) { + case HDRType.None: + case HDRType.Integer: { + s_bScreenEffectTextureIsUpdated = false; + + if (hdrType != HDRType.None) + DoPreBloomTonemapping(renderContext, x, y, w, h, autoExposureMin, autoExposureMax); + + bool performBloom = !postVGui && (bloomScale > 0.0f); + bool splitScreenHDR = MatSysVars.mat_show_ab_hdr.GetInt() != 0; + if (performBloom) { + ITexture src = materials.FindTexture("_rt_FullFrameFB", MaterialDefines.TEXTURE_GROUP_RENDER_TARGET)!; + int srcWidth = src.GetActualWidth(); + int srcHeight = src.GetActualHeight(); + + ITexture destRt1 = materials.FindTexture("_rt_SmallFB1", MaterialDefines.TEXTURE_GROUP_RENDER_TARGET)!; + + if (!s_bScreenEffectTextureIsUpdated) { + UpdateScreenEffectTexture(0, x, y, w, h, true); + s_bScreenEffectTextureIsUpdated = true; + } + + Generate8BitBloomTexture(renderContext, bloomScale, x, y, w, h); + + Vector4 fullViewportPostSrcCorners = new(0.0f, -0.5f, srcWidth / 4 - 1, srcHeight / 4 - 1); + System.Drawing.Rectangle fullViewportPostDestRect = new(x, y, w, h); + + Vector2 uvScale = new((srcWidth - (srcWidth / (float)w)) / (srcWidth - 1), + (srcHeight - (srcHeight / (float)h)) / (srcHeight - 1)); + CenterScaleQuadUVs(ref fullViewportPostSrcCorners, uvScale); + + System.Drawing.Rectangle partialViewportPostDestRect = fullViewportPostDestRect; + Vector4 partialViewportPostSrcCorners = fullViewportPostSrcCorners; + if (debug_postproc.GetInt() == 2) { + partialViewportPostDestRect.X += (int)(0.25f * fullViewportPostDestRect.Width); + partialViewportPostDestRect.Y += (int)(0.25f * fullViewportPostDestRect.Height); + partialViewportPostDestRect.Width -= (int)(0.50f * fullViewportPostDestRect.Width); + partialViewportPostDestRect.Height -= (int)(0.50f * fullViewportPostDestRect.Height); + + Vector2 partialUVScale = new(1.0f - ((w / 2) / (float)(w - 1)), + 1.0f - ((h / 2) / (float)(h - 1))); + CenterScaleQuadUVs(ref partialViewportPostSrcCorners, partialUVScale); + } + + IMaterial bloomMat = materials.FindMaterial("dev/bloomadd", MaterialDefines.TEXTURE_GROUP_OTHER, true)!; + RenderUtils renderUtils = Singleton(); + + if (splitScreenHDR) + renderContext.SetScissorRect(partialViewportPostDestRect.Width / 2, 0, partialViewportPostDestRect.Width, partialViewportPostDestRect.Height, true); + + if (mat_postprocessing_combine.GetInt() != 0) { + renderUtils.DrawScreenSpaceRectangle(bloomMat, + 0, 0, + partialViewportPostDestRect.Width, partialViewportPostDestRect.Height, + partialViewportPostSrcCorners.X, partialViewportPostSrcCorners.Y, + partialViewportPostSrcCorners.Z, partialViewportPostSrcCorners.W, + destRt1.GetActualWidth(), destRt1.GetActualHeight(), + C_World.GetClientWorldEntity(), + mat_postprocess_x.GetInt(), mat_postprocess_y.GetInt(), 0); + } + else { + renderUtils.DrawScreenSpaceRectangle(bloomMat, + partialViewportPostDestRect.X, partialViewportPostDestRect.Y, + partialViewportPostDestRect.Width, partialViewportPostDestRect.Height, + partialViewportPostSrcCorners.X, partialViewportPostSrcCorners.Y, + partialViewportPostSrcCorners.Z, partialViewportPostSrcCorners.W, + destRt1.GetActualWidth(), destRt1.GetActualHeight(), + C_World.GetClientWorldEntity(), 1, 1, 0); + } + + if (splitScreenHDR) + renderContext.SetScissorRect(-1, -1, -1, -1, false); + } + } + break; + } + } +} From cb19a59774ccd3cfc1cc5ce0939871876ff4e147 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:58:41 +0300 Subject: [PATCH 16/57] Port Map_CheckFeatureFlags --- Source.Common/Formats/BSP/BSPFile.cs | 9 ++++++++- Source.Engine/ModelLoader.cs | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/Source.Common/Formats/BSP/BSPFile.cs b/Source.Common/Formats/BSP/BSPFile.cs index a7ef73925..29f379afc 100644 --- a/Source.Common/Formats/BSP/BSPFile.cs +++ b/Source.Common/Formats/BSP/BSPFile.cs @@ -304,7 +304,14 @@ public byte[] ReadLumpBytes(Stream stream, LumpIndex index) { /// public struct BSPDFlagsLump { - public uint LevelFlags; + public LevelFlags LevelFlags; +} + +[Flags] +public enum LevelFlags : uint +{ + BakedStaticPropLightingNonHDR = 0x00000001, + BakedStaticPropLightingHDR = 0x00000002, } /// diff --git a/Source.Engine/ModelLoader.cs b/Source.Engine/ModelLoader.cs index 298bfbc9b..9c9d6bd7b 100644 --- a/Source.Engine/ModelLoader.cs +++ b/Source.Engine/ModelLoader.cs @@ -801,11 +801,32 @@ bool Map_CheckForHDR(Model mod, ReadOnlySpan loadName) { EnableHDR(enableHDR); + Map_CheckFeatureFlags(); + MapLoadHelper.Shutdown(); return hasHDR; } + internal static bool g_bLoadedMapHasBakedPropLighting = false; + internal static bool g_bBakedPropLightingNoSeparateHDR = false; + + void Map_CheckFeatureFlags() { + g_bLoadedMapHasBakedPropLighting = false; + g_bBakedPropLightingNoSeparateHDR = false; + + if (MapLoadHelper.GetLumpSize(LumpIndex.MapFlags) > 0) { + MapLoadHelper lh = new(LumpIndex.MapFlags); + BSPDFlagsLump flagsLump = lh.LoadLumpData()[0]; + + g_bLoadedMapHasBakedPropLighting = + (flagsLump.LevelFlags & LevelFlags.BakedStaticPropLightingNonHDR) != 0 || + (flagsLump.LevelFlags & LevelFlags.BakedStaticPropLightingHDR) != 0; + g_bBakedPropLightingNoSeparateHDR = + (flagsLump.LevelFlags & LevelFlags.BakedStaticPropLightingHDR) == 0; + } + } + private void Map_LoadModel(Model mod) { MapLoadCount++; From 6dc48452233a9d796115f25318c95bac291c53e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:02:17 +0300 Subject: [PATCH 17/57] Port StaticPropMgr.PropHasBakedLightingDisabled --- Source.Engine/StaticPropMgr.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Source.Engine/StaticPropMgr.cs b/Source.Engine/StaticPropMgr.cs index 266a7e831..9d98e78a4 100644 --- a/Source.Engine/StaticPropMgr.cs +++ b/Source.Engine/StaticPropMgr.cs @@ -259,7 +259,11 @@ public void GetAllStaticPropsInOBB(Vector3 origin, Vector3 extent1, Vector3 exte } public bool PropHasBakedLightingDisabled(IHandleEntity? handleEntity) { - throw new NotImplementedException(); + int index = HandleEntityToIndex(handleEntity); + + StaticProp prop = StaticProps[index]; + + return (prop.Flags() & (int)StaticPropFlags.NoPerVertexLighting) != 0; } public ref readonly Vector3 ViewOrigin() => ref LastViewOrigin; From 13176b9e17fa64cb870e01a6c55b16a1909d7ea1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:05:53 +0300 Subject: [PATCH 18/57] Port VertexBuilder.Specular4ub --- Source.Common/MaterialSystem/IMesh.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Source.Common/MaterialSystem/IMesh.cs b/Source.Common/MaterialSystem/IMesh.cs index 7103cb3ae..625c48275 100644 --- a/Source.Common/MaterialSystem/IMesh.cs +++ b/Source.Common/MaterialSystem/IMesh.cs @@ -475,6 +475,12 @@ internal void Specular3ub(byte r, byte g, byte b) { *(int*)pSpecular = col; } + internal void Specular4ub(byte r, byte g, byte b, byte a) { + byte* pSpecular = &Desc.Specular[CurrentVertex * Desc.SpecularSize]; + int col = r | (g << 8) | (b << 16) | (a << 24); + *(int*)pSpecular = col; + } + internal void Specular3ubv(ReadOnlySpan c) { byte* pSpecular = &Desc.Specular[CurrentVertex * Desc.SpecularSize]; int col = c[0] | (c[1] << 8) | (c[2] << 16) | unchecked((int)0xFF000000); @@ -972,7 +978,7 @@ public unsafe void Color4ubv(in Color rgba) { // Faster version of specular public void Specular3ub(byte r, byte g, byte b) => VertexBuilder.Specular3ub(r, g, b); public void Specular3ubv(ReadOnlySpan c) => VertexBuilder.Specular3ubv(c); - public void Specular4ub(byte r, byte g, byte b, byte a) => throw new NotImplementedException(); + public void Specular4ub(byte r, byte g, byte b, byte a) => VertexBuilder.Specular4ub(r, g, b, a); public void Specular4ubv(ReadOnlySpan c) => throw new NotImplementedException(); // texture coordinate setting From 5b3c6644e47a11420858a62a6fe1bc7ba0206afa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:10:29 +0300 Subject: [PATCH 19/57] Port disk baked static prop lighting --- Source.Common/MaterialSystem/HardwareVerts.cs | 36 +++++ Source.Engine/ImplStudio.cs | 125 +++++++++++++++++- 2 files changed, 158 insertions(+), 3 deletions(-) create mode 100644 Source.Common/MaterialSystem/HardwareVerts.cs diff --git a/Source.Common/MaterialSystem/HardwareVerts.cs b/Source.Common/MaterialSystem/HardwareVerts.cs new file mode 100644 index 000000000..eb1d76475 --- /dev/null +++ b/Source.Common/MaterialSystem/HardwareVerts.cs @@ -0,0 +1,36 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Source.Common.MaterialSystem; + +public static class HardwareVerts +{ + public const int VHV_VERSION = 2; + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct MeshHeader + { + public uint Lod; + public uint Vertexes; + public uint Offset; + public InlineArray4 Unused; + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct FileHeader + { + public int Version; + public uint Checksum; + public uint VertexFlags; + public uint VertexSize; + public uint Vertexes; + public int Meshes; + public InlineArray4 Unused; + + public static ref readonly MeshHeader Mesh(ReadOnlySpan file, int mesh) + => ref MemoryMarshal.Cast(file[Unsafe.SizeOf()..])[mesh]; + + public static ReadOnlySpan VertexBase(ReadOnlySpan file, int mesh) + => file[(int)Mesh(file, mesh).Offset..]; + } +} diff --git a/Source.Engine/ImplStudio.cs b/Source.Engine/ImplStudio.cs index 041fddde2..335b60a75 100644 --- a/Source.Engine/ImplStudio.cs +++ b/Source.Engine/ImplStudio.cs @@ -2,12 +2,14 @@ using Source.Common.Commands; using Source.Common.DataCache; using Source.Common.Engine; +using Source.Common.Filesystem; using Source.Common.Formats.BSP; using Source.Common.MaterialSystem; using Source.Common.Mathematics; using System.Numerics; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace Source.Engine; @@ -52,6 +54,7 @@ public class ColorMeshData public uint TotalSize; // FSAsyncControl_t AsyncControlVertex; // todo // FSAsyncControl_t AsyncControlTexel; // todo + public FSAsyncControl? AsyncControl; public bool HasInvalidVB; public bool ColorMeshValid; public bool ColorTextureValid; @@ -1103,8 +1106,8 @@ private bool UpdateStaticPropColorData(IHandleEntity? pProp, ModelInstanceHandle Assert(studioHdr != null && studioHWData != null); if (!debugColorSet && (inst.Flags & ModelInstanceFlags.HasDiskCompiledColor) != 0) { - // if (LoadStaticPropColorData(pProp, inst.ColorMeshHandle, studioHWData)) // todo - // return true; + if (LoadStaticPropColorData(pProp, inst.ColorMeshHandle, studioHWData!)) + return true; } colorMeshData.ColorMeshValid = false; @@ -1247,8 +1250,124 @@ private void ValidateStaticPropColorData(uint handle) { if (!HardwareConfig.SupportsColorOnSecondStream() || !StaticPropMgr().IsStaticProp(prop)) return; - // todo + if (!ModelLoader.g_bLoadedMapHasBakedPropLighting || StaticPropMgr().PropHasBakedLightingDisabled(prop)) + return; + + ReadOnlySpan fileName = StaticPropColorDataFileName(prop); + + Span buf = stackalloc byte[Unsafe.SizeOf()]; + if (!g_pFileSystem.ReadFile(fileName, "GAME", buf, 0)) + return; + + StudioHeader? studioHdr = MDLCache.GetStudioHdr(instance.Model!.Studio); + + ref readonly HardwareVerts.FileHeader vhvHdr = ref MemoryMarshal.Cast(buf)[0]; + if (vhvHdr.Version != HardwareVerts.VHV_VERSION || + vhvHdr.Checksum != (uint)studioHdr!.Checksum || + vhvHdr.VertexSize != 4) { + instance.Flags |= ModelInstanceFlags.DiskCompiledColorBad; + return; + } + + instance.Flags &= ~ModelInstanceFlags.DiskCompiledColorBad; + instance.Flags |= ModelInstanceFlags.HasDiskCompiledColor; + } + + static string StaticPropColorDataFileName(IHandleEntity prop) { + if (HardwareConfig.GetHDRType() == HDRType.None || ModelLoader.g_bBakedPropLightingNoSeparateHDR) + return $"sp_{StaticPropMgr().GetStaticPropIndex(prop)}.vhv"; + else + return $"sp_hdr_{StaticPropMgr().GetStaticPropIndex(prop)}.vhv"; + } + + class StaticPropAsyncContext + { + public DataCacheHandle_t ColorMeshHandle; + public ColorMeshData? ColorMeshData; + public int Meshes; + public uint RootLOD; + public string? Filename; + } + + static void StaticPropColorMeshCallback(in FileAsyncRequest request, int numReadBytes, FSAsyncStatus asyncStatus) { + StaticPropAsyncContext staticPropContext = (StaticPropAsyncContext)request.Context!; + + if (asyncStatus == FSAsyncStatus.OK) { + ReadOnlySpan data = request.Data.AsSpan(0, numReadBytes); + ref readonly HardwareVerts.FileHeader vhvHdr = ref MemoryMarshal.Cast(data)[0]; + + int startMesh; + for (startMesh = 0; startMesh < vhvHdr.Meshes; startMesh++) { + if (HardwareVerts.FileHeader.Mesh(data, startMesh).Lod == staticPropContext.RootLOD) + break; + } + + for (int meshID = startMesh; meshID < vhvHdr.Meshes; meshID++) { + int numVertexes = (int)HardwareVerts.FileHeader.Mesh(data, meshID).Vertexes; + if (numVertexes != staticPropContext.ColorMeshData!.MeshInfos![meshID - startMesh].NumVerts) + break; + + int id = meshID - startMesh; + + ReadOnlySpan input = HardwareVerts.FileHeader.VertexBase(data, meshID); + MeshBuilder meshBuilder = new(); + meshBuilder.Begin(staticPropContext.ColorMeshData.MeshInfos[id].Mesh!, MaterialPrimitiveType.Heterogenous, numVertexes, 0); + + for (int i = 0; i < numVertexes; i++) { + byte red = input[0]; + byte green = input[1]; + byte blue = input[2]; + meshBuilder.Specular4ub(blue, green, red, input[3]); + meshBuilder.AdvanceVertex(); + input = input[4..]; + } + + meshBuilder.End(); + } + } + + staticPropContext.ColorMeshData!.ColorMeshValid = true; + } + + private bool LoadStaticPropColorData(IHandleEntity? prop, DataCacheHandle_t colorMeshHandle, StudioHWData studioHWData) { + if (!ModelLoader.g_bLoadedMapHasBakedPropLighting || !r_proplightingfromdisk.GetBool()) + return false; + + ColorMeshData? colorMeshData = CacheGet(colorMeshHandle); + if (colorMeshData == null) + return false; + + if (colorMeshData.AsyncControl != null) + return true; + + string fileName = StaticPropColorDataFileName(prop!); + + colorMeshData.ColorMeshValid = false; + + StaticPropAsyncContext context = new() { + RootLOD = (uint)studioHWData.RootLOD, + Meshes = colorMeshData.NumMeshes, + ColorMeshHandle = colorMeshHandle, + ColorMeshData = colorMeshData, + Filename = fileName + }; + + FileAsyncRequest fileRequest = new() { + Context = context, + Callback = StaticPropColorMeshCallback, + Data = null, + FileName = fileName, + Offset = 0, + Flags = FSAsyncFlags.Sync, + Bytes = 0, + Priority = -1, + PathID = "GAME" + }; + + g_pFileSystem.AsyncRead(fileRequest, out colorMeshData.AsyncControl); + + return true; } From b4b6e912676b6b74d5806c5cad95f469a0d77861 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:17:39 +0300 Subject: [PATCH 20/57] Port MatRenderContext.SetRenderTarget --- Source.MaterialSystem/MatRenderContext.cs | 48 ++++++++++++++++++++--- Source.MaterialSystem/MaterialSystem.cs | 24 ++++++++---- 2 files changed, 60 insertions(+), 12 deletions(-) diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index 50e54d4ed..1c0bd1d01 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -1196,12 +1196,50 @@ public void SetPIXMarker(Color color, ReadOnlySpan name) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void SetRenderTarget(ITexture? texture) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void SetRenderTarget(ITexture? texture) => SetRenderTargetEx(0, texture); - public void SetRenderTargetEx(int renderTargetID, ITexture? texture) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); + public void SetRenderTargetEx(int renderTargetID, ITexture? newTarget) { + Assert(RenderTargetStack.Count > 0); + + ITexture? oldTarget = RenderTargetStack.Top()[renderTargetID]; + + RenderTargetStackElement newTOS = RenderTargetStack.Top(); + newTOS[renderTargetID] = newTarget; + RenderTargetStack.Pop(); + RenderTargetStack.Push(newTOS); + + if (newTarget != oldTarget) { + if (newTarget == null) { + if (renderTargetID == 0) { + ActiveViewport.TopLeftX = 0; + ActiveViewport.TopLeftY = 0; + shaderAPI.GetBackBufferDimensions(out ActiveViewport.Width, out ActiveViewport.Height); + shaderAPI.SetViewports(new Span(ref ActiveViewport)); + } + shaderAPI.SetRenderTargetEx(renderTargetID); + } + else { + bool reset = true; + if (renderTargetID == 0) { + ActiveViewport.TopLeftX = 0; + ActiveViewport.TopLeftY = 0; + ActiveViewport.Width = newTarget.GetActualWidth(); + ActiveViewport.Height = newTarget.GetActualHeight(); + shaderAPI.SetViewports(new Span(ref ActiveViewport)); + } + if (newTarget is ITextureInternal texInt) { + reset = !texInt.SetRenderTarget(renderTargetID); + if (reset) + shaderAPI.SetRenderTargetEx(renderTargetID); + } + + if (newTarget.GetImageFormat() == ImageFormat.RGBA16161616F) + shaderAPI.EnableLinearColorSpaceFrameBuffer(true); + else + shaderAPI.EnableLinearColorSpaceFrameBuffer(false); + } + } + CommitRenderTargetAndViewport(); } public void SetResetable(ColorCorrectionHandle_t handle, bool resetable) { diff --git a/Source.MaterialSystem/MaterialSystem.cs b/Source.MaterialSystem/MaterialSystem.cs index a55cbb0ea..c283c8aeb 100644 --- a/Source.MaterialSystem/MaterialSystem.cs +++ b/Source.MaterialSystem/MaterialSystem.cs @@ -1684,13 +1684,23 @@ public struct RenderTargetStackElement public ITexture? RenderTarget2; public ITexture? RenderTarget3; - public readonly ITexture? this[int index] => index switch { - 0 => RenderTarget0, - 1 => RenderTarget1, - 2 => RenderTarget2, - 3 => RenderTarget3, - _ => null - }; + public ITexture? this[int index] { + readonly get => index switch { + 0 => RenderTarget0, + 1 => RenderTarget1, + 2 => RenderTarget2, + 3 => RenderTarget3, + _ => null + }; + set { + switch (index) { + case 0: RenderTarget0 = value; break; + case 1: RenderTarget1 = value; break; + case 2: RenderTarget2 = value; break; + case 3: RenderTarget3 = value; break; + } + } + } public ITexture? DepthTexture; From 5c0a5642414d870f61bd6ec526e93c2995ba4d63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:24:41 +0300 Subject: [PATCH 21/57] Fix BaseVSShader.IsHDREnabled always returning false --- Source.StdShader.Gl46/BaseVSShader.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/Source.StdShader.Gl46/BaseVSShader.cs b/Source.StdShader.Gl46/BaseVSShader.cs index 169e8e555..fb268600f 100644 --- a/Source.StdShader.Gl46/BaseVSShader.cs +++ b/Source.StdShader.Gl46/BaseVSShader.cs @@ -1,3 +1,4 @@ +using Source.Common.Bitmap; using Source.Common.Commands; using Source.Common.MaterialSystem; using Source.Common.Mathematics; @@ -579,7 +580,21 @@ internal void SetModulationPixelShaderDynamicState_LinearColorSpace_LinearScale( } internal bool IsHDREnabled() { - // throw new NotImplementedException(); + HDRType hdrMode = HardwareConfig.GetHDRType(); + switch (hdrMode) { + case HDRType.None: + return false; + + case HDRType.Integer: + return true; + + case HDRType.Float: { + ITexture? rt = ShaderAPI!.GetRenderTargetEx(0); + if (rt != null && rt.GetImageFormat() == ImageFormat.RGBA16161616F) + return true; + } + break; + } return false; } From ca053dae2b68895c881ee809909ad861911d37f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:29:13 +0300 Subject: [PATCH 22/57] Port ShaderAPIGl46.CurrentTime --- Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index 26f0af03b..19e7fffcf 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -3475,7 +3475,7 @@ public void Color4ubv(ReadOnlySpan color) { } public double CurrentTime() { - throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); + return Platform.Time; } public void DisableTextureTransform(TextureStage textureStage) { From e6bd7ddf2f3a13f480981ddda6536be7c2123407 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:33:52 +0300 Subject: [PATCH 23/57] Port BaseShader.UsingEditor --- Source.StdShader.Gl46/BaseShader.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Source.StdShader.Gl46/BaseShader.cs b/Source.StdShader.Gl46/BaseShader.cs index b9a1867a8..c39bb7283 100644 --- a/Source.StdShader.Gl46/BaseShader.cs +++ b/Source.StdShader.Gl46/BaseShader.cs @@ -320,6 +320,13 @@ internal bool UsingFlashlight(IMaterialVar[] shaderParams) { return ShaderAPI!.InFlashlightMode(); } + internal bool UsingEditor(IMaterialVar[] shaderParams) { + if (IsSnapshotting()) + return IsFlag2Set(shaderParams, MaterialVarFlags2.UseEditor); + else + return ShaderAPI!.InEditorMode(); + } + protected void EnableAlphaBlending(ShaderBlendFactor srcFactor, ShaderBlendFactor dstFactor) { ShaderShadow!.EnableBlending(true); ShaderShadow!.BlendFunc(srcFactor, dstFactor); From 65acb128b00f8c5b28041c7f95a6aeac9819d274 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:41:27 +0300 Subject: [PATCH 24/57] Port BaseVSShader pixel constant gamma and W var helpers --- Source.StdShader.Gl46/BaseVSShader.cs | 43 +++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/Source.StdShader.Gl46/BaseVSShader.cs b/Source.StdShader.Gl46/BaseVSShader.cs index fb268600f..1a7abc271 100644 --- a/Source.StdShader.Gl46/BaseVSShader.cs +++ b/Source.StdShader.Gl46/BaseVSShader.cs @@ -493,6 +493,49 @@ public void SetPixelShaderConstant(int pixelReg, int constantVar) { ShaderAPI!.SetPixelShaderConstant(pixelReg, val); } + public void SetPixelShaderConstant(int pixelReg, int constantVar, int constantVar2) { + Assert(!IsSnapshotting()); + IMaterialVar[] shaderParams = Params!; + if (shaderParams == null || constantVar == -1 || constantVar2 == -1) + return; + + IMaterialVar pixelVar = shaderParams[constantVar]; + Assert(pixelVar != null); + IMaterialVar pixelVar2 = shaderParams[constantVar2]; + Assert(pixelVar2 != null); + + Span val = stackalloc float[4]; + if (pixelVar.GetVarType() == MaterialVarType.Vector) + pixelVar.GetVecValue(val[..3]); + else + val[0] = val[1] = val[2] = pixelVar.GetFloatValue(); + + val[3] = pixelVar2.GetFloatValue(); + ShaderAPI!.SetPixelShaderConstant(pixelReg, val); + } + + public void SetPixelShaderConstantGammaToLinear(int pixelReg, int constantVar) { + Assert(!IsSnapshotting()); + IMaterialVar[] shaderParams = Params!; + if (shaderParams == null || constantVar == -1) + return; + + IMaterialVar pixelVar = shaderParams[constantVar]; + Assert(pixelVar != null); + + Span val = stackalloc float[4]; + if (pixelVar.GetVarType() == MaterialVarType.Vector) + pixelVar.GetVecValue(val); + else + val[0] = val[1] = val[2] = val[3] = pixelVar.GetFloatValue(); + + val[0] = val[0] > 1.0f ? val[0] : MathLib.GammaToLinear(val[0]); + val[1] = val[1] > 1.0f ? val[1] : MathLib.GammaToLinear(val[1]); + val[2] = val[2] > 1.0f ? val[2] : MathLib.GammaToLinear(val[2]); + + ShaderAPI!.SetPixelShaderConstant(pixelReg, val); + } + public void InitUnlitGeneric(int baseTextureVar, int detailVar, int envmapVar, int envmapMaskVar) { IMaterialVar[] shaderParams = Params!; From 65bcab8b2475a0f45e9b0f69c14c08a197374712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:58:06 +0300 Subject: [PATCH 25/57] Port Water shader --- Game.Assets/hl2/shaders/water_gl460.fs | 209 ++++++++++ Game.Assets/hl2/shaders/water_gl460.vs | 102 +++++ Game.Assets/hl2/shaders/watercheap_gl460.fs | 126 ++++++ Game.Assets/hl2/shaders/watercheap_gl460.vs | 77 ++++ Source.StdShader.Gl46/Water.cs | 11 + Source.StdShader.Gl46/Water_DX90.cs | 402 ++++++++++++++++++++ Source.StdShader.Gl46/Water_DX9_HDR.cs | 14 + 7 files changed, 941 insertions(+) create mode 100644 Game.Assets/hl2/shaders/water_gl460.fs create mode 100644 Game.Assets/hl2/shaders/water_gl460.vs create mode 100644 Game.Assets/hl2/shaders/watercheap_gl460.fs create mode 100644 Game.Assets/hl2/shaders/watercheap_gl460.vs create mode 100644 Source.StdShader.Gl46/Water.cs create mode 100644 Source.StdShader.Gl46/Water_DX90.cs create mode 100644 Source.StdShader.Gl46/Water_DX9_HDR.cs diff --git a/Game.Assets/hl2/shaders/water_gl460.fs b/Game.Assets/hl2/shaders/water_gl460.fs new file mode 100644 index 000000000..da84c287a --- /dev/null +++ b/Game.Assets/hl2/shaders/water_gl460.fs @@ -0,0 +1,209 @@ +#version 460 +// STATIC: "BASETEXTURE" "0..1" +// STATIC: "MULTITEXTURE" "0..1" +// STATIC: "REFLECT" "0..1" +// STATIC: "REFRACT" "0..1" +// STATIC: "ABOVEWATER" "0..1" +// STATIC: "BLURRY_REFRACT" "0..1" +// STATIC: "NORMAL_DECODE_MODE" "0..0" + +// DYNAMIC: "PIXELFOGTYPE" "0..1" +// DYNAMIC: "WRITE_DEPTH_TO_DESTALPHA" "0..1" + +in vec2 vs_BumpTexCoord; +in vec3 vs_TangentEyeVect; +in vec4 vs_ReflectXY_RefractYX; +in float vs_W; +in vec4 vs_ProjPos; +#if MULTITEXTURE +in vec4 vs_ExtraBumpTexCoord; +#endif +#if BASETEXTURE +centroid in vec4 vs_LightmapTexCoord1And2; +centroid in vec4 vs_LightmapTexCoord3; +#endif + +layout(std140, binding = 6) uniform source_ps_constants { + vec4 ps_const[256]; +}; + +out vec4 fragColor; + +#include "common_gl460.fs" + +layout(binding = 0) uniform sampler2D RefractSampler; +#if BASETEXTURE +layout(binding = 1) uniform sampler2D BaseTextureSampler; +#endif +layout(binding = 2) uniform sampler2D ReflectSampler; +#if BASETEXTURE +layout(binding = 3) uniform sampler2D LightmapSampler; +#endif +layout(binding = 4) uniform sampler2D NormalSampler; + +#define vRefractTint ps_const[1] +#define vReflectTint ps_const[4] +#define g_ReflectRefractScale ps_const[5] +#define g_WaterFogColor ps_const[6] +#define g_WaterFogParams ps_const[7] +#define g_PixelFogParams ps_const[8] + +#define g_WaterFogStart g_WaterFogParams.x +#define g_WaterFogEndMinusStart g_WaterFogParams.y +#define g_Reflect_OverBright g_WaterFogParams.z + +void main() +{ + bool bReflect = REFLECT != 0; + bool bRefract = REFRACT != 0; + +#if MULTITEXTURE + vec4 vNormal = texture(NormalSampler, vs_BumpTexCoord); + vec4 vNormal1 = texture(NormalSampler, vs_ExtraBumpTexCoord.xy); + vec4 vNormal2 = texture(NormalSampler, vs_ExtraBumpTexCoord.zw); + vNormal = 0.33 * (vNormal + vNormal1 + vNormal2); + +#if ( NORMAL_DECODE_MODE == NORM_DECODE_ATI2N ) + vNormal.xy = vNormal.xy * 2.0 - 1.0; + vNormal.z = sqrt(1.0 - dot(vNormal.xy, vNormal.xy)); + vNormal.a = 1.0; +#else + vNormal.xyz = 2.0 * vNormal.xyz - 1.0; +#endif + +#else + vec4 vNormal = DecompressNormal(NormalSampler, vs_BumpTexCoord, NORMAL_DECODE_MODE); +#endif + + float ooW = 1.0 / vs_W; + + vec2 unwarpedRefractTexCoord = vs_ReflectXY_RefractYX.wz * ooW; + +#if ABOVEWATER + float waterFogDepthValue = texture(RefractSampler, unwarpedRefractTexCoord).a; +#else + float waterFogDepthValue = 1.0; +#endif + vec4 reflectRefractScale = g_ReflectRefractScale; +#if !BASETEXTURE +#if ( BLURRY_REFRACT == 0 ) + reflectRefractScale *= waterFogDepthValue; +#endif +#endif + + vec2 vReflectTexCoord; + vec2 vRefractTexCoord; + + vec4 vN; + vN.xy = vNormal.xy; + vN.w = vNormal.x; + vN.z = vNormal.y; + vec4 vDependentTexCoords = vN * vNormal.a * reflectRefractScale; + + vDependentTexCoords += (vs_ReflectXY_RefractYX * ooW); + vReflectTexCoord = vDependentTexCoords.xy; + vRefractTexCoord = vDependentTexCoords.wz; + + vec4 vReflectColor = texture(ReflectSampler, vReflectTexCoord); +#if BLURRY_REFRACT + vec2 ddx1 = vec2(0.005, 0.0); + vec2 ddy1 = vec2(0.0, 0.005); + vec4 vRefractColor = vec4(0.0); + + for (int ix = -2; ix <= 2; ix++) + { + for (int iy = -2; iy <= 2; iy++) + { + vRefractColor += texture(RefractSampler, vRefractTexCoord + ix * ddx1 + iy * ddy1); + } + } + float sumweights = 25.0; + + vRefractColor *= (1.0 / sumweights); + vReflectColor *= g_Reflect_OverBright; + vReflectColor *= vReflectTint; + vRefractColor *= vRefractTint; +# if ABOVEWATER + waterFogDepthValue = vRefractColor.a; +# endif +#else + vReflectColor *= vReflectTint; + vec4 vRefractColor = texture(RefractSampler, vRefractTexCoord); +# if ABOVEWATER + waterFogDepthValue = texture(RefractSampler, vRefractTexCoord).a; +# endif +#endif + + vec3 vEyeVect = normalize(vs_TangentEyeVect); + + float fNdotV = clamp(dot(vEyeVect, vNormal.xyz), 0.0, 1.0); + float fFresnel = pow(1.0 - fNdotV, 5.0); + +#if !BASETEXTURE + fFresnel *= clamp((waterFogDepthValue - 0.05) * 20.0, 0.0, 1.0); +#endif + +#if ABOVEWATER + vRefractColor = mix(vRefractColor, g_WaterFogColor * LINEAR_LIGHT_SCALE, clamp(waterFogDepthValue - 0.05, 0.0, 1.0)); +#else + float waterFogFactor = clamp((vs_ProjPos.z - g_WaterFogStart) / g_WaterFogEndMinusStart, 0.0, 1.0); + vRefractColor = mix(vRefractColor, g_WaterFogColor * LINEAR_LIGHT_SCALE, waterFogFactor); +#endif + +#if BASETEXTURE + vec4 baseSample = texture(BaseTextureSampler, vs_BumpTexCoord.xy); + vec2 bumpCoord1; + vec2 bumpCoord2; + vec2 bumpCoord3; + ComputeBumpedLightmapCoordinates(vs_LightmapTexCoord1And2, vs_LightmapTexCoord3.xy, + bumpCoord1, bumpCoord2, bumpCoord3); + + vec4 lightmapSample1 = texture(LightmapSampler, bumpCoord1); + vec3 lightmapColor1 = lightmapSample1.rgb; + vec3 lightmapColor2 = texture(LightmapSampler, bumpCoord2).rgb; + vec3 lightmapColor3 = texture(LightmapSampler, bumpCoord3).rgb; + + vec3 dp; + dp.x = clamp(dot(vNormal.xyz, bumpBasis[0]), 0.0, 1.0); + dp.y = clamp(dot(vNormal.xyz, bumpBasis[1]), 0.0, 1.0); + dp.z = clamp(dot(vNormal.xyz, bumpBasis[2]), 0.0, 1.0); + dp *= dp; + + vec3 diffuseLighting = dp.x * lightmapColor1 + + dp.y * lightmapColor2 + + dp.z * lightmapColor3; + float sum = dot(dp, vec3(1.0, 1.0, 1.0)); + diffuseLighting *= LIGHT_MAP_SCALE / sum; + vec3 diffuseComponent = baseSample.rgb * diffuseLighting; +#endif + + vec4 result; + if (bReflect && bRefract) + { + result = mix(vRefractColor, vReflectColor, fFresnel); + } + else if (bReflect) + { +#if BASETEXTURE + result = vec4(diffuseComponent, 1.0) + vReflectColor * fFresnel * baseSample.a; +#else + result = vReflectColor; +#endif + } + else if (bRefract) + { + result = vRefractColor; + } + else + { + result = vec4(0.0, 0.0, 0.0, 0.0); + } + +#if (PIXELFOGTYPE == PIXEL_FOG_TYPE_RANGE) + float fogFactor = CalcRangeFog(vs_ProjPos.z, g_PixelFogParams.x, g_PixelFogParams.z, g_PixelFogParams.w); +#else + float fogFactor = 0.0; +#endif + + fragColor = FinalOutput(vec4(result.rgb, 1.0), fogFactor, PIXELFOGTYPE, TONEMAP_SCALE_NONE, WRITE_DEPTH_TO_DESTALPHA != 0, vs_ProjPos.z); +} diff --git a/Game.Assets/hl2/shaders/water_gl460.vs b/Game.Assets/hl2/shaders/water_gl460.vs new file mode 100644 index 000000000..01ffc9f46 --- /dev/null +++ b/Game.Assets/hl2/shaders/water_gl460.vs @@ -0,0 +1,102 @@ +#version 460 +// STATIC: "BASETEXTURE" "0..1" +// STATIC: "MULTITEXTURE" "0..1" + +layout(location = 0) in vec3 v_Position; +layout(location = 1) in vec3 v_Normal; +layout(location = 4) in vec3 v_TangentS; +layout(location = 5) in vec3 v_TangentT; +layout(location = 10) in vec2 v_TexCoord0; +layout(location = 11) in vec2 v_TexCoord1; +layout(location = 12) in vec2 v_TexCoord2; + +layout(std140, binding = 0) uniform source_matrices { + mat4 viewMatrix; + mat4 projectionMatrix; + mat4 modelMatrix; +}; + +layout(std140, binding = 2) uniform source_vertex_sharedUBO { + int numBones; + int lightCount; + int vertexSharedPad0; + int vertexSharedPad1; + vec4 lightEnabled; +}; + +layout(std140, binding = 5) uniform source_vs_constants { + vec4 vs_const[256]; +}; + +const int VERTEX_SHADER_CAMERA_POS = 2; +const int VERTEX_SHADER_AMBIENT_LIGHT = 21; +const int VERTEX_SHADER_LIGHT_INFO = 27; +const int SHADER_SPECIFIC_CONST_1 = 49; +const int SHADER_SPECIFIC_CONST_3 = 51; + +#include "common_gl460.vs" + +#define cBumpTexCoordTransform0 vs_const[SHADER_SPECIFIC_CONST_1 + 0] +#define cBumpTexCoordTransform1 vs_const[SHADER_SPECIFIC_CONST_1 + 1] +#define TexOffsets vs_const[SHADER_SPECIFIC_CONST_3] + +out vec2 vs_BumpTexCoord; +out vec3 vs_TangentEyeVect; +out vec4 vs_ReflectXY_RefractYX; +out float vs_W; +out vec4 vs_ProjPos; +#if MULTITEXTURE +out vec4 vs_ExtraBumpTexCoord; +#endif +#if BASETEXTURE +centroid out vec4 vs_LightmapTexCoord1And2; +centroid out vec4 vs_LightmapTexCoord3; +#endif + +void main() +{ + vec3 vObjNormal = v_Normal; + + vec3 vWorldPos = (modelMatrix * vec4(v_Position, 1.0)).xyz; + vec4 vProjPos = projectionMatrix * viewMatrix * vec4(vWorldPos, 1.0); + gl_Position = vProjPos; + vs_ProjPos = vProjPos; + + vec2 vReflectPos; + vReflectPos.x = vProjPos.x; + vReflectPos.y = -vProjPos.y; + vReflectPos = (vReflectPos + vProjPos.w) * 0.5; + + vec2 vRefractPos = (vProjPos.xy + vProjPos.w) * 0.5; + + vs_ReflectXY_RefractYX = vec4(vReflectPos.x, vReflectPos.y, vRefractPos.y, vRefractPos.x); + vs_W = vProjPos.w; + + vec3 vWorldEyeVect = cEyePos - vWorldPos; + vs_TangentEyeVect.x = dot(vWorldEyeVect, v_TangentS); + vs_TangentEyeVect.y = dot(vWorldEyeVect, v_TangentT); + vs_TangentEyeVect.z = dot(vWorldEyeVect, vObjNormal); + + vs_BumpTexCoord.x = dot(v_TexCoord0, cBumpTexCoordTransform0.xy) + cBumpTexCoordTransform0.w; + vs_BumpTexCoord.y = dot(v_TexCoord0, cBumpTexCoordTransform1.xy) + cBumpTexCoordTransform1.w; + float f45x = v_TexCoord0.x + v_TexCoord0.y; + float f45y = v_TexCoord0.y - v_TexCoord0.x; +#if MULTITEXTURE + vs_ExtraBumpTexCoord.x = f45x * 0.1 + TexOffsets.x; + vs_ExtraBumpTexCoord.y = f45y * 0.1 + TexOffsets.y; + vs_ExtraBumpTexCoord.z = v_TexCoord0.y * 0.45 + TexOffsets.z; + vs_ExtraBumpTexCoord.w = v_TexCoord0.x * 0.45 + TexOffsets.w; +#endif + +#if BASETEXTURE + vs_LightmapTexCoord1And2.xy = v_TexCoord1 + v_TexCoord2; + + vec2 lightmapTexCoord2 = vs_LightmapTexCoord1And2.xy + v_TexCoord2; + vec2 lightmapTexCoord3 = lightmapTexCoord2 + v_TexCoord2; + + vs_LightmapTexCoord1And2.w = lightmapTexCoord2.x; + vs_LightmapTexCoord1And2.z = lightmapTexCoord2.y; + + vs_LightmapTexCoord3 = vec4(lightmapTexCoord3, 0.0, 0.0); +#endif +} diff --git a/Game.Assets/hl2/shaders/watercheap_gl460.fs b/Game.Assets/hl2/shaders/watercheap_gl460.fs new file mode 100644 index 000000000..705c6b69a --- /dev/null +++ b/Game.Assets/hl2/shaders/watercheap_gl460.fs @@ -0,0 +1,126 @@ +#version 460 +// STATIC: "MULTITEXTURE" "0..1" +// STATIC: "FRESNEL" "0..1" +// STATIC: "BLEND" "0..1" +// STATIC: "REFRACTALPHA" "0..1" +// STATIC: "HDRTYPE" "0..2" +// STATIC: "NORMAL_DECODE_MODE" "0..0" + +// DYNAMIC: "HDRENABLED" "0..1" +// DYNAMIC: "PIXELFOGTYPE" "0..1" + +in vec2 vs_NormalMapTexCoord; +in vec3 vs_WorldVertToEyeVector; +in mat3 vs_TangentSpaceTranspose; +in vec4 vs_Refract_W_ProjZ; +#if MULTITEXTURE +in vec4 vs_ExtraBumpTexCoord; +#endif + +layout(std140, binding = 6) uniform source_ps_constants { + vec4 ps_const[256]; +}; + +out vec4 fragColor; + +#include "common_gl460.fs" + +layout(binding = 0) uniform samplerCube EnvmapSampler; +layout(binding = 1) uniform sampler2D NormalMapSampler; +#if REFRACTALPHA +layout(binding = 2) uniform sampler2D RefractSampler; +#endif + +#define g_WaterFogColor ps_const[0].rgb +#define g_CheapWaterParams ps_const[1] +#define g_ReflectTint ps_const[2] +#define g_PixelFogParams ps_const[3] + +#define g_CheapWaterStart g_CheapWaterParams.x +#define g_CheapWaterEnd g_CheapWaterParams.y +#define g_CheapWaterDeltaRecip g_CheapWaterParams.z +#define g_CheapWaterStartDivDelta g_CheapWaterParams.w + +void main() +{ + bool bBlend = BLEND != 0; + +#if MULTITEXTURE + vec3 vNormal = texture(NormalMapSampler, vs_NormalMapTexCoord).xyz; + vec3 vNormal1 = texture(NormalMapSampler, vs_ExtraBumpTexCoord.xy).xyz; + vec3 vNormal2 = texture(NormalMapSampler, vs_ExtraBumpTexCoord.zw).xyz; + vNormal = 0.33 * (vNormal + vNormal1 + vNormal2); + +#if ( NORMAL_DECODE_MODE == NORM_DECODE_ATI2N ) + vNormal.xy = vNormal.xy * 2.0 - 1.0; + vNormal.z = sqrt(1.0 - dot(vNormal.xy, vNormal.xy)); +#else + vNormal = 2.0 * vNormal - 1.0; +#endif + +#else + vec3 vNormal = DecompressNormal(NormalMapSampler, vs_NormalMapTexCoord, NORMAL_DECODE_MODE).xyz; +#endif + + vec3 worldSpaceNormal = vs_TangentSpaceTranspose * vNormal; + vec3 worldSpaceEye; + + float flWorldSpaceDist = 1.0; + + if (bBlend) + { + worldSpaceEye = vs_WorldVertToEyeVector; + flWorldSpaceDist = length(worldSpaceEye); + worldSpaceEye /= flWorldSpaceDist; + } + else + { + worldSpaceEye = normalize(vs_WorldVertToEyeVector); + } + + vec3 reflectVect = CalcReflectionVectorUnnormalized(worldSpaceNormal, worldSpaceEye); + vec3 specularLighting = ENV_MAP_SCALE * texture(EnvmapSampler, reflectVect).rgb; + specularLighting *= g_ReflectTint.rgb; + +#if FRESNEL + float flDotResult = dot(worldSpaceEye, worldSpaceNormal); + flDotResult = 1.0 - max(0.0, flDotResult); + + float flFresnelFactor = flDotResult * flDotResult; + flFresnelFactor *= flFresnelFactor; + flFresnelFactor *= flDotResult; +#else + float flFresnelFactor = g_ReflectTint.a; +#endif + + float flAlpha; + if (bBlend) + { + float flReflectAmount = clamp(flWorldSpaceDist * g_CheapWaterDeltaRecip - g_CheapWaterStartDivDelta, 0.0, 1.0); + flAlpha = clamp(flFresnelFactor + flReflectAmount, 0.0, 1.0); + +#if REFRACTALPHA + float ooW = 1.0 / vs_Refract_W_ProjZ.z; + vec2 unwarpedRefractTexCoord = vs_Refract_W_ProjZ.xy * ooW; + float fogDepthValue = texture(RefractSampler, unwarpedRefractTexCoord).a; + flAlpha *= clamp((fogDepthValue - 0.05) * 20.0, 0.0, 1.0); +#endif + } + else + { + flAlpha = 1.0; +#if HDRTYPE == 0 || HDRENABLED == 0 + specularLighting = mix(g_WaterFogColor, specularLighting, flFresnelFactor); +#else + specularLighting = mix(GammaToLinear(g_WaterFogColor), specularLighting, flFresnelFactor); +#endif + } + +#if (PIXELFOGTYPE == PIXEL_FOG_TYPE_RANGE) + float fogFactor = CalcRangeFog(vs_Refract_W_ProjZ.w, g_PixelFogParams.x, g_PixelFogParams.z, g_PixelFogParams.w); +#else + float fogFactor = 0.0; +#endif + + fragColor = FinalOutput(vec4(specularLighting, flAlpha), fogFactor, PIXELFOGTYPE, TONEMAP_SCALE_LINEAR); +} diff --git a/Game.Assets/hl2/shaders/watercheap_gl460.vs b/Game.Assets/hl2/shaders/watercheap_gl460.vs new file mode 100644 index 000000000..66f2f00a0 --- /dev/null +++ b/Game.Assets/hl2/shaders/watercheap_gl460.vs @@ -0,0 +1,77 @@ +#version 460 +// STATIC: "BLEND" "0..1" + +layout(location = 0) in vec3 v_Position; +layout(location = 1) in vec3 v_Normal; +layout(location = 4) in vec3 v_TangentS; +layout(location = 5) in vec3 v_TangentT; +layout(location = 10) in vec2 v_TexCoord0; + +layout(std140, binding = 0) uniform source_matrices { + mat4 viewMatrix; + mat4 projectionMatrix; + mat4 modelMatrix; +}; + +layout(std140, binding = 2) uniform source_vertex_sharedUBO { + int numBones; + int lightCount; + int vertexSharedPad0; + int vertexSharedPad1; + vec4 lightEnabled; +}; + +layout(std140, binding = 5) uniform source_vs_constants { + vec4 vs_const[256]; +}; + +const int VERTEX_SHADER_CAMERA_POS = 2; +const int VERTEX_SHADER_AMBIENT_LIGHT = 21; +const int VERTEX_SHADER_LIGHT_INFO = 27; +const int SHADER_SPECIFIC_CONST_3 = 51; + +#include "common_gl460.vs" + +#define VSHADER_VECT_SCALE 1.0 +#define TexOffsets vs_const[SHADER_SPECIFIC_CONST_3] + +out vec2 vs_NormalMapTexCoord; +out vec3 vs_WorldVertToEyeVector; +out mat3 vs_TangentSpaceTranspose; +out vec4 vs_Refract_W_ProjZ; +out vec4 vs_ExtraBumpTexCoord; + +void main() +{ + vec3 vObjNormal = v_Normal; + + vec3 worldPos = (modelMatrix * vec4(v_Position, 1.0)).xyz; + vec4 projPos = projectionMatrix * viewMatrix * vec4(worldPos, 1.0); + gl_Position = projPos; + + vs_Refract_W_ProjZ = vec4(0.0); +#if BLEND + vs_Refract_W_ProjZ.xy = (projPos.xy + projPos.w) * 0.5; + vs_Refract_W_ProjZ.z = projPos.w; +#endif + + vs_Refract_W_ProjZ.w = projPos.z; + + vec3 worldTangentS = mat3(modelMatrix) * v_TangentS; + vec3 worldTangentT = mat3(modelMatrix) * v_TangentT; + vec3 worldNormal = mat3(modelMatrix) * vObjNormal; + vs_TangentSpaceTranspose[0] = worldTangentS; + vs_TangentSpaceTranspose[1] = worldTangentT; + vs_TangentSpaceTranspose[2] = worldNormal; + + vs_WorldVertToEyeVector = VSHADER_VECT_SCALE * (cEyePos - worldPos); + + vs_NormalMapTexCoord = v_TexCoord0; + + float f45x = v_TexCoord0.x + v_TexCoord0.y; + float f45y = v_TexCoord0.y - v_TexCoord0.x; + vs_ExtraBumpTexCoord.x = f45x * 0.1 + TexOffsets.x; + vs_ExtraBumpTexCoord.y = f45y * 0.1 + TexOffsets.y; + vs_ExtraBumpTexCoord.z = v_TexCoord0.y * 0.45 + TexOffsets.z; + vs_ExtraBumpTexCoord.w = v_TexCoord0.x * 0.45 + TexOffsets.w; +} diff --git a/Source.StdShader.Gl46/Water.cs b/Source.StdShader.Gl46/Water.cs new file mode 100644 index 000000000..3cb8ba327 --- /dev/null +++ b/Source.StdShader.Gl46/Water.cs @@ -0,0 +1,11 @@ +using Source.Common.MaterialSystem; + +namespace Source.StdShader.Gl46; + +public class Water : BaseVSShader +{ + public static string HelpString = "Help for Water"; + public static int Flags = 0; + + public override string? GetFallbackShader(IMaterialVar[] vars) => "Water_DX9_HDR"; +} diff --git a/Source.StdShader.Gl46/Water_DX90.cs b/Source.StdShader.Gl46/Water_DX90.cs new file mode 100644 index 000000000..4b558b47e --- /dev/null +++ b/Source.StdShader.Gl46/Water_DX90.cs @@ -0,0 +1,402 @@ +using Source.Common; +using Source.Common.Bitmap; +using Source.Common.Commands; +using Source.Common.MaterialSystem; +using Source.Common.Mathematics; +using Source.Common.ShaderAPI; +using Source.Common.ShaderLib; + +namespace Source.StdShader.Gl46; + +public class Water_DX90 : BaseVSShader +{ + public static string HelpString = "Help for Water"; + public static int Flags = 0; + public static List ShaderParams = []; + + public class ShaderParam + { + public readonly ShaderParamInfo Info; + public readonly int Index; + public ShaderParam(string name, ShaderParamType type, ReadOnlySpan defaultParam, ReadOnlySpan help, int flags = 0) { + Info.Name = name; + Info.Type = type; + Info.DefaultValue = new(defaultParam); + Info.Help = new(help); + Info.Flags = (ShaderParamFlags)flags; + Index = (int)ShaderMaterialVars.Count + ShaderParams.Count; + ShaderParams.Add(this); + } + public static implicit operator int(ShaderParam param) => param.Index; + public ReadOnlySpan GetName() => Info.Name; + public ShaderParamType GetType() => Info.Type; + public ReadOnlySpan GetDefaultValue() => Info.DefaultValue; + public int GetFlags() => (int)Info.Flags; + public ReadOnlySpan GetHelp() => Info.Help; + } + + public static readonly ShaderParam REFRACTTEXTURE = new($"${nameof(REFRACTTEXTURE)}", ShaderParamType.Texture, "_rt_WaterRefraction", ""); + public static readonly ShaderParam REFLECTTEXTURE = new($"${nameof(REFLECTTEXTURE)}", ShaderParamType.Texture, "_rt_WaterReflection", ""); + public static readonly ShaderParam REFRACTAMOUNT = new($"${nameof(REFRACTAMOUNT)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam REFRACTTINT = new($"${nameof(REFRACTTINT)}", ShaderParamType.Color, "[1 1 1]", "refraction tint"); + public static readonly ShaderParam REFLECTAMOUNT = new($"${nameof(REFLECTAMOUNT)}", ShaderParamType.Float, "0.8", ""); + public static readonly ShaderParam REFLECTTINT = new($"${nameof(REFLECTTINT)}", ShaderParamType.Color, "[1 1 1]", "reflection tint"); + public static readonly ShaderParam NORMALMAP = new($"${nameof(NORMALMAP)}", ShaderParamType.Texture, "dev/water_normal", "normal map"); + public static readonly ShaderParam BUMPFRAME = new($"${nameof(BUMPFRAME)}", ShaderParamType.Integer, "0", "frame number for $bumpmap"); + public static readonly ShaderParam BUMPTRANSFORM = new($"${nameof(BUMPTRANSFORM)}", ShaderParamType.Matrix, "center .5 .5 scale 1 1 rotate 0 translate 0 0", "$bumpmap texcoord transform"); + public static readonly ShaderParam SCALE = new($"${nameof(SCALE)}", ShaderParamType.Vec2, "[1 1]", ""); + public static readonly ShaderParam TIME = new($"${nameof(TIME)}", ShaderParamType.Float, "", ""); + public static readonly ShaderParam WATERDEPTH = new($"${nameof(WATERDEPTH)}", ShaderParamType.Float, "", ""); + public static readonly ShaderParam CHEAPWATERSTARTDISTANCE = new($"${nameof(CHEAPWATERSTARTDISTANCE)}", ShaderParamType.Float, "", "This is the distance from the eye in inches that the shader should start transitioning to a cheaper water shader."); + public static readonly ShaderParam CHEAPWATERENDDISTANCE = new($"${nameof(CHEAPWATERENDDISTANCE)}", ShaderParamType.Float, "", "This is the distance from the eye in inches that the shader should finish transitioning to a cheaper water shader."); + public static readonly ShaderParam ENVMAP = new($"${nameof(ENVMAP)}", ShaderParamType.Texture, "env_cubemap", "envmap"); + public static readonly ShaderParam ENVMAPFRAME = new($"${nameof(ENVMAPFRAME)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam FOGCOLOR = new($"${nameof(FOGCOLOR)}", ShaderParamType.Color, "", ""); + public static readonly ShaderParam FORCECHEAP = new($"${nameof(FORCECHEAP)}", ShaderParamType.Bool, "", ""); + public static readonly ShaderParam FORCEEXPENSIVE = new($"${nameof(FORCEEXPENSIVE)}", ShaderParamType.Bool, "", ""); + public static readonly ShaderParam REFLECTENTITIES = new($"${nameof(REFLECTENTITIES)}", ShaderParamType.Bool, "", ""); + public static readonly ShaderParam FOGSTART = new($"${nameof(FOGSTART)}", ShaderParamType.Float, "", ""); + public static readonly ShaderParam FOGEND = new($"${nameof(FOGEND)}", ShaderParamType.Float, "", ""); + public static readonly ShaderParam ABOVEWATER = new($"${nameof(ABOVEWATER)}", ShaderParamType.Bool, "", ""); + public static readonly ShaderParam REFLECTBLENDFACTOR = new($"${nameof(REFLECTBLENDFACTOR)}", ShaderParamType.Float, "1.0", ""); + public static readonly ShaderParam NOFRESNEL = new($"${nameof(NOFRESNEL)}", ShaderParamType.Bool, "0", ""); + public static readonly ShaderParam NOLOWENDLIGHTMAP = new($"${nameof(NOLOWENDLIGHTMAP)}", ShaderParamType.Bool, "0", ""); + public static readonly ShaderParam SCROLL1 = new($"${nameof(SCROLL1)}", ShaderParamType.Color, "", ""); + public static readonly ShaderParam SCROLL2 = new($"${nameof(SCROLL2)}", ShaderParamType.Color, "", ""); + public static readonly ShaderParam BLURREFRACT = new($"${nameof(BLURREFRACT)}", ShaderParamType.Bool, "0", "Cause the refraction to be blurry on ps2b hardware"); + + static readonly ConVar r_waterforceexpensive = new("r_waterforceexpensive", "0", FCvar.Archive); + + const float PSHADER_VECT_SCALE = 1.0f; + const float VSHADER_VECT_SCALE = 1.0f; + + public override int GetFlags() => Flags; + public override int GetNumParams() => base.GetNumParams() + ShaderParams.Count; + public override ReadOnlySpan GetParamName(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamName(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetName(); + } + public override ReadOnlySpan GetParamHelp(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamHelp(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetHelp(); + } + public override ShaderParamType GetParamType(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamType(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetType(); + } + public override ReadOnlySpan GetParamDefault(int paramIndex) { + int baseClassParamCount = base.GetNumParams(); + if (paramIndex < baseClassParamCount) + return base.GetParamDefault(paramIndex); + else + return ShaderParams[paramIndex - baseClassParamCount].GetDefaultValue(); + } + + protected override void OnInitShaderParams(IMaterialVar[] vars, ReadOnlySpan materialName) { + if (!vars[ABOVEWATER].IsDefined()) { + Warning($"***need to set $abovewater for material {materialName}\n"); + vars[ABOVEWATER].SetIntValue(1); + } + SetFlags2(vars, MaterialVarFlags2.NeedsTangentSpaces); + if (!vars[CHEAPWATERSTARTDISTANCE].IsDefined()) + vars[CHEAPWATERSTARTDISTANCE].SetFloatValue(500.0f); + if (!vars[CHEAPWATERENDDISTANCE].IsDefined()) + vars[CHEAPWATERENDDISTANCE].SetFloatValue(1000.0f); + if (!vars[SCALE].IsDefined()) + vars[SCALE].SetVecValue(1.0f, 1.0f); + if (!vars[SCROLL1].IsDefined()) + vars[SCROLL1].SetVecValue(0.0f, 0.0f, 0.0f); + if (!vars[SCROLL2].IsDefined()) + vars[SCROLL2].SetVecValue(0.0f, 0.0f, 0.0f); + if (!vars[FOGCOLOR].IsDefined()) { + vars[FOGCOLOR].SetVecValue(1.0f, 0.0f, 0.0f); + Warning($"material {materialName} needs to have a $fogcolor.\n"); + } + if (!vars[REFLECTENTITIES].IsDefined()) + vars[REFLECTENTITIES].SetIntValue(0); + if (!vars[REFLECTBLENDFACTOR].IsDefined()) + vars[REFLECTBLENDFACTOR].SetFloatValue(1.0f); + + if (!vars[FORCEEXPENSIVE].IsDefined()) + vars[FORCEEXPENSIVE].SetIntValue(1); + if (vars[FORCEEXPENSIVE].GetIntValue() != 0 && vars[FORCECHEAP].GetIntValue() != 0) + vars[FORCEEXPENSIVE].SetIntValue(0); + + if (vars[NOLOWENDLIGHTMAP].GetIntValue() == 0) + SetFlags2(vars, MaterialVarFlags2.LightingLightmap); + + SetFlags2(vars, MaterialVarFlags2.LightingLightmap); + if (Config.UseBumpmapping() && vars[NORMALMAP].IsDefined()) + SetFlags2(vars, MaterialVarFlags2.LightingBumpedLightmap); + } + + protected override void OnInitShaderInstance(IMaterialVar[] vars, ReadOnlySpan materialName) { + Assert(vars[WATERDEPTH].IsDefined()); + + if (vars[REFRACTTEXTURE].IsDefined()) + LoadTexture(REFRACTTEXTURE, (int)TextureFlags.SRGB); + if (vars[REFLECTTEXTURE].IsDefined()) + LoadTexture(REFLECTTEXTURE, (int)TextureFlags.SRGB); + if (vars[ENVMAP].IsDefined()) + LoadCubeMap(ENVMAP, (int)TextureFlags.SRGB); + if (vars[NORMALMAP].IsDefined()) + LoadBumpMap(NORMALMAP); + if (vars[(int)ShaderMaterialVars.BaseTexture].IsDefined()) + LoadTexture((int)ShaderMaterialVars.BaseTexture, (int)TextureFlags.SRGB); + } + + void DrawReflectionRefraction(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, bool reflection, bool refraction) { + if (IsSnapshotting()) { + SetInitialShadowState(); + if (refraction) { + ShaderShadow.EnableTexture(Sampler.Sampler0, true); + ShaderShadow.EnableTexture(Sampler.Sampler1, true); + ShaderShadow.EnableSRGBRead(Sampler.Sampler0, true); + } + if (reflection) { + ShaderShadow.EnableTexture(Sampler.Sampler2, true); + ShaderShadow.EnableTexture(Sampler.Sampler3, true); + ShaderShadow.EnableSRGBRead(Sampler.Sampler2, true); + if (vars[(int)ShaderMaterialVars.BaseTexture].IsTexture()) { + ShaderShadow.EnableTexture(Sampler.Sampler1, true); + ShaderShadow.EnableSRGBRead(Sampler.Sampler1, true); + ShaderShadow.EnableTexture(Sampler.Sampler3, true); + ShaderShadow.EnableSRGBRead(Sampler.Sampler3, true); + } + } + ShaderShadow.EnableTexture(Sampler.Sampler4, true); + ShaderShadow.EnableTexture(Sampler.Sampler5, true); + + VertexFormat fmt = VertexFormat.Position | VertexFormat.Normal | VertexFormat.TangentS | VertexFormat.TangentT; + + int numTexCoords = 1; + if (vars[(int)ShaderMaterialVars.BaseTexture].IsTexture()) + numTexCoords = 3; + ShaderShadow.VertexShaderVertexFormat(fmt, numTexCoords, null, 0); + + Span scroll1 = stackalloc float[4]; + vars[SCROLL1].GetVecValue(scroll1); + + StaticShaderIndex vshIndex = new(ShaderShadow, ShaderType.Vertex, "water"); + vshIndex.Set("MULTITEXTURE", MathF.Abs(scroll1[0]) > 0.0f); + vshIndex.Set("BASETEXTURE", vars[(int)ShaderMaterialVars.BaseTexture].IsTexture()); + ShaderShadow.SetVertexShader("water", vshIndex.GetIndex()); + + StaticShaderIndex pshIndex = new(ShaderShadow, ShaderType.Pixel, "water"); + pshIndex.Set("REFLECT", reflection); + pshIndex.Set("REFRACT", refraction); + pshIndex.Set("ABOVEWATER", vars[ABOVEWATER].GetIntValue()); + pshIndex.Set("MULTITEXTURE", MathF.Abs(scroll1[0]) > 0.0f); + pshIndex.Set("BASETEXTURE", vars[(int)ShaderMaterialVars.BaseTexture].IsTexture()); + pshIndex.Set("BLURRY_REFRACT", vars[BLURREFRACT].GetIntValue()); + pshIndex.Set("NORMAL_DECODE_MODE", (int)NormalDecodeMode.None); + ShaderShadow.SetPixelShader("water", pshIndex.GetIndex()); + + ShaderShadow.EnableSRGBWrite(true); + + ShaderShadow.EnableAlphaWrites(true); + } + else { + shaderAPI.SetDefaultState(); + if (refraction) + BindTexture(Sampler.Sampler0, REFRACTTEXTURE, -1); + if (reflection) + BindTexture(Sampler.Sampler2, REFLECTTEXTURE, -1); + BindTexture(Sampler.Sampler4, NORMALMAP, BUMPFRAME); + if (vars[(int)ShaderMaterialVars.BaseTexture].IsTexture()) { + BindTexture(Sampler.Sampler1, (int)ShaderMaterialVars.BaseTexture, (int)ShaderMaterialVars.Frame); + shaderAPI.BindStandardTexture(Sampler.Sampler3, StandardTextureId.Lightmap); + } + + shaderAPI.BindStandardTexture(Sampler.Sampler5, StandardTextureId.NormalizationCubemapSigned); + + if (refraction) + SetPixelShaderConstantGammaToLinear(1, REFRACTTINT); + if (reflection) { + if (HardwareConfig.GetHDRType() == HDRType.Integer) { + Span gammaReflectTint = stackalloc float[3]; + vars[REFLECTTINT].GetVecValue(gammaReflectTint); + Span linearReflectTint = [ + MathLib.GammaToLinear(gammaReflectTint[0]) * 4.0f, + MathLib.GammaToLinear(gammaReflectTint[1]) * 4.0f, + MathLib.GammaToLinear(gammaReflectTint[2]) * 4.0f, + 1.0f + ]; + shaderAPI.SetPixelShaderConstant(4, linearReflectTint, 1); + } + else + SetPixelShaderConstantGammaToLinear(4, REFLECTTINT); + } + + SetVertexShaderTextureTransform(VertexShaderConst.ShaderSpecificConst1, BUMPTRANSFORM); + + float curtime = (float)shaderAPI.CurrentTime(); + Span vc0 = stackalloc float[4]; + Span v0 = stackalloc float[4]; + vars[SCROLL1].GetVecValue(v0); + vc0[0] = curtime * v0[0]; + vc0[1] = curtime * v0[1]; + vars[SCROLL2].GetVecValue(v0); + vc0[2] = curtime * v0[0]; + vc0[3] = curtime * v0[1]; + shaderAPI.SetVertexShaderConstant(VertexShaderConst.ShaderSpecificConst3, vc0, 1); + + Span c0 = [1.0f / 3.0f, 1.0f / 3.0f, 1.0f / 3.0f, 0.0f]; + shaderAPI.SetPixelShaderConstant(0, c0, 1); + + Span c2 = [0.5f, 0.5f, 0.5f, 0.5f]; + shaderAPI.SetPixelShaderConstant(2, c2, 1); + + Span c3 = [1.0f, 0.0f, 0.0f, 0.0f]; + shaderAPI.SetPixelShaderConstant(3, c3, 1); + + Span c5 = [vars[REFLECTAMOUNT].GetFloatValue(), vars[REFLECTAMOUNT].GetFloatValue(), + vars[REFRACTAMOUNT].GetFloatValue(), vars[REFRACTAMOUNT].GetFloatValue()]; + shaderAPI.SetPixelShaderConstant(5, c5, 1); + + SetPixelShaderConstantGammaToLinear(6, FOGCOLOR); + + Span c7 = [ + vars[FOGSTART].GetFloatValue(), + vars[FOGEND].GetFloatValue() - vars[FOGSTART].GetFloatValue(), + 1.0f, + 0.0f + ]; + if (HardwareConfig.GetHDRType() == HDRType.Integer) + c7[2] = 4.0f; + shaderAPI.SetPixelShaderConstant(7, c7, 1); + + DynamicShaderIndex vshIndex = new(shaderAPI, ShaderType.Vertex); + shaderAPI.SetVertexShaderIndex(vshIndex.GetIndex()); + + DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo()); + pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", shaderAPI.ShouldWriteDepthToDestAlpha()); + shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); + } + Draw(); + } + + void DrawCheapWater(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, bool blend, bool refraction) { + if (IsSnapshotting()) { + SetInitialShadowState(); + + if (UsingEditor(vars)) + ShaderShadow.EnableCulling(false); + + if (blend) + EnableAlphaBlending(ShaderBlendFactor.SrcAlpha, ShaderBlendFactor.OneMinusSrcAlpha); + ShaderShadow.EnableTexture(Sampler.Sampler0, true); + ShaderShadow.EnableTexture(Sampler.Sampler1, true); + if (refraction && blend) + ShaderShadow.EnableTexture(Sampler.Sampler2, true); + ShaderShadow.EnableTexture(Sampler.Sampler6, true); + VertexFormat fmt = VertexFormat.Position | VertexFormat.Normal | VertexFormat.TangentS | VertexFormat.TangentT; + ShaderShadow.VertexShaderVertexFormat(fmt, 1, null, 0); + + StaticShaderIndex vshIndex = new(ShaderShadow, ShaderType.Vertex, "watercheap"); + vshIndex.Set("BLEND", blend && refraction); + ShaderShadow.SetVertexShader("watercheap", vshIndex.GetIndex()); + + Span scroll1 = stackalloc float[4]; + vars[SCROLL1].GetVecValue(scroll1); + + StaticShaderIndex pshIndex = new(ShaderShadow, ShaderType.Pixel, "watercheap"); + pshIndex.Set("FRESNEL", vars[NOFRESNEL].GetIntValue() == 0); + pshIndex.Set("BLEND", blend); + pshIndex.Set("REFRACTALPHA", refraction); + pshIndex.Set("HDRTYPE", (int)HardwareConfig.GetHDRType()); + pshIndex.Set("MULTITEXTURE", MathF.Abs(scroll1[0]) > 0.0f); + pshIndex.Set("NORMAL_DECODE_MODE", (int)NormalDecodeMode.None); + ShaderShadow.SetPixelShader("watercheap", pshIndex.GetIndex()); + + if (HardwareConfig.GetHDRType() != HDRType.None) + ShaderShadow.EnableSRGBWrite(true); + } + else { + shaderAPI.SetDefaultState(); + + BindTexture(Sampler.Sampler0, ENVMAP, ENVMAPFRAME); + BindTexture(Sampler.Sampler1, NORMALMAP, BUMPFRAME); + if (refraction && blend) + BindTexture(Sampler.Sampler2, REFRACTTEXTURE, -1); + shaderAPI.BindStandardTexture(Sampler.Sampler6, StandardTextureId.NormalizationCubemapSigned); + + SetPixelShaderConstant(0, FOGCOLOR); + + float cheapWaterStartDistance = vars[CHEAPWATERSTARTDISTANCE].GetFloatValue(); + float cheapWaterEndDistance = vars[CHEAPWATERENDDISTANCE].GetFloatValue(); + Span cheapWaterParams = [ + cheapWaterStartDistance * VSHADER_VECT_SCALE, + cheapWaterEndDistance * VSHADER_VECT_SCALE, + PSHADER_VECT_SCALE / (cheapWaterEndDistance - cheapWaterStartDistance), + cheapWaterStartDistance / (cheapWaterEndDistance - cheapWaterStartDistance), + ]; + shaderAPI.SetPixelShaderConstant(1, cheapWaterParams); + + if (Config.ShowSpecular) + SetPixelShaderConstant(2, REFLECTTINT, REFLECTBLENDFACTOR); + else { + Span zero = [0.0f, 0.0f, 0.0f, vars[REFLECTBLENDFACTOR].GetFloatValue()]; + shaderAPI.SetPixelShaderConstant(2, zero); + } + + if (vars[SCROLL1].IsDefined()) { + float curtime = (float)shaderAPI.CurrentTime(); + Span vc0 = stackalloc float[4]; + Span v0 = stackalloc float[4]; + vars[SCROLL1].GetVecValue(v0); + vc0[0] = curtime * v0[0]; + vc0[1] = curtime * v0[1]; + vars[SCROLL2].GetVecValue(v0); + vc0[2] = curtime * v0[0]; + vc0[3] = curtime * v0[1]; + shaderAPI.SetVertexShaderConstant(VertexShaderConst.ShaderSpecificConst3, vc0, 1); + } + + DynamicShaderIndex vshIndex = new(shaderAPI, ShaderType.Vertex); + shaderAPI.SetVertexShaderIndex(vshIndex.GetIndex()); + + DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); + pshIndex.Set("HDRENABLED", IsHDREnabled()); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo()); + shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); + } + Draw(); + } + + protected override void OnDrawElements(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, VertexCompressionType vertexCompression) { + bool forceExpensive = r_waterforceexpensive.GetBool(); + bool forceCheap = (vars[FORCECHEAP].GetIntValue() != 0) || UsingEditor(vars); + if (forceCheap) + forceExpensive = false; + else + forceExpensive = forceExpensive || (vars[FORCEEXPENSIVE].GetIntValue() != 0); + Assert(!(forceCheap && forceExpensive)); + + bool refraction = vars[REFRACTTEXTURE].IsTexture(); + bool reflection = forceExpensive && vars[REFLECTTEXTURE].IsTexture(); + bool drewSomething = false; + if (!forceCheap && (reflection || refraction)) { + drewSomething = true; + DrawReflectionRefraction(vars, shaderAPI, reflection, refraction); + } + + if (!reflection && vars[ENVMAP].IsTexture() && !IsFlagSet(vars, MaterialVarFlags.Decal)) { + drewSomething = true; + DrawCheapWater(vars, shaderAPI, !forceCheap, refraction); + } + + if (!drewSomething) + Draw(); + } +} diff --git a/Source.StdShader.Gl46/Water_DX9_HDR.cs b/Source.StdShader.Gl46/Water_DX9_HDR.cs new file mode 100644 index 000000000..c7b280865 --- /dev/null +++ b/Source.StdShader.Gl46/Water_DX9_HDR.cs @@ -0,0 +1,14 @@ +using Source.Common.MaterialSystem; + +namespace Source.StdShader.Gl46; + +public class Water_DX9_HDR : Water_DX90 +{ + public static new string HelpString = "Help for Water_DX9_HDR"; + + public override string? GetFallbackShader(IMaterialVar[] vars) { + if (HardwareConfig.GetHDRType() == HDRType.None) + return "WATER_DX90"; + return null; + } +} From 196ea1b8d21be3af00d87234999a3df7ac575f7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:07:34 +0300 Subject: [PATCH 26/57] Fix water vertex shaders missing the bone matrices block --- Game.Assets/hl2/shaders/water_gl460.vs | 4 ++++ Game.Assets/hl2/shaders/watercheap_gl460.vs | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/Game.Assets/hl2/shaders/water_gl460.vs b/Game.Assets/hl2/shaders/water_gl460.vs index 01ffc9f46..3a13f60cd 100644 --- a/Game.Assets/hl2/shaders/water_gl460.vs +++ b/Game.Assets/hl2/shaders/water_gl460.vs @@ -24,6 +24,10 @@ layout(std140, binding = 2) uniform source_vertex_sharedUBO { vec4 lightEnabled; }; +layout(std140, binding = 4) uniform source_bone_matrices { + mat4 bones[256]; +}; + layout(std140, binding = 5) uniform source_vs_constants { vec4 vs_const[256]; }; diff --git a/Game.Assets/hl2/shaders/watercheap_gl460.vs b/Game.Assets/hl2/shaders/watercheap_gl460.vs index 66f2f00a0..ca1eb30a9 100644 --- a/Game.Assets/hl2/shaders/watercheap_gl460.vs +++ b/Game.Assets/hl2/shaders/watercheap_gl460.vs @@ -21,6 +21,10 @@ layout(std140, binding = 2) uniform source_vertex_sharedUBO { vec4 lightEnabled; }; +layout(std140, binding = 4) uniform source_bone_matrices { + mat4 bones[256]; +}; + layout(std140, binding = 5) uniform source_vs_constants { vec4 vs_const[256]; }; From b849525eec27ec475ad29b7de0a8f1da156dcf54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:14:52 +0300 Subject: [PATCH 27/57] Split GLSL vertex includes and remove dead shader code --- Game.Assets/hl2/shaders/common_gl460.fs | 28 -- Game.Assets/hl2/shaders/common_gl460.glsl | 40 --- Game.Assets/hl2/shaders/common_gl460.vs | 307 +----------------- .../hl2/shaders/common_lighting_gl460.vs | 191 +++++++++++ Game.Assets/hl2/shaders/common_morph_gl460.vs | 44 +++ .../hl2/shaders/common_skinning_gl460.vs | 65 ++++ .../hl2/shaders/common_vertex_shared_gl460.vs | 12 + .../shaders/common_vertexlitgeneric_gl460.fs | 13 - .../hl2/shaders/constant_color_gl460.fs | 1 - Game.Assets/hl2/shaders/eyes_gl460.fs | 2 - Game.Assets/hl2/shaders/eyes_gl460.vs | 23 +- .../hl2/shaders/lightmappedgeneric_gl460.fs | 16 +- .../hl2/shaders/lightmappedgeneric_gl460.vs | 37 +-- Game.Assets/hl2/shaders/skin_gl460.fs | 1 - Game.Assets/hl2/shaders/skin_gl460.vs | 25 +- Game.Assets/hl2/shaders/teeth_bump_gl460.fs | 2 - Game.Assets/hl2/shaders/teeth_bump_gl460.vs | 24 +- Game.Assets/hl2/shaders/teeth_gl460.fs | 1 - Game.Assets/hl2/shaders/teeth_gl460.vs | 23 +- Game.Assets/hl2/shaders/unlitgeneric_gl460.fs | 3 - Game.Assets/hl2/shaders/unlitgeneric_gl460.vs | 1 - .../hl2/shaders/unlittwotexture_gl460.fs | 1 - .../hl2/shaders/unlittwotexture_gl460.vs | 24 +- .../shaders/vertexlitgeneric_bump_gl460.fs | 11 - .../shaders/vertexlitgeneric_bump_gl460.vs | 30 +- .../hl2/shaders/vertexlitgeneric_gl460.fs | 12 - .../hl2/shaders/vertexlitgeneric_gl460.vs | 26 +- Game.Assets/hl2/shaders/water_gl460.fs | 9 +- Game.Assets/hl2/shaders/water_gl460.vs | 15 - Game.Assets/hl2/shaders/watercheap_gl460.fs | 10 +- Game.Assets/hl2/shaders/watercheap_gl460.vs | 15 - Game.Assets/hl2/shaders/white_gl460.fs | 10 - .../shaders/worldvertextransition_gl460.vs | 1 - Source.StdShader.Gl46/Water_DX90.cs | 3 - 34 files changed, 339 insertions(+), 687 deletions(-) create mode 100644 Game.Assets/hl2/shaders/common_lighting_gl460.vs create mode 100644 Game.Assets/hl2/shaders/common_morph_gl460.vs create mode 100644 Game.Assets/hl2/shaders/common_skinning_gl460.vs create mode 100644 Game.Assets/hl2/shaders/common_vertex_shared_gl460.vs diff --git a/Game.Assets/hl2/shaders/common_gl460.fs b/Game.Assets/hl2/shaders/common_gl460.fs index 670abbee7..e34f61462 100644 --- a/Game.Assets/hl2/shaders/common_gl460.fs +++ b/Game.Assets/hl2/shaders/common_gl460.fs @@ -21,8 +21,6 @@ #define cFlashlightScreenScale ps_const[31] // .zw are currently unused #define flFlashlightNoLambertValue cFlashlightColor.w // This is either 0.0 or 2.0 -#define HDR_INPUT_MAP_SCALE 16.0 - #define TONEMAP_SCALE_NONE 0 #define TONEMAP_SCALE_LINEAR 1 #define TONEMAP_SCALE_GAMMA 2 @@ -30,7 +28,6 @@ #define PIXEL_FOG_TYPE_NONE -1 //MATERIAL_FOG_NONE is handled by PIXEL_FOG_TYPE_RANGE, this is for explicitly disabling fog in the shader #define PIXEL_FOG_TYPE_RANGE 0 //range+none packed together in ps2b. Simply none in ps20 (instruction limits) #define PIXEL_FOG_TYPE_HEIGHT 1 -#define PIXEL_FOG_TYPE_RANGE_RADIAL 2 // If you change these, make the corresponding change in hardwareconfig.cpp #define NVIDIA_PCF_POISSON 0 @@ -119,11 +116,6 @@ vec4 TextureCombine(vec4 baseColor, vec4 detailColor, int combine_mode, float fB return baseColor; } -vec3 lerp5(vec3 f1, vec3 f2, float i1, float i2, float x) -{ - return f1 + (f2 - f1) * (x - i1) / (i2 - i1); -} - vec3 TextureCombinePostLighting(vec3 lit_baseColor, vec4 detailColor, int combine_mode, float fBlendFactor) { if (combine_mode == TCOMBINE_RGB_ADDITIVE_SELFILLUM) @@ -177,26 +169,6 @@ float CalcPixelFogFactor(int iPIXELFOGTYPE, vec4 fogParams, float flEyePosZ, flo return retVal; } -//g_FogParams not defined by default, but this is the same layout for every shader that does define it -#define g_FogEndOverRange g_FogParams.x -#define g_WaterZ g_FogParams.y -#define g_FogMaxDensity g_FogParams.z -#define g_FogOORange g_FogParams.w - -vec3 BlendPixelFog(vec3 vShaderColor, float pixelFogFactor, vec3 vFogColor, int iPIXELFOGTYPE) -{ - if (iPIXELFOGTYPE == PIXEL_FOG_TYPE_RANGE || iPIXELFOGTYPE == PIXEL_FOG_TYPE_RANGE_RADIAL) //either range fog or no fog depending on fog parameters and whether this is ps20 or ps2b - { - pixelFogFactor = clamp(pixelFogFactor, 0.0, 1.0); - return mix(vShaderColor.rgb, vFogColor.rgb, pixelFogFactor * pixelFogFactor); //squaring the factor will get the middle range mixing closer to hardware fog - } - else if (iPIXELFOGTYPE == PIXEL_FOG_TYPE_HEIGHT) - { - return mix(vShaderColor.rgb, vFogColor.rgb, clamp(pixelFogFactor, 0.0, 1.0)); - } - return vShaderColor; -} - // The framebuffer performs the linear->gamma conversion for us (GL_FRAMEBUFFER_SRGB), which is // the equivalent of the CONVERT_TO_SRGB == 0 path. vec3 SRGBOutput(vec3 vShaderColor) diff --git a/Game.Assets/hl2/shaders/common_gl460.glsl b/Game.Assets/hl2/shaders/common_gl460.glsl index eab6d740b..0452db9eb 100644 --- a/Game.Assets/hl2/shaders/common_gl460.glsl +++ b/Game.Assets/hl2/shaders/common_gl460.glsl @@ -7,11 +7,6 @@ const vec3 bumpBasis[3] = vec3[3]( vec3( -0.40824833512306213, 0.70710676908493042, OO_SQRT_3 ), vec3( -0.40824821591377258, -0.7071068286895752, OO_SQRT_3 ) ); -const vec3 bumpBasisTranspose[3] = vec3[3]( - vec3( 0.81649661064147949, -0.40824833512306213, -0.40824833512306213 ), - vec3( 0.0, 0.70710676908493042, -0.7071068286895752 ), - vec3( OO_SQRT_3, OO_SQRT_3, OO_SQRT_3 ) -); vec3 CalcReflectionVectorUnnormalized(vec3 normal, vec3 eyeVector) { @@ -32,45 +27,11 @@ vec3 Vec3TangentToWorld(vec3 iTangentVector, vec3 iWorldNormal, vec3 iWorldTange return vWorldVector.xyz; // Return without normalizing } -vec3 Vec3TangentToWorldNormalized(vec3 iTangentVector, vec3 iWorldNormal, vec3 iWorldTangent, vec3 iWorldBinormal) -{ - return normalize(Vec3TangentToWorld(iTangentVector, iWorldNormal, iWorldTangent, iWorldBinormal)); -} - -vec3 LinearToGamma(vec3 f3linear) -{ - return pow(f3linear, vec3(1.0 / 2.2)); -} - vec3 GammaToLinear(vec3 gamma) { return pow(gamma, vec3(2.2)); } -#ifndef AA_CLAMP -#define AA_CLAMP 0 -#endif - -#if (AA_CLAMP==1) -vec2 ComputeLightmapCoordinates(vec4 Lightmap1and2Coord, vec2 Lightmap3Coord) -{ - vec2 result = clamp(Lightmap1and2Coord.xy, 0.0, 1.0) * Lightmap1and2Coord.wz * 0.99; - result += Lightmap3Coord; - return result; -} - -void ComputeBumpedLightmapCoordinates(vec4 Lightmap1and2Coord, vec2 Lightmap3Coord, - out vec2 bumpCoord1, - out vec2 bumpCoord2, - out vec2 bumpCoord3) -{ - vec2 result = clamp(Lightmap1and2Coord.xy, 0.0, 1.0) * Lightmap1and2Coord.wz * 0.99; - result += Lightmap3Coord; - bumpCoord1 = result + vec2(Lightmap1and2Coord.z, 0); - bumpCoord2 = result + 2.0 * vec2(Lightmap1and2Coord.z, 0); - bumpCoord3 = result + 3.0 * vec2(Lightmap1and2Coord.z, 0); -} -#else vec2 ComputeLightmapCoordinates(vec4 Lightmap1and2Coord, vec2 Lightmap3Coord) { return Lightmap1and2Coord.xy; @@ -85,6 +46,5 @@ void ComputeBumpedLightmapCoordinates(vec4 Lightmap1and2Coord, vec2 Lightmap3Coo bumpCoord2 = Lightmap1and2Coord.wz; // reversed order!!! bumpCoord3 = Lightmap3Coord.xy; } -#endif #endif // COMMON_GL460_GLSL diff --git a/Game.Assets/hl2/shaders/common_gl460.vs b/Game.Assets/hl2/shaders/common_gl460.vs index 056ed2581..ddff1ef87 100644 --- a/Game.Assets/hl2/shaders/common_gl460.vs +++ b/Game.Assets/hl2/shaders/common_gl460.vs @@ -3,314 +3,9 @@ #include "common_gl460.glsl" -#define FOGTYPE_RANGE 0 -#define FOGTYPE_HEIGHT 1 -#define FOGTYPE_RANGE_RADIAL 2 - -#define cOverbright 2.0 -#define cOOOverbright (1.0 / 2.0) +const int VERTEX_SHADER_CAMERA_POS = 2; #define cEyePosWaterZ vs_const[VERTEX_SHADER_CAMERA_POS] #define cEyePos cEyePosWaterZ.xyz -#define cViewProjZ vs_const[13] - -const int VERTEX_SHADER_FLEXSCALE = 3; -#define cFlexScale vs_const[VERTEX_SHADER_FLEXSCALE] - -#define cFogParams vs_const[16] -#define cFogEndOverFogRange cFogParams.x -#define cFogOne cFogParams.y -#define cFogMaxDensity cFogParams.z -#define cOOFogRange cFogParams.w - -#define g_bLightEnabled lightEnabled -#define g_nLightCount lightCount - -struct LightInfo -{ - vec4 color; - vec4 dir; - vec4 pos; - vec4 spotParams; - vec4 atten; -}; - -// Four lights x 5 constants each = 20 constants -LightInfo cLightInfo[4]; - -void InitLightInfo() -{ - for (int i = 0; i < 4; ++i) - { - cLightInfo[i].color = vs_const[VERTEX_SHADER_LIGHT_INFO + i * 5 + 0]; - cLightInfo[i].dir = vs_const[VERTEX_SHADER_LIGHT_INFO + i * 5 + 1]; - cLightInfo[i].pos = vs_const[VERTEX_SHADER_LIGHT_INFO + i * 5 + 2]; - cLightInfo[i].spotParams = vs_const[VERTEX_SHADER_LIGHT_INFO + i * 5 + 3]; - cLightInfo[i].atten = vs_const[VERTEX_SHADER_LIGHT_INFO + i * 5 + 4]; - } -} - -vec3 AmbientLight(vec3 worldNormal) -{ - vec3 nSquared = worldNormal * worldNormal; - ivec3 isNegative = ivec3(lessThan(worldNormal, vec3(0.0))); - vec3 color; - color = nSquared.x * vs_const[VERTEX_SHADER_AMBIENT_LIGHT + isNegative.x].rgb; - color += nSquared.y * vs_const[VERTEX_SHADER_AMBIENT_LIGHT + 2 + isNegative.y].rgb; - color += nSquared.z * vs_const[VERTEX_SHADER_AMBIENT_LIGHT + 4 + isNegative.z].rgb; - return color; -} - -float RangeFog(vec3 projPos) -{ - return max(cFogMaxDensity, (-projPos.z * cOOFogRange + cFogEndOverFogRange)); -} - -float CalcFog(vec3 worldPos, vec3 projPos, int fogType) -{ - if (fogType == FOGTYPE_RANGE) - { - return RangeFog(projPos); - } - else - { - // We do this work in the pixel shader in dx9, so don't do any fog here. - return 1.0; - } -} - -// The following "internal" routines are called "privately" by other routines in this file which -// handle the particular flavor of vs20 control flow appropriate to the original caller -float VertexAttenInternal(vec3 worldPos, int lightNum) -{ - float result = 0.0; - - // Get light direction - vec3 lightDir = cLightInfo[lightNum].pos.xyz - worldPos; - - // Get light distance squared. - float lightDistSquared = dot(lightDir, lightDir); - - // Get 1/lightDistance - float ooLightDist = inversesqrt(lightDistSquared); - - // Normalize light direction - lightDir *= ooLightDist; - - vec3 vDist = vec3(1.0, lightDistSquared * ooLightDist, lightDistSquared); - - float flDistanceAtten = 1.0 / dot(cLightInfo[lightNum].atten.xyz, vDist); - - // Spot attenuation - float flCosTheta = dot(cLightInfo[lightNum].dir.xyz, -lightDir); - float flSpotAtten = (flCosTheta - cLightInfo[lightNum].spotParams.z) * cLightInfo[lightNum].spotParams.w; - flSpotAtten = max(0.0001, flSpotAtten); - flSpotAtten = pow(flSpotAtten, cLightInfo[lightNum].spotParams.x); - flSpotAtten = clamp(flSpotAtten, 0.0, 1.0); - - // Select between point and spot - float flAtten = mix(flDistanceAtten, flDistanceAtten * flSpotAtten, cLightInfo[lightNum].dir.w); - - // Select between above and directional (no attenuation) - result = mix(flAtten, 1.0, cLightInfo[lightNum].color.w); - - return result; -} - -float CosineTermInternal(vec3 worldPos, vec3 worldNormal, int lightNum, bool bHalfLambert) -{ - // Calculate light direction assuming this is a point or spot - vec3 lightDir = normalize(cLightInfo[lightNum].pos.xyz - worldPos); - - vec4 dirInv = -cLightInfo[lightNum].dir; - vec4 color = cLightInfo[lightNum].color; - - // Select the above direction or the one in the structure, based upon light type - lightDir = mix(lightDir, dirInv.xyz, color.www); - - // compute N dot L - float NDotL = dot(worldNormal, lightDir); - - if (!bHalfLambert) - { - NDotL = max(0.0, NDotL); - } - else // Half-Lambert - { - NDotL = NDotL * 0.5 + 0.5; - NDotL = NDotL * NDotL; - } - return NDotL; -} - -float GetVertexAttenForLight(vec3 worldPos, int lightNum, bool useStaticControlFlow) -{ - float result = 0.0; - - if (useStaticControlFlow) - { - if (g_bLightEnabled[lightNum] != 0.0) - result = VertexAttenInternal(worldPos, lightNum); - } - else - result = VertexAttenInternal(worldPos, lightNum); - - return result; -} - -vec3 DoLightInternal(vec3 worldPos, vec3 worldNormal, int lightNum, bool bHalfLambert) -{ - return cLightInfo[lightNum].color.xyz * - CosineTermInternal(worldPos, worldNormal, lightNum, bHalfLambert) * - VertexAttenInternal(worldPos, lightNum); -} - -vec3 DoLighting(vec3 worldPos, vec3 worldNormal, - vec3 staticLightingColor, bool bStaticLight, - bool bDynamicLight, bool bHalfLambert) -{ - vec3 linearColor = vec3(0.0, 0.0, 0.0); - - if (bStaticLight) // Static light - { - vec3 col = staticLightingColor * cOverbright; - linearColor += GammaToLinear(col); - } - - if (bDynamicLight) // Dynamic light - { - for (int i = 0; i < g_nLightCount; i++) - { - linearColor += DoLightInternal(worldPos, worldNormal, i, bHalfLambert); - } - } - - if (bDynamicLight) - { - linearColor += AmbientLight(worldNormal); //ambient light is already remapped - } - - return linearColor; -} - -vec3 DoLightingUnrolled(vec3 worldPos, vec3 worldNormal, - vec3 staticLightingColor, bool bStaticLight, - bool bDynamicLight, bool bHalfLambert, int nNumLights) -{ - vec3 linearColor = vec3(0.0, 0.0, 0.0); - - if (bStaticLight) // Static light - linearColor += GammaToLinear(staticLightingColor * cOverbright); - - if (bDynamicLight) // Ambient light - { - if (nNumLights >= 1) - linearColor += DoLightInternal(worldPos, worldNormal, 0, bHalfLambert); - if (nNumLights >= 2) - linearColor += DoLightInternal(worldPos, worldNormal, 1, bHalfLambert); - if (nNumLights >= 3) - linearColor += DoLightInternal(worldPos, worldNormal, 2, bHalfLambert); - if (nNumLights >= 4) - linearColor += DoLightInternal(worldPos, worldNormal, 3, bHalfLambert); - } - - if (bDynamicLight) - linearColor += AmbientLight(worldNormal); //ambient light is already remapped - - return linearColor; -} - -void SkinPositionAndNormal(bool bSkinning, vec4 modelPos, vec3 modelNormal, - ivec4 boneIndices, vec2 boneWeights, - out vec3 worldPos, out vec3 worldNormal) -{ - if (!bSkinning || numBones == 0) - { - worldPos = (modelMatrix * modelPos).xyz; - worldNormal = mat3(modelMatrix) * modelNormal; - } - else // skinning - always three bones - { - vec3 weights; - weights[0] = boneWeights.x; - weights[1] = boneWeights.y; - weights[2] = 1.0 - (boneWeights.x + boneWeights.y); - - mat4 blendMatrix = bones[boneIndices[0]] * weights[0] + - bones[boneIndices[1]] * weights[1] + - bones[boneIndices[2]] * weights[2]; - - worldPos = (blendMatrix * modelPos).xyz; - worldNormal = mat3(blendMatrix) * modelNormal; - } -} - -void SkinPositionNormalAndTangentSpace(bool bSkinning, vec4 modelPos, vec3 modelNormal, vec4 modelTangentS, - ivec4 boneIndices, vec2 boneWeights, - out vec3 worldPos, out vec3 worldNormal, - out vec3 worldTangentS, out vec3 worldTangentT) -{ - if (!bSkinning || numBones == 0) - { - worldPos = (modelMatrix * modelPos).xyz; - worldNormal = mat3(modelMatrix) * modelNormal; - worldTangentS = mat3(modelMatrix) * modelTangentS.xyz; - } - else // skinning - always three bones - { - vec3 weights; - weights[0] = boneWeights.x; - weights[1] = boneWeights.y; - weights[2] = 1.0 - (boneWeights.x + boneWeights.y); - - mat4 blendMatrix = bones[boneIndices[0]] * weights[0] + - bones[boneIndices[1]] * weights[1] + - bones[boneIndices[2]] * weights[2]; - - worldPos = (blendMatrix * modelPos).xyz; - worldNormal = mat3(blendMatrix) * modelNormal; - worldTangentS = mat3(blendMatrix) * modelTangentS.xyz; - } - - worldTangentT = cross(worldNormal, worldTangentS) * modelTangentS.w; -} - -bool ApplyMorph(vec3 vPosFlex, inout vec3 vPosition) -{ - vec3 vPosDelta = vPosFlex.xyz * cFlexScale.x; - vPosition.xyz += vPosDelta; - return true; -} - -bool ApplyMorph(vec3 vPosFlex, vec3 vNormalFlex, inout vec3 vPosition, inout vec3 vNormal) -{ - vec3 vPosDelta = vPosFlex.xyz * cFlexScale.x; - vec3 vNormalDelta = vNormalFlex.xyz * cFlexScale.x; - vPosition.xyz += vPosDelta; - vNormal += vNormalDelta; - return true; -} - -bool ApplyMorph(vec3 vPosFlex, vec3 vNormalFlex, inout vec3 vPosition, inout vec3 vNormal, inout vec3 vTangent) -{ - vec3 vPosDelta = vPosFlex.xyz * cFlexScale.x; - vec3 vNormalDelta = vNormalFlex.xyz * cFlexScale.x; - vPosition.xyz += vPosDelta; - vNormal += vNormalDelta; - vTangent.xyz += vNormalDelta; - return true; -} - -bool ApplyMorph(vec4 vPosFlex, vec3 vNormalFlex, inout vec3 vPosition, inout vec3 vNormal, inout vec3 vTangent, out float flWrinkle) -{ - vec3 vPosDelta = vPosFlex.xyz * cFlexScale.x; - vec3 vNormalDelta = vNormalFlex.xyz * cFlexScale.x; - flWrinkle = vPosFlex.w * cFlexScale.y; - vPosition.xyz += vPosDelta; - vNormal += vNormalDelta; - vTangent.xyz += vNormalDelta; - return true; -} - #endif // COMMON_GL460_VS diff --git a/Game.Assets/hl2/shaders/common_lighting_gl460.vs b/Game.Assets/hl2/shaders/common_lighting_gl460.vs new file mode 100644 index 000000000..773054a7c --- /dev/null +++ b/Game.Assets/hl2/shaders/common_lighting_gl460.vs @@ -0,0 +1,191 @@ +#ifndef COMMON_LIGHTING_GL460_VS +#define COMMON_LIGHTING_GL460_VS + +#include "common_gl460.glsl" +#include "common_vertex_shared_gl460.vs" + +#define cOverbright 2.0 + +const int VERTEX_SHADER_AMBIENT_LIGHT = 21; +const int VERTEX_SHADER_LIGHT_INFO = 27; + +#define g_bLightEnabled lightEnabled +#define g_nLightCount lightCount + +struct LightInfo +{ + vec4 color; + vec4 dir; + vec4 pos; + vec4 spotParams; + vec4 atten; +}; + +// Four lights x 5 constants each = 20 constants +LightInfo cLightInfo[4]; + +void InitLightInfo() +{ + for (int i = 0; i < 4; ++i) + { + cLightInfo[i].color = vs_const[VERTEX_SHADER_LIGHT_INFO + i * 5 + 0]; + cLightInfo[i].dir = vs_const[VERTEX_SHADER_LIGHT_INFO + i * 5 + 1]; + cLightInfo[i].pos = vs_const[VERTEX_SHADER_LIGHT_INFO + i * 5 + 2]; + cLightInfo[i].spotParams = vs_const[VERTEX_SHADER_LIGHT_INFO + i * 5 + 3]; + cLightInfo[i].atten = vs_const[VERTEX_SHADER_LIGHT_INFO + i * 5 + 4]; + } +} + +vec3 AmbientLight(vec3 worldNormal) +{ + vec3 nSquared = worldNormal * worldNormal; + ivec3 isNegative = ivec3(lessThan(worldNormal, vec3(0.0))); + vec3 color; + color = nSquared.x * vs_const[VERTEX_SHADER_AMBIENT_LIGHT + isNegative.x].rgb; + color += nSquared.y * vs_const[VERTEX_SHADER_AMBIENT_LIGHT + 2 + isNegative.y].rgb; + color += nSquared.z * vs_const[VERTEX_SHADER_AMBIENT_LIGHT + 4 + isNegative.z].rgb; + return color; +} + +// The following "internal" routines are called "privately" by other routines in this file which +// handle the particular flavor of vs20 control flow appropriate to the original caller +float VertexAttenInternal(vec3 worldPos, int lightNum) +{ + float result = 0.0; + + // Get light direction + vec3 lightDir = cLightInfo[lightNum].pos.xyz - worldPos; + + // Get light distance squared. + float lightDistSquared = dot(lightDir, lightDir); + + // Get 1/lightDistance + float ooLightDist = inversesqrt(lightDistSquared); + + // Normalize light direction + lightDir *= ooLightDist; + + vec3 vDist = vec3(1.0, lightDistSquared * ooLightDist, lightDistSquared); + + float flDistanceAtten = 1.0 / dot(cLightInfo[lightNum].atten.xyz, vDist); + + // Spot attenuation + float flCosTheta = dot(cLightInfo[lightNum].dir.xyz, -lightDir); + float flSpotAtten = (flCosTheta - cLightInfo[lightNum].spotParams.z) * cLightInfo[lightNum].spotParams.w; + flSpotAtten = max(0.0001, flSpotAtten); + flSpotAtten = pow(flSpotAtten, cLightInfo[lightNum].spotParams.x); + flSpotAtten = clamp(flSpotAtten, 0.0, 1.0); + + // Select between point and spot + float flAtten = mix(flDistanceAtten, flDistanceAtten * flSpotAtten, cLightInfo[lightNum].dir.w); + + // Select between above and directional (no attenuation) + result = mix(flAtten, 1.0, cLightInfo[lightNum].color.w); + + return result; +} + +float CosineTermInternal(vec3 worldPos, vec3 worldNormal, int lightNum, bool bHalfLambert) +{ + // Calculate light direction assuming this is a point or spot + vec3 lightDir = normalize(cLightInfo[lightNum].pos.xyz - worldPos); + + vec4 dirInv = -cLightInfo[lightNum].dir; + vec4 color = cLightInfo[lightNum].color; + + // Select the above direction or the one in the structure, based upon light type + lightDir = mix(lightDir, dirInv.xyz, color.www); + + // compute N dot L + float NDotL = dot(worldNormal, lightDir); + + if (!bHalfLambert) + { + NDotL = max(0.0, NDotL); + } + else // Half-Lambert + { + NDotL = NDotL * 0.5 + 0.5; + NDotL = NDotL * NDotL; + } + return NDotL; +} + +float GetVertexAttenForLight(vec3 worldPos, int lightNum, bool useStaticControlFlow) +{ + float result = 0.0; + + if (useStaticControlFlow) + { + if (g_bLightEnabled[lightNum] != 0.0) + result = VertexAttenInternal(worldPos, lightNum); + } + else + result = VertexAttenInternal(worldPos, lightNum); + + return result; +} + +vec3 DoLightInternal(vec3 worldPos, vec3 worldNormal, int lightNum, bool bHalfLambert) +{ + return cLightInfo[lightNum].color.xyz * + CosineTermInternal(worldPos, worldNormal, lightNum, bHalfLambert) * + VertexAttenInternal(worldPos, lightNum); +} + +vec3 DoLighting(vec3 worldPos, vec3 worldNormal, + vec3 staticLightingColor, bool bStaticLight, + bool bDynamicLight, bool bHalfLambert) +{ + vec3 linearColor = vec3(0.0, 0.0, 0.0); + + if (bStaticLight) // Static light + { + vec3 col = staticLightingColor * cOverbright; + linearColor += GammaToLinear(col); + } + + if (bDynamicLight) // Dynamic light + { + for (int i = 0; i < g_nLightCount; i++) + { + linearColor += DoLightInternal(worldPos, worldNormal, i, bHalfLambert); + } + } + + if (bDynamicLight) + { + linearColor += AmbientLight(worldNormal); //ambient light is already remapped + } + + return linearColor; +} + +vec3 DoLightingUnrolled(vec3 worldPos, vec3 worldNormal, + vec3 staticLightingColor, bool bStaticLight, + bool bDynamicLight, bool bHalfLambert, int nNumLights) +{ + vec3 linearColor = vec3(0.0, 0.0, 0.0); + + if (bStaticLight) // Static light + linearColor += GammaToLinear(staticLightingColor * cOverbright); + + if (bDynamicLight) // Ambient light + { + if (nNumLights >= 1) + linearColor += DoLightInternal(worldPos, worldNormal, 0, bHalfLambert); + if (nNumLights >= 2) + linearColor += DoLightInternal(worldPos, worldNormal, 1, bHalfLambert); + if (nNumLights >= 3) + linearColor += DoLightInternal(worldPos, worldNormal, 2, bHalfLambert); + if (nNumLights >= 4) + linearColor += DoLightInternal(worldPos, worldNormal, 3, bHalfLambert); + } + + if (bDynamicLight) + linearColor += AmbientLight(worldNormal); //ambient light is already remapped + + return linearColor; +} + +#endif diff --git a/Game.Assets/hl2/shaders/common_morph_gl460.vs b/Game.Assets/hl2/shaders/common_morph_gl460.vs new file mode 100644 index 000000000..0fda5aa68 --- /dev/null +++ b/Game.Assets/hl2/shaders/common_morph_gl460.vs @@ -0,0 +1,44 @@ +#ifndef COMMON_MORPH_GL460_VS +#define COMMON_MORPH_GL460_VS + +const int VERTEX_SHADER_FLEXSCALE = 3; +#define cFlexScale vs_const[VERTEX_SHADER_FLEXSCALE] + +bool ApplyMorph(vec3 vPosFlex, inout vec3 vPosition) +{ + vec3 vPosDelta = vPosFlex.xyz * cFlexScale.x; + vPosition.xyz += vPosDelta; + return true; +} + +bool ApplyMorph(vec3 vPosFlex, vec3 vNormalFlex, inout vec3 vPosition, inout vec3 vNormal) +{ + vec3 vPosDelta = vPosFlex.xyz * cFlexScale.x; + vec3 vNormalDelta = vNormalFlex.xyz * cFlexScale.x; + vPosition.xyz += vPosDelta; + vNormal += vNormalDelta; + return true; +} + +bool ApplyMorph(vec3 vPosFlex, vec3 vNormalFlex, inout vec3 vPosition, inout vec3 vNormal, inout vec3 vTangent) +{ + vec3 vPosDelta = vPosFlex.xyz * cFlexScale.x; + vec3 vNormalDelta = vNormalFlex.xyz * cFlexScale.x; + vPosition.xyz += vPosDelta; + vNormal += vNormalDelta; + vTangent.xyz += vNormalDelta; + return true; +} + +bool ApplyMorph(vec4 vPosFlex, vec3 vNormalFlex, inout vec3 vPosition, inout vec3 vNormal, inout vec3 vTangent, out float flWrinkle) +{ + vec3 vPosDelta = vPosFlex.xyz * cFlexScale.x; + vec3 vNormalDelta = vNormalFlex.xyz * cFlexScale.x; + flWrinkle = vPosFlex.w * cFlexScale.y; + vPosition.xyz += vPosDelta; + vNormal += vNormalDelta; + vTangent.xyz += vNormalDelta; + return true; +} + +#endif diff --git a/Game.Assets/hl2/shaders/common_skinning_gl460.vs b/Game.Assets/hl2/shaders/common_skinning_gl460.vs new file mode 100644 index 000000000..02116bc15 --- /dev/null +++ b/Game.Assets/hl2/shaders/common_skinning_gl460.vs @@ -0,0 +1,65 @@ +#ifndef COMMON_SKINNING_GL460_VS +#define COMMON_SKINNING_GL460_VS + +#include "common_vertex_shared_gl460.vs" + +layout(std140, binding = 4) uniform source_bone_matrices { + mat4 bones[256]; +}; + +void SkinPositionAndNormal(bool bSkinning, vec4 modelPos, vec3 modelNormal, + ivec4 boneIndices, vec2 boneWeights, + out vec3 worldPos, out vec3 worldNormal) +{ + if (!bSkinning || numBones == 0) + { + worldPos = (modelMatrix * modelPos).xyz; + worldNormal = mat3(modelMatrix) * modelNormal; + } + else // skinning - always three bones + { + vec3 weights; + weights[0] = boneWeights.x; + weights[1] = boneWeights.y; + weights[2] = 1.0 - (boneWeights.x + boneWeights.y); + + mat4 blendMatrix = bones[boneIndices[0]] * weights[0] + + bones[boneIndices[1]] * weights[1] + + bones[boneIndices[2]] * weights[2]; + + worldPos = (blendMatrix * modelPos).xyz; + worldNormal = mat3(blendMatrix) * modelNormal; + } +} + +void SkinPositionNormalAndTangentSpace(bool bSkinning, vec4 modelPos, vec3 modelNormal, vec4 modelTangentS, + ivec4 boneIndices, vec2 boneWeights, + out vec3 worldPos, out vec3 worldNormal, + out vec3 worldTangentS, out vec3 worldTangentT) +{ + if (!bSkinning || numBones == 0) + { + worldPos = (modelMatrix * modelPos).xyz; + worldNormal = mat3(modelMatrix) * modelNormal; + worldTangentS = mat3(modelMatrix) * modelTangentS.xyz; + } + else // skinning - always three bones + { + vec3 weights; + weights[0] = boneWeights.x; + weights[1] = boneWeights.y; + weights[2] = 1.0 - (boneWeights.x + boneWeights.y); + + mat4 blendMatrix = bones[boneIndices[0]] * weights[0] + + bones[boneIndices[1]] * weights[1] + + bones[boneIndices[2]] * weights[2]; + + worldPos = (blendMatrix * modelPos).xyz; + worldNormal = mat3(blendMatrix) * modelNormal; + worldTangentS = mat3(blendMatrix) * modelTangentS.xyz; + } + + worldTangentT = cross(worldNormal, worldTangentS) * modelTangentS.w; +} + +#endif diff --git a/Game.Assets/hl2/shaders/common_vertex_shared_gl460.vs b/Game.Assets/hl2/shaders/common_vertex_shared_gl460.vs new file mode 100644 index 000000000..2f7eb34d8 --- /dev/null +++ b/Game.Assets/hl2/shaders/common_vertex_shared_gl460.vs @@ -0,0 +1,12 @@ +#ifndef COMMON_VERTEX_SHARED_GL460_VS +#define COMMON_VERTEX_SHARED_GL460_VS + +layout(std140, binding = 2) uniform source_vertex_sharedUBO { + int numBones; + int lightCount; + int vertexSharedPad0; + int vertexSharedPad1; + vec4 lightEnabled; +}; + +#endif diff --git a/Game.Assets/hl2/shaders/common_vertexlitgeneric_gl460.fs b/Game.Assets/hl2/shaders/common_vertexlitgeneric_gl460.fs index b4d04d43f..b333f687e 100644 --- a/Game.Assets/hl2/shaders/common_vertexlitgeneric_gl460.fs +++ b/Game.Assets/hl2/shaders/common_vertexlitgeneric_gl460.fs @@ -28,12 +28,6 @@ struct PixelShaderLightInfo }; #define cOverbright 2.0 -#define cOOOverbright 0.5 - -#define LIGHTTYPE_NONE 0 -#define LIGHTTYPE_SPOT 1 -#define LIGHTTYPE_POINT 2 -#define LIGHTTYPE_DIRECTIONAL 3 // Better suited to Pixel shader models, 11 instructions in pixel shader // ... actually, now only 9: mul, cmp, cmp, mul, mad, mad, mad, mad, mad @@ -347,13 +341,6 @@ void PixelShaderDoSpecularLighting(vec3 worldPos, vec3 worldNormal, float fSpecu } } -vec3 PixelShaderDoRimLighting(vec3 worldNormal, vec3 vEyeDir, vec3 cAmbientCube[6], float fFresnel) -{ - vec3 vReflect = reflect(-vEyeDir, worldNormal); // Reflect view through normal - - return fFresnel * PixelShaderAmbientLight(vEyeDir, cAmbientCube); -} - // Called directly by newer shaders or through the following wrapper for older shaders vec3 PixelShaderDoLighting(vec3 worldPos, vec3 worldNormal, vec3 staticLightingColor, bool bStaticLight, diff --git a/Game.Assets/hl2/shaders/constant_color_gl460.fs b/Game.Assets/hl2/shaders/constant_color_gl460.fs index 35a201505..50519bbac 100644 --- a/Game.Assets/hl2/shaders/constant_color_gl460.fs +++ b/Game.Assets/hl2/shaders/constant_color_gl460.fs @@ -1,6 +1,5 @@ #version 460 -in vec2 vs_BaseTexCoord; layout(std140, binding = 3) uniform source_pixel_sharedUBO { bool isAlphaTesting; diff --git a/Game.Assets/hl2/shaders/eyes_gl460.fs b/Game.Assets/hl2/shaders/eyes_gl460.fs index 1fd5c4102..414bcde59 100644 --- a/Game.Assets/hl2/shaders/eyes_gl460.fs +++ b/Game.Assets/hl2/shaders/eyes_gl460.fs @@ -7,7 +7,6 @@ in vec2 vs_IrisTexCoord; in vec2 vs_GlintTexCoord; in vec3 vs_Color; in vec4 vs_WorldPos_ProjPosZ; -in vec4 vs_FogFactorW; layout(std140, binding = 6) uniform source_ps_constants { vec4 ps_const[256]; @@ -25,7 +24,6 @@ layout(binding = 2) uniform sampler2D GlintSampler; #define g_EyePos_SpecExponent ps_const[11] #define g_FogParams ps_const[12] -#define fDilationFactor cEyeScalars.x #define fGlintDamping cEyeScalars.y void main() diff --git a/Game.Assets/hl2/shaders/eyes_gl460.vs b/Game.Assets/hl2/shaders/eyes_gl460.vs index 9b8099263..30f66c22c 100644 --- a/Game.Assets/hl2/shaders/eyes_gl460.vs +++ b/Game.Assets/hl2/shaders/eyes_gl460.vs @@ -3,9 +3,7 @@ // STATIC: "HALFLAMBERT" "0..1" // STATIC: "USE_STATIC_CONTROL_FLOW" "0..1" -// DYNAMIC: "COMPRESSED_VERTS" "0..1" // DYNAMIC: "SKINNING" "0..1" -// DYNAMIC: "DOWATERFOG" "0..1" // DYNAMIC: "DYNAMIC_LIGHT" "0..1" // DYNAMIC: "STATIC_LIGHT" "0..1" // DYNAMIC: "NUM_LIGHTS" "0..2" @@ -22,25 +20,10 @@ layout(std140, binding = 0) uniform source_matrices { mat4 modelMatrix; }; -layout(std140, binding = 2) uniform source_vertex_sharedUBO { - int numBones; - int lightCount; - int vertexSharedPad0; - int vertexSharedPad1; - vec4 lightEnabled; -}; - -layout(std140, binding = 4) uniform source_bone_matrices { - mat4 bones[256]; -}; - layout(std140, binding = 5) uniform source_vs_constants { vec4 vs_const[256]; }; -const int VERTEX_SHADER_CAMERA_POS = 2; -const int VERTEX_SHADER_AMBIENT_LIGHT = 21; -const int VERTEX_SHADER_LIGHT_INFO = 27; const int SHADER_SPECIFIC_CONST_0 = 48; const int SHADER_SPECIFIC_CONST_1 = 49; const int SHADER_SPECIFIC_CONST_2 = 50; @@ -50,10 +33,12 @@ const int SHADER_SPECIFIC_CONST_5 = 53; const int SHADER_SPECIFIC_CONST_6 = 54; #include "common_gl460.vs" +#include "common_lighting_gl460.vs" +#include "common_morph_gl460.vs" +#include "common_skinning_gl460.vs" #include "vortwarp_gl460.vs" const bool g_bSkinning = SKINNING != 0; -const int g_FogType = DOWATERFOG; const bool g_bHalfLambert = HALFLAMBERT != 0; #define cEyeOrigin vs_const[SHADER_SPECIFIC_CONST_0].xyz @@ -73,7 +58,6 @@ out vec2 vs_IrisTexCoord; out vec2 vs_GlintTexCoord; out vec3 vs_Color; out vec4 vs_WorldPos_ProjPosZ; -out vec4 vs_FogFactorW; void main() { @@ -100,7 +84,6 @@ void main() gl_Position = vProjPos; vs_WorldPos_ProjPosZ = vec4(worldPos.xyz, vProjPos.z); - vs_FogFactorW.w = CalcFog(worldPos, vProjPos.xyz, g_FogType); worldNormal = worldPos - cEyeOrigin; diff --git a/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs b/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs index 9a0d4667e..a2a304f90 100644 --- a/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs +++ b/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs @@ -15,7 +15,6 @@ // STATIC: "WARPLIGHTING" "0..1" // STATIC: "FANCY_BLENDING" "0..1" // STATIC: "MASKEDBLENDING" "0..1" -// STATIC: "RELIEF_MAPPING" "0..0" // STATIC: "SEAMLESS" "0..1" // STATIC: "OUTLINE" "0..1" // STATIC: "SOFTEDGES" "0..1" @@ -41,10 +40,8 @@ in vec4 vs_DetailOrBumpAndEnvmapMaskTexCoord; // envmap mask #else in vec2 vs_BaseTexCoord; // detail textures and bumpmaps are mutually exclusive so that we have enough texcoords. -#if ( RELIEF_MAPPING == 0 ) in vec4 vs_DetailOrBumpAndEnvmapMaskTexCoord; #endif -#endif centroid in vec4 vs_LightmapTexCoord1And2; centroid in vec4 vs_LightmapTexCoord3; in vec4 vs_WorldPos_ProjPosZ; @@ -52,7 +49,7 @@ in vec4 vs_WorldPos_ProjPosZ; in mat3 vs_TangentSpaceTranspose; #endif in vec4 vs_Color; -in vec4 vs_VertexBlendX_FogFactorW; +in float vs_VertexBlendX; layout(std140, binding = 6) uniform source_ps_constants { vec4 ps_const[256]; @@ -223,14 +220,6 @@ void main() } #endif -#if RELIEF_MAPPING - // in the parallax case, all texcoords must be the same in order to free - // up an iterator for the tangent space view vector - vec2 detailTexCoord = vs_BaseTexCoord.xy; - vec2 bumpmapTexCoord = vs_BaseTexCoord.xy; - vec2 envmapMaskTexCoord = vs_BaseTexCoord.xy; -#else - #if ( DETAILTEXTURE == 1 ) vec2 detailTexCoord = vs_DetailOrBumpAndEnvmapMaskTexCoord.xy; vec2 bumpmapTexCoord = vs_BaseTexCoord.xy; @@ -244,7 +233,6 @@ void main() #endif vec2 envmapMaskTexCoord = vs_DetailOrBumpAndEnvmapMaskTexCoord.wz; -#endif // !RELIEF_MAPPING vec4 detailColor = vec4(1.0, 1.0, 1.0, 1.0); #if DETAILTEXTURE @@ -284,7 +272,7 @@ void main() #if MASKEDBLENDING float blendfactor = 0.5; #else - float blendfactor = vs_VertexBlendX_FogFactorW.r; + float blendfactor = vs_VertexBlendX; #endif if (bBaseTexture2) diff --git a/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.vs b/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.vs index e9fcfa8f6..53ae605f7 100644 --- a/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.vs +++ b/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.vs @@ -5,12 +5,10 @@ // STATIC: "DIFFUSEBUMPMAP" "0..1" // STATIC: "VERTEXCOLOR" "0..1" // STATIC: "VERTEXALPHATEXBLENDFACTOR" "0..1" -// STATIC: "RELIEF_MAPPING" "0..0" // STATIC: "SEAMLESS" "0..1" // STATIC: "BUMPMASK" "0..1" // DYNAMIC: "FASTPATH" "0..1" -// DYNAMIC: "DOWATERFOG" "0..1" // DYNAMIC: "LIGHTING_PREVIEW" "0..1" layout(location = 0) in vec3 v_Position; @@ -28,25 +26,10 @@ layout(std140, binding = 0) uniform source_matrices { mat4 modelMatrix; }; -layout(std140, binding = 2) uniform source_vertex_sharedUBO { - int numBones; - int lightCount; - int vertexSharedPad0; - int vertexSharedPad1; - vec4 lightEnabled; -}; - -layout(std140, binding = 4) uniform source_bone_matrices { - mat4 bones[256]; -}; - layout(std140, binding = 5) uniform source_vs_constants { vec4 vs_const[256]; }; -const int VERTEX_SHADER_CAMERA_POS = 2; -const int VERTEX_SHADER_AMBIENT_LIGHT = 21; -const int VERTEX_SHADER_LIGHT_INFO = 27; const int VERTEX_SHADER_MODULATION_COLOR = 47; const int SHADER_SPECIFIC_CONST_0 = 48; const int SHADER_SPECIFIC_CONST_2 = 50; @@ -72,9 +55,7 @@ const int SHADER_SPECIFIC_CONST_10 = 58; #define cBlendMaskTexCoordTransform0 vs_const[SHADER_SPECIFIC_CONST_10 + 0] // not contiguous with the rest! #define cBlendMaskTexCoordTransform1 vs_const[SHADER_SPECIFIC_CONST_10 + 1] -const int g_FogType = DOWATERFOG; const bool g_UseSeparateEnvmapMask = ENVMAP_MASK != 0; -const bool g_bTangentSpace = TANGENTSPACE != 0; const bool g_bBumpmap = BUMPMAP != 0; const bool g_bBumpmapDiffuseLighting = DIFFUSEBUMPMAP != 0; const bool g_bVertexColor = VERTEXCOLOR != 0; @@ -87,12 +68,8 @@ out vec4 vs_DetailOrBumpAndEnvmapMaskTexCoord; // envmap mask #else out vec2 vs_BaseTexCoord; // detail textures and bumpmaps are mutually exclusive so that we have enough texcoords. -#if RELIEF_MAPPING -out vec3 vs_TangentSpaceViewRay; -#else out vec4 vs_DetailOrBumpAndEnvmapMaskTexCoord; #endif -#endif centroid out vec4 vs_LightmapTexCoord1And2; centroid out vec4 vs_LightmapTexCoord3; // and basetexcoord*mask_scale out vec4 vs_WorldPos_ProjPosZ; @@ -102,7 +79,7 @@ out mat3 vs_TangentSpaceTranspose; #endif out vec4 vs_Color; // in seamless, r g b = blend weights -out vec4 vs_VertexBlendX_FogFactorW; +out float vs_VertexBlendX; void main() { @@ -111,11 +88,7 @@ void main() vs_DetailOrBumpAndEnvmapMaskTexCoord = vec4(0.0); #else vs_BaseTexCoord = vec2(0.0); -#if RELIEF_MAPPING - vs_TangentSpaceViewRay = vec3(0.0); -#else vs_DetailOrBumpAndEnvmapMaskTexCoord = vec4(0.0); -#endif #endif vs_LightmapTexCoord1And2 = vec4(0.0); vs_LightmapTexCoord3 = vec4(0.0); @@ -157,7 +130,6 @@ void main() vs_BaseTexCoord.x = dot(v_TexCoord0, cBaseTexCoordTransform0.xy) + cBaseTexCoordTransform0.w; vs_BaseTexCoord.y = dot(v_TexCoord0, cBaseTexCoordTransform1.xy) + cBaseTexCoordTransform1.w; } -#if ( RELIEF_MAPPING == 0 ) { // calculate detailorbumptexcoord if (FASTPATH != 0) @@ -168,7 +140,6 @@ void main() vs_DetailOrBumpAndEnvmapMaskTexCoord.y = dot(v_TexCoord0, cDetailOrBumpTexCoordTransform1.xy) + cDetailOrBumpTexCoordTransform1.w; } } -#endif } #endif if (FASTPATH != 0) @@ -200,7 +171,6 @@ void main() vs_LightmapTexCoord1And2.xy = v_TexCoord1; } -#if ( RELIEF_MAPPING == 0) if (g_UseSeparateEnvmapMask || g_BumpMask) { // reversed component order @@ -211,9 +181,8 @@ void main() vs_DetailOrBumpAndEnvmapMaskTexCoord.z = dot(v_TexCoord0, cEnvmapMaskTexCoordTransform1.xy) + cEnvmapMaskTexCoordTransform1.w; # endif } -#endif - vs_VertexBlendX_FogFactorW = vec4(CalcFog(worldPos, vProjPos.xyz, g_FogType)); + vs_VertexBlendX = 0.0; if (!g_bVertexColor) { @@ -244,6 +213,6 @@ void main() if (g_bVertexAlphaTexBlendFactor) { - vs_VertexBlendX_FogFactorW.r = v_Color.a; + vs_VertexBlendX = v_Color.a; } } diff --git a/Game.Assets/hl2/shaders/skin_gl460.fs b/Game.Assets/hl2/shaders/skin_gl460.fs index 2a9862f91..1a24ccb0c 100644 --- a/Game.Assets/hl2/shaders/skin_gl460.fs +++ b/Game.Assets/hl2/shaders/skin_gl460.fs @@ -1,5 +1,4 @@ #version 460 -// STATIC: "CONVERT_TO_SRGB" "0..0" // STATIC: "CUBEMAP" "0..1" // STATIC: "SELFILLUM" "0..1" // STATIC: "SELFILLUMFRESNEL" "0..1" diff --git a/Game.Assets/hl2/shaders/skin_gl460.vs b/Game.Assets/hl2/shaders/skin_gl460.vs index 33b4dd13d..2ec4b4534 100644 --- a/Game.Assets/hl2/shaders/skin_gl460.vs +++ b/Game.Assets/hl2/shaders/skin_gl460.vs @@ -2,21 +2,15 @@ // STATIC: "USE_STATIC_CONTROL_FLOW" "0..1" -// DYNAMIC: "COMPRESSED_VERTS" "0..1" -// DYNAMIC: "DOWATERFOG" "0..1" // DYNAMIC: "SKINNING" "0..1" -// DYNAMIC: "LIGHTING_PREVIEW" "0..1" // DYNAMIC: "NUM_LIGHTS" "0..2" layout(location = 0) in vec3 v_Position; layout(location = 1) in vec3 v_Normal; -layout(location = 2) in vec4 v_Color; -layout(location = 3) in vec4 v_Specular; layout(location = 7) in ivec4 v_BoneIndex; layout(location = 8) in vec2 v_BoneWeights; layout(location = 9) in vec4 v_UserData; layout(location = 10) in vec4 v_TexCoord0; -layout(location = 11) in vec4 v_TexCoord1; layout(location = 14) in vec4 v_FlexPosition; layout(location = 15) in vec3 v_FlexNormal; @@ -26,29 +20,17 @@ layout(std140, binding = 0) uniform source_matrices { mat4 modelMatrix; }; -layout(std140, binding = 2) uniform source_vertex_sharedUBO { - int numBones; - int lightCount; - int vertexSharedPad0; - int vertexSharedPad1; - vec4 lightEnabled; -}; - -layout(std140, binding = 4) uniform source_bone_matrices { - mat4 bones[256]; -}; - layout(std140, binding = 5) uniform source_vs_constants { vec4 vs_const[256]; }; -const int VERTEX_SHADER_CAMERA_POS = 2; -const int VERTEX_SHADER_AMBIENT_LIGHT = 21; -const int VERTEX_SHADER_LIGHT_INFO = 27; const int SHADER_SPECIFIC_CONST_0 = 48; const int SHADER_SPECIFIC_CONST_4 = 52; #include "common_gl460.vs" +#include "common_lighting_gl460.vs" +#include "common_morph_gl460.vs" +#include "common_skinning_gl460.vs" #define cBaseTexCoordTransform0 vs_const[SHADER_SPECIFIC_CONST_0 + 0] #define cBaseTexCoordTransform1 vs_const[SHADER_SPECIFIC_CONST_0 + 1] @@ -56,7 +38,6 @@ const int SHADER_SPECIFIC_CONST_4 = 52; #define cDetailTexCoordTransform1 vs_const[SHADER_SPECIFIC_CONST_4 + 1] const bool g_bSkinning = SKINNING != 0; -const int g_FogType = DOWATERFOG; out vec4 vs_BaseTexCoord; // includes detail tex coord out vec3 vs_LightAtten; diff --git a/Game.Assets/hl2/shaders/teeth_bump_gl460.fs b/Game.Assets/hl2/shaders/teeth_bump_gl460.fs index 03e671075..9c1a7ca36 100644 --- a/Game.Assets/hl2/shaders/teeth_bump_gl460.fs +++ b/Game.Assets/hl2/shaders/teeth_bump_gl460.fs @@ -10,7 +10,6 @@ in mat3 vs_TangentSpace; in vec4 vs_WorldPos_ProjPosZ; in vec2 vs_LightAtten01; in vec2 vs_LightAtten23; -in vec4 vs_FogFactorW; layout(std140, binding = 6) uniform source_ps_constants { vec4 ps_const[256]; @@ -22,7 +21,6 @@ out vec4 fragColor; layout(binding = 0) uniform sampler2D BaseTextureSampler; layout(binding = 1) uniform sampler2D BumpTextureSampler; -layout(binding = 2) uniform samplerCube NormalizeSampler; #define g_EyePos_SpecExponent ps_const[11] #define g_FogParams ps_const[12] diff --git a/Game.Assets/hl2/shaders/teeth_bump_gl460.vs b/Game.Assets/hl2/shaders/teeth_bump_gl460.vs index 39c86fe24..56bda8575 100644 --- a/Game.Assets/hl2/shaders/teeth_bump_gl460.vs +++ b/Game.Assets/hl2/shaders/teeth_bump_gl460.vs @@ -2,10 +2,7 @@ // STATIC: "INTRO" "0..1" // STATIC: "USE_STATIC_CONTROL_FLOW" "0..1" -// DYNAMIC: "COMPRESSED_VERTS" "0..1" -// DYNAMIC: "DOWATERFOG" "0..1" // DYNAMIC: "SKINNING" "0..1" -// DYNAMIC: "STATIC_LIGHT" "0..1" // DYNAMIC: "NUM_LIGHTS" "0..2" layout(location = 0) in vec3 v_Position; @@ -23,32 +20,19 @@ layout(std140, binding = 0) uniform source_matrices { mat4 modelMatrix; }; -layout(std140, binding = 2) uniform source_vertex_sharedUBO { - int numBones; - int lightCount; - int vertexSharedPad0; - int vertexSharedPad1; - vec4 lightEnabled; -}; - -layout(std140, binding = 4) uniform source_bone_matrices { - mat4 bones[256]; -}; - layout(std140, binding = 5) uniform source_vs_constants { vec4 vs_const[256]; }; -const int VERTEX_SHADER_CAMERA_POS = 2; -const int VERTEX_SHADER_AMBIENT_LIGHT = 21; -const int VERTEX_SHADER_LIGHT_INFO = 27; const int SHADER_SPECIFIC_CONST_0 = 48; const int SHADER_SPECIFIC_CONST_1 = 49; #include "common_gl460.vs" +#include "common_lighting_gl460.vs" +#include "common_morph_gl460.vs" +#include "common_skinning_gl460.vs" #include "vortwarp_gl460.vs" -const int g_FogType = DOWATERFOG; const bool g_bSkinning = SKINNING != 0; #define cTeethLighting vs_const[SHADER_SPECIFIC_CONST_0] @@ -64,7 +48,6 @@ out mat3 vs_TangentSpace; out vec4 vs_WorldPos_ProjPosZ; out vec2 vs_LightAtten01; out vec2 vs_LightAtten23; -out vec4 vs_FogFactorW; void main() { @@ -91,7 +74,6 @@ void main() gl_Position = vProjPos; vs_WorldPos_ProjPosZ = vec4(worldPos, vProjPos.z); - vs_FogFactorW.w = CalcFog(worldPos, vProjPos.xyz, g_FogType); vs_WorldVertToEyeVector_Darkening.xyz = cEyePos - worldPos; diff --git a/Game.Assets/hl2/shaders/teeth_gl460.fs b/Game.Assets/hl2/shaders/teeth_gl460.fs index c66599483..d3beff1f8 100644 --- a/Game.Assets/hl2/shaders/teeth_gl460.fs +++ b/Game.Assets/hl2/shaders/teeth_gl460.fs @@ -5,7 +5,6 @@ in vec2 vs_BaseTexCoord; in vec3 vs_VertAtten; in vec4 vs_WorldPos_ProjPosZ; -in vec4 vs_FogFactorW; layout(std140, binding = 6) uniform source_ps_constants { vec4 ps_const[256]; diff --git a/Game.Assets/hl2/shaders/teeth_gl460.vs b/Game.Assets/hl2/shaders/teeth_gl460.vs index 61faf2d2c..68340951e 100644 --- a/Game.Assets/hl2/shaders/teeth_gl460.vs +++ b/Game.Assets/hl2/shaders/teeth_gl460.vs @@ -2,8 +2,6 @@ // STATIC: "INTRO" "0..1" // STATIC: "USE_STATIC_CONTROL_FLOW" "0..1" -// DYNAMIC: "COMPRESSED_VERTS" "0..1" -// DYNAMIC: "DOWATERFOG" "0..1" // DYNAMIC: "SKINNING" "0..1" // DYNAMIC: "DYNAMIC_LIGHT" "0..1" // DYNAMIC: "STATIC_LIGHT" "0..1" @@ -23,32 +21,19 @@ layout(std140, binding = 0) uniform source_matrices { mat4 modelMatrix; }; -layout(std140, binding = 2) uniform source_vertex_sharedUBO { - int numBones; - int lightCount; - int vertexSharedPad0; - int vertexSharedPad1; - vec4 lightEnabled; -}; - -layout(std140, binding = 4) uniform source_bone_matrices { - mat4 bones[256]; -}; - layout(std140, binding = 5) uniform source_vs_constants { vec4 vs_const[256]; }; -const int VERTEX_SHADER_CAMERA_POS = 2; -const int VERTEX_SHADER_AMBIENT_LIGHT = 21; -const int VERTEX_SHADER_LIGHT_INFO = 27; const int SHADER_SPECIFIC_CONST_0 = 48; const int SHADER_SPECIFIC_CONST_1 = 49; #include "common_gl460.vs" +#include "common_lighting_gl460.vs" +#include "common_morph_gl460.vs" +#include "common_skinning_gl460.vs" #include "vortwarp_gl460.vs" -const int g_FogType = DOWATERFOG; const bool g_bSkinning = SKINNING != 0; #define cTeethLighting vs_const[SHADER_SPECIFIC_CONST_0] @@ -61,7 +46,6 @@ const bool g_bSkinning = SKINNING != 0; out vec2 vs_BaseTexCoord; out vec3 vs_VertAtten; out vec4 vs_WorldPos_ProjPosZ; -out vec4 vs_FogFactorW; void main() { @@ -87,7 +71,6 @@ void main() gl_Position = vProjPos; vs_WorldPos_ProjPosZ = vec4(worldPos.xyz, vProjPos.z); - vs_FogFactorW.w = CalcFog(worldPos, vProjPos.xyz, g_FogType); InitLightInfo(); #if USE_STATIC_CONTROL_FLOW diff --git a/Game.Assets/hl2/shaders/unlitgeneric_gl460.fs b/Game.Assets/hl2/shaders/unlitgeneric_gl460.fs index c2a458a0f..b030de42c 100644 --- a/Game.Assets/hl2/shaders/unlitgeneric_gl460.fs +++ b/Game.Assets/hl2/shaders/unlitgeneric_gl460.fs @@ -10,10 +10,7 @@ layout(std140, binding = 3) uniform source_pixel_sharedUBO { float alphaTestRef; }; -const int VertexColor = 16; -const int VertexAlpha = 32; -uniform int flags; uniform sampler2D basetexture; out vec4 fragColor; diff --git a/Game.Assets/hl2/shaders/unlitgeneric_gl460.vs b/Game.Assets/hl2/shaders/unlitgeneric_gl460.vs index 13f5174ad..08be8ce38 100644 --- a/Game.Assets/hl2/shaders/unlitgeneric_gl460.vs +++ b/Game.Assets/hl2/shaders/unlitgeneric_gl460.vs @@ -1,7 +1,6 @@ #version 460 layout(location = 0) in vec3 v_Position; -layout(location = 1) in vec3 v_Normal; layout(location = 2) in vec4 v_Color; layout(location = 10) in vec2 v_TexCoord; diff --git a/Game.Assets/hl2/shaders/unlittwotexture_gl460.fs b/Game.Assets/hl2/shaders/unlittwotexture_gl460.fs index 3422f6d5d..19872c6c1 100644 --- a/Game.Assets/hl2/shaders/unlittwotexture_gl460.fs +++ b/Game.Assets/hl2/shaders/unlittwotexture_gl460.fs @@ -5,7 +5,6 @@ in vec2 vs_BaseTexCoord; in vec2 vs_BaseTexCoord2; in vec4 vs_WorldPos_ProjPosZ; -in vec4 vs_FogFactorW; layout(std140, binding = 6) uniform source_ps_constants { vec4 ps_const[256]; diff --git a/Game.Assets/hl2/shaders/unlittwotexture_gl460.vs b/Game.Assets/hl2/shaders/unlittwotexture_gl460.vs index b5fa9b90f..48bb21ce5 100644 --- a/Game.Assets/hl2/shaders/unlittwotexture_gl460.vs +++ b/Game.Assets/hl2/shaders/unlittwotexture_gl460.vs @@ -1,6 +1,4 @@ #version 460 -// DYNAMIC: "COMPRESSED_VERTS" "0..1" -// DYNAMIC: "DOWATERFOG" "0..1" // DYNAMIC: "SKINNING" "0..1" layout(location = 0) in vec3 v_Position; @@ -15,44 +13,26 @@ layout(std140, binding = 0) uniform source_matrices { mat4 modelMatrix; }; -layout(std140, binding = 2) uniform source_vertex_sharedUBO { - int numBones; - int lightCount; - int vertexSharedPad0; - int vertexSharedPad1; - vec4 lightEnabled; -}; - -layout(std140, binding = 4) uniform source_bone_matrices { - mat4 bones[256]; -}; - layout(std140, binding = 5) uniform source_vs_constants { vec4 vs_const[256]; }; -const int VERTEX_SHADER_CAMERA_POS = 2; -const int VERTEX_SHADER_AMBIENT_LIGHT = 21; -const int VERTEX_SHADER_LIGHT_INFO = 27; const int SHADER_SPECIFIC_CONST_0 = 48; const int SHADER_SPECIFIC_CONST_2 = 50; #include "common_gl460.vs" +#include "common_skinning_gl460.vs" const bool g_bSkinning = SKINNING != 0; -const int g_FogType = DOWATERFOG; #define cBaseTexCoordTransform0 vs_const[SHADER_SPECIFIC_CONST_0 + 0] #define cBaseTexCoordTransform1 vs_const[SHADER_SPECIFIC_CONST_0 + 1] #define cBaseTexCoordTransform2_0 vs_const[SHADER_SPECIFIC_CONST_2 + 0] #define cBaseTexCoordTransform2_1 vs_const[SHADER_SPECIFIC_CONST_2 + 1] -#define cModulationColor vs_const[47] out vec2 vs_BaseTexCoord; out vec2 vs_BaseTexCoord2; out vec4 vs_WorldPos_ProjPosZ; -out vec4 vs_Color; -out vec4 vs_FogFactorW; void main() { @@ -67,7 +47,6 @@ void main() vec4 vProjPos = projectionMatrix * viewMatrix * vec4(worldPos, 1.0); gl_Position = vProjPos; - vs_FogFactorW.w = CalcFog(worldPos, vProjPos.xyz, g_FogType); vs_WorldPos_ProjPosZ = vec4(worldPos.xyz, vProjPos.z); @@ -77,5 +56,4 @@ void main() vs_BaseTexCoord2.x = dot(v_TexCoord0, cBaseTexCoordTransform2_0); vs_BaseTexCoord2.y = dot(v_TexCoord0, cBaseTexCoordTransform2_1); - vs_Color = cModulationColor; } diff --git a/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.fs b/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.fs index 881af1fdc..00838eadd 100644 --- a/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.fs +++ b/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.fs @@ -25,7 +25,6 @@ in vec4 vs_WorldTangent; in vec4 vs_ProjPos; in vec4 vs_WorldPos_ProjPosZ; in vec3 vs_DetailTexCoord_Atten3; -in vec4 vs_FogFactorW; layout(std140, binding = 6) uniform source_ps_constants { vec4 ps_const[256]; @@ -63,8 +62,6 @@ layout(binding = 0) uniform sampler2D BaseTextureSampler; layout(binding = 1) uniform samplerCube EnvmapSampler; layout(binding = 2) uniform sampler2D DetailSampler; layout(binding = 3) uniform sampler2D BumpmapSampler; -layout(binding = 4) uniform sampler2D EnvmapMaskSampler; -layout(binding = 5) uniform sampler2D NormalizeSampler; layout(binding = 6) uniform sampler2D RandRotSampler; // RandomRotation sampler layout(binding = 7) uniform sampler2D FlashlightSampler; layout(binding = 8) uniform sampler2DShadow ShadowDepthSampler; // Flashlight shadow depth map sampler @@ -80,14 +77,6 @@ float CalcPixelFogFactorConst(float fPixelFogType, vec4 fogParams, float flEyePo } // Blend both types of Fog and lerp to get result -vec3 BlendPixelFogConst(vec3 vShaderColor, float pixelFogFactor, vec3 vFogColor, float fPixelFogType) -{ - pixelFogFactor = clamp(pixelFogFactor, 0.0, 1.0); - vec3 fRangeResult = mix(vShaderColor.rgb, vFogColor.rgb, pixelFogFactor * pixelFogFactor); //squaring the factor will get the middle range mixing closer to hardware fog - vec3 fHeightResult = mix(vShaderColor.rgb, vFogColor.rgb, clamp(pixelFogFactor, 0.0, 1.0)); - return mix(fRangeResult, fHeightResult, fPixelFogType); -} - vec4 FinalOutputConst(vec4 vShaderColor, float pixelFogFactor, float fPixelFogType, int iTONEMAP_SCALE_TYPE, float fWriteDepthToDestAlpha, float flProjZ) { vec4 result = vShaderColor; diff --git a/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.vs b/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.vs index 78456e3c8..3656cf931 100644 --- a/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.vs +++ b/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.vs @@ -1,22 +1,16 @@ #version 460 -// STATIC: "HALFLAMBERT" "0..1" // STATIC: "USE_WITH_2B" "0..1" // STATIC: "USE_STATIC_CONTROL_FLOW" "0..1" -// DYNAMIC: "COMPRESSED_VERTS" "0..1" -// DYNAMIC: "DOWATERFOG" "0..1" // DYNAMIC: "SKINNING" "0..1" // DYNAMIC: "NUM_LIGHTS" "0..2" layout(location = 0) in vec3 v_Position; layout(location = 1) in vec3 v_Normal; -layout(location = 2) in vec4 v_Color; -layout(location = 3) in vec4 v_Specular; layout(location = 7) in ivec4 v_BoneIndex; layout(location = 8) in vec2 v_BoneWeights; layout(location = 9) in vec4 v_UserData; layout(location = 10) in vec4 v_TexCoord0; -layout(location = 11) in vec4 v_TexCoord1; layout(location = 14) in vec4 v_FlexPosition; layout(location = 15) in vec3 v_FlexNormal; @@ -26,30 +20,17 @@ layout(std140, binding = 0) uniform source_matrices { mat4 modelMatrix; }; -layout(std140, binding = 2) uniform source_vertex_sharedUBO { - int numBones; - int lightCount; - int vertexSharedPad0; - int vertexSharedPad1; - vec4 lightEnabled; -}; - -layout(std140, binding = 4) uniform source_bone_matrices { - mat4 bones[256]; -}; - layout(std140, binding = 5) uniform source_vs_constants { vec4 vs_const[256]; }; -const int VERTEX_SHADER_CAMERA_POS = 2; -const int VERTEX_SHADER_AMBIENT_LIGHT = 21; -const int VERTEX_SHADER_LIGHT_INFO = 27; const int SHADER_SPECIFIC_CONST_0 = 48; const int SHADER_SPECIFIC_CONST_4 = 52; -const int SHADER_SPECIFIC_CONST_6 = 54; #include "common_gl460.vs" +#include "common_lighting_gl460.vs" +#include "common_morph_gl460.vs" +#include "common_skinning_gl460.vs" #define cBaseTexCoordTransform0 vs_const[SHADER_SPECIFIC_CONST_0 + 0] // 0 & 1 #define cBaseTexCoordTransform1 vs_const[SHADER_SPECIFIC_CONST_0 + 1] @@ -57,7 +38,6 @@ const int SHADER_SPECIFIC_CONST_6 = 54; #define cDetailTexCoordTransform1 vs_const[SHADER_SPECIFIC_CONST_4 + 1] const bool g_bSkinning = SKINNING != 0; -const int g_FogType = DOWATERFOG; //----------------------------------------------------------------------------- // Output vertex format @@ -70,11 +50,9 @@ out vec4 vs_WorldTangent; #if USE_WITH_2B out vec4 vs_ProjPos; #else -out vec3 vs_WorldBinormal; #endif out vec4 vs_WorldPos_ProjPosZ; out vec3 vs_DetailTexCoord_Atten3; -out vec4 vs_FogFactorW; //----------------------------------------------------------------------------- // Main shader entry point @@ -109,10 +87,8 @@ void main() #if USE_WITH_2B vs_ProjPos = vProjPos; #else - vs_WorldBinormal.xyz = worldTangentT.xyz; #endif - vs_FogFactorW = vec4(CalcFog(worldPos, vProjPos.xyz, g_FogType)); // Needed for water fog alpha and diffuse lighting // FIXME: we shouldn't have to compute this all the time. diff --git a/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.fs b/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.fs index 3cd618917..ed0602073 100644 --- a/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.fs +++ b/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.fs @@ -46,7 +46,6 @@ in vec3 vs_WorldVertToEyeVector; in vec3 vs_WorldSpaceNormal; in vec4 vs_ProjPos; in vec4 vs_WorldPos_ProjPosZ; -in vec4 vs_FogFactorW; #if SEAMLESS_DETAIL || SEAMLESS_BASE in vec3 vs_SeamlessWeights; #endif @@ -104,14 +103,9 @@ out vec4 fragColor; #define SOFT_MASK_MIN g_DistanceAlphaParams.y #define g_OutlineColor ps_const[8] -#define OUTLINE_COLOR g_OutlineColor // these are ordered this way for optimal ps20 swizzling #define g_OutlineParams ps_const[9] -#define OUTLINE_MIN_VALUE0 g_OutlineParams.x -#define OUTLINE_MAX_VALUE1 g_OutlineParams.y -#define OUTLINE_MAX_VALUE0 g_OutlineParams.z -#define OUTLINE_MIN_VALUE1 g_OutlineParams.w #if DETAILTEXTURE #define g_DetailTint ps_const[10].rgb @@ -139,12 +133,6 @@ float CalcPixelFogFactorConst(float fPixelFogType, vec4 fogParams, float flEyePo } // Blend both types of Fog and lerp to get result -vec3 BlendPixelFogConst(vec3 vShaderColor, float pixelFogFactor, vec3 vFogColor, float fPixelFogType) -{ - pixelFogFactor = mix(pixelFogFactor * pixelFogFactor, pixelFogFactor, fPixelFogType); - return mix(vShaderColor.rgb, vFogColor.rgb, pixelFogFactor); -} - vec4 FinalOutputConst(vec4 vShaderColor, float pixelFogFactor, float fPixelFogType, int iTONEMAP_SCALE_TYPE, float fWriteDepthToDestAlpha, float flProjZ) { vec4 result = vShaderColor; diff --git a/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.vs b/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.vs index 35de6c62e..a9e1c26af 100644 --- a/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.vs +++ b/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.vs @@ -8,10 +8,8 @@ // STATIC: "SEPARATE_DETAIL_UVS" "0..1" // STATIC: "USE_STATIC_CONTROL_FLOW" "0..1" // STATIC: "DONT_GAMMA_CONVERT_VERTEX_COLOR" "0..1" -// DYNAMIC: "COMPRESSED_VERTS" "0..1" // DYNAMIC: "DYNAMIC_LIGHT" "0..1" // DYNAMIC: "STATIC_LIGHT" "0..1" -// DYNAMIC: "DOWATERFOG" "0..1" // DYNAMIC: "SKINNING" "0..1" // DYNAMIC: "LIGHTING_PREVIEW" "0..1" // DYNAMIC: "NUM_LIGHTS" "0..2" @@ -22,7 +20,6 @@ layout(location = 2) in vec4 v_Color; layout(location = 3) in vec4 v_Specular; layout(location = 7) in ivec4 v_BoneIndex; layout(location = 8) in vec2 v_BoneWeights; -layout(location = 9) in vec4 v_UserData; layout(location = 10) in vec4 v_TexCoord0; layout(location = 11) in vec4 v_TexCoord1; layout(location = 14) in vec4 v_FlexPosition; @@ -34,30 +31,18 @@ layout(std140, binding = 0) uniform source_matrices { mat4 modelMatrix; }; -layout(std140, binding = 2) uniform source_vertex_sharedUBO { - int numBones; - int lightCount; - int vertexSharedPad0; - int vertexSharedPad1; - vec4 lightEnabled; -}; - -layout(std140, binding = 4) uniform source_bone_matrices { - mat4 bones[256]; -}; - layout(std140, binding = 5) uniform source_vs_constants { vec4 vs_const[256]; }; -const int VERTEX_SHADER_CAMERA_POS = 2; -const int VERTEX_SHADER_AMBIENT_LIGHT = 21; -const int VERTEX_SHADER_LIGHT_INFO = 27; const int SHADER_SPECIFIC_CONST_0 = 48; const int SHADER_SPECIFIC_CONST_2 = 50; const int SHADER_SPECIFIC_CONST_4 = 52; #include "common_gl460.vs" +#include "common_lighting_gl460.vs" +#include "common_morph_gl460.vs" +#include "common_skinning_gl460.vs" #define cBaseTexCoordTransform0 vs_const[SHADER_SPECIFIC_CONST_0 + 0] #define cBaseTexCoordTransform1 vs_const[SHADER_SPECIFIC_CONST_0 + 1] @@ -67,10 +52,7 @@ const int SHADER_SPECIFIC_CONST_4 = 52; #define cDetailTexCoordTransform1 vs_const[SHADER_SPECIFIC_CONST_4 + 1] const bool g_bSkinning = SKINNING != 0; -const int g_FogType = DOWATERFOG; const bool g_bVertexColor = VERTEXCOLOR != 0; -const bool g_bCubemap = CUBEMAP != 0; -const bool g_bFlashlight = FLASHLIGHT != 0; const bool g_bHalfLambert = HALFLAMBERT != 0; #if SEAMLESS_BASE @@ -93,7 +75,6 @@ out vec3 vs_WorldSpaceNormal; // Necessary for cubemaps and flashlight out vec4 vs_ProjPos; out vec4 vs_WorldPos_ProjPosZ; -out vec4 vs_FogFactorW; #if SEAMLESS_DETAIL || SEAMLESS_BASE out vec3 vs_SeamlessWeights; // x y z projection weights #endif @@ -135,7 +116,6 @@ void main() gl_Position = vProjPos; vs_ProjPos = vProjPos; - vs_FogFactorW.w = CalcFog(worldPos, vProjPos.xyz, g_FogType); vs_WorldPos_ProjPosZ.xyz = worldPos.xyz; vs_WorldPos_ProjPosZ.w = vProjPos.z; diff --git a/Game.Assets/hl2/shaders/water_gl460.fs b/Game.Assets/hl2/shaders/water_gl460.fs index da84c287a..0d069a50a 100644 --- a/Game.Assets/hl2/shaders/water_gl460.fs +++ b/Game.Assets/hl2/shaders/water_gl460.fs @@ -5,7 +5,6 @@ // STATIC: "REFRACT" "0..1" // STATIC: "ABOVEWATER" "0..1" // STATIC: "BLURRY_REFRACT" "0..1" -// STATIC: "NORMAL_DECODE_MODE" "0..0" // DYNAMIC: "PIXELFOGTYPE" "0..1" // DYNAMIC: "WRITE_DEPTH_TO_DESTALPHA" "0..1" @@ -63,16 +62,10 @@ void main() vec4 vNormal2 = texture(NormalSampler, vs_ExtraBumpTexCoord.zw); vNormal = 0.33 * (vNormal + vNormal1 + vNormal2); -#if ( NORMAL_DECODE_MODE == NORM_DECODE_ATI2N ) - vNormal.xy = vNormal.xy * 2.0 - 1.0; - vNormal.z = sqrt(1.0 - dot(vNormal.xy, vNormal.xy)); - vNormal.a = 1.0; -#else vNormal.xyz = 2.0 * vNormal.xyz - 1.0; -#endif #else - vec4 vNormal = DecompressNormal(NormalSampler, vs_BumpTexCoord, NORMAL_DECODE_MODE); + vec4 vNormal = DecompressNormal(NormalSampler, vs_BumpTexCoord, NORM_DECODE_NONE); #endif float ooW = 1.0 / vs_W; diff --git a/Game.Assets/hl2/shaders/water_gl460.vs b/Game.Assets/hl2/shaders/water_gl460.vs index 3a13f60cd..283b5a4df 100644 --- a/Game.Assets/hl2/shaders/water_gl460.vs +++ b/Game.Assets/hl2/shaders/water_gl460.vs @@ -16,25 +16,10 @@ layout(std140, binding = 0) uniform source_matrices { mat4 modelMatrix; }; -layout(std140, binding = 2) uniform source_vertex_sharedUBO { - int numBones; - int lightCount; - int vertexSharedPad0; - int vertexSharedPad1; - vec4 lightEnabled; -}; - -layout(std140, binding = 4) uniform source_bone_matrices { - mat4 bones[256]; -}; - layout(std140, binding = 5) uniform source_vs_constants { vec4 vs_const[256]; }; -const int VERTEX_SHADER_CAMERA_POS = 2; -const int VERTEX_SHADER_AMBIENT_LIGHT = 21; -const int VERTEX_SHADER_LIGHT_INFO = 27; const int SHADER_SPECIFIC_CONST_1 = 49; const int SHADER_SPECIFIC_CONST_3 = 51; diff --git a/Game.Assets/hl2/shaders/watercheap_gl460.fs b/Game.Assets/hl2/shaders/watercheap_gl460.fs index 705c6b69a..78e6aead5 100644 --- a/Game.Assets/hl2/shaders/watercheap_gl460.fs +++ b/Game.Assets/hl2/shaders/watercheap_gl460.fs @@ -4,7 +4,6 @@ // STATIC: "BLEND" "0..1" // STATIC: "REFRACTALPHA" "0..1" // STATIC: "HDRTYPE" "0..2" -// STATIC: "NORMAL_DECODE_MODE" "0..0" // DYNAMIC: "HDRENABLED" "0..1" // DYNAMIC: "PIXELFOGTYPE" "0..1" @@ -36,8 +35,6 @@ layout(binding = 2) uniform sampler2D RefractSampler; #define g_ReflectTint ps_const[2] #define g_PixelFogParams ps_const[3] -#define g_CheapWaterStart g_CheapWaterParams.x -#define g_CheapWaterEnd g_CheapWaterParams.y #define g_CheapWaterDeltaRecip g_CheapWaterParams.z #define g_CheapWaterStartDivDelta g_CheapWaterParams.w @@ -51,15 +48,10 @@ void main() vec3 vNormal2 = texture(NormalMapSampler, vs_ExtraBumpTexCoord.zw).xyz; vNormal = 0.33 * (vNormal + vNormal1 + vNormal2); -#if ( NORMAL_DECODE_MODE == NORM_DECODE_ATI2N ) - vNormal.xy = vNormal.xy * 2.0 - 1.0; - vNormal.z = sqrt(1.0 - dot(vNormal.xy, vNormal.xy)); -#else vNormal = 2.0 * vNormal - 1.0; -#endif #else - vec3 vNormal = DecompressNormal(NormalMapSampler, vs_NormalMapTexCoord, NORMAL_DECODE_MODE).xyz; + vec3 vNormal = DecompressNormal(NormalMapSampler, vs_NormalMapTexCoord, NORM_DECODE_NONE).xyz; #endif vec3 worldSpaceNormal = vs_TangentSpaceTranspose * vNormal; diff --git a/Game.Assets/hl2/shaders/watercheap_gl460.vs b/Game.Assets/hl2/shaders/watercheap_gl460.vs index ca1eb30a9..9f5399b92 100644 --- a/Game.Assets/hl2/shaders/watercheap_gl460.vs +++ b/Game.Assets/hl2/shaders/watercheap_gl460.vs @@ -13,25 +13,10 @@ layout(std140, binding = 0) uniform source_matrices { mat4 modelMatrix; }; -layout(std140, binding = 2) uniform source_vertex_sharedUBO { - int numBones; - int lightCount; - int vertexSharedPad0; - int vertexSharedPad1; - vec4 lightEnabled; -}; - -layout(std140, binding = 4) uniform source_bone_matrices { - mat4 bones[256]; -}; - layout(std140, binding = 5) uniform source_vs_constants { vec4 vs_const[256]; }; -const int VERTEX_SHADER_CAMERA_POS = 2; -const int VERTEX_SHADER_AMBIENT_LIGHT = 21; -const int VERTEX_SHADER_LIGHT_INFO = 27; const int SHADER_SPECIFIC_CONST_3 = 51; #include "common_gl460.vs" diff --git a/Game.Assets/hl2/shaders/white_gl460.fs b/Game.Assets/hl2/shaders/white_gl460.fs index fb7498a79..0420cc52a 100644 --- a/Game.Assets/hl2/shaders/white_gl460.fs +++ b/Game.Assets/hl2/shaders/white_gl460.fs @@ -1,15 +1,5 @@ #version 460 -in vec4 vs_Color; - -layout(std140, binding = 3) uniform source_pixel_sharedUBO { - bool isAlphaTesting; - int alphaTestFunc; - float alphaTestRef; -}; - -uniform int flags; - out vec4 fragColor; void main() diff --git a/Game.Assets/hl2/shaders/worldvertextransition_gl460.vs b/Game.Assets/hl2/shaders/worldvertextransition_gl460.vs index d654bb2ff..e14df114c 100644 --- a/Game.Assets/hl2/shaders/worldvertextransition_gl460.vs +++ b/Game.Assets/hl2/shaders/worldvertextransition_gl460.vs @@ -1,7 +1,6 @@ #version 460 layout(location = 0) in vec3 v_Position; -layout(location = 1) in vec3 v_Normal; layout(location = 2) in vec4 v_Color; layout(location = 10) in vec2 v_TexCoord0; layout(location = 11) in vec2 v_TexCoord1; diff --git a/Source.StdShader.Gl46/Water_DX90.cs b/Source.StdShader.Gl46/Water_DX90.cs index 4b558b47e..204eaa697 100644 --- a/Source.StdShader.Gl46/Water_DX90.cs +++ b/Source.StdShader.Gl46/Water_DX90.cs @@ -1,5 +1,4 @@ using Source.Common; -using Source.Common.Bitmap; using Source.Common.Commands; using Source.Common.MaterialSystem; using Source.Common.Mathematics; @@ -198,7 +197,6 @@ void DrawReflectionRefraction(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, pshIndex.Set("MULTITEXTURE", MathF.Abs(scroll1[0]) > 0.0f); pshIndex.Set("BASETEXTURE", vars[(int)ShaderMaterialVars.BaseTexture].IsTexture()); pshIndex.Set("BLURRY_REFRACT", vars[BLURREFRACT].GetIntValue()); - pshIndex.Set("NORMAL_DECODE_MODE", (int)NormalDecodeMode.None); ShaderShadow.SetPixelShader("water", pshIndex.GetIndex()); ShaderShadow.EnableSRGBWrite(true); @@ -316,7 +314,6 @@ void DrawCheapWater(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, bool blend pshIndex.Set("REFRACTALPHA", refraction); pshIndex.Set("HDRTYPE", (int)HardwareConfig.GetHDRType()); pshIndex.Set("MULTITEXTURE", MathF.Abs(scroll1[0]) > 0.0f); - pshIndex.Set("NORMAL_DECODE_MODE", (int)NormalDecodeMode.None); ShaderShadow.SetPixelShader("watercheap", pshIndex.GetIndex()); if (HardwareConfig.GetHDRType() != HDRType.None) From 02880ccf425e71cb0473e92cafb8d038386b0e50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:29:07 +0300 Subject: [PATCH 28/57] Fix screen space rectangles using the D3D9 half pixel offset --- Source.Engine/RenderUtils.cs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Source.Engine/RenderUtils.cs b/Source.Engine/RenderUtils.cs index 09489c847..7f1217352 100644 --- a/Source.Engine/RenderUtils.cs +++ b/Source.Engine/RenderUtils.cs @@ -39,13 +39,11 @@ float depth meshBuilder.Begin(mesh, MaterialPrimitiveType.Quads, xSegments * ySegments); { renderContext.GetRenderTargetDimensions(out int screenWidth, out int screenHeight); - float flOffset = 0.5f; + float flLeftX = destX; + float flRightX = destX + width; - float flLeftX = destX - flOffset; - float flRightX = destX + width - flOffset; - - float flTopY = destY - flOffset; - float flBottomY = destY + height - flOffset; + float flTopY = destY; + float flBottomY = destY + height; float flSubrectWidth = srcTextureX1 - srcTextureX0; float flSubrectHeight = srcTextureY1 - srcTextureY0; From a104b17bfa9cf1cd344dc1a23cdd835876cacdfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:41:23 +0300 Subject: [PATCH 29/57] Fix CdllEngineInterface.Con_NPrintf doing nothing --- Source.Engine/CdllEngineInterface.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Source.Engine/CdllEngineInterface.cs b/Source.Engine/CdllEngineInterface.cs index 7f1918569..0b01bff2a 100644 --- a/Source.Engine/CdllEngineInterface.cs +++ b/Source.Engine/CdllEngineInterface.cs @@ -247,7 +247,9 @@ public ReadOnlySpan Key_BindingForKey(ButtonCode code) { public bool CheckDoneKeyTrapping(out ButtonCode code) => Key.CheckDoneTrapping(out code); public void Con_NPrintf(int pos, ReadOnlySpan text) { - // todo +#if !SWDS + Con.NPrintF(pos, text); +#endif } public bool IsBoxInViewCluster(in Vector3 mins, in Vector3 maxs) { From 77b510d77d9b526e266df5b5e94ad144a40568cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:40:14 +0300 Subject: [PATCH 30/57] Set default bloom scale to 0.5, 1 as a default is too strong --- Game.Client/ViewPostProcess.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Game.Client/ViewPostProcess.cs b/Game.Client/ViewPostProcess.cs index c96f1b738..1712523ce 100644 --- a/Game.Client/ViewPostProcess.cs +++ b/Game.Client/ViewPostProcess.cs @@ -43,7 +43,7 @@ public static class ViewPostProcess public static readonly ConVar mat_debug_bloom = new("mat_debug_bloom", "0", FCvar.Cheat); public static readonly ConVar mat_non_hdr_bloom_scalefactor = new("mat_non_hdr_bloom_scalefactor", ".3"); - static readonly ConVar mat_bloom_scalefactor_scalar = new("mat_bloom_scalefactor_scalar", "1.0"); + static readonly ConVar mat_bloom_scalefactor_scalar = new("mat_bloom_scalefactor_scalar", "0.5"); public static readonly ConVar mat_exposure_center_region_x = new("mat_exposure_center_region_x", "0.9", FCvar.Cheat); public static readonly ConVar mat_exposure_center_region_y = new("mat_exposure_center_region_y", "0.85", FCvar.Cheat); From 3a420ddf83d6381b6aa665f5d520a76a1a8bc0d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:49:38 +0300 Subject: [PATCH 31/57] Fix render targets ignoring sRGB read like D3D9 --- Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index 19e7fffcf..68ee12b93 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -1979,6 +1979,8 @@ public unsafe void CreateTextures( bool managed = (creationFlags & CreateTextureFlags.Managed) != 0; bool isDepthBuffer = (creationFlags & CreateTextureFlags.DepthBuffer) != 0; bool isDynamic = (creationFlags & CreateTextureFlags.Dynamic) != 0; + if (isRenderTarget && !isDepthBuffer && SupportsSRGBDecode()) + creationFlags |= CreateTextureFlags.SRGB; bool isSRGB = (creationFlags & CreateTextureFlags.SRGB) != 0; InternalTextureFlags setFlags = 0; @@ -2593,12 +2595,19 @@ public void CopyRenderTargetToTextureEx(ShaderAPITextureHandle_t textureHandle, int srcY0 = srcHeight - (src.Y + src.Height); int dstY0 = tex.Height - (dst.Y + dst.Height); + bool srgbWriteEnabled = !boardStateValid || lastBoardState.SRGBWriteEnable; + if (srgbWriteEnabled) + glToggle(GL_FRAMEBUFFER_SRGB, false); + glNamedFramebufferTexture(copyFBO, GL_COLOR_ATTACHMENT0, GetGL46Texture(textureHandle), 0); glBlitNamedFramebuffer(UsingTextureRenderTarget ? renderFBO : 0, copyFBO, src.X, srcY0, src.X + src.Width, srcY0 + src.Height, dst.X, dstY0, dst.X + dst.Width, dstY0 + dst.Height, GL_COLOR_BUFFER_BIT, GL_LINEAR); glNamedFramebufferTexture(copyFBO, GL_COLOR_ATTACHMENT0, 0, 0); + + if (boardStateValid && lastBoardState.SRGBWriteEnable) + glToggle(GL_FRAMEBUFFER_SRGB, true); } public IMesh CreateStaticMesh(VertexFormat format, ReadOnlySpan textureGroup, IMaterial? material) { From 824c1b11b0947a05bee40c578d26695a60ac37c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:01:43 +0300 Subject: [PATCH 32/57] Fix textures loaded in full never getting their reflectivity --- Source.MaterialSystem/Texture.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Source.MaterialSystem/Texture.cs b/Source.MaterialSystem/Texture.cs index 63fcbb716..04c8a2450 100644 --- a/Source.MaterialSystem/Texture.cs +++ b/Source.MaterialSystem/Texture.cs @@ -695,6 +695,8 @@ private void MigrateShaderAPITextures() { DimsAllocated = allocated; } + Reflectivity = vtfTexture.Reflectivity(); + // TODO: How does Source stream textures? if (ConvertToActualFormat(vtfTexture)) { @@ -795,6 +797,7 @@ private ImageFormat ComputeActualFormat(ImageFormat srcFormat) { private IVTFTexture? HandleFileLoadFailedTexture(IVTFTexture? vtfTexture) { vtfTexture.Init(32, 32, 1, ImageFormat.BGRA8888, (int)Flags, 1); Init(vtfTexture.Width(), vtfTexture.Height(), vtfTexture.Depth(), vtfTexture.Format(), vtfTexture.Flags(), vtfTexture.FrameCount()); + Reflectivity = new(0.5f, 0.5f, 0.5f); DimsAllocated.Width = DimsActual.Width = DimsMapping.Width = (ushort)vtfTexture.Width(); DimsAllocated.Height = DimsActual.Height = DimsMapping.Height = (ushort)vtfTexture.Height(); From 07031804613c4a6be3281c263238878c01943c6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:06:19 +0300 Subject: [PATCH 33/57] Fix LightcacheGetStatic checking light styles instead of dlights --- Source.Engine/Lightcache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source.Engine/Lightcache.cs b/Source.Engine/Lightcache.cs index 6c67c842c..c207639d5 100644 --- a/Source.Engine/Lightcache.cs +++ b/Source.Engine/Lightcache.cs @@ -1271,7 +1271,7 @@ public ref LightingState LightcacheGetStatic(LightCacheHandle_t cache, out IText bool recalcStaticLighting = false; bool recalcLightStyles = pcache.HasLightStyle() && pcache.LastFrameUpdatedLightStyles != r_framecount && !IsCachedLightStylesValid(pcache); - bool recalcDLights = pcache.HasLightStyle() && pcache.LastFrameUpdatedDynamicLighting != r_framecount; + bool recalcDLights = pcache.HasDlights() && pcache.LastFrameUpdatedDynamicLighting != r_framecount; if (flags != (LightCacheFlags)pcache.Flags) { recalcStaticLighting = true; From 53e55d79f63e670af9fe8038ff2770b30f23ae6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:24:52 +0300 Subject: [PATCH 34/57] Fix AvgLightColor reading the end of the lighting lump --- Source.Common/Formats/BSP/BSPFile.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Source.Common/Formats/BSP/BSPFile.cs b/Source.Common/Formats/BSP/BSPFile.cs index 29f379afc..1f211ebe0 100644 --- a/Source.Common/Formats/BSP/BSPFile.cs +++ b/Source.Common/Formats/BSP/BSPFile.cs @@ -528,10 +528,14 @@ public struct BSPMSurfaceLighting public nint SurfNum; public Span AvgLightColor(int lightStyleIndex) { - if (lightStyleIndex < 0 || lightStyleIndex >= (Samples.Length)) + if (!MemoryMarshal.TryGetArray(Samples, out ArraySegment segment)) + throw new InvalidOperationException(); + + int index = segment.Offset - (lightStyleIndex + 1); + if (index < 0) throw new IndexOutOfRangeException(); - return Samples.Span![(Samples.Length - 1 - lightStyleIndex)..]; + return segment.Array.AsSpan(index); } // Lightmap info From 8a786ad47b41a76fbda8e05500dfd233fca1e6b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:37:26 +0300 Subject: [PATCH 35/57] Deploy game assets as Game.Assets content items --- Game.Assets/Game.Assets.csproj | 4 ++++ Source.Dedicated/Source.Dedicated.csproj | 9 --------- Source.Launcher/Source.Launcher.csproj | 9 --------- 3 files changed, 4 insertions(+), 18 deletions(-) diff --git a/Game.Assets/Game.Assets.csproj b/Game.Assets/Game.Assets.csproj index 019474cde..3024508f2 100644 --- a/Game.Assets/Game.Assets.csproj +++ b/Game.Assets/Game.Assets.csproj @@ -15,5 +15,9 @@ + + + + diff --git a/Source.Dedicated/Source.Dedicated.csproj b/Source.Dedicated/Source.Dedicated.csproj index 71174a5b3..ee0c3ed91 100644 --- a/Source.Dedicated/Source.Dedicated.csproj +++ b/Source.Dedicated/Source.Dedicated.csproj @@ -38,13 +38,4 @@ - - - - - - - - - diff --git a/Source.Launcher/Source.Launcher.csproj b/Source.Launcher/Source.Launcher.csproj index 352046b80..293d23d5b 100644 --- a/Source.Launcher/Source.Launcher.csproj +++ b/Source.Launcher/Source.Launcher.csproj @@ -47,13 +47,4 @@ - - - - - - - - - \ No newline at end of file From 1a2ce5e1be83ee840e2d39a2a615259e611d3246 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:41:09 +0300 Subject: [PATCH 36/57] Re-enable cubemap reflections in LightmappedGeneric --- Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs b/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs index a2a304f90..492cd61fb 100644 --- a/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs +++ b/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs @@ -29,11 +29,6 @@ // DYNAMIC: "WRITEWATERFOGTODESTALPHA" "0..1" // DYNAMIC: "LIGHTING_PREVIEW" "0..1" -// SDN: FIXME something about cubemaps is wrong, wether its as simple as a typo, I've yet to figure out -// But for now, instead of messed up reflections etc, i'm just gonna disable it -Callum -#undef CUBEMAP -#define CUBEMAP 0 - #if SEAMLESS in vec3 vs_SeamlessTexCoord; // zy xz in vec4 vs_DetailOrBumpAndEnvmapMaskTexCoord; // envmap mask From 81fd8dc0b143f56782f5cff64f9c61a172b03994 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:47:52 +0300 Subject: [PATCH 37/57] Add fog volume and water box queries to the render view --- Source.Common/IRenderView.cs | 12 +++ Source.Engine/GLRSurf.cs | 146 +++++++++++++++++++++++++++++++---- Source.Engine/View.cs | 23 ++++++ 3 files changed, 166 insertions(+), 15 deletions(-) diff --git a/Source.Common/IRenderView.cs b/Source.Common/IRenderView.cs index 32e69f16e..3a0771687 100644 --- a/Source.Common/IRenderView.cs +++ b/Source.Common/IRenderView.cs @@ -20,6 +20,16 @@ public struct WorldListInfo public List LeafFogVolume; } +public struct VisibleFogVolumeInfo +{ + public int VisibleFogVolume; + public int VisibleFogVolumeLeaf; + public bool EyeInFogVolume; + public float DistanceToWater; + public float WaterHeight; + public IMaterial? FogVolumeMaterial; +} + public enum DrawBrushModelMode { DrawAll = 0, @@ -94,6 +104,8 @@ public interface IRenderView void DrawWorldLists(IWorldRenderList? list, uint flags, float waterZAdjust); void DrawTranslucentSurfaces(IWorldRenderList? list, int sortIndex, uint flags, bool shadowDepth); bool LeafContainsTranslucentSurfaces(IWorldRenderList? list, int sortIndex, uint flags); + void GetVisibleFogVolume(in Vector3 eyePoint, ref VisibleFogVolumeInfo info); + bool DoesBoxIntersectWaterVolume(in Vector3 mins, in Vector3 maxs, int leafWaterDataID); void BeginUpdateLightmaps(); void EndUpdateLightmaps(); void Push3DView(in ViewSetup viewRender, ClearFlags clearFlags, ITexture? rtColor, Frustum frustum, ITexture? rtDepth); diff --git a/Source.Engine/GLRSurf.cs b/Source.Engine/GLRSurf.cs index f35dab5ba..3c71e67e1 100644 --- a/Source.Engine/GLRSurf.cs +++ b/Source.Engine/GLRSurf.cs @@ -35,16 +35,6 @@ public struct FogVolumeInfo public int FogVolumeID; } -public struct VisibleFogVolumeInfo -{ - public int VisibleFogVolume; - public int VisibleFogVolumeLeaf; - public bool EyeInFogVolume; - public float DistanceToWater; - public float WaterHeight; - public IMaterial? FogVolumeMaterial; -} - public struct CachedConvars { public int DrawLeaf; @@ -1165,7 +1155,33 @@ static void R_RecursiveWorldNode(WorldRenderList renderList, BSPMNode node, int node = node.Children[side == 0 ? 1 : 0]!; } } - public static IMaterial R_GetFogVolumeMaterial(int fogVolume, bool eyeInFogVolume) => throw new NotImplementedException(); + public const float INVALID_WATER_HEIGHT = 1000000.0f; + + static float R_GetWaterHeight(int fogVolume) { + if (fogVolume < 0 || fogVolume >= host_state.WorldBrush!.LeafWaterData!.Length) + return INVALID_WATER_HEIGHT; + + return host_state.WorldBrush!.LeafWaterData![fogVolume].SurfaceZ; + } + + public static IMaterial? R_GetFogVolumeMaterial(int fogVolume, bool eyeInFogVolume) { + if (fogVolume < 0 || fogVolume >= host_state.WorldBrush!.LeafWaterData!.Length) + return null; + + ref BSPMLeafWaterData leafWaterData = ref host_state.WorldBrush!.LeafWaterData![fogVolume]; + ref ModelTexInfo texInfo = ref host_state.WorldBrush!.TexInfo![leafWaterData.SurfaceTexInfoID]; + + IMaterial? material = texInfo.Material; + if (eyeInFogVolume) { + IMaterialVar? var = material!.FindVar("$bottommaterial", out _); + if (var != null) { + ReadOnlySpan materialName = var.GetStringValue(); + if (!materialName.IsEmpty) + material = materials.FindMaterial(materialName, MaterialDefines.TEXTURE_GROUP_OTHER); + } + } + return material; + } public static void R_SetFogVolumeState(int fogVolume, bool useHeightFog) => throw new NotImplementedException(); static bool R_CullNodeTopView(BSPMNode node) => throw new NotImplementedException(); static void R_DrawTopViewLeaf(WorldRenderList renderList, BSPMLeaf leaf) => throw new NotImplementedException(); @@ -1218,8 +1234,58 @@ public static void R_BuildWorldLists(IWorldRenderList renderListIn, ref WorldLis info.LeafFogVolume = renderList.VisibleLeafFogVolumes; } - static void ClearFogInfo(ref VisibleFogVolumeInfo info) => throw new NotImplementedException(); - public static void R_GetVisibleFogVolume(in Vector3 eyePoint, ref VisibleFogVolumeInfo info) => throw new NotImplementedException(); + static void ClearFogInfo(ref VisibleFogVolumeInfo info) { + info.EyeInFogVolume = false; + info.VisibleFogVolume = -1; + info.VisibleFogVolumeLeaf = -1; + info.FogVolumeMaterial = null; + info.WaterHeight = INVALID_WATER_HEIGHT; + } + + static readonly ConVar fast_fogvolume = new("fast_fogvolume", "0"); + + public static void R_GetVisibleFogVolume(in Vector3 eyePoint, ref VisibleFogVolumeInfo info) { + WorldBrushData brush = host_state.WorldBrush!; + if (brush.LeafWaterData == null || brush.LeafWaterData.Length == 0) { + ClearFogInfo(ref info); + return; + } + + int leafID = CM.PointLeafnum(eyePoint); + BSPMLeaf leaf = brush.Leafs![leafID]; + + Contents leafContents = (Contents)leaf.Contents; + if (leaf.LeafWaterDataID != -1) { + Assert((leafContents & (Contents.Slime | Contents.Water)) != 0); + info.EyeInFogVolume = true; + info.VisibleFogVolume = leaf.LeafWaterDataID; + info.VisibleFogVolumeLeaf = leafID; + info.FogVolumeMaterial = R_GetFogVolumeMaterial(info.VisibleFogVolume, true); + info.WaterHeight = R_GetWaterHeight(info.VisibleFogVolume); + } + else if ((leafContents & Contents.TestFogVolume) != 0) { + Assert((leafContents & (Contents.Slime | Contents.Water)) == 0); + if (fast_fogvolume.GetBool() && brush.LeafWaterData.Length == 1) { + info.VisibleFogVolume = 0; + info.VisibleFogVolumeLeaf = brush.LeafWaterData[0].FirstLeafIndex; + } + else { + VisibleFogVolumeQuery query = new(); + query.FindVisibleFogVolume(eyePoint, out info.VisibleFogVolume, out info.VisibleFogVolumeLeaf); + } + + info.EyeInFogVolume = false; + info.FogVolumeMaterial = R_GetFogVolumeMaterial(info.VisibleFogVolume, false); + info.WaterHeight = R_GetWaterHeight(info.VisibleFogVolume); + } + else + ClearFogInfo(ref info); + + if (brush.LeafMinDistToWater != null) + info.DistanceToWater = brush.LeafMinDistToWater[leafID]; + else + info.DistanceToWater = 0.0f; + } public static void R_DrawWorldLists(IWorldRenderList renderListIn, DrawWorldListFlags flags, float waterZAdjust) { WorldRenderList renderList = (WorldRenderList)renderListIn; @@ -1303,8 +1369,58 @@ public class VisibleFogVolumeQuery int VisibleFogVolume; int VisibleFogVolumeLeaf; - public void FindVisibleFogVolume(in Vector3 viewPoint, out int visibleFogVolume, out int visibleFogVolumeLeaf) => throw new NotImplementedException(); - bool RecursiveGetVisibleFogVolume(BSPMNode node) => throw new NotImplementedException(); + public void FindVisibleFogVolume(in Vector3 viewPoint, out int visibleFogVolume, out int visibleFogVolumeLeaf) { + R_SetupAreaBits(); + + SearchPoint = viewPoint; + VisibleFogVolume = -1; + VisibleFogVolumeLeaf = -1; + + RecursiveGetVisibleFogVolume(host_state.WorldBrush!.Nodes![0]); + + visibleFogVolume = VisibleFogVolume; + visibleFogVolumeLeaf = VisibleFogVolumeLeaf; + } + + bool RecursiveGetVisibleFogVolume(BSPMNode node) { + if (node.Contents == (int)Contents.Solid) + return true; + + if (node.VisFrame != r_visframecount) + return true; + + int fixmeTempRemove = FRUSTUM_CLIP_ALL; + if (R_CullNode(g_Frustum, node, ref fixmeTempRemove)) + return true; + + if (node.Contents >= 0) { + BSPMLeaf leaf = (BSPMLeaf)node; + + if (leaf.LeafWaterDataID == -1) + return true; + + if ((leaf.Contents & (int)Contents.Slime) != 0) + return true; + + VisibleFogVolume = leaf.LeafWaterDataID; + VisibleFogVolumeLeaf = leaf.Index; + return false; + } + + ref CollisionPlane plane = ref node.Plane; + float dot; + if ((byte)plane.Type <= 2) + dot = SearchPoint[(byte)plane.Type] - plane.Dist; + else + dot = Vector3.Dot(SearchPoint, plane.Normal) - plane.Dist; + + int side = (dot >= 0) ? 0 : 1; + + if (!RecursiveGetVisibleFogVolume(node.Children[side]!)) + return false; + + return RecursiveGetVisibleFogVolume(node.Children[side == 0 ? 1 : 0]!); + } } public class BrushSurface : IBrushSurface diff --git a/Source.Engine/View.cs b/Source.Engine/View.cs index f8ecdf754..4ff6eec59 100644 --- a/Source.Engine/View.cs +++ b/Source.Engine/View.cs @@ -114,6 +114,29 @@ public void SetAreaState(ReadOnlySpan areaBits, ReadOnlySpan areaPor public void DrawWorldLists(IWorldRenderList? list, uint flags, float waterZAdjust) => engineRenderer.DrawWorldLists(list, flags, waterZAdjust); public void DrawTranslucentSurfaces(IWorldRenderList? list, int sortIndex, uint flags, bool shadowDepth) => GLRSurf.Shader_DrawTranslucentSurfaces(list!, sortIndex, flags, shadowDepth); public bool LeafContainsTranslucentSurfaces(IWorldRenderList? list, int sortIndex, uint flags) => GLRSurf.Shader_LeafContainsTranslucentSurfaces(list!, sortIndex, flags); + public void GetVisibleFogVolume(in Vector3 eyePoint, ref VisibleFogVolumeInfo info) => R_GetVisibleFogVolume(in eyePoint, ref info); + + struct BoxIntersectWaterContext : ISpatialLeafEnumerator + { + public bool FoundWaterLeaf; + public int LeafWaterDataID; + + public bool EnumerateLeaf(int leaf, nint context) { + if (host_state.WorldBrush!.Leafs![leaf].LeafWaterDataID == LeafWaterDataID) { + FoundWaterLeaf = true; + return false; + } + return true; + } + } + + public bool DoesBoxIntersectWaterVolume(in Vector3 mins, in Vector3 maxs, int leafWaterDataID) { + BoxIntersectWaterContext context = default; + context.FoundWaterLeaf = false; + context.LeafWaterDataID = leafWaterDataID; + g_ToolBSPTree.EnumerateLeavesInBox(in mins, in maxs, ref context, 0); + return context.FoundWaterLeaf; + } public void BeginUpdateLightmaps() => engineRenderer.BeginUpdateLightmaps(); public void EndUpdateLightmaps() => engineRenderer.EndUpdateLightmaps(); From c2e5b374a32b27db7ca9460a1952d2e5d33eef35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:53:38 +0300 Subject: [PATCH 38/57] Add user clip planes to MatRenderContext and the GL ShaderAPI --- Game.Assets/hl2/shaders/blurfilter_gl460.vs | 3 + .../hl2/shaders/common_clipplanes_gl460.vs | 14 ++ Game.Assets/hl2/shaders/downsample_gl460.vs | 3 + Game.Assets/hl2/shaders/eyeglint_gl460.vs | 3 + Game.Assets/hl2/shaders/eyes_gl460.vs | 3 + .../hl2/shaders/lightmappedgeneric_gl460.vs | 3 + .../hl2/shaders/screenspaceeffect_gl460.vs | 3 + Game.Assets/hl2/shaders/shadow_gl460.vs | 3 + Game.Assets/hl2/shaders/shadowmodel_gl460.vs | 3 + Game.Assets/hl2/shaders/skin_gl460.vs | 3 + Game.Assets/hl2/shaders/sky_gl460.vs | 3 + Game.Assets/hl2/shaders/teeth_bump_gl460.vs | 3 + Game.Assets/hl2/shaders/teeth_gl460.vs | 3 + Game.Assets/hl2/shaders/unlitgeneric_gl460.vs | 3 + .../hl2/shaders/unlittwotexture_gl460.vs | 3 + .../shaders/vertexlitgeneric_bump_gl460.vs | 3 + .../hl2/shaders/vertexlitgeneric_gl460.vs | 3 + Game.Assets/hl2/shaders/water_gl460.vs | 3 + Game.Assets/hl2/shaders/watercheap_gl460.vs | 3 + .../shaders/worldvertextransition_gl460.vs | 3 + Game.Assets/hl2/shaders/writez_gl460.vs | 3 + Source.MaterialSystem/MatRenderContext.cs | 126 ++++++++++++++++-- Source.ShaderAPI.Gl46/HardwareConfig.cs | 6 +- Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 73 +++++++++- 24 files changed, 261 insertions(+), 18 deletions(-) create mode 100644 Game.Assets/hl2/shaders/common_clipplanes_gl460.vs diff --git a/Game.Assets/hl2/shaders/blurfilter_gl460.vs b/Game.Assets/hl2/shaders/blurfilter_gl460.vs index 8c915a90c..cd39e0a6a 100644 --- a/Game.Assets/hl2/shaders/blurfilter_gl460.vs +++ b/Game.Assets/hl2/shaders/blurfilter_gl460.vs @@ -24,9 +24,12 @@ vec2 FlipV(vec2 uv) return vec2(uv.x, 1.0 - uv.y); } +#include "common_clipplanes_gl460.vs" + void main() { gl_Position = vec4(v_Position, 1.0); + WriteUserClipDistances(gl_Position); vs_CoordTap0 = FlipV(v_TexCoord); vs_CoordTap1 = FlipV(v_TexCoord + vsTapOffs0); diff --git a/Game.Assets/hl2/shaders/common_clipplanes_gl460.vs b/Game.Assets/hl2/shaders/common_clipplanes_gl460.vs new file mode 100644 index 000000000..b0a367a24 --- /dev/null +++ b/Game.Assets/hl2/shaders/common_clipplanes_gl460.vs @@ -0,0 +1,14 @@ +#ifndef COMMON_CLIPPLANES_GL460_VS +#define COMMON_CLIPPLANES_GL460_VS + +layout(std140, binding = 7) uniform source_clip_planes { + vec4 clipPlanes[2]; +}; + +void WriteUserClipDistances(vec4 projPos) +{ + gl_ClipDistance[0] = dot(projPos, clipPlanes[0]); + gl_ClipDistance[1] = dot(projPos, clipPlanes[1]); +} + +#endif diff --git a/Game.Assets/hl2/shaders/downsample_gl460.vs b/Game.Assets/hl2/shaders/downsample_gl460.vs index b74445d1f..43b5f1873 100644 --- a/Game.Assets/hl2/shaders/downsample_gl460.vs +++ b/Game.Assets/hl2/shaders/downsample_gl460.vs @@ -22,9 +22,12 @@ vec2 FlipV(vec2 uv) return vec2(uv.x, 1.0 - uv.y); } +#include "common_clipplanes_gl460.vs" + void main() { gl_Position = vec4(v_Position, 1.0); + WriteUserClipDistances(gl_Position); vs_CoordTap0 = FlipV(v_TexCoord + vsTapOffs0); vs_CoordTap1 = FlipV(v_TexCoord + vsTapOffs1); diff --git a/Game.Assets/hl2/shaders/eyeglint_gl460.vs b/Game.Assets/hl2/shaders/eyeglint_gl460.vs index 5581b4dca..a469a3265 100644 --- a/Game.Assets/hl2/shaders/eyeglint_gl460.vs +++ b/Game.Assets/hl2/shaders/eyeglint_gl460.vs @@ -9,9 +9,12 @@ out vec2 vs_TexCoord; out vec2 vs_GlintCenter; out vec3 vs_GlintColor; +#include "common_clipplanes_gl460.vs" + void main() { gl_Position = vec4(v_Position, 1.0); + WriteUserClipDistances(gl_Position); vs_TexCoord = v_TexCoord0; vs_GlintCenter = v_TexCoord1; vs_GlintColor = v_TexCoord2; diff --git a/Game.Assets/hl2/shaders/eyes_gl460.vs b/Game.Assets/hl2/shaders/eyes_gl460.vs index 30f66c22c..db4a29985 100644 --- a/Game.Assets/hl2/shaders/eyes_gl460.vs +++ b/Game.Assets/hl2/shaders/eyes_gl460.vs @@ -59,6 +59,8 @@ out vec2 vs_GlintTexCoord; out vec3 vs_Color; out vec4 vs_WorldPos_ProjPosZ; +#include "common_clipplanes_gl460.vs" + void main() { bool bDynamicLight = DYNAMIC_LIGHT != 0; @@ -82,6 +84,7 @@ void main() vec4 vProjPos = projectionMatrix * viewMatrix * vec4(worldPos, 1.0); gl_Position = vProjPos; + WriteUserClipDistances(gl_Position); vs_WorldPos_ProjPosZ = vec4(worldPos.xyz, vProjPos.z); diff --git a/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.vs b/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.vs index 53ae605f7..5fd1ea750 100644 --- a/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.vs +++ b/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.vs @@ -81,6 +81,8 @@ out mat3 vs_TangentSpaceTranspose; out vec4 vs_Color; // in seamless, r g b = blend weights out float vs_VertexBlendX; +#include "common_clipplanes_gl460.vs" + void main() { #if SEAMLESS @@ -100,6 +102,7 @@ void main() vec4 vProjPos = projectionMatrix * viewMatrix * vec4(worldPos, 1.0); gl_Position = vProjPos; + WriteUserClipDistances(gl_Position); vs_WorldPos_ProjPosZ = vec4(worldPos, vProjPos.z); diff --git a/Game.Assets/hl2/shaders/screenspaceeffect_gl460.vs b/Game.Assets/hl2/shaders/screenspaceeffect_gl460.vs index 86b8a62bb..7c8bf863f 100644 --- a/Game.Assets/hl2/shaders/screenspaceeffect_gl460.vs +++ b/Game.Assets/hl2/shaders/screenspaceeffect_gl460.vs @@ -5,8 +5,11 @@ layout(location = 10) in vec2 v_TexCoord; out vec2 vs_BaseTexCoord; +#include "common_clipplanes_gl460.vs" + void main() { gl_Position = vec4(v_Position, 1.0); + WriteUserClipDistances(gl_Position); vs_BaseTexCoord = vec2(v_TexCoord.x, 1.0 - v_TexCoord.y); } diff --git a/Game.Assets/hl2/shaders/shadow_gl460.vs b/Game.Assets/hl2/shaders/shadow_gl460.vs index 90873555d..a9a81d5d0 100644 --- a/Game.Assets/hl2/shaders/shadow_gl460.vs +++ b/Game.Assets/hl2/shaders/shadow_gl460.vs @@ -26,11 +26,14 @@ centroid out vec2 vs_TexCoord3; centroid out vec2 vs_TexCoord4; out vec4 vs_ShadowColor; +#include "common_clipplanes_gl460.vs" + void main() { mat4 mvp = projectionMatrix * viewMatrix * modelMatrix; gl_Position = mvp * vec4(v_Position, 1.0); + WriteUserClipDistances(gl_Position); vs_ShadowColor = v_Color; diff --git a/Game.Assets/hl2/shaders/shadowmodel_gl460.vs b/Game.Assets/hl2/shaders/shadowmodel_gl460.vs index fd79dfa70..187ac37ec 100644 --- a/Game.Assets/hl2/shaders/shadowmodel_gl460.vs +++ b/Game.Assets/hl2/shaders/shadowmodel_gl460.vs @@ -31,12 +31,15 @@ out vec3 vs_T2; out float vs_T3; out vec4 vs_Color; +#include "common_clipplanes_gl460.vs" + void main() { vec3 worldPos = (modelMatrix * vec4(v_Position, 1.0)).xyz; vec3 worldNormal = mat3(modelMatrix) * v_Normal; gl_Position = projectionMatrix * viewMatrix * vec4(worldPos, 1.0); + WriteUserClipDistances(gl_Position); vec3 vTexturePos; vTexturePos.x = dot(vec4(worldPos, 1.0), cShadowTextureMatrix0); diff --git a/Game.Assets/hl2/shaders/skin_gl460.vs b/Game.Assets/hl2/shaders/skin_gl460.vs index 2ec4b4534..006c3995f 100644 --- a/Game.Assets/hl2/shaders/skin_gl460.vs +++ b/Game.Assets/hl2/shaders/skin_gl460.vs @@ -49,6 +49,8 @@ out vec4 vs_ProjPos_WrinkleWeight; //----------------------------------------------------------------------------- // Main shader entry point //----------------------------------------------------------------------------- +#include "common_clipplanes_gl460.vs" + void main() { vec4 vPosition = vec4(v_Position, 1.0); @@ -73,6 +75,7 @@ void main() // Transform into projection space vec4 vProjPos = projectionMatrix * viewMatrix * vec4(worldPos, 1.0); gl_Position = vProjPos; + WriteUserClipDistances(gl_Position); vs_ProjPos_WrinkleWeight.xyz = vProjPos.xyz; vs_ProjPos_WrinkleWeight.w = flWrinkleWeight; diff --git a/Game.Assets/hl2/shaders/sky_gl460.vs b/Game.Assets/hl2/shaders/sky_gl460.vs index 8dfe2d1bb..edc41bef7 100644 --- a/Game.Assets/hl2/shaders/sky_gl460.vs +++ b/Game.Assets/hl2/shaders/sky_gl460.vs @@ -28,9 +28,12 @@ out vec2 vs_BaseTexCoord10; out vec2 vs_BaseTexCoord11; out vec2 vs_BaseTexCoord_In_Pixels; +#include "common_clipplanes_gl460.vs" + void main() { gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(v_Position, 1.0); + WriteUserClipDistances(gl_Position); vec4 vTexCoordInput = vec4(v_TexCoord0.x, v_TexCoord0.y, 0.0, 1.0); vec2 vTexCoord; diff --git a/Game.Assets/hl2/shaders/teeth_bump_gl460.vs b/Game.Assets/hl2/shaders/teeth_bump_gl460.vs index 56bda8575..e164626f3 100644 --- a/Game.Assets/hl2/shaders/teeth_bump_gl460.vs +++ b/Game.Assets/hl2/shaders/teeth_bump_gl460.vs @@ -49,6 +49,8 @@ out vec4 vs_WorldPos_ProjPosZ; out vec2 vs_LightAtten01; out vec2 vs_LightAtten23; +#include "common_clipplanes_gl460.vs" + void main() { vec4 vPosition = vec4(v_Position, 1.0); @@ -72,6 +74,7 @@ void main() vec4 vProjPos = projectionMatrix * viewMatrix * vec4(worldPos, 1.0); gl_Position = vProjPos; + WriteUserClipDistances(gl_Position); vs_WorldPos_ProjPosZ = vec4(worldPos, vProjPos.z); diff --git a/Game.Assets/hl2/shaders/teeth_gl460.vs b/Game.Assets/hl2/shaders/teeth_gl460.vs index 68340951e..569dd4b16 100644 --- a/Game.Assets/hl2/shaders/teeth_gl460.vs +++ b/Game.Assets/hl2/shaders/teeth_gl460.vs @@ -47,6 +47,8 @@ out vec2 vs_BaseTexCoord; out vec3 vs_VertAtten; out vec4 vs_WorldPos_ProjPosZ; +#include "common_clipplanes_gl460.vs" + void main() { bool bDynamicLight = DYNAMIC_LIGHT != 0; @@ -69,6 +71,7 @@ void main() vec4 vProjPos = projectionMatrix * viewMatrix * vec4(worldPos, 1.0); gl_Position = vProjPos; + WriteUserClipDistances(gl_Position); vs_WorldPos_ProjPosZ = vec4(worldPos.xyz, vProjPos.z); diff --git a/Game.Assets/hl2/shaders/unlitgeneric_gl460.vs b/Game.Assets/hl2/shaders/unlitgeneric_gl460.vs index 08be8ce38..872ef14d8 100644 --- a/Game.Assets/hl2/shaders/unlitgeneric_gl460.vs +++ b/Game.Assets/hl2/shaders/unlitgeneric_gl460.vs @@ -22,11 +22,14 @@ uniform int flags; out vec2 vs_TexCoord; out vec4 vs_Color; +#include "common_clipplanes_gl460.vs" + void main() { mat4 mvp = projectionMatrix * viewMatrix * modelMatrix; gl_Position = mvp * vec4(v_Position, 1.0); + WriteUserClipDistances(gl_Position); vs_TexCoord = v_TexCoord; vec4 color = vs_const[47]; diff --git a/Game.Assets/hl2/shaders/unlittwotexture_gl460.vs b/Game.Assets/hl2/shaders/unlittwotexture_gl460.vs index 48bb21ce5..e60b17c3e 100644 --- a/Game.Assets/hl2/shaders/unlittwotexture_gl460.vs +++ b/Game.Assets/hl2/shaders/unlittwotexture_gl460.vs @@ -34,6 +34,8 @@ out vec2 vs_BaseTexCoord; out vec2 vs_BaseTexCoord2; out vec4 vs_WorldPos_ProjPosZ; +#include "common_clipplanes_gl460.vs" + void main() { vec4 vPosition = vec4(v_Position, 1.0); @@ -47,6 +49,7 @@ void main() vec4 vProjPos = projectionMatrix * viewMatrix * vec4(worldPos, 1.0); gl_Position = vProjPos; + WriteUserClipDistances(gl_Position); vs_WorldPos_ProjPosZ = vec4(worldPos.xyz, vProjPos.z); diff --git a/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.vs b/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.vs index 3656cf931..c3a06f430 100644 --- a/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.vs +++ b/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.vs @@ -57,6 +57,8 @@ out vec3 vs_DetailTexCoord_Atten3; //----------------------------------------------------------------------------- // Main shader entry point //----------------------------------------------------------------------------- +#include "common_clipplanes_gl460.vs" + void main() { vec4 vPosition = vec4(v_Position, 1.0); @@ -83,6 +85,7 @@ void main() // Transform into projection space vec4 vProjPos = projectionMatrix * viewMatrix * vec4(worldPos, 1.0); gl_Position = vProjPos; + WriteUserClipDistances(gl_Position); #if USE_WITH_2B vs_ProjPos = vProjPos; diff --git a/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.vs b/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.vs index a9e1c26af..662ebf713 100644 --- a/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.vs +++ b/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.vs @@ -79,6 +79,8 @@ out vec4 vs_WorldPos_ProjPosZ; out vec3 vs_SeamlessWeights; // x y z projection weights #endif +#include "common_clipplanes_gl460.vs" + void main() { bool bDynamicLight = DYNAMIC_LIGHT != 0; @@ -114,6 +116,7 @@ void main() // Transform into projection space vec4 vProjPos = projectionMatrix * viewMatrix * vec4(worldPos, 1.0); gl_Position = vProjPos; + WriteUserClipDistances(gl_Position); vs_ProjPos = vProjPos; vs_WorldPos_ProjPosZ.xyz = worldPos.xyz; diff --git a/Game.Assets/hl2/shaders/water_gl460.vs b/Game.Assets/hl2/shaders/water_gl460.vs index 283b5a4df..92be927a9 100644 --- a/Game.Assets/hl2/shaders/water_gl460.vs +++ b/Game.Assets/hl2/shaders/water_gl460.vs @@ -42,6 +42,8 @@ centroid out vec4 vs_LightmapTexCoord1And2; centroid out vec4 vs_LightmapTexCoord3; #endif +#include "common_clipplanes_gl460.vs" + void main() { vec3 vObjNormal = v_Normal; @@ -49,6 +51,7 @@ void main() vec3 vWorldPos = (modelMatrix * vec4(v_Position, 1.0)).xyz; vec4 vProjPos = projectionMatrix * viewMatrix * vec4(vWorldPos, 1.0); gl_Position = vProjPos; + WriteUserClipDistances(gl_Position); vs_ProjPos = vProjPos; vec2 vReflectPos; diff --git a/Game.Assets/hl2/shaders/watercheap_gl460.vs b/Game.Assets/hl2/shaders/watercheap_gl460.vs index 9f5399b92..dba0acdf7 100644 --- a/Game.Assets/hl2/shaders/watercheap_gl460.vs +++ b/Game.Assets/hl2/shaders/watercheap_gl460.vs @@ -30,6 +30,8 @@ out mat3 vs_TangentSpaceTranspose; out vec4 vs_Refract_W_ProjZ; out vec4 vs_ExtraBumpTexCoord; +#include "common_clipplanes_gl460.vs" + void main() { vec3 vObjNormal = v_Normal; @@ -37,6 +39,7 @@ void main() vec3 worldPos = (modelMatrix * vec4(v_Position, 1.0)).xyz; vec4 projPos = projectionMatrix * viewMatrix * vec4(worldPos, 1.0); gl_Position = projPos; + WriteUserClipDistances(gl_Position); vs_Refract_W_ProjZ = vec4(0.0); #if BLEND diff --git a/Game.Assets/hl2/shaders/worldvertextransition_gl460.vs b/Game.Assets/hl2/shaders/worldvertextransition_gl460.vs index e14df114c..250e1827a 100644 --- a/Game.Assets/hl2/shaders/worldvertextransition_gl460.vs +++ b/Game.Assets/hl2/shaders/worldvertextransition_gl460.vs @@ -15,11 +15,14 @@ out vec2 vs_TexCoord0; centroid out vec2 vs_TexCoord1; out vec4 vs_Color; +#include "common_clipplanes_gl460.vs" + void main() { mat4 mvp = projectionMatrix * viewMatrix * modelMatrix; gl_Position = mvp * vec4(v_Position, 1.0); + WriteUserClipDistances(gl_Position); vs_TexCoord0 = v_TexCoord0; vs_TexCoord1 = v_TexCoord1; vs_Color = v_Color; diff --git a/Game.Assets/hl2/shaders/writez_gl460.vs b/Game.Assets/hl2/shaders/writez_gl460.vs index 7c7fbb698..b6572f527 100644 --- a/Game.Assets/hl2/shaders/writez_gl460.vs +++ b/Game.Assets/hl2/shaders/writez_gl460.vs @@ -8,8 +8,11 @@ layout(std140, binding = 0) uniform source_matrices { mat4 modelMatrix; }; +#include "common_clipplanes_gl460.vs" + void main() { mat4 mvp = projectionMatrix * viewMatrix * modelMatrix; gl_Position = mvp * vec4(v_Position, 1.0); + WriteUserClipDistances(gl_Position); } \ No newline at end of file diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index 1c0bd1d01..e63563f55 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -8,6 +8,7 @@ using System.Numerics; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace Source.MaterialSystem; @@ -317,6 +318,15 @@ public void EndBatch() { bool DirtyViewProjState; bool EnableClippingValue; MaterialHeightClipMode HeightClipMode; + float HeightClipZ; + + struct PlaneStackElement + { + public InlineArray4 Values; + public bool Hack_IsHeightClipPlane; + } + + readonly List CustomClipPlanes = []; public bool EnableClipping(bool enable) { if (enable != EnableClippingValue) { @@ -329,8 +339,110 @@ public bool EnableClipping(bool enable) { public MaterialHeightClipMode GetHeightClipMode() => HeightClipMode; public void SetHeightClipMode(MaterialHeightClipMode heightClipMode) { - if (HeightClipMode != heightClipMode) + if (HeightClipMode != heightClipMode) { HeightClipMode = heightClipMode; + UpdateHeightClipUserClipPlane(); + } + } + + public void SetHeightClipZ(float z) { + if (z != HeightClipZ) { + HeightClipZ = z; + UpdateHeightClipUserClipPlane(); + } + } + + void UpdateHeightClipUserClipPlane() { + PlaneStackElement pse = default; + pse.Hack_IsHeightClipPlane = true; + + int existingHeightClipPlaneIndex; + for (existingHeightClipPlaneIndex = CustomClipPlanes.Count; --existingHeightClipPlaneIndex >= 0;) { + if (CustomClipPlanes[existingHeightClipPlaneIndex].Hack_IsHeightClipPlane) + break; + } + + switch (HeightClipMode) { + case MaterialHeightClipMode.Disable: + if (existingHeightClipPlaneIndex != -1) + CustomClipPlanes.RemoveAt(existingHeightClipPlaneIndex); + break; + case MaterialHeightClipMode.RenderAboveHeight: + pse.Values[0] = 0.0f; + pse.Values[1] = 0.0f; + pse.Values[2] = 1.0f; + pse.Values[3] = HeightClipZ; + if (existingHeightClipPlaneIndex != -1) + CustomClipPlanes[existingHeightClipPlaneIndex] = pse; + else + CustomClipPlanes.Add(pse); + break; + case MaterialHeightClipMode.RenderBelowHeight: + pse.Values[0] = 0.0f; + pse.Values[1] = 0.0f; + pse.Values[2] = -1.0f; + pse.Values[3] = -HeightClipZ; + if (existingHeightClipPlaneIndex != -1) + CustomClipPlanes[existingHeightClipPlaneIndex] = pse; + else + CustomClipPlanes.Add(pse); + break; + } + + ApplyCustomClipPlanes(); + } + + public void PushCustomClipPlane(ReadOnlySpan plane) { + PlaneStackElement pse = default; + plane[..4].CopyTo(pse.Values); + pse.Hack_IsHeightClipPlane = false; + CustomClipPlanes.Add(pse); + ApplyCustomClipPlanes(); + } + + public void PopCustomClipPlane() { + Assert(CustomClipPlanes.Count != 0); + + int i; + for (i = CustomClipPlanes.Count; --i >= 0;) { + if (!CustomClipPlanes[i].Hack_IsHeightClipPlane) { + CustomClipPlanes.RemoveAt(i); + break; + } + } + Assert(i != -1); + ApplyCustomClipPlanes(); + } + + void ApplyCustomClipPlanes() { + int maxClipPlanes = materials.HardwareConfig.MaxUserClipPlanes(); + int customPlanes = EnableClippingValue ? CustomClipPlanes.Count : 0; + + float fakePlaneVal = BitConverter.Int32BitsToSingle(unchecked((int)0xFFFFFFFF)); + ReadOnlySpan fakePlane = [fakePlaneVal, fakePlaneVal, fakePlaneVal, fakePlaneVal]; + + SyncMatrices(); + + Span planes = CollectionsMarshal.AsSpan(CustomClipPlanes); + if (maxClipPlanes >= customPlanes) { + int i; + for (i = 0; i < customPlanes; ++i) { + shaderAPI.SetClipPlane(i, planes[i].Values); + shaderAPI.EnableClipPlane(i, true); + } + for (; i < maxClipPlanes; ++i) { + shaderAPI.EnableClipPlane(i, false); + shaderAPI.SetClipPlane(i, fakePlane); + } + } + else { + int customPlaneOffset = customPlanes - maxClipPlanes; + + for (int i = customPlaneOffset; i < customPlanes; ++i) { + shaderAPI.SetClipPlane(i % maxClipPlanes, planes[i].Values); + shaderAPI.EnableClipPlane(i % maxClipPlanes, true); + } + } } public bool InFlashlightMode() { @@ -1085,10 +1197,6 @@ public void PickMatrix(int x, int y, int width, int height) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void PopCustomClipPlane() { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } - public void PopDeformation() { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } @@ -1097,10 +1205,6 @@ public void PopSelectionName() { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void PushCustomClipPlane(ReadOnlySpan plane) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } - public void PushDeformation(ref readonly DeformationBase deformation) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } @@ -1178,10 +1282,6 @@ public void SetGoalToneMappingScale(float monoscale) { GoalToneMapScale = monoscale; } - public void SetHeightClipZ(float z) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } - public void SetIntRenderingParameter(int parm_number, int value) => shaderAPI.SetIntRenderingParameter(parm_number, value); public void SetLookupWeight(ColorCorrectionHandle_t handle, float weight) { diff --git a/Source.ShaderAPI.Gl46/HardwareConfig.cs b/Source.ShaderAPI.Gl46/HardwareConfig.cs index fa9a85af8..fc39fad1f 100644 --- a/Source.ShaderAPI.Gl46/HardwareConfig.cs +++ b/Source.ShaderAPI.Gl46/HardwareConfig.cs @@ -159,8 +159,10 @@ public unsafe int MaxTextureWidth() { return *maxTextureSize; } + public const int MAXUSERCLIPPLANES = 2; + public int MaxUserClipPlanes() { - throw new NotImplementedException(); + return MAXUSERCLIPPLANES; } public int MaxVertexShaderBlendMatrices() { @@ -328,7 +330,7 @@ public nint TextureMemorySize() { } public bool UseFastClipping() { - throw new NotImplementedException(); + return false; } static readonly ConVar r_shader_srgb = new("r_shader_srgb", "0", 0, "-1 = use hardware caps. 0 = use hardware srgb. 1 = use shader srgb(software lookup)"); diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index 68ee12b93..2b8a344d8 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -46,7 +46,8 @@ public enum UniformBufferBindingLocation VertexShaderConstants = 5, /// source_ps_constants: Pixel shader float constants. PixelShaderConstants = 6, - Count = 7 + UserClipPlanes = 7, + Count = 8 } public static class UniformBufferBindings @@ -253,6 +254,47 @@ private unsafe void CreateMatrixStacks() { glObjectLabel(GL_BUFFER, uboPixelConstants, "ShaderAPI Pixel Shader Constants UBO"); glNamedBufferData(uboPixelConstants, sizeof(float) * NUM_PIXEL_SHADER_CONSTANTS * 4, null, GL_DYNAMIC_DRAW); UniformBufferBindings.Bind(UniformBufferBindingLocation.PixelShaderConstants, uboPixelConstants); + + uboClipPlanes = glCreateBuffer(); + glObjectLabel(GL_BUFFER, uboClipPlanes, "ShaderAPI User Clip Planes UBO"); + glNamedBufferData(uboClipPlanes, sizeof(Vector4) * Gl46.HardwareConfig.MAXUSERCLIPPLANES, null, GL_DYNAMIC_DRAW); + UniformBufferBindings.Bind(UniformBufferBindingLocation.UserClipPlanes, uboClipPlanes); + } + + uint uboClipPlanes; + int UserClipPlaneEnabled; + int UserClipPlaneChanged; + readonly Vector4[] UserClipPlaneWorld = new Vector4[Gl46.HardwareConfig.MAXUSERCLIPPLANES]; + readonly Vector4[] UserClipPlaneProj = new Vector4[Gl46.HardwareConfig.MAXUSERCLIPPLANES]; + + private void MarkAllUserClipPlanesDirty() { + UserClipPlaneChanged |= (1 << Gl46.HardwareConfig.MAXUSERCLIPPLANES) - 1; + } + + private unsafe void CommitUserClipPlanes() { + if ((UserClipPlaneChanged & UserClipPlaneEnabled & ((1 << Gl46.HardwareConfig.MAXUSERCLIPPLANES) - 1)) == 0) + return; + + Matrix4x4 worldToProjectionInvTrans = Matrices[(int)MaterialMatrixMode.View] * Matrices[(int)MaterialMatrixMode.Projection]; + Matrix4x4.Invert(worldToProjectionInvTrans, out worldToProjectionInvTrans); + worldToProjectionInvTrans = Matrix4x4.Transpose(worldToProjectionInvTrans); + + for (int i = 0; i < Gl46.HardwareConfig.MAXUSERCLIPPLANES; ++i) { + if ((UserClipPlaneEnabled & (1 << i)) == 0) + continue; + + if ((UserClipPlaneChanged & (1 << i)) == 0) + continue; + + UserClipPlaneChanged &= ~(1 << i); + + Vector4 clipPlaneProj = Vector4.Transform(UserClipPlaneWorld[i], worldToProjectionInvTrans); + + if (clipPlaneProj != UserClipPlaneProj[i]) { + glNamedBufferSubData(uboClipPlanes, i * sizeof(Vector4), sizeof(Vector4), &clipPlaneProj); + UserClipPlaneProj[i] = clipPlaneProj; + } + } } private void AcquireInternalRenderTargets() { @@ -931,6 +973,8 @@ private void CommitStateChanges() { CommitVertexShaderLighting(); + if (UserClipPlaneEnabled != 0) + CommitUserClipPlanes(); } [Flags] @@ -1594,6 +1638,9 @@ public unsafe void LoadMatrix(in Matrix4x4 m4x4) { CacheWorldSpaceCameraPosition(); UpdateVertexShaderFogParams(); } + + if (currentMode == MaterialMatrixMode.View || currentMode == MaterialMatrixMode.Projection) + MarkAllUserClipPlanesDirty(); } public void GetMatrix(MaterialMatrixMode matrixMode, out Matrix4x4 dst) { @@ -3124,7 +3171,18 @@ public void EnableAlphaToCoverage() { } public void EnableClipPlane(int index, bool bEnable) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + Assert(index < Gl46.HardwareConfig.MAXUSERCLIPPLANES && index >= 0); + if (((UserClipPlaneEnabled & (1 << index)) != 0) != bEnable) { + FlushBufferedPrimitives(); + if (bEnable) { + UserClipPlaneEnabled |= 1 << index; + glEnable(GL_CLIP_DISTANCE0 + index); + } + else { + UserClipPlaneEnabled &= ~(1 << index); + glDisable(GL_CLIP_DISTANCE0 + index); + } + } } public void EnableFastClip(bool enable) { @@ -3356,7 +3414,16 @@ public void SetAnisotropicLevel(int anisotropyLevel) { } public void SetClipPlane(int index, ReadOnlySpan plane) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + Assert(index < Gl46.HardwareConfig.MAXUSERCLIPPLANES && index >= 0); + + Vector4 worldPlane = new(plane[0], plane[1], plane[2], -plane[3]); + + if (worldPlane != UserClipPlaneWorld[index]) { + FlushBufferedPrimitives(); + + UserClipPlaneChanged |= 1 << index; + UserClipPlaneWorld[index] = worldPlane; + } } public void SetDisallowAccess(bool access) { From a1c54cbb3ab7083ee1e7670b05c905b67eb2c99d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:55:14 +0300 Subject: [PATCH 39/57] Fix EnableClipping starting disabled and not reapplying clip planes --- Source.MaterialSystem/MatRenderContext.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index e63563f55..4b5354d5a 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -316,7 +316,7 @@ public void EndBatch() { bool FlashlightEnable; bool DirtyViewState; bool DirtyViewProjState; - bool EnableClippingValue; + bool EnableClippingValue = true; MaterialHeightClipMode HeightClipMode; float HeightClipZ; @@ -331,6 +331,8 @@ struct PlaneStackElement public bool EnableClipping(bool enable) { if (enable != EnableClippingValue) { EnableClippingValue = enable; + ApplyCustomClipPlanes(); + return !enable; } return enable; From 6a003469e2a2b8e5ae128fa1fd5de9e4f680ec29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:56:47 +0300 Subject: [PATCH 40/57] Implement SetFogZ in MatRenderContext and the GL ShaderAPI --- Source.MaterialSystem/MatRenderContext.cs | 4 +--- Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 9 +++++++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index 4b5354d5a..12d2346b0 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -1270,9 +1270,7 @@ public void SetFlexWeights(int firstWeight, ReadOnlySpan weights) { public void SetFloatRenderingParameter(int parm_number, float value) => shaderAPI.SetFloatRenderingParameter(parm_number, value); - public void SetFogZ(float fogZ) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void SetFogZ(float fogZ) => shaderAPI.SetFogZ(fogZ); public void SetFullScreenDepthTextureValidityFlag(bool isValid) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index 2b8a344d8..bb428855c 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -266,6 +266,7 @@ private unsafe void CreateMatrixStacks() { int UserClipPlaneChanged; readonly Vector4[] UserClipPlaneWorld = new Vector4[Gl46.HardwareConfig.MAXUSERCLIPPLANES]; readonly Vector4[] UserClipPlaneProj = new Vector4[Gl46.HardwareConfig.MAXUSERCLIPPLANES]; + float FogZ; private void MarkAllUserClipPlanesDirty() { UserClipPlaneChanged |= (1 << Gl46.HardwareConfig.MAXUSERCLIPPLANES) - 1; @@ -820,7 +821,7 @@ private void UpdateVertexShaderFogParams() { WorldSpaceCameraPosition.X, WorldSpaceCameraPosition.Y, WorldSpaceCameraPosition.Z, - 0.0f, // todo: waterheight + FogZ, ]; SetVertexShaderConstant(VertexShaderConst.CameraPos, vertexShaderCameraPos); @@ -3443,7 +3444,11 @@ public void SetFlexWeights(int firstWeight, ReadOnlySpan weights) { } public void SetFogZ(float fogZ) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + if (fogZ != FogZ) { + FlushBufferedPrimitives(); + FogZ = fogZ; + UpdateVertexShaderFogParams(); + } } public void SetFullScreenTextureHandle(ShaderAPITextureHandle_t h) { From db2d7b706717d831b680c9c7fed3b12785020262 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 03:04:21 +0300 Subject: [PATCH 41/57] Port the water reflection and refraction views --- Game.Client/C_WaterLODControl.cs | 5 + Game.Client/View.cs | 161 +++++++++++- Game.Client/ViewRender.cs | 418 ++++++++++++++++++++++++++++++- 3 files changed, 568 insertions(+), 16 deletions(-) diff --git a/Game.Client/C_WaterLODControl.cs b/Game.Client/C_WaterLODControl.cs index 1937413a1..eb545061f 100644 --- a/Game.Client/C_WaterLODControl.cs +++ b/Game.Client/C_WaterLODControl.cs @@ -20,5 +20,10 @@ public class C_WaterLODControl : C_BaseEntity public float CheapWaterStartDistance; [NetworkName("m_flCheapWaterEndDistance")] public float CheapWaterEndDistance; + + public override void OnDataChanged(DataUpdateType updateType) { + view.SetCheapWaterStartDistance(CheapWaterStartDistance); + view.SetCheapWaterEndDistance(CheapWaterEndDistance); + } } diff --git a/Game.Client/View.cs b/Game.Client/View.cs index c9cab4fdb..5d9998712 100644 --- a/Game.Client/View.cs +++ b/Game.Client/View.cs @@ -135,6 +135,8 @@ public DrawFlags GetDrawFlags() { throw new NotImplementedException(); } + public DrawFlags GetBaseDrawFlags() => BaseDrawFlags; + public Frustum GetFrustum() => ActiveRenderer?.GetFrustrum() ?? Frustum; public ref ViewSetup GetPlayerViewSetup() => ref GetView(StereoEye.Mono); @@ -641,11 +643,154 @@ private void ViewDrawScene_Intro(in ViewSetup view, ClearFlags clearFlags, Intro static RenderUtils? _renderUtils; static RenderUtils renderUtils => _renderUtils ??= Singleton(); - private void DrawWorldAndEntities(bool drawSkybox, in ViewSetup viewRender, ClearFlags clearFlags) { - SimpleWorldView noWaterView = new SimpleWorldView(this); - noWaterView.Setup(in viewRender, clearFlags, drawSkybox); - AddViewToScene(noWaterView); - noWaterView.ReleaseLists(); + float CheapWaterStartDistance = 0.0f; + float CheapWaterEndDistance = 0.1f; + + private void DetermineWaterRenderInfo(in VisibleFogVolumeInfo fogVolumeInfo, out WaterRenderInfo info) { + info.CheapWater = true; + info.Refract = false; + info.Reflect = false; + info.ReflectEntities = false; + info.DrawWaterSurface = false; + info.OpaqueWater = true; + + IMaterial? waterMaterial = fogVolumeInfo.FogVolumeMaterial; + if ((fogVolumeInfo.VisibleFogVolume == -1) || waterMaterial == null) + return; + + info.DrawWaterSurface = mat_drawwater.GetBool(); + if (!info.DrawWaterSurface) { + info.OpaqueWater = false; + return; + } + + bool forceExpensive = r_waterforceexpensive.GetBool(); + bool forceReflectEntities = r_waterforcereflectentities.GetBool(); + + info.OpaqueWater = !waterMaterial.IsTranslucent(); + + bool forceCheap = false; + + waterMaterial.TryFindVar("$forcecheap", out IMaterialVar? forceCheapVar, false); + waterMaterial.TryFindVar("$forceexpensive", out IMaterialVar? forceExpensiveVar, false); + if (forceCheapVar != null && forceCheapVar.IsDefined()) { + forceCheap = forceCheapVar.GetIntValue() != 0; + if (forceCheap) + forceExpensive = false; + } + if (!forceCheap && forceExpensiveVar != null && forceExpensiveVar.IsDefined()) + forceExpensive = forceExpensive || (forceExpensiveVar.GetIntValue() != 0); + + bool debugCheapWater = r_debugcheapwater.GetBool(); + if (debugCheapWater) + Msg($"Water material: {waterMaterial.GetName()} dist to water: {fogVolumeInfo.DistanceToWater}\nforcecheap: {(forceCheap ? "true" : "false")} forceexpensive: {(forceExpensive ? "true" : "false")}\n"); + + bool localReflection; + if (!forceExpensive || !r_WaterDrawReflection.GetBool()) + localReflection = false; + else { + waterMaterial.TryFindVar("$reflecttexture", out IMaterialVar? reflectTextureVar, false); + localReflection = reflectTextureVar != null && (reflectTextureVar.GetVarType() == MaterialVarType.Texture); + } + + if (((fogVolumeInfo.DistanceToWater >= CheapWaterEndDistance) && !localReflection) || forceCheap) + return; + + if (!r_WaterDrawRefraction.GetBool()) + info.Refract = false; + else { + waterMaterial.TryFindVar("$refracttexture", out IMaterialVar? refractTextureVar, true); + info.Refract = refractTextureVar != null && (refractTextureVar.GetVarType() == MaterialVarType.Texture); + + if (info.Refract) + info.OpaqueWater = false; + } + + info.Reflect = localReflection; + if (info.Reflect) { + if (forceReflectEntities) + info.ReflectEntities = true; + else { + waterMaterial.TryFindVar("$reflectentities", out IMaterialVar? reflectEntitiesVar, false); + info.ReflectEntities = reflectEntitiesVar != null && (reflectEntitiesVar.GetIntValue() != 0); + } + } + + info.CheapWater = !info.Reflect && !info.Refract; + + if (debugCheapWater) + Warning($"refract: {(info.Refract ? "true" : "false")} reflect: {(info.Reflect ? "true" : "false")}\n"); + } + + private void DrawWorldAndEntities(bool drawSkybox, in ViewSetup viewIn, ClearFlags clearFlags) { + VisibleFogVolumeInfo fogVolumeInfo = default; + render.GetVisibleFogVolume(in viewIn.Origin, ref fogVolumeInfo); + + DetermineWaterRenderInfo(in fogVolumeInfo, out WaterRenderInfo info); + + if (info.CheapWater) { + SimpleWorldView noWaterView = new SimpleWorldView(this); + noWaterView.Setup(in viewIn, clearFlags, drawSkybox, in fogVolumeInfo, in info); + AddViewToScene(noWaterView); + noWaterView.ReleaseLists(); + return; + } + + if (!r_ForceWaterLeaf.GetBool()) + fogVolumeInfo.VisibleFogVolumeLeaf = -1; + + if (!fogVolumeInfo.EyeInFogVolume) { + AboveWaterView aboveWaterView = new AboveWaterView(this); + aboveWaterView.Setup(in viewIn, drawSkybox, in fogVolumeInfo, in info); + AddViewToScene(aboveWaterView); + aboveWaterView.ReleaseLists(); + } + else { + UnderWaterView underWaterView = new UnderWaterView(this); + underWaterView.Setup(in viewIn, drawSkybox, in fogVolumeInfo, in info); + AddViewToScene(underWaterView); + underWaterView.ReleaseLists(); + } + } + + public static bool DoesViewPlaneIntersectWater(float waterZ, int leafWaterDataID) { + if (leafWaterDataID == -1) + return false; + + using MatRenderContextPtr renderContext = new(SourceDllMain.materials); + + renderContext.GetMatrix(MaterialMatrixMode.View, out Matrix4x4 viewMatrix); + renderContext.GetMatrix(MaterialMatrixMode.Projection, out Matrix4x4 projectionMatrix); + MathLib.MatrixMultiply(in projectionMatrix, in viewMatrix, out Matrix4x4 viewProjectionMatrix); + MathLib.MatrixInverseGeneral(in viewProjectionMatrix, out Matrix4x4 inverseViewProjectionMatrix); + + MathLib.ClearBounds(out Vector3 mins, out Vector3 maxs); + ReadOnlySpan testPoint = [ + new(-1.0f, -1.0f, 0.0f), + new(-1.0f, 1.0f, 0.0f), + new(1.0f, -1.0f, 0.0f), + new(1.0f, 1.0f, 0.0f), + ]; + bool above = false; + bool below = false; + float fudge = 7.0f; + for (int i = 0; i < 4; i++) { + MathLib.Vector3DMultiplyPositionProjective(in inverseViewProjectionMatrix, in testPoint[i], out Vector3 worldPos); + MathLib.AddPointToBounds(worldPos, ref mins, ref maxs); + if (worldPos.Z + fudge > waterZ) + above = true; + if (worldPos.Z - fudge < waterZ) + below = true; + } + + if (!(above && below)) + return false; + + Vector3 vecFudge = new(fudge, fudge, fudge); + mins -= vecFudge; + maxs += vecFudge; + + return SourceDllMain.render.DoesBoxIntersectWaterVolume(in mins, in maxs, leafWaterDataID); } public static Vector3 g_VecRenderOrigin = new(0, 0, 0); @@ -797,7 +942,7 @@ private void CleanupMain3DView(in ViewSetup viewRender) { render.PopView(GetFrustum()); } - private void AddViewToScene(Rendering3dView view) { + public void AddViewToScene(Rendering3dView view) { SimpleExecutor.AddView(view); } @@ -813,11 +958,11 @@ private void SetupMain3DView(in ViewSetup viewRender, ClearFlags clearFlags) { } public void SetCheapWaterEndDistance(float cheapWaterEndDistance) { - throw new NotImplementedException(); + CheapWaterEndDistance = cheapWaterEndDistance; } public void SetCheapWaterStartDistance(float cheapWaterStartDistance) { - throw new NotImplementedException(); + CheapWaterStartDistance = cheapWaterStartDistance; } public void SetScreenOverlayMaterial(IMaterial? pMaterial) { diff --git a/Game.Client/ViewRender.cs b/Game.Client/ViewRender.cs index aefa79c68..f3ee8e8d3 100644 --- a/Game.Client/ViewRender.cs +++ b/Game.Client/ViewRender.cs @@ -28,6 +28,24 @@ public static class ViewRenderConVars internal readonly static ConVar r_drawopaquerenderables = new("1", FCvar.Cheat); internal readonly static ConVar r_threaded_renderables = new("0", 0); internal readonly static ConVar r_DrawDetailProps = new("1", FCvar.None, "0=Off, 1=Normal, 2=Wireframe"); + internal readonly static ConVar r_debugcheapwater = new("0", FCvar.Cheat); + internal readonly static ConVar r_waterforceexpensive = new("0", FCvar.Archive); + internal readonly static ConVar r_waterforcereflectentities = new("0", 0); + internal readonly static ConVar r_WaterDrawRefraction = new("1", 0, "Enable water refraction"); + internal readonly static ConVar r_WaterDrawReflection = new("1", 0, "Enable water reflection"); + internal readonly static ConVar r_ForceWaterLeaf = new("1", 0, "Enable for optimization to water - considers view in leaf under water for purposes of culling"); + internal readonly static ConVar mat_drawwater = new("1", FCvar.Cheat); + internal readonly static ConVar mat_clipz = new("1", 0); +} + +public struct WaterRenderInfo +{ + public bool CheapWater; + public bool Reflect; + public bool Refract; + public bool ReflectEntities; + public bool DrawWaterSurface; + public bool OpaqueWater; } public class RenderExecutor @@ -106,20 +124,136 @@ public Base3dView(ViewRender mainView) { public class BaseWorldView : Rendering3dView { public BaseWorldView(ViewRender mainView) : base(mainView) { } - protected void DrawSetup(float waterHeight, DrawFlags setupFlags, float waterZAdjust) { + + static Vector3 SavedLinearLightMapScale = new(-1, -1, -1); + + static void SetLightmapScaleForWater() { + if (Singleton().GetHDRType() == HDRType.Integer) { + using MatRenderContextPtr renderContext = new(materials); + SavedLinearLightMapScale = renderContext.GetToneMappingScaleLinear(); + Vector3 t25 = SavedLinearLightMapScale; + t25 *= 0.25f; + renderContext.SetToneMappingScaleLinear(t25); + } + } + + protected bool AdjustView(float waterHeight) { + if ((DrawFlags & DrawFlags.RenderRefraction) != 0) { + ITexture texture = RenderTexture.GetWaterRefractionTexture()!; + + setup.X = setup.Y = 0; + setup.Width = texture.GetActualWidth(); + setup.Height = texture.GetActualHeight(); + + return true; + } + + if ((DrawFlags & DrawFlags.RenderReflection) != 0) { + ITexture texture = RenderTexture.GetWaterReflectionTexture()!; + + if (setup.ViewToProjectionOverride) + setup.ViewToProjection.M23 = -setup.ViewToProjection.M23; + + setup.X = setup.Y = 0; + setup.Width = texture.GetActualWidth(); + setup.Height = texture.GetActualHeight(); + setup.Angles.X = -setup.Angles.X; + setup.Angles.Z = -setup.Angles.Z; + setup.Origin.Z -= 2.0f * (setup.Origin.Z - waterHeight); + return true; + } + + return false; + } + + protected void PushView(float waterHeight) { + float spread = 2.0f; + if ((DrawFlags & DrawFlags.FudgeUp) != 0) + waterHeight += spread; + else + waterHeight -= spread; + + MaterialHeightClipMode clipMode = MaterialHeightClipMode.Disable; + if ((DrawFlags & DrawFlags.ClipZ) != 0 && mat_clipz.GetBool()) { + if ((DrawFlags & DrawFlags.ClipBelow) != 0) + clipMode = MaterialHeightClipMode.RenderAboveHeight; + else + clipMode = MaterialHeightClipMode.RenderBelowHeight; + } + + using MatRenderContextPtr renderContext = new(mainView.materials); + + if ((DrawFlags & DrawFlags.RenderRefraction) != 0) { + renderContext.SetFogZ(waterHeight); + renderContext.SetHeightClipZ(waterHeight); + renderContext.SetHeightClipMode(clipMode); + + render.Push3DView(in setup, ClearFlags, RenderTexture.GetWaterRefractionTexture(), GetFrustrum(), null); + + return; + } + + if ((DrawFlags & DrawFlags.RenderReflection) != 0) { + ITexture? texture = RenderTexture.GetWaterReflectionTexture(); + + renderContext.SetFogZ(waterHeight); + renderContext.SetHeightClipZ(waterHeight); + renderContext.SetHeightClipMode(clipMode); + + render.Push3DView(in setup, ClearFlags, texture, GetFrustrum(), null); + + SetLightmapScaleForWater(); + return; + } + + if ((ClearFlags & (ClearFlags.ClearDepth | ClearFlags.ClearColor | ClearFlags.ClearStencil)) != 0) { + if ((ClearFlags & ClearFlags.ClearObeyStencil) != 0) + renderContext.ClearBuffersObeyStencil((ClearFlags & ClearFlags.ClearColor) != 0, (ClearFlags & ClearFlags.ClearDepth) != 0); + else + renderContext.ClearBuffers((ClearFlags & ClearFlags.ClearColor) != 0, (ClearFlags & ClearFlags.ClearDepth) != 0, (ClearFlags & ClearFlags.ClearStencil) != 0); + } + + renderContext.SetHeightClipMode(clipMode); + if (clipMode != MaterialHeightClipMode.Disable) + renderContext.SetHeightClipZ(waterHeight); + } + + protected void PopView() { + using MatRenderContextPtr renderContext = new(mainView.materials); + + renderContext.SetHeightClipMode(MaterialHeightClipMode.Disable); + if ((DrawFlags & (DrawFlags.RenderRefraction | DrawFlags.RenderReflection)) != 0) { + render.PopView(GetFrustrum()); + if (SavedLinearLightMapScale.X >= 0) { + renderContext.SetToneMappingScaleLinear(SavedLinearLightMapScale); + SavedLinearLightMapScale.X = -1; + } + } + } + + protected void DrawSetup(float waterHeight, DrawFlags setupFlags, float waterZAdjust, int forceViewLeaf = -1) { ViewID savedViewID = ViewRender.g_CurrentViewID; ViewRender.g_CurrentViewID = ViewID.Illegal; + bool viewChanged = AdjustView(waterHeight); + + if (viewChanged) + render.Push3DView(in setup, 0, null, GetFrustrum(), null); + render.BeginUpdateLightmaps(); bool drawEntities = (setupFlags & DrawFlags.DrawEntities) != 0; - BuildWorldRenderLists(drawEntities, -1, true); + bool drawReflection = (setupFlags & DrawFlags.RenderReflection) != 0; + BuildWorldRenderLists(drawEntities, forceViewLeaf, true, false, drawReflection ? new Span(ref waterHeight) : default); if (drawEntities) BuildRenderableRenderLists(savedViewID); render.EndUpdateLightmaps(); + if (viewChanged) + render.PopView(GetFrustrum()); + ViewRender.g_CurrentViewID = savedViewID; } @@ -142,10 +276,19 @@ protected void DrawExecute(float waterHeight, ViewID viewID, float waterZAdjust) g_ClientShadowMgr.ComputeShadowTextures(in setup, WorldListInfo.LeafCount, WorldListInfo.LeafList); MaybeInvalidateLocalPlayerAnimation(); - ViewRender.g_CurrentViewID = savedViewID; + engine.Sound_ExtraUpdate(); + + ViewRender.g_CurrentViewID = viewID; + + DrawFlags drawFlagsBackup = DrawFlags; + DrawFlags |= mainView.GetBaseDrawFlags(); + + PushView(waterHeight); using MatRenderContextPtr renderContext = new(mainView.materials); - renderContext.ClearBuffers(false, true, false); + + ITexture? saveFrameBufferCopyTexture = renderContext.GetFrameBufferCopyTexture(0); + renderContext.SetFrameBufferCopyTexture(RenderTexture.GetPowerOfTwoFrameBufferTexture()); RenderDepthMode depthMode = RenderDepthMode.Normal; @@ -154,27 +297,286 @@ protected void DrawExecute(float waterHeight, ViewID viewID, float waterZAdjust) DrawOpaqueRenderables(depthMode); DrawTranslucentRenderables(depthMode); } + else { + DrawWorld(waterZAdjust); + DrawTranslucentWorldInLeaves(false); + } + + renderContext.SetFrameBufferCopyTexture(saveFrameBufferCopyTexture); + PopView(); + + DrawFlags = drawFlagsBackup; + + ViewRender.g_CurrentViewID = savedViewID; } } public class SimpleWorldView : BaseWorldView { + VisibleFogVolumeInfo FogInfo; + public SimpleWorldView(ViewRender mainView) : base(mainView) { } - public void Setup(in ViewSetup view, ClearFlags clearFlags, bool drawSkybox) { + public void Setup(in ViewSetup view, ClearFlags clearFlags, bool drawSkybox, in VisibleFogVolumeInfo fogInfo, in WaterRenderInfo waterInfo) { base.Setup(in view); ClearFlags = clearFlags; DrawFlags = DrawFlags.DrawEntities; - DrawFlags |= DrawFlags.RenderUnderwater | DrawFlags.RenderAbovewater; + if (!waterInfo.OpaqueWater) + DrawFlags |= DrawFlags.RenderUnderwater | DrawFlags.RenderAbovewater; + else { + bool viewIntersectsWater = ViewRender.DoesViewPlaneIntersectWater(fogInfo.WaterHeight, fogInfo.VisibleFogVolume); + if (viewIntersectsWater) + DrawFlags |= DrawFlags.RenderUnderwater | DrawFlags.RenderAbovewater; + else if (fogInfo.EyeInFogVolume) + DrawFlags |= DrawFlags.RenderUnderwater; + else + DrawFlags |= DrawFlags.RenderAbovewater; + } + if (waterInfo.DrawWaterSurface) + DrawFlags |= DrawFlags.RenderWater; + + if (!fogInfo.EyeInFogVolume && drawSkybox) + DrawFlags |= DrawFlags.DrawSkybox; + + FogInfo = fogInfo; + } + public override void Draw() { + DrawSetup(0, DrawFlags, 0); + + if (FogInfo.EyeInFogVolume) + ClearFlags |= ClearFlags.ClearColor; + + DrawExecute(0, CurrentViewID(), 0); + + using MatRenderContextPtr renderContext = new(mainView.materials); + renderContext.ClearColor4ub(0, 0, 0, 255); + } +} + +public class BaseWaterView : BaseWorldView +{ + protected VisibleFogVolumeInfo FogInfo; + protected float WaterHeight; + + public BaseWaterView(ViewRender mainView) : base(mainView) { } +} + +public class AboveWaterView : BaseWaterView +{ + WaterRenderInfo WaterInfo; + readonly ReflectionView Reflection; + readonly RefractionView Refraction; + readonly IntersectionView Intersection; + + public AboveWaterView(ViewRender mainView) : base(mainView) { + Reflection = new(mainView, this); + Refraction = new(mainView, this); + Intersection = new(mainView, this); + } + + public void Setup(in ViewSetup view, bool drawSkybox, in VisibleFogVolumeInfo fogInfo, in WaterRenderInfo waterInfo) { + base.Setup(in view); + + WaterHeight = fogInfo.WaterHeight; + + DrawFlags = DrawFlags.RenderAbovewater | DrawFlags.DrawEntities; + ClearFlags = ClearFlags.ClearDepth; if (drawSkybox) DrawFlags |= DrawFlags.DrawSkybox; + + if (waterInfo.DrawWaterSurface) + DrawFlags |= DrawFlags.RenderWater; + if (!waterInfo.Refract && !waterInfo.OpaqueWater) + DrawFlags |= DrawFlags.RenderUnderwater; + + FogInfo = fogInfo; + WaterInfo = waterInfo; + } + + public override void ReleaseLists() { + base.ReleaseLists(); + Reflection.ReleaseLists(); + Refraction.ReleaseLists(); + Intersection.ReleaseLists(); } + public override void Draw() { + if (WaterInfo.Reflect) { + Reflection.Setup(WaterInfo.ReflectEntities); + mainView.AddViewToScene(Reflection); + } + + bool viewIntersectsWater = false; + + if (WaterInfo.Refract) { + Refraction.Setup(); + mainView.AddViewToScene(Refraction); + + viewIntersectsWater = ViewRender.DoesViewPlaneIntersectWater(FogInfo.WaterHeight, FogInfo.VisibleFogVolume); + } + else if ((DrawFlags & DrawFlags.DrawSkybox) == 0) + ClearFlags |= ClearFlags.ClearColor; + + if (viewIntersectsWater) + DrawFlags |= DrawFlags.ClipZ | DrawFlags.ClipBelow; + + DrawSetup(WaterHeight, DrawFlags, 0); + DrawExecute(WaterHeight, CurrentViewID(), 0); + + if (WaterInfo.Refract && viewIntersectsWater) { + Intersection.Setup(); + mainView.AddViewToScene(Intersection); + } + } + + class ReflectionView(ViewRender mainView, AboveWaterView outer) : BaseWorldView(mainView) + { + public void Setup(bool reflectEntities) { + base.Setup(in outer.setup); + + ClearFlags = ClearFlags.ClearDepth; + + DrawFlags = DrawFlags.RenderReflection | DrawFlags.ClipZ | DrawFlags.ClipBelow | DrawFlags.RenderAbovewater; + + DrawFlags |= DrawFlags.DrawSkybox; + + if (reflectEntities) + DrawFlags |= DrawFlags.DrawEntities; + } + + public override void Draw() { + ViewID saveViewID = CurrentViewID(); + SetupCurrentView(in setup.Origin, in setup.Angles, ViewID.Reflection); + + DrawSetup(outer.FogInfo.WaterHeight, DrawFlags, 0.0f, outer.FogInfo.VisibleFogVolumeLeaf); + + DrawExecute(outer.FogInfo.WaterHeight, ViewID.Reflection, 0.0f); + + SetupCurrentView(in setup.Origin, in setup.Angles, saveViewID); + + using MatRenderContextPtr renderContext = new(mainView.materials); + renderContext.Flush(); + } + } + + class RefractionView(ViewRender mainView, AboveWaterView outer) : BaseWorldView(mainView) + { + public void Setup() { + base.Setup(in outer.setup); + + ClearFlags = ClearFlags.ClearColor | ClearFlags.ClearDepth; + + DrawFlags = DrawFlags.RenderRefraction | DrawFlags.ClipZ | DrawFlags.RenderUnderwater | DrawFlags.FudgeUp | DrawFlags.DrawEntities; + } + + public override void Draw() { + ViewID saveViewID = CurrentViewID(); + SetupCurrentView(in setup.Origin, in setup.Angles, ViewID.Refraction); + + DrawSetup(outer.WaterHeight, DrawFlags, 0); + + DrawExecute(outer.WaterHeight, ViewID.Refraction, 0); + + SetupCurrentView(in setup.Origin, in setup.Angles, saveViewID); + + using MatRenderContextPtr renderContext = new(mainView.materials); + renderContext.ClearColor4ub(0, 0, 0, 255); + renderContext.Flush(); + } + } + + class IntersectionView(ViewRender mainView, AboveWaterView outer) : BaseWorldView(mainView) + { + public void Setup() { + base.Setup(in outer.setup); + DrawFlags = DrawFlags.RenderUnderwater | DrawFlags.ClipZ | DrawFlags.DrawEntities; + } + + public override void Draw() { + DrawSetup(outer.FogInfo.WaterHeight, DrawFlags, 0); + + DrawExecute(outer.FogInfo.WaterHeight, ViewID.None, 0); + using MatRenderContextPtr renderContext = new(mainView.materials); + renderContext.ClearColor4ub(0, 0, 0, 255); + } + } +} + +public class UnderWaterView : BaseWaterView +{ + WaterRenderInfo WaterInfo; + bool DrawSkybox; + readonly RefractionView Refraction; + + public UnderWaterView(ViewRender mainView) : base(mainView) { + Refraction = new(mainView, this); + } + + public void Setup(in ViewSetup view, bool drawSkybox, in VisibleFogVolumeInfo fogInfo, in WaterRenderInfo waterInfo) { + base.Setup(in view); + + WaterHeight = fogInfo.WaterHeight; + + DrawFlags = DrawFlags.FudgeUp | DrawFlags.RenderUnderwater | DrawFlags.DrawEntities; + ClearFlags = ClearFlags.ClearDepth; + + DrawFlags |= DrawFlags.ClipZ; + if (waterInfo.DrawWaterSurface) + DrawFlags |= DrawFlags.RenderWater; + if (!waterInfo.Refract && !waterInfo.OpaqueWater) + DrawFlags |= DrawFlags.RenderAbovewater; + + FogInfo = fogInfo; + WaterInfo = waterInfo; + DrawSkybox = drawSkybox; + } + + public override void ReleaseLists() { + base.ReleaseLists(); + Refraction.ReleaseLists(); + } + + public override void Draw() { + if (WaterInfo.Refract) { + Refraction.Setup(); + mainView.AddViewToScene(Refraction); + } + + DrawSetup(WaterHeight, DrawFlags, 0); + DrawExecute(WaterHeight, CurrentViewID(), 0); + ClearFlags = 0; + using MatRenderContextPtr renderContext = new(mainView.materials); - DrawSetup(0, DrawFlags, 0); - DrawExecute(0, ViewRender.g_CurrentViewID, 0); + renderContext.ClearColor4ub(0, 0, 0, 255); + } + + class RefractionView(ViewRender mainView, UnderWaterView outer) : BaseWorldView(mainView) + { + public void Setup() { + base.Setup(in outer.setup); + DrawFlags = DrawFlags.ClipZ | DrawFlags.ClipBelow | DrawFlags.RenderAbovewater | DrawFlags.DrawEntities; + + ClearFlags = ClearFlags.ClearDepth; + if (outer.DrawSkybox) { + ClearFlags |= ClearFlags.ClearColor; + DrawFlags |= DrawFlags.DrawSkybox | DrawFlags.ClipSkybox; + } + } + + public override void Draw() { + using MatRenderContextPtr renderContext = new(mainView.materials); + + DrawSetup(outer.WaterHeight, DrawFlags, 0); + + DrawExecute(outer.WaterHeight, ViewID.Refraction, 0); + + System.Drawing.Rectangle srcRect = new(setup.X, setup.Y, setup.Width, setup.Height); + + ITexture? texture = RenderTexture.GetWaterRefractionTexture(); + renderContext.CopyRenderTargetToTextureEx(texture, 0, ref srcRect, ref System.Runtime.CompilerServices.Unsafe.NullRef()); + } } } public class Rendering3dView : Base3dView From 23ba9b7cd81d9b6d7ebc4d5bcbf72fc3b96e9bd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 04:33:14 +0300 Subject: [PATCH 42/57] Fix world surfaces never being sorted by water --- Source.Engine/ModelLoader.cs | 83 ++++++++++++++++++++++++++++++++++++ Source.Engine/Render.cs | 3 ++ 2 files changed, 86 insertions(+) diff --git a/Source.Engine/ModelLoader.cs b/Source.Engine/ModelLoader.cs index 9c9d6bd7b..446bed500 100644 --- a/Source.Engine/ModelLoader.cs +++ b/Source.Engine/ModelLoader.cs @@ -1106,6 +1106,89 @@ static void MarkBrushModelWaterSurfaces(Model world, in Vector3 mins, in Vector3 host_state.SetWorldModel(pTemp); } + static void MarkWaterSurfaces_ProcessLeafNode(BSPMLeaf leaf) { + int i; + + SurfDraw flags = (leaf.LeafWaterDataID == -1) ? SurfDraw.AboveWater : SurfDraw.UnderWater; + + Span handles = host_state.WorldBrush!.MarkSurfaces.AsSpan(leaf.FirstMarkSurface); + + for (i = 0; i < leaf.NumMarkSurfaces; i++) { + ref BSPMSurface2 surfID = ref SurfaceHandleFromIndex(handles[i]); + if ((MSurf_Flags(ref surfID) & SurfDraw.WaterSurface) != 0) + continue; + + if (SurfaceHasDispInfo(ref surfID)) + continue; + + MSurf_Flags(ref surfID) |= flags; + } + + for (i = 0; i < leaf.DispCount; i++) { + IDispInfo? dispInfo = DispInfo.MLeaf_Disaplcement(leaf, i); + + if (dispInfo != null) { + ref BSPMSurface2 parentSurfID = ref dispInfo.GetParent(); + MSurf_Flags(ref parentSurfID) |= flags; + } + } + } + + static void MarkWaterSurfaces_r(BSPMNode node) { + if (node.Contents == (int)Contents.Solid) + return; + + if (node.Contents >= 0) { + MarkWaterSurfaces_ProcessLeafNode((BSPMLeaf)node); + return; + } + + MarkWaterSurfaces_r(node.Children[0]!); + MarkWaterSurfaces_r(node.Children[1]!); + } + + static int SurfFlagsToSortGroup(ref BSPMSurface2 surfID, SurfDraw flags) { + if ((flags & SurfDraw.WaterSurface) != 0) + return (int)MatSortGroup.WaterSurface; + + if ((flags & (SurfDraw.UnderWater | SurfDraw.AboveWater)) == (SurfDraw.UnderWater | SurfDraw.AboveWater)) + return (int)MatSortGroup.IntersectsWaterSurface; + + if ((flags & SurfDraw.UnderWater) != 0) + return (int)MatSortGroup.StrictlyUnderwater; + + if ((flags & SurfDraw.AboveWater) != 0) + return (int)MatSortGroup.StrictlyAboveWater; + + if (++SurfFlagsToSortGroupWarningCount < 10) { + DevWarning($"SurfFlagsToSortGroup: unhandled flags ({(int)flags:X}) ({MSurf_TexInfo(ref surfID).Material!.GetName()})!\n"); + DevWarning("- This implies you have a surface (usually a displacement) embedded in solid.\n"); + } + return (int)MatSortGroup.StrictlyAboveWater; + } + + static int SurfFlagsToSortGroupWarningCount; + + public static bool Mod_MarkWaterSurfaces(Model model) { + bool hasWaterSurfaces = false; + Model? saveModel = host_state.WorldModel; + + host_state.SetWorldModel(model); + MarkWaterSurfaces_r(model.Brush.Shared!.Nodes![0]); + for (int i = 0; i < model.Brush.Shared.NumSurfaces; i++) { + ref BSPMSurface2 surfID = ref SurfaceHandleFromIndex(i, model.Brush.Shared); + + int sortGroup = SurfFlagsToSortGroup(ref surfID, MSurf_Flags(ref surfID)); + if (sortGroup == (int)MatSortGroup.WaterSurface) + hasWaterSurfaces = true; + + MSurf_SetSortGroup(ref surfID, sortGroup); + } + host_state.SetWorldModel(saveModel); + + return hasWaterSurfaces; + } + public void RecomputeSurfaceFlags(Model mod) { for (int i = 0; i < mod.Brush.Shared!.NumSubModels; i++) { Model subModel = InlineModels[i]; diff --git a/Source.Engine/Render.cs b/Source.Engine/Render.cs index b34d16b33..ff799c57f 100644 --- a/Source.Engine/Render.cs +++ b/Source.Engine/Render.cs @@ -387,6 +387,9 @@ private void LoadWorldGeometry() { MaterialSystem.CreateSortInfo(); modelLoader.Map_LoadDisplacements(MaterialSystem.MaterialSortInfoArray!, host_state.WorldModel!); + + ModelLoader.Mod_MarkWaterSurfaces(host_state.WorldModel!); + RebuildLightmaps(); } private void Surface_LevelInit() { } From 42f25ddcf02ef03599091cc5b774b592dac523b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 04:34:51 +0300 Subject: [PATCH 43/57] Port the AnimatedTexture material proxy --- Game.Client/AnimatedTextureProxy.cs | 7 ++ Game.Client/BaseAnimatedTextureProxy.cs | 92 +++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 Game.Client/AnimatedTextureProxy.cs create mode 100644 Game.Client/BaseAnimatedTextureProxy.cs diff --git a/Game.Client/AnimatedTextureProxy.cs b/Game.Client/AnimatedTextureProxy.cs new file mode 100644 index 000000000..074c7539a --- /dev/null +++ b/Game.Client/AnimatedTextureProxy.cs @@ -0,0 +1,7 @@ +namespace Game.Client; + +[ExposeMaterialProxy(Name = "AnimatedTexture")] +public class AnimatedTextureProxy : BaseAnimatedTextureProxy +{ + protected override TimeUnit_t GetAnimationStartTime(object? baseEntity) => 0; +} diff --git a/Game.Client/BaseAnimatedTextureProxy.cs b/Game.Client/BaseAnimatedTextureProxy.cs new file mode 100644 index 000000000..089d95102 --- /dev/null +++ b/Game.Client/BaseAnimatedTextureProxy.cs @@ -0,0 +1,92 @@ +using Source.Common.Formats.Keyvalues; +using Source.Common.MaterialSystem; + +namespace Game.Client; + +public abstract class BaseAnimatedTextureProxy : IMaterialProxy +{ + public BaseAnimatedTextureProxy() { + Cleanup(); + } + + public virtual bool Init(IMaterial material, KeyValues keyValues) { + ReadOnlySpan animatedTextureVarName = keyValues.GetString("animatedTextureVar"); + if (animatedTextureVarName.IsEmpty) + return false; + + AnimatedTextureVar = material.FindVar(animatedTextureVarName, out bool foundVar, false); + if (!foundVar) + return false; + + ReadOnlySpan animatedTextureFrameNumVarName = keyValues.GetString("animatedTextureFrameNumVar"); + if (animatedTextureFrameNumVarName.IsEmpty) + return false; + + AnimatedTextureFrameNumVar = material.FindVar(animatedTextureFrameNumVarName, out foundVar, false); + if (!foundVar) + return false; + + FrameRate = keyValues.GetFloat("animatedTextureFrameRate", 15); + WrapAnimation = keyValues.GetInt("animationNoWrap", 0) == 0; + return true; + } + + void Cleanup() { + AnimatedTextureVar = null; + AnimatedTextureFrameNumVar = null; + } + + public virtual void OnBind(object? entity) { + Assert(AnimatedTextureVar != null); + + if (AnimatedTextureVar!.GetVarType() != MaterialVarType.Texture) + return; + + ITexture texture = AnimatedTextureVar.GetTextureValue()!; + int numFrames = texture.GetNumAnimationFrames(); + + if (numFrames <= 0) { + AssertMsg(false, "0 frames in material calling animated texture proxy"); + return; + } + + TimeUnit_t startTime = GetAnimationStartTime(entity); + TimeUnit_t deltaTime = gpGlobals.CurTime - startTime; + TimeUnit_t prevTime = deltaTime - gpGlobals.FrameTime; + + if (deltaTime < 0.0) + deltaTime = 0.0; + if (prevTime < 0.0) + prevTime = 0.0; + + TimeUnit_t frame = FrameRate * deltaTime; + TimeUnit_t prevFrame = FrameRate * prevTime; + + int intFrame = ((int)frame) % numFrames; + int intPrevFrame = ((int)prevFrame) % numFrames; + + if (intPrevFrame > intFrame) { + if (WrapAnimation) + AnimationWrapped(entity); + else { + if (prevFrame < numFrames) + AnimationWrapped(entity); + intFrame = numFrames - 1; + } + } + + AnimatedTextureFrameNumVar!.SetIntValue(intFrame); + } + + public virtual void Release() { } + + public virtual IMaterial GetMaterial() => AnimatedTextureVar!.GetOwningMaterial(); + + protected abstract TimeUnit_t GetAnimationStartTime(object? baseEntity); + protected virtual void AnimationWrapped(object? baseEntity) { } + + protected IMaterialVar? AnimatedTextureVar; + protected IMaterialVar? AnimatedTextureFrameNumVar; + protected float FrameRate; + protected bool WrapAnimation; +} From f3868af7c005735f7f88ddbd50e2d696e8c3eda7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 04:36:27 +0300 Subject: [PATCH 44/57] Port scene fog state to the material system and GL ShaderAPI --- .../MaterialSystem/IMaterialSystem.cs | 11 + Source.Common/MaterialSystem/IShader.cs | 1 + Source.Common/ShaderAPI/IShaderAPI.cs | 2 + Source.MaterialSystem/MatRenderContext.cs | 50 ++-- Source.MaterialSystem/MatStub.cs | 2 + Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 242 ++++++++++++++++-- Source.ShaderAPI.Gl46/ShaderShadow.cs | 10 +- Source.StdShader.Gl46/BaseShader.cs | 52 ++++ 8 files changed, 323 insertions(+), 47 deletions(-) diff --git a/Source.Common/MaterialSystem/IMaterialSystem.cs b/Source.Common/MaterialSystem/IMaterialSystem.cs index 5b30b198c..68b29bf0c 100644 --- a/Source.Common/MaterialSystem/IMaterialSystem.cs +++ b/Source.Common/MaterialSystem/IMaterialSystem.cs @@ -1221,6 +1221,9 @@ void DrawScreenSpaceRectangle( void FogMaxDensity(float maxDensity); + void FogRadial(bool radial); + bool GetFogRadial(); + IMaterial? GetCurrentMaterial(); int GetCurrentNumBones(); object? GetCurrentProxy(); @@ -1527,6 +1530,14 @@ public void FogMode(MaterialFogMode fogMode) { Context.FogMode(fogMode); } + public void FogRadial(bool radial) { + Context.FogRadial(radial); + } + + public bool GetFogRadial() { + return Context.GetFogRadial(); + } + public void FogStart(float start) { Context.FogStart(start); } diff --git a/Source.Common/MaterialSystem/IShader.cs b/Source.Common/MaterialSystem/IShader.cs index e059aeb7f..f9890eed3 100644 --- a/Source.Common/MaterialSystem/IShader.cs +++ b/Source.Common/MaterialSystem/IShader.cs @@ -242,6 +242,7 @@ public interface IShaderDynamicAPI void GetDX9LightState(out LightState state); int GetPixelFogCombo(); //0 is either range fog, or no fog simulated with rigged range fog values. 1 is height fog + int GetPixelFogCombo1(bool supportsRadial); void BindStandardVertexTexture(VertexTextureSampler sampler, StandardTextureId id); diff --git a/Source.Common/ShaderAPI/IShaderAPI.cs b/Source.Common/ShaderAPI/IShaderAPI.cs index 48e5362ab..180e213d5 100644 --- a/Source.Common/ShaderAPI/IShaderAPI.cs +++ b/Source.Common/ShaderAPI/IShaderAPI.cs @@ -274,6 +274,8 @@ void SetRenderTarget(ShaderAPITextureHandle_t colorTextureHandle = (ShaderAPITex void SceneFogColor3ub(byte r, byte g, byte b); void GetSceneFogColor(out Color rgb); void SceneFogMode(MaterialFogMode fogMode); + void SceneFogRadial(bool radial); + bool GetSceneFogRadial(); // Can we download textures? bool CanDownloadTextures(); diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index 12d2346b0..22d883380 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -1047,36 +1047,34 @@ public void EndPIXEvent() { } public void FogColor3f(float r, float g, float b) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); + byte r8 = (byte)Math.Clamp((int)(r * 255.0f), 0, 255); + byte g8 = (byte)Math.Clamp((int)(g * 255.0f), 0, 255); + byte b8 = (byte)Math.Clamp((int)(b * 255.0f), 0, 255); + shaderAPI.SceneFogColor3ub(r8, g8, b8); } public void FogColor3fv(ReadOnlySpan rgb) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); + byte r8 = (byte)Math.Clamp((int)(rgb[0] * 255.0f), 0, 255); + byte g8 = (byte)Math.Clamp((int)(rgb[1] * 255.0f), 0, 255); + byte b8 = (byte)Math.Clamp((int)(rgb[2] * 255.0f), 0, 255); + shaderAPI.SceneFogColor3ub(r8, g8, b8); } - public void FogColor3ub(byte r, byte g, byte b) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void FogColor3ub(byte r, byte g, byte b) => shaderAPI.SceneFogColor3ub(r, g, b); - public void FogColor3ubv(ReadOnlySpan rgb) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void FogColor3ubv(ReadOnlySpan rgb) => shaderAPI.SceneFogColor3ub(rgb[0], rgb[1], rgb[2]); - public void FogEnd(float end) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void FogEnd(float end) => shaderAPI.FogEnd(end); - public void FogMaxDensity(float maxDensity) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void FogMaxDensity(float maxDensity) => shaderAPI.FogMaxDensity(maxDensity); - public void FogMode(MaterialFogMode fogMode) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void FogMode(MaterialFogMode fogMode) => shaderAPI.SceneFogMode(fogMode); - public void FogStart(float start) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void FogStart(float start) => shaderAPI.FogStart(start); + + public void FogRadial(bool radial) => shaderAPI.SceneFogRadial(radial); + + public bool GetFogRadial() => shaderAPI.GetSceneFogRadial(); public void GMOD_FlushQueue() { throw new NotImplementedException("Incomplete port of IMatRenderContext"); @@ -1086,17 +1084,11 @@ public void GMOD_FlushQueue() { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void GetFogColor(out Color rgb) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void GetFogColor(out Color rgb) => shaderAPI.GetSceneFogColor(out rgb); - public void GetFogDistances(out float start, out float end, out float fogZ) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void GetFogDistances(out float start, out float end, out float fogZ) => shaderAPI.GetFogDistances(out start, out end, out fogZ); - public MaterialFogMode GetFogMode() { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public MaterialFogMode GetFogMode() => shaderAPI.GetSceneFogMode(); public void GetMatrix(MaterialMatrixMode matrixMode, out Matrix3x4 matrix) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); diff --git a/Source.MaterialSystem/MatStub.cs b/Source.MaterialSystem/MatStub.cs index 5a01799f4..f80169feb 100644 --- a/Source.MaterialSystem/MatStub.cs +++ b/Source.MaterialSystem/MatStub.cs @@ -552,6 +552,8 @@ public void FogStart(float fStart) { } public void FogEnd(float fEnd) { } public void SetFogZ(float fogZ) { } public MaterialFogMode GetFogMode() => MaterialFogMode.None; + public void FogRadial(bool radial) { } + public bool GetFogRadial() => false; public void FogColor3f(float r, float g, float b) { } public void FogColor3fv(ReadOnlySpan rgb) { } public void FogColor3ub(byte r, byte g, byte b) { } diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index bb428855c..ca785fdf0 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -184,6 +184,7 @@ public unsafe void ClearBuffers(bool clearColor, bool clearDepth, bool clearSten ShadowStateGl46? currentShadow; internal void SetCurrentShadow(ShadowStateGl46 shadow) { currentShadow = shadow; + ApplyCurrentShadowFogMode(false); } public void SetVertexShaderIndex(int index) { @@ -815,7 +816,20 @@ private void CacheWorldSpaceCameraPosition() { } private void UpdateVertexShaderFogParams() { - // todo: fog params + float ooFogRange = 1.0f; + + float start = VertexShaderFogParams[0]; + float end = VertexShaderFogParams[1]; + + if (end != start) + ooFogRange = 1.0f / (end - start); + + Span fogParams = [ + ooFogRange * end, + 1.0f, + 1.0f - Math.Clamp(FogMaxDensityValue, 0.0f, 1.0f), + ooFogRange, + ]; Span vertexShaderCameraPos = [ WorldSpaceCameraPosition.X, @@ -824,9 +838,136 @@ private void UpdateVertexShaderFogParams() { FogZ, ]; + SetVertexShaderConstant(VertexShaderConst.FogParams, fogParams); + SetVertexShaderConstant(VertexShaderConst.CameraPos, vertexShaderCameraPos); } + readonly float[] VertexShaderFogParams = new float[2]; + float FogMaxDensityValue = -1.0f; + float FogStartValue = -1.0f; + float FogEndValue = -1.0f; + readonly byte[] SceneFogColor = new byte[3]; + bool SceneFogRadialValue; + Vector3 PixelFogColor; + bool FogGammaCorrectionDisabled; + ShaderFogMode AppliedFogMode = ShaderFogMode.Num; + bool AppliedFogSRGBWrite; + bool AppliedFogDisableGammaCorrection; + float DestAlphaDepthRange = 8192.0f; + + private void UpdatePixelFogColorConstant() { + Span fogColor = stackalloc float[4]; + + switch (GetPixelFogMode()) { + case MaterialFogMode.None: + for (int i = 0; i != 3; ++i) + fogColor[i] = 0.0f; + break; + + case MaterialFogMode.Linear: + for (int i = 0; i != 3; ++i) + fogColor[i] = PixelFogColor[i]; + + if (currentShadow != null && currentShadow.State.SRGBWriteEnable) { + for (int i = 0; i != 3; ++i) + fogColor[i] = GammaToLinear_HardwareSpecific(fogColor[i]); + } + + if (!FogGammaCorrectionDisabled && HardwareConfig.GetHDRType() == HDRType.Integer) { + for (int i = 0; i != 3; ++i) + fogColor[i] *= ToneMappingScale.X; + } + break; + + case MaterialFogMode.LinearBelowFogZ: + for (int i = 0; i != 3; ++i) + fogColor[i] = GammaToLinear_HardwareSpecific(PixelFogColor[i]); + + if (!FogGammaCorrectionDisabled && HardwareConfig.GetHDRType() == HDRType.Integer) { + for (int i = 0; i != 3; ++i) + fogColor[i] *= ToneMappingScale.X; + } + break; + } + + fogColor[3] = 1.0f / DestAlphaDepthRange; + + SetPixelShaderConstant((int)PixelShaderConst.LinearFogColor, fogColor); + } + + private void ApplyFogMode(ShaderFogMode fogMode, bool srgbWritesEnabled, bool disableFogGammaCorrection) { + if (fogMode == ShaderFogMode.Disabled) + return; + + bool shouldGammaCorrect = true; + byte r = 0, g = 0, b = 0; + + switch (fogMode) { + case ShaderFogMode.Black: + shouldGammaCorrect = false; + break; + case ShaderFogMode.Overbright: + case ShaderFogMode.Grey: + r = g = b = 128; + break; + case ShaderFogMode.White: + r = g = b = 255; + shouldGammaCorrect = false; + break; + case ShaderFogMode.FogColor: + r = SceneFogColor[0]; + g = SceneFogColor[1]; + b = SceneFogColor[2]; + break; + } + + shouldGammaCorrect &= !disableFogGammaCorrection; + FogGammaCorrectionDisabled = !shouldGammaCorrect; + + const float colorScale = 1.0f / 255.0f; + PixelFogColor.X = r * colorScale; + PixelFogColor.Y = g * colorScale; + PixelFogColor.Z = b * colorScale; + + UpdatePixelFogColorConstant(); + } + + private void ApplyCurrentShadowFogMode(bool force) { + if (currentShadow == null) + return; + + ShaderFogMode fogMode = currentShadow.FogModeState; + bool srgbWrite = currentShadow.State.SRGBWriteEnable; + bool disableGammaCorrection = currentShadow.DisableFogGammaCorrectionState; + + if (!force && fogMode == AppliedFogMode && srgbWrite == AppliedFogSRGBWrite && disableGammaCorrection == AppliedFogDisableGammaCorrection) + return; + + AppliedFogMode = fogMode; + AppliedFogSRGBWrite = srgbWrite; + AppliedFogDisableGammaCorrection = disableGammaCorrection; + ApplyFogMode(fogMode, srgbWrite, disableGammaCorrection); + } + + private MaterialFogMode GetPixelFogMode() { + if (ShouldUsePixelFogForMode(SceneFogMode)) + return SceneFogMode; + else + return MaterialFogMode.None; + } + + private static bool ShouldUsePixelFogForMode(MaterialFogMode fogMode) => fogMode != MaterialFogMode.None; + + public void SceneFogRadial(bool radial) { + if (SceneFogRadialValue != radial) { + FlushBufferedPrimitives(); + SceneFogRadialValue = radial; + } + } + + public bool GetSceneFogRadial() => SceneFogRadialValue; + private void InitVertexAndPixelShaders() { // TODO; everything before this call ShaderManager.ResetShaderState(); @@ -2888,8 +3029,17 @@ public void GetWorldSpaceCameraPosition(Span eyePos) { } public int GetPixelFogCombo() { - // throw new NotImplementedException(); - return (int)MaterialFogMode.None; // TODO! + if ((SceneFogMode != MaterialFogMode.None) && ShouldUsePixelFogForMode(SceneFogMode)) + return (int)SceneFogMode - 1; + else + return (int)MaterialFogMode.None; + } + + public int GetPixelFogCombo1(bool supportsRadial) { + if (supportsRadial && SceneFogRadialValue && SceneFogMode == MaterialFogMode.Linear) + return 2; + + return GetPixelFogCombo(); } public bool ShouldWriteDepthToDestAlpha() => @@ -2966,7 +3116,7 @@ private void ExecuteCommandBuffer(ICommandStorageBuffer storage, Span cmdB case CommandBufferCommand.SetPixelShaderFogParams: { int reg = MemoryMarshal.Read(cmdBuf[(offset + 4)..]); - // SetPixelShaderFogParams(reg); + SetPixelShaderFogParams(reg); offset += 8; break; } @@ -3220,15 +3370,32 @@ public void FlushHardware() { } public void FogEnd(float end) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + if (end != FogEndValue) { + FlushBufferedPrimitives(); + + VertexShaderFogParams[1] = end; + UpdateVertexShaderFogParams(); + FogEndValue = end; + } } public void FogMaxDensity(float maxDensity) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + if (maxDensity != FogMaxDensityValue) { + FlushBufferedPrimitives(); + + FogMaxDensityValue = maxDensity; + UpdateVertexShaderFogParams(); + } } public void FogStart(float start) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + if (start != FogStartValue) { + FlushBufferedPrimitives(); + + VertexShaderFogParams[0] = start; + UpdateVertexShaderFogParams(); + FogStartValue = start; + } } public void ForceDepthFuncEquals(bool bEnable) { @@ -3239,12 +3406,12 @@ public void ForceHardwareSync() { throw new NotImplementedException("Incomplete port of IShaderAPI"); } - public float GammaToLinear_HardwareSpecific(float gamma) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); - } + public float GammaToLinear_HardwareSpecific(float gamma) => MathLib.SrgbGammaToLinear(gamma); public void GetFogDistances(out float start, out float end, out float fogZ) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + start = FogStartValue; + end = FogEndValue; + fogZ = FogZ; } public void GetMaxToRender(IMesh mesh, bool maxUntilFlush, out int maxVerts, out int maxIndices) { @@ -3256,7 +3423,7 @@ public ImageFormat GetNearestRenderTargetFormat(ImageFormat fmt) { } public void GetSceneFogColor(out Color rgb) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + rgb = new Color(SceneFogColor[0], SceneFogColor[1], SceneFogColor[2], 255); } public void HandleDeviceLost() { @@ -3390,11 +3557,23 @@ public void ReleaseThreadOwnership() { } public void SceneFogColor3ub(byte r, byte g, byte b) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + if (SceneFogColor[0] != r || SceneFogColor[1] != g || SceneFogColor[2] != b) { + FlushBufferedPrimitives(); + SceneFogColor[0] = r; + SceneFogColor[1] = g; + SceneFogColor[2] = b; + + ApplyCurrentShadowFogMode(true); + } } void IShaderAPI.SceneFogMode(MaterialFogMode fogMode) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + if (SceneFogMode != fogMode) { + FlushBufferedPrimitives(); + SceneFogMode = fogMode; + + ApplyCurrentShadowFogMode(true); + } } public void SelectionBuffer(Span buffer) { @@ -3618,7 +3797,9 @@ public int GetPackedDeformationInformation(int maskOfUnderstoodDeformations, Spa } public void GetSceneFogColor(Span rgb) { - throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); + rgb[0] = SceneFogColor[0]; + rgb[1] = SceneFogColor[1]; + rgb[2] = SceneFogColor[2]; } public void GetStandardTextureDimensions(out int width, out int height, StandardTextureId id) { @@ -3722,7 +3903,36 @@ public void SetPSNearAndFarZ(int reg) { } public void SetPixelShaderFogParams(int reg) { - throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); + ShaderFogMode fogMode = currentShadow?.FogModeState ?? ShaderFogMode.Disabled; + Span fogParams = stackalloc float[4]; + + if ((GetPixelFogMode() != MaterialFogMode.None) && (fogMode != ShaderFogMode.Disabled)) { + float ooFogRange = 1.0f; + + float start = VertexShaderFogParams[0]; + float end = VertexShaderFogParams[1]; + + if (end != start) + ooFogRange = 1.0f / (end - start); + + fogParams[0] = start * ooFogRange; + fogParams[1] = FogZ; + fogParams[2] = Math.Clamp(FogMaxDensityValue, 0.0f, 1.0f); + fogParams[3] = ooFogRange; + + if (GetPixelFogMode() == MaterialFogMode.LinearBelowFogZ) { + fogParams[0] = 0.0f; + fogParams[2] = 1.0f; + } + } + else { + fogParams[0] = 0.0f; + fogParams[1] = FogZ; + fogParams[2] = 1.0f; + fogParams[3] = 0.0f; + } + + SetPixelShaderConstant(reg, fogParams); } public void SetTextureTransformDimension(TextureStage textureStage, int dimension, bool projected) { diff --git a/Source.ShaderAPI.Gl46/ShaderShadow.cs b/Source.ShaderAPI.Gl46/ShaderShadow.cs index 2082973bc..f86a536e5 100644 --- a/Source.ShaderAPI.Gl46/ShaderShadow.cs +++ b/Source.ShaderAPI.Gl46/ShaderShadow.cs @@ -345,8 +345,12 @@ public void ComputeAggregateShadowState() { } } + public ShaderFogMode FogModeState; + public bool DisableFogGammaCorrectionState; + public void FogMode(ShaderFogMode fogMode) { - throw new NotImplementedException(); + Assert(fogMode >= 0 && fogMode < ShaderFogMode.Num); + FogModeState = fogMode; } public void SetDiffuseMaterialSource(ShaderMaterialSource materialSource) { @@ -354,7 +358,7 @@ public void SetDiffuseMaterialSource(ShaderMaterialSource materialSource) { } public void DisableFogGammaCorrection(bool bDisable) { - throw new NotImplementedException(); + DisableFogGammaCorrectionState = bDisable; } public void EnableAlphaToCoverage(bool enable) { @@ -393,6 +397,8 @@ public void SetDefaultState() { EnableAlphaToCoverage(false); EnableSRGBWrite(false); EnablePolyOffset(PolygonOffsetMode.Disable); + FogMode(ShaderFogMode.Disabled); + DisableFogGammaCorrection(false); int samplerCount = HardwareConfig.GetSamplerCount(); for (int i = 0; i < samplerCount; i++) { diff --git a/Source.StdShader.Gl46/BaseShader.cs b/Source.StdShader.Gl46/BaseShader.cs index c39bb7283..5e859178e 100644 --- a/Source.StdShader.Gl46/BaseShader.cs +++ b/Source.StdShader.Gl46/BaseShader.cs @@ -337,6 +337,58 @@ protected void DisableAlphaBlending() { ShaderShadow!.EnableBlending(false); } + public void FogToOOOverbright() { + Assert(IsSnapshotting()); + if ((CurrentMaterialVarFlags() & (int)MaterialVarFlags.NoFog) == 0) + ShaderShadow!.FogMode(ShaderFogMode.Overbright); + else + ShaderShadow!.FogMode(ShaderFogMode.Disabled); + } + + public void FogToWhite() { + Assert(IsSnapshotting()); + if ((CurrentMaterialVarFlags() & (int)MaterialVarFlags.NoFog) == 0) + ShaderShadow!.FogMode(ShaderFogMode.White); + else + ShaderShadow!.FogMode(ShaderFogMode.Disabled); + } + + public void FogToBlack() { + Assert(IsSnapshotting()); + if ((CurrentMaterialVarFlags() & (int)MaterialVarFlags.NoFog) == 0) + ShaderShadow!.FogMode(ShaderFogMode.Black); + else + ShaderShadow!.FogMode(ShaderFogMode.Disabled); + } + + public void FogToGrey() { + Assert(IsSnapshotting()); + if ((CurrentMaterialVarFlags() & (int)MaterialVarFlags.NoFog) == 0) + ShaderShadow!.FogMode(ShaderFogMode.Grey); + else + ShaderShadow!.FogMode(ShaderFogMode.Disabled); + } + + public void FogToFogColor() { + Assert(IsSnapshotting()); + if ((CurrentMaterialVarFlags() & (int)MaterialVarFlags.NoFog) == 0) + ShaderShadow!.FogMode(ShaderFogMode.FogColor); + else + ShaderShadow!.FogMode(ShaderFogMode.Disabled); + } + + public void DisableFog() { + Assert(IsSnapshotting()); + ShaderShadow!.FogMode(ShaderFogMode.Disabled); + } + + public void DefaultFog() { + if ((CurrentMaterialVarFlags() & (int)MaterialVarFlags.Additive) != 0) + FogToBlack(); + else + FogToFogColor(); + } + internal void SetBlendingShadowState(BlendType blendType) { switch (blendType) { case BlendType.None: From 9f8636c12a2401355837ba11ab214cb7bba699d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 04:37:58 +0300 Subject: [PATCH 45/57] Enable pixel fog with radial support in the stock shaders --- Game.Assets/hl2/shaders/common_gl460.fs | 45 +++++++++++++++++-- Game.Assets/hl2/shaders/eyes_gl460.fs | 4 +- .../hl2/shaders/lightmappedgeneric_gl460.fs | 2 +- Game.Assets/hl2/shaders/skin_gl460.fs | 4 +- Game.Assets/hl2/shaders/teeth_bump_gl460.fs | 4 +- Game.Assets/hl2/shaders/teeth_gl460.fs | 4 +- .../shaders/vertexlitgeneric_bump_gl460.fs | 40 +++-------------- .../hl2/shaders/vertexlitgeneric_gl460.fs | 42 +++-------------- Source.StdShader.Gl46/EyesHelper.cs | 8 +++- .../LightmappedGenericHelper.cs | 4 +- Source.StdShader.Gl46/SkinHelper.cs | 14 +++--- Source.StdShader.Gl46/Teeth.cs | 12 +++-- Source.StdShader.Gl46/UnlitTwoTexture.cs | 4 ++ .../VertexLitGenericHelper.cs | 13 +++--- Source.StdShader.Gl46/Water_DX90.cs | 8 ++++ 15 files changed, 105 insertions(+), 103 deletions(-) diff --git a/Game.Assets/hl2/shaders/common_gl460.fs b/Game.Assets/hl2/shaders/common_gl460.fs index e34f61462..48fc777b5 100644 --- a/Game.Assets/hl2/shaders/common_gl460.fs +++ b/Game.Assets/hl2/shaders/common_gl460.fs @@ -28,6 +28,7 @@ #define PIXEL_FOG_TYPE_NONE -1 //MATERIAL_FOG_NONE is handled by PIXEL_FOG_TYPE_RANGE, this is for explicitly disabling fog in the shader #define PIXEL_FOG_TYPE_RANGE 0 //range+none packed together in ps2b. Simply none in ps20 (instruction limits) #define PIXEL_FOG_TYPE_HEIGHT 1 +#define PIXEL_FOG_TYPE_RANGE_RADIAL 2 // If you change these, make the corresponding change in hardwareconfig.cpp #define NVIDIA_PCF_POISSON 0 @@ -150,7 +151,13 @@ float CalcRangeFog(float flProjPosZ, float flFogStartOverRange, float flFogMaxDe return clamp(min(flFogMaxDensity, (flProjPosZ * flFogOORange) - flFogStartOverRange), 0.0, 1.0); } -float CalcPixelFogFactor(int iPIXELFOGTYPE, vec4 fogParams, float flEyePosZ, float flWorldPosZ, float flProjPosZ) +float CalcRadialFog_NonFixedFunction(vec3 vWorldPos, vec3 vEyePos, float flFogMaxDensity, float flFogEndOverRange, float flFogOORange) +{ + float flDistance = distance(vEyePos.xyz, vWorldPos.xyz); + return min(flFogMaxDensity, clamp((flDistance * flFogOORange) - flFogEndOverRange, 0.0, 1.0)); +} + +float CalcPixelFogFactor(int iPIXELFOGTYPE, vec4 fogParams, vec3 vEyePos, vec3 vWorldPos, float flProjPosZ) { float retVal = 0.0; if (iPIXELFOGTYPE == PIXEL_FOG_TYPE_NONE) @@ -161,14 +168,45 @@ float CalcPixelFogFactor(int iPIXELFOGTYPE, vec4 fogParams, float flEyePosZ, flo { retVal = CalcRangeFog(flProjPosZ, fogParams.x, fogParams.z, fogParams.w); } + else if (iPIXELFOGTYPE == PIXEL_FOG_TYPE_RANGE_RADIAL) + { + float flFogMaxDensity = fogParams.z; + float flFogEndOverRange = fogParams.x; + float flFogOORange = fogParams.w; + + retVal = CalcRadialFog_NonFixedFunction(vWorldPos, vEyePos, flFogMaxDensity, flFogEndOverRange, flFogOORange); + } else if (iPIXELFOGTYPE == PIXEL_FOG_TYPE_HEIGHT) //height fog { - retVal = CalcWaterFogAlpha(fogParams.y, flEyePosZ, flWorldPosZ, flProjPosZ, fogParams.w); + retVal = CalcWaterFogAlpha(fogParams.y, vEyePos.z, vWorldPos.z, flProjPosZ, fogParams.w); } return retVal; } +float CalcPixelFogFactor(int iPIXELFOGTYPE, vec4 fogParams, float flEyePosZ, float flWorldPosZ, float flProjPosZ) +{ + if (iPIXELFOGTYPE == PIXEL_FOG_TYPE_RANGE_RADIAL) + return CalcPixelFogFactor(PIXEL_FOG_TYPE_RANGE, fogParams, vec3(0.0, 0.0, flEyePosZ), vec3(0.0, 0.0, flWorldPosZ), flProjPosZ); + + return CalcPixelFogFactor(iPIXELFOGTYPE, fogParams, vec3(0.0, 0.0, flEyePosZ), vec3(0.0, 0.0, flWorldPosZ), flProjPosZ); +} + +vec3 BlendPixelFog(vec3 vShaderColor, float pixelFogFactor, vec3 vFogColor, int iPIXELFOGTYPE) +{ + if (iPIXELFOGTYPE == PIXEL_FOG_TYPE_RANGE || iPIXELFOGTYPE == PIXEL_FOG_TYPE_RANGE_RADIAL) + { + pixelFogFactor = clamp(pixelFogFactor, 0.0, 1.0); + return mix(vShaderColor.rgb, vFogColor.rgb, pixelFogFactor * pixelFogFactor); + } + else if (iPIXELFOGTYPE == PIXEL_FOG_TYPE_HEIGHT) + { + return mix(vShaderColor.rgb, vFogColor.rgb, clamp(pixelFogFactor, 0.0, 1.0)); + } + + return vShaderColor; +} + // The framebuffer performs the linear->gamma conversion for us (GL_FRAMEBUFFER_SRGB), which is // the equivalent of the CONVERT_TO_SRGB == 0 path. vec3 SRGBOutput(vec3 vShaderColor) @@ -207,8 +245,7 @@ vec4 FinalOutput(vec4 vShaderColor, float pixelFogFactor, int iPIXELFOGTYPE, int else result.a = vShaderColor.a; - // TODO: fog - // result.rgb = BlendPixelFog(result.rgb, pixelFogFactor, g_LinearFogColor.rgb, iPIXELFOGTYPE); + result.rgb = BlendPixelFog(result.rgb, pixelFogFactor, g_LinearFogColor.rgb, iPIXELFOGTYPE); result.rgb = SRGBOutput(result.rgb); //SRGB in pixel shader conversion diff --git a/Game.Assets/hl2/shaders/eyes_gl460.fs b/Game.Assets/hl2/shaders/eyes_gl460.fs index 414bcde59..4d9636c5f 100644 --- a/Game.Assets/hl2/shaders/eyes_gl460.fs +++ b/Game.Assets/hl2/shaders/eyes_gl460.fs @@ -1,6 +1,6 @@ #version 460 // DYNAMIC: "WRITE_DEPTH_TO_DESTALPHA" "0..1" -// DYNAMIC: "PIXELFOGTYPE" "0..1" +// DYNAMIC: "PIXELFOGTYPE" "0..2" in vec2 vs_BaseTexCoord; in vec2 vs_IrisTexCoord; @@ -41,6 +41,6 @@ void main() bool bWriteDepthToAlpha = WRITE_DEPTH_TO_DESTALPHA != 0; - float fogFactor = CalcPixelFogFactor(PIXELFOGTYPE, g_FogParams, g_EyePos_SpecExponent.z, vs_WorldPos_ProjPosZ.z, vs_WorldPos_ProjPosZ.w); + float fogFactor = CalcPixelFogFactor(PIXELFOGTYPE, g_FogParams, g_EyePos_SpecExponent.xyz, vs_WorldPos_ProjPosZ.xyz, vs_WorldPos_ProjPosZ.w); fragColor = FinalOutput(result, fogFactor, PIXELFOGTYPE, TONEMAP_SCALE_LINEAR, bWriteDepthToAlpha, vs_WorldPos_ProjPosZ.w); } diff --git a/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs b/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs index 492cd61fb..8aa32bea7 100644 --- a/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs +++ b/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs @@ -483,7 +483,7 @@ void main() // ps_2_b and beyond bWriteDepthToAlpha = (WRITE_DEPTH_TO_DESTALPHA != 0) && (WRITEWATERFOGTODESTALPHA == 0); - float fogFactor = CalcPixelFogFactor(PIXELFOGTYPE, g_FogParams, g_EyePos.z, vs_WorldPos_ProjPosZ.z, vs_WorldPos_ProjPosZ.w); + float fogFactor = CalcPixelFogFactor(PIXELFOGTYPE, g_FogParams, g_EyePos.xyz, vs_WorldPos_ProjPosZ.xyz, vs_WorldPos_ProjPosZ.w); #if WRITEWATERFOGTODESTALPHA && (PIXELFOGTYPE == PIXEL_FOG_TYPE_HEIGHT) alpha = fogFactor; diff --git a/Game.Assets/hl2/shaders/skin_gl460.fs b/Game.Assets/hl2/shaders/skin_gl460.fs index 1a24ccb0c..55403a0cc 100644 --- a/Game.Assets/hl2/shaders/skin_gl460.fs +++ b/Game.Assets/hl2/shaders/skin_gl460.fs @@ -14,7 +14,7 @@ // STATIC: "BLENDTINTBYBASEALPHA" "0..1" // DYNAMIC: "WRITEWATERFOGTODESTALPHA" "0..1" -// DYNAMIC: "PIXELFOGTYPE" "0..1" +// DYNAMIC: "PIXELFOGTYPE" "0..2" // DYNAMIC: "NUM_LIGHTS" "0..4" // DYNAMIC: "WRITE_DEPTH_TO_DESTALPHA" "0..1" // DYNAMIC: "FLASHLIGHTSHADOWS" "0..1" @@ -138,7 +138,7 @@ void main() baseColor = TextureCombine(baseColor, detailColor, DETAIL_BLEND_MODE, g_SelfIllumTint_and_DetailBlendFactor.w); #endif - float fogFactor = CalcPixelFogFactor(PIXELFOGTYPE, g_FogParams, g_EyePos_SpecExponent.z, vWorldPos.z, vProjPos.z); + float fogFactor = CalcPixelFogFactor(PIXELFOGTYPE, g_FogParams, g_EyePos_SpecExponent.xyz, vWorldPos.xyz, vProjPos.z); vec3 vEyeDir = normalize(vs_WorldVertToEyeVector.xyz); vec3 vRimAmbientCubeColor = PixelShaderAmbientLight(vEyeDir, cAmbientCube); diff --git a/Game.Assets/hl2/shaders/teeth_bump_gl460.fs b/Game.Assets/hl2/shaders/teeth_bump_gl460.fs index 9c1a7ca36..0e6411593 100644 --- a/Game.Assets/hl2/shaders/teeth_bump_gl460.fs +++ b/Game.Assets/hl2/shaders/teeth_bump_gl460.fs @@ -1,5 +1,5 @@ #version 460 -// DYNAMIC: "PIXELFOGTYPE" "0..1" +// DYNAMIC: "PIXELFOGTYPE" "0..2" // DYNAMIC: "NUM_LIGHTS" "0..4" // DYNAMIC: "AMBIENT_LIGHT" "0..1" // DYNAMIC: "WRITE_DEPTH_TO_DESTALPHA" "0..1" @@ -71,6 +71,6 @@ void main() bool bWriteDepthToAlpha = WRITE_DEPTH_TO_DESTALPHA != 0; - float fogFactor = CalcPixelFogFactor(PIXELFOGTYPE, g_FogParams, g_EyePos_SpecExponent.z, vs_WorldPos_ProjPosZ.z, vs_WorldPos_ProjPosZ.w); + float fogFactor = CalcPixelFogFactor(PIXELFOGTYPE, g_FogParams, g_EyePos_SpecExponent.xyz, vs_WorldPos_ProjPosZ.xyz, vs_WorldPos_ProjPosZ.w); fragColor = FinalOutput(vec4(result, 1.0), fogFactor, PIXELFOGTYPE, TONEMAP_SCALE_LINEAR, bWriteDepthToAlpha, vs_WorldPos_ProjPosZ.w); } diff --git a/Game.Assets/hl2/shaders/teeth_gl460.fs b/Game.Assets/hl2/shaders/teeth_gl460.fs index d3beff1f8..068da978a 100644 --- a/Game.Assets/hl2/shaders/teeth_gl460.fs +++ b/Game.Assets/hl2/shaders/teeth_gl460.fs @@ -1,5 +1,5 @@ #version 460 -// DYNAMIC: "PIXELFOGTYPE" "0..1" +// DYNAMIC: "PIXELFOGTYPE" "0..2" // DYNAMIC: "WRITE_DEPTH_TO_DESTALPHA" "0..1" in vec2 vs_BaseTexCoord; @@ -29,6 +29,6 @@ void main() bool bWriteDepthToAlpha = WRITE_DEPTH_TO_DESTALPHA != 0; - float fogFactor = CalcPixelFogFactor(PIXELFOGTYPE, g_FogParams, g_EyePos_SpecExponent.z, vs_WorldPos_ProjPosZ.z, vs_WorldPos_ProjPosZ.w); + float fogFactor = CalcPixelFogFactor(PIXELFOGTYPE, g_FogParams, g_EyePos_SpecExponent.xyz, vs_WorldPos_ProjPosZ.xyz, vs_WorldPos_ProjPosZ.w); fragColor = FinalOutput(result, fogFactor, PIXELFOGTYPE, TONEMAP_SCALE_LINEAR, bWriteDepthToAlpha, vs_WorldPos_ProjPosZ.w); } diff --git a/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.fs b/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.fs index 00838eadd..0b13ca07c 100644 --- a/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.fs +++ b/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.fs @@ -16,6 +16,7 @@ // DYNAMIC: "NUM_LIGHTS" "0..4" // DYNAMIC: "AMBIENT_LIGHT" "0..1" // DYNAMIC: "FLASHLIGHTSHADOWS" "0..1" +// DYNAMIC: "PIXELFOGTYPE" "0..2" in vec4 vs_BaseTexCoord2_TangentSpaceVertToEyeVectorXY; in vec3 vs_LightAtten; @@ -47,7 +48,6 @@ out vec4 fragColor; #define g_SelfIllumScaleBiasExpBrightness ps_const[11] #define g_ShaderControls ps_const[12] -#define g_fPixelFogType g_ShaderControls.x #define g_fWriteDepthToAlpha g_ShaderControls.y #define g_fWriteWaterFogToDestAlpha g_ShaderControls.z @@ -68,36 +68,6 @@ layout(binding = 8) uniform sampler2DShadow ShadowDepthSampler; // Flashlight sh layout(binding = 8) uniform sampler2D ShadowDepthSamplerRaw; layout(binding = 9) uniform sampler2D DiffuseWarpSampler; // Lighting warp sampler (1D texture for diffuse lighting modification) -// Calculate both types of Fog and lerp to get result -float CalcPixelFogFactorConst(float fPixelFogType, vec4 fogParams, float flEyePosZ, float flWorldPosZ, float flProjPosZ) -{ - float fRangeFog = CalcRangeFog(flProjPosZ, fogParams.x, fogParams.z, fogParams.w); - float fHeightFog = CalcWaterFogAlpha(fogParams.y, flEyePosZ, flWorldPosZ, flProjPosZ, fogParams.w); - return mix(fRangeFog, fHeightFog, fPixelFogType); -} - -// Blend both types of Fog and lerp to get result -vec4 FinalOutputConst(vec4 vShaderColor, float pixelFogFactor, float fPixelFogType, int iTONEMAP_SCALE_TYPE, float fWriteDepthToDestAlpha, float flProjZ) -{ - vec4 result = vShaderColor; - if (iTONEMAP_SCALE_TYPE == TONEMAP_SCALE_LINEAR) - { - result.rgb *= LINEAR_LIGHT_SCALE; - } - else if (iTONEMAP_SCALE_TYPE == TONEMAP_SCALE_GAMMA) - { - result.rgb *= GAMMA_LIGHT_SCALE; - } - - result.a = mix(result.a, DepthToDestAlpha(flProjZ), fWriteDepthToDestAlpha); - - // TODO! fog - // result.rgb = BlendPixelFogConst(result.rgb, pixelFogFactor, g_LinearFogColor.rgb, fPixelFogType); - result.rgb = SRGBOutput(result.rgb); //SRGB in pixel shader conversion - - return result; -} - void main() { bool bCubemap = CUBEMAP != 0; @@ -242,9 +212,11 @@ void main() vec3 result = diffuseComponent + specularLighting; - float fogFactor = CalcPixelFogFactorConst(g_fPixelFogType, g_FogParams, g_EyePos.z, vs_WorldPos_ProjPosZ.z, vs_WorldPos_ProjPosZ.w); + float fogFactor = CalcPixelFogFactor(PIXELFOGTYPE, g_FogParams, g_EyePos.xyz, vs_WorldPos_ProjPosZ.xyz, vs_WorldPos_ProjPosZ.w); - alpha = mix(alpha, fogFactor, g_fPixelFogType * g_fWriteWaterFogToDestAlpha); // Use the fog factor if it's height fog +#if (PIXELFOGTYPE == PIXEL_FOG_TYPE_HEIGHT) + alpha = mix(alpha, fogFactor, g_fWriteWaterFogToDestAlpha); +#endif - fragColor = FinalOutputConst(vec4(result.rgb, alpha), fogFactor, g_fPixelFogType, TONEMAP_SCALE_LINEAR, g_fWriteDepthToAlpha, vs_WorldPos_ProjPosZ.w); + fragColor = FinalOutput(vec4(result.rgb, alpha), fogFactor, PIXELFOGTYPE, TONEMAP_SCALE_LINEAR, g_fWriteDepthToAlpha != 0.0, vs_WorldPos_ProjPosZ.w); } diff --git a/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.fs b/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.fs index ed0602073..74164bb11 100644 --- a/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.fs +++ b/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.fs @@ -24,6 +24,7 @@ // DYNAMIC: "LIGHTING_PREVIEW" "0..2" // DYNAMIC: "FLASHLIGHTSHADOWS" "0..1" +// DYNAMIC: "PIXELFOGTYPE" "0..2" #if SEAMLESS_BASE in vec3 vs_SeamlessTexCoord; @@ -93,7 +94,6 @@ out vec4 fragColor; #define OUTER_GLOW_MAX_DVALUE g_GlowParameters.w #define OUTER_GLOW_COLOR g_GlowColor -#define g_fPixelFogType g_ShaderControls.x #define g_fWriteDepthToAlpha g_ShaderControls.y #define g_fWriteWaterFogToDestAlpha g_ShaderControls.z #define g_fVertexAlpha g_ShaderControls.w @@ -122,38 +122,6 @@ layout(binding = 8) uniform sampler2D ShadowDepthSamplerRaw; layout(binding = 10) uniform sampler2D DepthSampler; //depth buffer sampler for depth blending layout(binding = 11) uniform sampler2D SelfIllumMaskSampler; // selfillummask -// Calculate unified fog -float CalcPixelFogFactorConst(float fPixelFogType, vec4 fogParams, float flEyePosZ, float flWorldPosZ, float flProjPosZ) -{ - float flDepthBelowWater = fPixelFogType * fogParams.y - flWorldPosZ; // above water = negative, below water = positive - float flDepthBelowEye = fPixelFogType * flEyePosZ - flWorldPosZ; // above eye = negative, below eye = positive - // if fPixelFogType == 0, then flDepthBelowWater == flDepthBelowEye and frac will be 1 - float frac = (flDepthBelowEye == 0.0) ? 1.0 : clamp(flDepthBelowWater / flDepthBelowEye, 0.0, 1.0); - return clamp(min(fogParams.z, flProjPosZ * fogParams.w * frac - fogParams.x), 0.0, 1.0); -} - -// Blend both types of Fog and lerp to get result -vec4 FinalOutputConst(vec4 vShaderColor, float pixelFogFactor, float fPixelFogType, int iTONEMAP_SCALE_TYPE, float fWriteDepthToDestAlpha, float flProjZ) -{ - vec4 result = vShaderColor; - if (iTONEMAP_SCALE_TYPE == TONEMAP_SCALE_LINEAR) - { - result.rgb *= LINEAR_LIGHT_SCALE; - } - else if (iTONEMAP_SCALE_TYPE == TONEMAP_SCALE_GAMMA) - { - result.rgb *= GAMMA_LIGHT_SCALE; - } - - result.a = mix(result.a, DepthToDestAlpha(flProjZ), fWriteDepthToDestAlpha); - - // todo FOG - // result.rgb = BlendPixelFogConst(result.rgb, pixelFogFactor, g_LinearFogColor.rgb, fPixelFogType); - result.rgb = SRGBOutput(result.rgb); //SRGB in pixel shader conversion - - return result; -} - void main() { bool bDetailTexture = DETAILTEXTURE != 0; @@ -391,9 +359,11 @@ void main() } #endif - float fogFactor = CalcPixelFogFactorConst(g_fPixelFogType, g_FogParams, g_EyePos.z, vs_WorldPos_ProjPosZ.z, vs_ProjPos.z); - alpha = mix(alpha, fogFactor, g_fWriteWaterFogToDestAlpha); // Use the fog factor if it's height fog - fragColor = FinalOutputConst(vec4(result.rgb, alpha), fogFactor, g_fPixelFogType, TONEMAP_SCALE_LINEAR, g_fWriteDepthToAlpha, vs_ProjPos.z); + float fogFactor = CalcPixelFogFactor(PIXELFOGTYPE, g_FogParams, g_EyePos.xyz, vs_WorldPos_ProjPosZ.xyz, vs_ProjPos.z); +#if (PIXELFOGTYPE == PIXEL_FOG_TYPE_HEIGHT) + alpha = mix(alpha, fogFactor, g_fWriteWaterFogToDestAlpha); +#endif + fragColor = FinalOutput(vec4(result.rgb, alpha), fogFactor, PIXELFOGTYPE, TONEMAP_SCALE_LINEAR, g_fWriteDepthToAlpha != 0.0, vs_ProjPos.z); #endif } diff --git a/Source.StdShader.Gl46/EyesHelper.cs b/Source.StdShader.Gl46/EyesHelper.cs index c5aaa5284..8ef8917bb 100644 --- a/Source.StdShader.Gl46/EyesHelper.cs +++ b/Source.StdShader.Gl46/EyesHelper.cs @@ -75,6 +75,8 @@ private void DrawEyesUsingVertexShader(BaseVSShader shader, IMaterialVar[] parms shaderShadow.EnableSRGBRead(Sampler.Sampler0, true); shaderShadow.EnableSRGBRead(Sampler.Sampler1, true); shaderShadow.EnableSRGBWrite(true); + + shader.FogToFogColor(); } else if (shaderAPI != null) { shader.BindTexture(Sampler.Sampler0, info.BaseTexture, info.Frame); @@ -124,6 +126,8 @@ private void DrawEyesUsingVertexShader(BaseVSShader shader, IMaterialVar[] parms Span psConst = [parms[info.Dilation].GetFloatValue(), glintDamping, 0.0f, 0.0f]; shaderAPI.SetPixelShaderConstant(0, psConst); + shaderAPI.SetPixelShaderFogParams((int)PixelShaderConst.FogParams); + Span eyePos_SpecExponent = [0, 0, 0, 0]; shaderAPI.GetWorldSpaceCameraPosition(eyePos_SpecExponent); eyePos_SpecExponent[3] = 0.0f; @@ -132,7 +136,7 @@ private void DrawEyesUsingVertexShader(BaseVSShader shader, IMaterialVar[] parms if (!HardwareConfig.HasFastVertexTextures()) { if (HardwareConfig.SupportsPixelShaders_2_b()) { DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); - pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo()); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo1(true)); pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", shaderAPI.ShouldWriteDepthToDestAlpha()); shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); } @@ -144,7 +148,7 @@ private void DrawEyesUsingVertexShader(BaseVSShader shader, IMaterialVar[] parms } else { DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); - pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo()); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo1(true)); pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", shaderAPI.ShouldWriteDepthToDestAlpha()); shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); } diff --git a/Source.StdShader.Gl46/LightmappedGenericHelper.cs b/Source.StdShader.Gl46/LightmappedGenericHelper.cs index dea461112..7af6a31c2 100644 --- a/Source.StdShader.Gl46/LightmappedGenericHelper.cs +++ b/Source.StdShader.Gl46/LightmappedGenericHelper.cs @@ -411,7 +411,7 @@ internal void DrawLightmappedGeneric_Internal(BaseVSShader shader, IMaterialVar[ shaderShadow.EnableAlphaWrites(fullyOpaque); shaderShadow.EnableSRGBWrite(true); - // shader.DefaultFog(); // TODO + shader.DefaultFog(); } } @@ -611,7 +611,7 @@ internal void DrawLightmappedGeneric_Internal(BaseVSShader shader, IMaterialVar[ DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); pshIndex.Set("FASTPATH", pixelShaderFastPath || contextData.PixelShaderForceFastPathBecauseOutline); pshIndex.Set("FASTPATHENVMAPCONTRAST", pixelShaderFastPath && envmapContrast == 1.0f); - pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo()); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo1(true)); pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", writeDepthToAlpha); pshIndex.Set("WRITEWATERFOGTODESTALPHA", writeWaterFogToAlpha); pshIndex.Set("LIGHTING_PREVIEW", fixedLightingMode); diff --git a/Source.StdShader.Gl46/SkinHelper.cs b/Source.StdShader.Gl46/SkinHelper.cs index 14ea6ab26..d56df06d6 100644 --- a/Source.StdShader.Gl46/SkinHelper.cs +++ b/Source.StdShader.Gl46/SkinHelper.cs @@ -338,10 +338,10 @@ private void DrawSkin_Internal(BaseVSShader shader, IMaterialVar[] parms, IShade shaderShadow.SetPixelShader("skin", pshIndex.GetIndex()); } - // if (hasFlashlight) - // shader.FogToBlack(); - // else - // shader.DefaultFog(); + if (hasFlashlight) + shader.FogToBlack(); + else + shader.DefaultFog(); shaderShadow.EnableAlphaWrites(fullyOpaque); } @@ -461,7 +461,7 @@ private void DrawSkin_Internal(BaseVSShader shader, IMaterialVar[] parms, IShade pshIndex.Set("NUM_LIGHTS", lightState.NumLights); pshIndex.Set("WRITEWATERFOGTODESTALPHA", writeWaterFogToAlpha); pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", writeDepthToAlpha); - pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo()); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo1(true)); pshIndex.Set("FLASHLIGHTSHADOWS", flashlightShadows); shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); } @@ -480,7 +480,7 @@ private void DrawSkin_Internal(BaseVSShader shader, IMaterialVar[] parms, IShade pshIndex.Set("NUM_LIGHTS", lightState.NumLights); pshIndex.Set("WRITEWATERFOGTODESTALPHA", writeWaterFogToAlpha); pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", writeDepthToAlpha); - pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo()); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo1(true)); pshIndex.Set("FLASHLIGHTSHADOWS", flashlightShadows); shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); @@ -620,7 +620,7 @@ private void DrawSkin_Internal(BaseVSShader shader, IMaterialVar[] parms, IShade shaderAPI.SetPixelShaderConstant((int)PixelShaderConst.FresnelSpecParams, fresnelRanges_SpecBoost); shaderAPI.SetPixelShaderConstant((int)PixelShaderConst.FlashlightPositionRimBoost, vRimBoost); shaderAPI.SetPixelShaderConstant((int)PixelShaderConst.SpecRimParams, specularTint); - // ShaderAPI.SetPixelShaderFogParams(PSREG_FOG_PARAMS); + shaderAPI.SetPixelShaderFogParams((int)PixelShaderConst.FogParams); if (hasFlashlight) { Span atten = [0, 0, 0, 0], pos = [0, 0, 0, 0], tweaks = [0, 0, 0, 0]; diff --git a/Source.StdShader.Gl46/Teeth.cs b/Source.StdShader.Gl46/Teeth.cs index 58e01485f..7937c6d14 100644 --- a/Source.StdShader.Gl46/Teeth.cs +++ b/Source.StdShader.Gl46/Teeth.cs @@ -183,6 +183,8 @@ void DrawUsingVertexShader(IMaterialVar[] parms, IShaderDynamicAPI? shaderAPI, I shaderShadow.EnableSRGBRead(Sampler.Sampler0, true); shaderShadow.EnableSRGBWrite(true); + FogToFogColor(); + shaderShadow.EnableAlphaWrites(fullyOpaque); } else if (shaderAPI != null) { @@ -201,6 +203,8 @@ void DrawUsingVertexShader(IMaterialVar[] parms, IShaderDynamicAPI? shaderAPI, I shaderAPI.GetDX9LightState(out LightState lightState); + shaderAPI.SetPixelShaderFogParams((int)PixelShaderConst.FogParams); + Span eyePos_SpecExponent = [0, 0, 0, 0]; shaderAPI.GetWorldSpaceCameraPosition(eyePos_SpecExponent); eyePos_SpecExponent[3] = 0.0f; @@ -223,7 +227,7 @@ void DrawUsingVertexShader(IMaterialVar[] parms, IShaderDynamicAPI? shaderAPI, I shaderAPI.SetPixelShaderConstant((int)PixelShaderConst.EyePosSpecExponent, specExponent); DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); - pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo()); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo1(true)); pshIndex.Set("NUM_LIGHTS", lightState.NumLights); pshIndex.Set("AMBIENT_LIGHT", lightState.AmbientLight ? 1 : 0); pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", fullyOpaque && shaderAPI.ShouldWriteDepthToDestAlpha()); @@ -250,7 +254,7 @@ void DrawUsingVertexShader(IMaterialVar[] parms, IShaderDynamicAPI? shaderAPI, I shaderAPI.SetPixelShaderConstant((int)PixelShaderConst.EyePosSpecExponent, specExponent); DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); - pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo()); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo1(true)); pshIndex.Set("NUM_LIGHTS", lightState.NumLights); pshIndex.Set("AMBIENT_LIGHT", lightState.AmbientLight ? 1 : 0); pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", fullyOpaque && shaderAPI.ShouldWriteDepthToDestAlpha()); @@ -274,7 +278,7 @@ void DrawUsingVertexShader(IMaterialVar[] parms, IShaderDynamicAPI? shaderAPI, I if (HardwareConfig.SupportsPixelShaders_2_b()) { DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); - pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo()); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo1(true)); pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", fullyOpaque && shaderAPI.ShouldWriteDepthToDestAlpha()); shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); } @@ -295,7 +299,7 @@ void DrawUsingVertexShader(IMaterialVar[] parms, IShaderDynamicAPI? shaderAPI, I shaderAPI.SetVertexShaderIndex(vshIndex.GetIndex()); DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); - pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo()); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo1(true)); pshIndex.Set("WRITE_DEPTH_TO_DESTALPHA", fullyOpaque && shaderAPI.ShouldWriteDepthToDestAlpha()); shaderAPI.SetPixelShaderIndex(pshIndex.GetIndex()); } diff --git a/Source.StdShader.Gl46/UnlitTwoTexture.cs b/Source.StdShader.Gl46/UnlitTwoTexture.cs index 5edc875c8..41d6dbafe 100644 --- a/Source.StdShader.Gl46/UnlitTwoTexture.cs +++ b/Source.StdShader.Gl46/UnlitTwoTexture.cs @@ -174,6 +174,8 @@ protected override void OnDrawElements(IMaterialVar[] parms, IShaderDynamicAPI s StaticShaderIndex pshIndex = new(ShaderShadow, ShaderType.Pixel, "unlittwotexture"); ShaderShadow.SetPixelShader("unlittwotexture", pshIndex.GetIndex()); + DefaultFog(); + ShaderShadow.EnableAlphaWrites(fullyOpaque); } else if (ShaderAPI != null) { @@ -183,6 +185,8 @@ protected override void OnDrawElements(IMaterialVar[] parms, IShaderDynamicAPI s SetVertexShaderTextureTransform(VertexShaderConst.ShaderSpecificConst2, TEXTURE2TRANSFORM); SetModulationPixelShaderDynamicState_LinearColorSpace(1); + ShaderAPI.SetPixelShaderFogParams((int)PixelShaderConst.FogParams); + Span eyePos_SpecExponent = [0, 0, 0, 0]; ShaderAPI.GetWorldSpaceCameraPosition(eyePos_SpecExponent); eyePos_SpecExponent[3] = 0.0f; diff --git a/Source.StdShader.Gl46/VertexLitGenericHelper.cs b/Source.StdShader.Gl46/VertexLitGenericHelper.cs index e18f777db..55bda996f 100644 --- a/Source.StdShader.Gl46/VertexLitGenericHelper.cs +++ b/Source.StdShader.Gl46/VertexLitGenericHelper.cs @@ -540,11 +540,10 @@ private void DrawVertexLitGeneric_Internal(BaseVSShader shader, IMaterialVar[] p } } - // todo - // if (hasFlashlight) - // shader.FogToBlack(); - // else - // shader.DefaultFog(); + if (hasFlashlight) + shader.FogToBlack(); + else + shader.DefaultFog(); shaderShadow.EnableAlphaWrites(fullyOpaque); } @@ -795,6 +794,7 @@ private void DrawVertexLitGeneric_Internal(BaseVSShader shader, IMaterialVar[] p pshIndex.Set("NUM_LIGHTS", lightState.NumLights); pshIndex.Set("AMBIENT_LIGHT", lightState.AmbientLight ? 1 : 0); pshIndex.Set("FLASHLIGHTSHADOWS", bFlashlightShadows); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo1(true)); dynamicCmdsOut.SetPixelShaderIndex(pshIndex.GetIndex()); } else { @@ -820,6 +820,7 @@ private void DrawVertexLitGeneric_Internal(BaseVSShader shader, IMaterialVar[] p pshIndex.Set("NUM_LIGHTS", lightState.NumLights); pshIndex.Set("AMBIENT_LIGHT", lightState.AmbientLight ? 1 : 0); pshIndex.Set("FLASHLIGHTSHADOWS", bFlashlightShadows); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo1(true)); dynamicCmdsOut.SetPixelShaderIndex(pshIndex.GetIndex()); Span unusedTexCoords = [false, false, !shaderAPI.IsHWMorphingEnabled() || !isDecal]; @@ -849,6 +850,7 @@ private void DrawVertexLitGeneric_Internal(BaseVSShader shader, IMaterialVar[] p if (HardwareConfig.SupportsPixelShaders_2_b() || HardwareConfig.ShouldAlwaysUseShaderModel2bShaders()) { DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); pshIndex.Set("FLASHLIGHTSHADOWS", bFlashlightShadows); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo1(true)); pshIndex.Set("LIGHTING_PREVIEW", shaderAPI.GetIntRenderingParameter((int)RenderParamInt.EnableFixedLighting)); dynamicCmdsOut.SetPixelShaderIndex(pshIndex.GetIndex()); } @@ -874,6 +876,7 @@ private void DrawVertexLitGeneric_Internal(BaseVSShader shader, IMaterialVar[] p DynamicShaderIndex pshIndex = new(shaderAPI, ShaderType.Pixel); pshIndex.Set("FLASHLIGHTSHADOWS", bFlashlightShadows); + pshIndex.Set("PIXELFOGTYPE", shaderAPI.GetPixelFogCombo1(true)); pshIndex.Set("LIGHTING_PREVIEW", shaderAPI.GetIntRenderingParameter((int)RenderParamInt.EnableFixedLighting)); dynamicCmdsOut.SetPixelShaderIndex(pshIndex.GetIndex()); diff --git a/Source.StdShader.Gl46/Water_DX90.cs b/Source.StdShader.Gl46/Water_DX90.cs index 204eaa697..2385703c1 100644 --- a/Source.StdShader.Gl46/Water_DX90.cs +++ b/Source.StdShader.Gl46/Water_DX90.cs @@ -199,6 +199,8 @@ void DrawReflectionRefraction(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, pshIndex.Set("BLURRY_REFRACT", vars[BLURREFRACT].GetIntValue()); ShaderShadow.SetPixelShader("water", pshIndex.GetIndex()); + FogToFogColor(); + ShaderShadow.EnableSRGBWrite(true); ShaderShadow.EnableAlphaWrites(true); @@ -273,6 +275,8 @@ void DrawReflectionRefraction(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, c7[2] = 4.0f; shaderAPI.SetPixelShaderConstant(7, c7, 1); + shaderAPI.SetPixelShaderFogParams(8); + DynamicShaderIndex vshIndex = new(shaderAPI, ShaderType.Vertex); shaderAPI.SetVertexShaderIndex(vshIndex.GetIndex()); @@ -318,6 +322,8 @@ void DrawCheapWater(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, bool blend if (HardwareConfig.GetHDRType() != HDRType.None) ShaderShadow.EnableSRGBWrite(true); + + FogToFogColor(); } else { shaderAPI.SetDefaultState(); @@ -347,6 +353,8 @@ void DrawCheapWater(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, bool blend shaderAPI.SetPixelShaderConstant(2, zero); } + shaderAPI.SetPixelShaderFogParams(3); + if (vars[SCROLL1].IsDefined()) { float curtime = (float)shaderAPI.CurrentTime(); Span vc0 = stackalloc float[4]; From 25abc1e28a1da1b7cda15ff023f89df5000d9f7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 04:39:36 +0300 Subject: [PATCH 46/57] Port water fog volume state to the render view --- Source.Common/IRenderView.cs | 1 + Source.Engine/GLRSurf.cs | 29 ++++++++++++++++++++++++++++- Source.Engine/View.cs | 1 + 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/Source.Common/IRenderView.cs b/Source.Common/IRenderView.cs index 3a0771687..786d8ab08 100644 --- a/Source.Common/IRenderView.cs +++ b/Source.Common/IRenderView.cs @@ -105,6 +105,7 @@ public interface IRenderView void DrawTranslucentSurfaces(IWorldRenderList? list, int sortIndex, uint flags, bool shadowDepth); bool LeafContainsTranslucentSurfaces(IWorldRenderList? list, int sortIndex, uint flags); void GetVisibleFogVolume(in Vector3 eyePoint, ref VisibleFogVolumeInfo info); + void SetFogVolumeState(int fogVolume, bool useHeightFog); bool DoesBoxIntersectWaterVolume(in Vector3 mins, in Vector3 maxs, int leafWaterDataID); void BeginUpdateLightmaps(); void EndUpdateLightmaps(); diff --git a/Source.Engine/GLRSurf.cs b/Source.Engine/GLRSurf.cs index 3c71e67e1..d75ddef7b 100644 --- a/Source.Engine/GLRSurf.cs +++ b/Source.Engine/GLRSurf.cs @@ -1182,7 +1182,34 @@ static float R_GetWaterHeight(int fogVolume) { } return material; } - public static void R_SetFogVolumeState(int fogVolume, bool useHeightFog) => throw new NotImplementedException(); + public static void R_SetFogVolumeState(int fogVolume, bool useHeightFog) { + IMaterial? material = R_GetFogVolumeMaterial(fogVolume, !useHeightFog); + ref BSPMLeafWaterData leafWaterData = ref host_state.WorldBrush!.LeafWaterData![fogVolume]; + IMaterialVar fogColorVar = material!.FindVar("$fogcolor", out _); + IMaterialVar fogEnableVar = material.FindVar("$fogenable", out _); + IMaterialVar fogStartVar = material.FindVar("$fogstart", out _); + IMaterialVar fogEndVar = material.FindVar("$fogend", out _); + + using MatRenderContextPtr renderContext = new(materials); + + if (material != null && fogEnableVar.GetIntValue() != 0 && fog_enable_water_fog.GetBool()) { + renderContext.SetFogZ(leafWaterData.SurfaceZ); + if (useHeightFog) + renderContext.FogMode(MaterialFogMode.LinearBelowFogZ); + else + renderContext.FogMode(MaterialFogMode.Linear); + + Span fogColor = stackalloc float[3]; + fogColorVar.GetVecValue(fogColor); + + renderContext.FogColor3fv(fogColor); + renderContext.FogStart(fogStartVar.GetFloatValue()); + renderContext.FogEnd(fogEndVar.GetFloatValue()); + renderContext.FogMaxDensity(1.0f); + } + else + renderContext.FogMode(MaterialFogMode.None); + } static bool R_CullNodeTopView(BSPMNode node) => throw new NotImplementedException(); static void R_DrawTopViewLeaf(WorldRenderList renderList, BSPMLeaf leaf) => throw new NotImplementedException(); public static void R_RenderWorldTopView(WorldRenderList renderList, BSPMNode node) => throw new NotImplementedException(); diff --git a/Source.Engine/View.cs b/Source.Engine/View.cs index 4ff6eec59..fd24ae03a 100644 --- a/Source.Engine/View.cs +++ b/Source.Engine/View.cs @@ -115,6 +115,7 @@ public void SetAreaState(ReadOnlySpan areaBits, ReadOnlySpan areaPor public void DrawTranslucentSurfaces(IWorldRenderList? list, int sortIndex, uint flags, bool shadowDepth) => GLRSurf.Shader_DrawTranslucentSurfaces(list!, sortIndex, flags, shadowDepth); public bool LeafContainsTranslucentSurfaces(IWorldRenderList? list, int sortIndex, uint flags) => GLRSurf.Shader_LeafContainsTranslucentSurfaces(list!, sortIndex, flags); public void GetVisibleFogVolume(in Vector3 eyePoint, ref VisibleFogVolumeInfo info) => R_GetVisibleFogVolume(in eyePoint, ref info); + public void SetFogVolumeState(int fogVolume, bool useHeightFog) => R_SetFogVolumeState(fogVolume, useHeightFog); struct BoxIntersectWaterContext : ISpatialLeafEnumerator { From e94823e0281a3ef72203beb47fdd50af84b531eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 04:40:43 +0300 Subject: [PATCH 47/57] Port world, skybox and water fog to the view renderer --- Game.Client/C_BasePlayer.cs | 77 ++++++- Game.Client/View.cs | 12 ++ Game.Client/ViewRender.cs | 408 ++++++++++++++++++++++++++++++++++- Game.Shared/PlayerNetVars.cs | 2 +- 4 files changed, 491 insertions(+), 8 deletions(-) diff --git a/Game.Client/C_BasePlayer.cs b/Game.Client/C_BasePlayer.cs index ab7310dfb..287d84043 100644 --- a/Game.Client/C_BasePlayer.cs +++ b/Game.Client/C_BasePlayer.cs @@ -195,7 +195,77 @@ public virtual void UpdateClientData() { GetWeapon(i).UpdateClientData(this); } } - public virtual void UpdateFogController() { } + FogParams CurrentFog = new(); + Handle OldFogController = new(); + + public ref FogParams GetFogParams() => ref CurrentFog; + + public override void OnPreDataChanged(DataUpdateType updateType) { + for (int i = 0; i < MAX_AMMO_TYPES; ++i) + OldAmmo[i] = GetAmmoCount(i); + + WasFreezeFraming = GetObserverMode() == Shared.ObserverMode.FreezeCam; + OldFogController = Local.PlayerFog.Ctrl; + + base.OnPreDataChanged(updateType); + } + + public void FogControllerChanged(bool snap) { + if (Local.PlayerFog.Ctrl.Get() is Game.Server.C_FogController ctrl) { + ref FogParams fogParams = ref ctrl.Fog; + + Local.PlayerFog.OldColor = CurrentFog.ColorPrimary; + Local.PlayerFog.OldStart = CurrentFog.Start; + Local.PlayerFog.OldEnd = CurrentFog.End; + + Local.PlayerFog.NewColor = fogParams.ColorPrimary; + Local.PlayerFog.NewStart = fogParams.Start; + Local.PlayerFog.NewEnd = fogParams.End; + + Local.PlayerFog.TransitionTime = snap ? -1 : gpGlobals.CurTime; + + CurrentFog = fogParams; + + UpdateFogController(); + } + } + + public virtual void UpdateFogController() { + if (Local.PlayerFog.Ctrl.Get() is Game.Server.C_FogController ctrl) { + if (Local.PlayerFog.TransitionTime == -1 && (OldFogController == Local.PlayerFog.Ctrl)) + CurrentFog = ctrl.Fog; + } + else { + if (CurrentFog.FarZ != -1 || CurrentFog.Enable != false) { + CurrentFog.FarZ = -1; + CurrentFog.Enable = false; + } + } + + UpdateFogBlend(); + } + + public void UpdateFogBlend() { + if (Local.PlayerFog.TransitionTime != -1) { + TimeUnit_t timeDelta = gpGlobals.CurTime - Local.PlayerFog.TransitionTime; + if (timeDelta < CurrentFog.Duration) { + float scale = (float)(timeDelta / CurrentFog.Duration); + CurrentFog.ColorPrimary.R = (byte)((Local.PlayerFog.NewColor.R * scale) + (Local.PlayerFog.OldColor.R * (1.0f - scale))); + CurrentFog.ColorPrimary.G = (byte)((Local.PlayerFog.NewColor.G * scale) + (Local.PlayerFog.OldColor.G * (1.0f - scale))); + CurrentFog.ColorPrimary.B = (byte)((Local.PlayerFog.NewColor.B * scale) + (Local.PlayerFog.OldColor.B * (1.0f - scale))); + CurrentFog.Start = (Local.PlayerFog.NewStart * scale) + (Local.PlayerFog.OldStart * (1.0f - scale)); + CurrentFog.End = (Local.PlayerFog.NewEnd * scale) + (Local.PlayerFog.OldEnd * (1.0f - scale)); + } + else { + CurrentFog.ColorPrimary.R = Local.PlayerFog.NewColor.R; + CurrentFog.ColorPrimary.G = Local.PlayerFog.NewColor.G; + CurrentFog.ColorPrimary.B = Local.PlayerFog.NewColor.B; + CurrentFog.Start = Local.PlayerFog.NewStart; + CurrentFog.End = Local.PlayerFog.NewEnd; + Local.PlayerFog.TransitionTime = -1; + } + } + } public void UpdateFlashlight() { if (IsEffectActive(EntityEffects.DimLight)) { @@ -328,9 +398,8 @@ public override void OnDataChanged(DataUpdateType updateType) { Soundscape_Update(ref Local.Audio); - // todo - // if (OldFogController != Local.PlayerFog.Ctrl) - // FogControllerChanged(updateType == DataUpdateType.Created); + if (OldFogController != Local.PlayerFog.Ctrl) + FogControllerChanged(updateType == DataUpdateType.Created); } } public void SetViewAngles(in QAngle angles) { diff --git a/Game.Client/View.cs b/Game.Client/View.cs index 5d9998712..a66b7a1aa 100644 --- a/Game.Client/View.cs +++ b/Game.Client/View.cs @@ -137,6 +137,11 @@ public DrawFlags GetDrawFlags() { public DrawFlags GetBaseDrawFlags() => BaseDrawFlags; + public void DisableFog() { + using MatRenderContextPtr renderContext = new(materials); + renderContext.FogMode(MaterialFogMode.None); + } + public Frustum GetFrustum() => ActiveRenderer?.GetFrustrum() ?? Frustum; public ref ViewSetup GetPlayerViewSetup() => ref GetView(StereoEye.Mono); @@ -429,6 +434,9 @@ public void RenderView(in ViewSetup viewRender, ClearFlags clearFlags, RenderVie ViewDrawScene(drew3dSkybox, skyboxVisible, in viewRender, clearFlags, ViewID.Main, (whatToDraw & RenderViewInfo.DrawViewmodel) != 0); else ViewDrawScene_Intro(in viewRender, clearFlags, IntroData.g_pIntroData); + + DisableFog(); + render.SceneEnd(); RenderPlayerSprites(); @@ -541,6 +549,8 @@ private void ViewDrawScene(bool drew3dSkybox, SkyboxVisibility skyboxVisible, in DrawWorldAndEntities(drawSkybox, in viewRender, clearFlags); + DisableFog(); + DebugViewRender.Draw3DDebuggingInfo(in viewRender); // todo @@ -633,6 +643,8 @@ private void ViewDrawScene_Intro(in ViewSetup view, ClearFlags clearFlags, Intro renderContext.MatrixMode(MaterialMatrixMode.Projection); renderContext.PopMatrix(); + DisableFog(); + // Make sure sound doesn't stutter engine.Sound_ExtraUpdate(); diff --git a/Game.Client/ViewRender.cs b/Game.Client/ViewRender.cs index f3ee8e8d3..557b85760 100644 --- a/Game.Client/ViewRender.cs +++ b/Game.Client/ViewRender.cs @@ -7,6 +7,7 @@ using Source.Common.Client; using Source.Common.Commands; using Source.Common.Engine; +using Source.Common.GarrysMod.Lua; using Source.Common.MaterialSystem; using Source.Common.Mathematics; using Source.Engine; @@ -36,6 +37,19 @@ public static class ViewRenderConVars internal readonly static ConVar r_ForceWaterLeaf = new("1", 0, "Enable for optimization to water - considers view in leaf under water for purposes of culling"); internal readonly static ConVar mat_drawwater = new("1", FCvar.Cheat); internal readonly static ConVar mat_clipz = new("1", 0); + internal readonly static ConVar fog_override = new("0", FCvar.Cheat); + internal readonly static ConVar fog_start = new("-1", FCvar.Cheat); + internal readonly static ConVar fog_end = new("-1", FCvar.Cheat); + internal readonly static ConVar fog_color = new("-1 -1 -1", FCvar.Cheat); + internal readonly static ConVar fog_enable = new("1", FCvar.Cheat); + internal readonly static ConVar fog_startskybox = new("-1", FCvar.Cheat); + internal readonly static ConVar fog_endskybox = new("-1", FCvar.Cheat); + internal readonly static ConVar fog_maxdensityskybox = new("-1", FCvar.Cheat); + internal readonly static ConVar fog_colorskybox = new("-1 -1 -1", FCvar.Cheat); + internal readonly static ConVar fog_enableskybox = new("1", FCvar.Cheat); + internal readonly static ConVar fog_maxdensity = new("-1", FCvar.Cheat); + internal readonly static ConVar fog_radial = new("-1", FCvar.Cheat); + internal readonly static ConVar fog_radialskybox = new("-1", FCvar.Cheat); } public struct WaterRenderInfo @@ -344,9 +358,19 @@ public void Setup(in ViewSetup view, ClearFlags clearFlags, bool drawSkybox, in public override void Draw() { DrawSetup(0, DrawFlags, 0); - if (FogInfo.EyeInFogVolume) + if (!FogInfo.EyeInFogVolume) + EnableWorldFog(); + else { ClearFlags |= ClearFlags.ClearColor; + SetFogVolumeState(in FogInfo, false); + + using MatRenderContextPtr fogRenderContext = new(mainView.materials); + + fogRenderContext.GetFogColor(out Color fogColor); + fogRenderContext.ClearColor4ub(fogColor.R, fogColor.G, fogColor.B, 255); + } + DrawExecute(0, CurrentViewID(), 0); using MatRenderContextPtr renderContext = new(mainView.materials); @@ -423,6 +447,7 @@ public override void Draw() { DrawFlags |= DrawFlags.ClipZ | DrawFlags.ClipBelow; DrawSetup(WaterHeight, DrawFlags, 0); + EnableWorldFog(); DrawExecute(WaterHeight, CurrentViewID(), 0); if (WaterInfo.Refract && viewIntersectsWater) { @@ -452,6 +477,7 @@ public override void Draw() { DrawSetup(outer.FogInfo.WaterHeight, DrawFlags, 0.0f, outer.FogInfo.VisibleFogVolumeLeaf); + EnableWorldFog(); DrawExecute(outer.FogInfo.WaterHeight, ViewID.Reflection, 0.0f); SetupCurrentView(in setup.Origin, in setup.Angles, saveViewID); @@ -477,6 +503,8 @@ public override void Draw() { DrawSetup(outer.WaterHeight, DrawFlags, 0); + SetFogVolumeState(in outer.FogInfo, true); + SetClearColorToFogColor(); DrawExecute(outer.WaterHeight, ViewID.Refraction, 0); SetupCurrentView(in setup.Origin, in setup.Angles, saveViewID); @@ -497,6 +525,8 @@ public void Setup() { public override void Draw() { DrawSetup(outer.FogInfo.WaterHeight, DrawFlags, 0); + SetFogVolumeState(in outer.FogInfo, true); + SetClearColorToFogColor(); DrawExecute(outer.FogInfo.WaterHeight, ViewID.None, 0); using MatRenderContextPtr renderContext = new(mainView.materials); renderContext.ClearColor4ub(0, 0, 0, 255); @@ -539,16 +569,23 @@ public override void ReleaseLists() { } public override void Draw() { + using MatRenderContextPtr renderContext = new(mainView.materials); if (WaterInfo.Refract) { Refraction.Setup(); mainView.AddViewToScene(Refraction); } + if (!WaterInfo.Refract) { + SetFogVolumeState(in FogInfo, true); + renderContext.GetFogColor(out Color fogColor); + renderContext.ClearColor4ub(fogColor.R, fogColor.G, fogColor.B, 255); + } + DrawSetup(WaterHeight, DrawFlags, 0); + SetFogVolumeState(in FogInfo, false); DrawExecute(WaterHeight, CurrentViewID(), 0); ClearFlags = 0; - using MatRenderContextPtr renderContext = new(mainView.materials); renderContext.ClearColor4ub(0, 0, 0, 255); } @@ -568,8 +605,13 @@ public void Setup() { public override void Draw() { using MatRenderContextPtr renderContext = new(mainView.materials); + SetFogVolumeState(in outer.FogInfo, true); + renderContext.GetFogColor(out Color fogColor); + renderContext.ClearColor4ub(fogColor.R, fogColor.G, fogColor.B, 255); + DrawSetup(outer.WaterHeight, DrawFlags, 0); + EnableWorldFog(); DrawExecute(outer.WaterHeight, ViewID.Refraction, 0); System.Drawing.Rectangle srcRect = new(setup.X, setup.Y, setup.Width, setup.Height); @@ -920,7 +962,316 @@ private void DrawTranslucentRenderable(IClientRenderable ent, bool twoPass, Rend render.SetBlend(1); } - protected void EnableWorldFog() => throw new NotImplementedException(); + protected static void SetClearColorToFogColor() { + using MatRenderContextPtr renderContext = new(materials); + + renderContext.GetFogColor(out Color fogColor); + if (Singleton().GetHDRType() == HDRType.Integer) { + float scale = MathLib.LinearToGammaFullRange(renderContext.GetToneMappingScaleLinear().X); + fogColor.R = (byte)(fogColor.R * scale); + fogColor.G = (byte)(fogColor.G * scale); + fogColor.B = (byte)(fogColor.B * scale); + } + renderContext.ClearColor4ub(fogColor.R, fogColor.G, fogColor.B, 255); + } + + static void ParseFogColor(string fogColorString, Span color) { + string[] tokens = fogColorString.Split(' ', StringSplitOptions.RemoveEmptyEntries); + for (int i = 0; i < 3 && i < tokens.Length; i++) { + if (!float.TryParse(tokens[i], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float value)) + break; + color[i] = value; + } + } + + static void CheckAndTransitionColor(float percent, Span color, ReadOnlySpan lerpToColor) { + if (lerpToColor[0] != color[0] || lerpToColor[1] != color[1] || lerpToColor[2] != color[2]) { + color[0] = MathLib.Lerp(percent, color[0], lerpToColor[0]); + color[1] = MathLib.Lerp(percent, color[1], lerpToColor[1]); + color[2] = MathLib.Lerp(percent, color[2], lerpToColor[2]); + } + else { + color[0] = lerpToColor[0]; + color[1] = lerpToColor[1]; + color[2] = lerpToColor[2]; + } + } + + static void GetFogColorTransition(ref FogParams fogParams, Span colorPrimary, Span colorSecondary) { + if (fogParams.LerpTime >= gpGlobals.CurTime) { + float percent = (float)(1.0 - ((fogParams.LerpTime - gpGlobals.CurTime) / fogParams.Duration)); + + ReadOnlySpan primaryColorLerp = [fogParams.ColorPrimaryLerpTo.R, fogParams.ColorPrimaryLerpTo.G, fogParams.ColorPrimaryLerpTo.B]; + ReadOnlySpan secondaryColorLerp = [fogParams.ColorSecondaryLerpTo.R, fogParams.ColorSecondaryLerpTo.G, fogParams.ColorSecondaryLerpTo.B]; + + CheckAndTransitionColor(percent, colorPrimary, primaryColorLerp); + CheckAndTransitionColor(percent, colorSecondary, secondaryColorLerp); + } + } + + static void GetFogColor(C_BasePlayer? pbp, Span color) { + if (pbp == null) + return; + + ref FogParams fogParams = ref pbp.GetFogParams(); + + if (fog_override.GetInt() != 0) + ParseFogColor(fog_color.GetString(), color); + else { + Span primaryColor = [fogParams.ColorPrimary.R, fogParams.ColorPrimary.G, fogParams.ColorPrimary.B]; + Span secondaryColor = [fogParams.ColorSecondary.R, fogParams.ColorSecondary.G, fogParams.ColorSecondary.B]; + + GetFogColorTransition(ref fogParams, primaryColor, secondaryColor); + + if (fogParams.Blend) { + pbp.EyeVectors(out Vector3 forward); + + MathLib.VectorNormalize(ref fogParams.DirPrimary); + + float blendFactor = 0.5f * Vector3.Dot(forward, fogParams.DirPrimary) + 0.5f; + + color[0] = primaryColor[0] * blendFactor + secondaryColor[0] * (1 - blendFactor); + color[1] = primaryColor[1] * blendFactor + secondaryColor[1] * (1 - blendFactor); + color[2] = primaryColor[2] * blendFactor + secondaryColor[2] * (1 - blendFactor); + } + else { + color[0] = primaryColor[0]; + color[1] = primaryColor[1]; + color[2] = primaryColor[2]; + } + } + + color[0] *= 1.0f / 255.0f; + color[1] *= 1.0f / 255.0f; + color[2] *= 1.0f / 255.0f; + } + + static float GetFogStart(C_BasePlayer? pbp) { + if (pbp == null) + return 0.0f; + + ref FogParams fogParams = ref pbp.GetFogParams(); + + if (fog_override.GetInt() != 0) { + if (fog_start.GetFloat() == -1.0f) + return fogParams.Start; + else + return fog_start.GetFloat(); + } + else { + if (fogParams.LerpTime > gpGlobals.CurTime) { + if (fogParams.Start != fogParams.StartLerpTo) { + if (fogParams.LerpTime > gpGlobals.CurTime) { + float percent = (float)(1.0 - ((fogParams.LerpTime - gpGlobals.CurTime) / fogParams.Duration)); + + return MathLib.Lerp(percent, fogParams.Start, fogParams.StartLerpTo); + } + else { + if (fogParams.Start != fogParams.StartLerpTo) + fogParams.Start = fogParams.StartLerpTo; + } + } + } + + return fogParams.Start; + } + } + + static float GetFogEnd(C_BasePlayer? pbp) { + if (pbp == null) + return 0.0f; + + ref FogParams fogParams = ref pbp.GetFogParams(); + + if (fog_override.GetInt() != 0) { + if (fog_end.GetFloat() == -1.0f) + return fogParams.End; + else + return fog_end.GetFloat(); + } + else { + if (fogParams.LerpTime > gpGlobals.CurTime) { + if (fogParams.End != fogParams.EndLerpTo) { + if (fogParams.LerpTime > gpGlobals.CurTime) { + float percent = (float)(1.0 - ((fogParams.LerpTime - gpGlobals.CurTime) / fogParams.Duration)); + + return MathLib.Lerp(percent, fogParams.End, fogParams.EndLerpTo); + } + else { + if (fogParams.End != fogParams.EndLerpTo) + fogParams.End = fogParams.EndLerpTo; + } + } + } + + return fogParams.End; + } + } + + static bool GetFogEnable(C_BasePlayer? pbp) { + if (fog_override.GetInt() != 0) + return fog_enable.GetInt() != 0; + else { + if (pbp != null) + return pbp.GetFogParams().Enable != false; + + return false; + } + } + + static float GetFogMaxDensity(C_BasePlayer? pbp) { + if (pbp == null) + return 1.0f; + + ref FogParams fogParams = ref pbp.GetFogParams(); + + if (fog_override.GetInt() != 0) { + if (fog_maxdensity.GetFloat() == -1.0f) + return fogParams.MaxDensity; + else + return fog_maxdensity.GetFloat(); + } + else + return fogParams.MaxDensity; + } + + static bool GetFogRadial(C_BasePlayer? pbp) { + if (fog_override.GetInt() != 0) { + if (fog_radial.GetInt() != -1) + return fog_radial.GetBool(); + } + + if (pbp == null) + return false; + + return pbp.GetFogParams().Radial; + } + + protected static void GetSkyboxFogColor(Span color) { + C_BasePlayer? pbp = C_BasePlayer.GetLocalPlayer(); + if (pbp == null) + return; + + PlayerLocalData local = pbp.Local; + + if (fog_override.GetInt() != 0) + ParseFogColor(fog_colorskybox.GetString(), color); + else { + if (local.Skybox3D.Fog.Blend) { + pbp.EyeVectors(out Vector3 forward); + + MathLib.VectorNormalize(ref local.Skybox3D.Fog.DirPrimary); + + float blendFactor = 0.5f * Vector3.Dot(forward, local.Skybox3D.Fog.DirPrimary) + 0.5f; + + color[0] = local.Skybox3D.Fog.ColorPrimary.R * blendFactor + local.Skybox3D.Fog.ColorSecondary.R * (1 - blendFactor); + color[1] = local.Skybox3D.Fog.ColorPrimary.G * blendFactor + local.Skybox3D.Fog.ColorSecondary.G * (1 - blendFactor); + color[2] = local.Skybox3D.Fog.ColorPrimary.B * blendFactor + local.Skybox3D.Fog.ColorSecondary.B * (1 - blendFactor); + } + else { + color[0] = local.Skybox3D.Fog.ColorPrimary.R; + color[1] = local.Skybox3D.Fog.ColorPrimary.G; + color[2] = local.Skybox3D.Fog.ColorPrimary.B; + } + } + + color[0] *= 1.0f / 255.0f; + color[1] *= 1.0f / 255.0f; + color[2] *= 1.0f / 255.0f; + } + + protected static float GetSkyboxFogStart() { + C_BasePlayer? pbp = C_BasePlayer.GetLocalPlayer(); + if (pbp == null) + return 0.0f; + + PlayerLocalData local = pbp.Local; + + if (fog_override.GetInt() != 0) { + if (fog_startskybox.GetFloat() == -1.0f) + return local.Skybox3D.Fog.Start; + else + return fog_startskybox.GetFloat(); + } + else + return local.Skybox3D.Fog.Start; + } + + protected static float GetSkyboxFogEnd() { + C_BasePlayer? pbp = C_BasePlayer.GetLocalPlayer(); + if (pbp == null) + return 0.0f; + + PlayerLocalData local = pbp.Local; + + if (fog_override.GetInt() != 0) { + if (fog_endskybox.GetFloat() == -1.0f) + return local.Skybox3D.Fog.End; + else + return fog_endskybox.GetFloat(); + } + else + return local.Skybox3D.Fog.End; + } + + protected static float GetSkyboxFogMaxDensity() { + C_BasePlayer? pbp = C_BasePlayer.GetLocalPlayer(); + if (pbp == null) + return 1.0f; + + PlayerLocalData local = pbp.Local; + + if (fog_override.GetInt() != 0) { + if (fog_maxdensityskybox.GetFloat() == -1.0f) + return local.Skybox3D.Fog.MaxDensity; + else + return fog_maxdensityskybox.GetFloat(); + } + else + return local.Skybox3D.Fog.MaxDensity; + } + + protected static bool GetSkyboxFogRadial() { + C_BasePlayer? pbp = C_BasePlayer.GetLocalPlayer(); + if (pbp == null) + return false; + + PlayerLocalData local = pbp.Local; + + if (fog_override.GetInt() != 0) { + if (fog_radialskybox.GetInt() != -1) + return fog_radialskybox.GetBool(); + } + + return local.Skybox3D.Fog.Radial; + } + + protected void EnableWorldFog() { + using MatRenderContextPtr renderContext = new(mainView.materials); + + C_BasePlayer? pbp = C_BasePlayer.GetLocalPlayer(); + + if (gGM != null && gGM.Call((int)LUA_POOLEDSTRING.SetupWorldFog)) + return; + + if (GetFogEnable(pbp)) { + Span fogColor = stackalloc float[3]; + GetFogColor(pbp, fogColor); + + renderContext.FogMode(MaterialFogMode.Linear); + renderContext.FogColor3fv(fogColor); + renderContext.FogStart(GetFogStart(pbp)); + renderContext.FogEnd(GetFogEnd(pbp)); + renderContext.FogMaxDensity(GetFogMaxDensity(pbp)); + renderContext.FogRadial(GetFogRadial(pbp)); + } + else + renderContext.FogMode(MaterialFogMode.None); + } + + protected void SetFogVolumeState(in VisibleFogVolumeInfo fogInfo, bool useHeightFog) { + render.SetFogVolumeState(fogInfo.VisibleFogVolume, useHeightFog); + } protected void SetupRenderablesList(ViewID viewID) { // Clear the list. int i; @@ -1049,6 +1400,8 @@ private void DrawInternal(ViewID skyBoxViewID, bool invokePreAndPostRender, ITex setup.Origin += sky3dParams.Origin; Rendering3DSkybox = true; + Enable3dSkyboxFog(); + render.ViewSetupVisEx(false, new(ref sky3dParams.Origin), out _); render.Push3DView(in setup, ClearFlags, rtColor, GetFrustrum(), rtDepth); @@ -1073,6 +1426,8 @@ private void DrawInternal(ViewID skyBoxViewID, bool invokePreAndPostRender, ITex DrawTranslucentRenderables(RenderDepthMode.Normal); // todo: DrawNoZBufferTranslucentRenderables() + mainView.DisableFog(); + // restore old area bits saveBits.CopyTo(areaBits); @@ -1110,6 +1465,53 @@ private SafeFieldPointer PreRender3dSkyboxWorld(re static ref Sky3DParams GetSkybox3DRef(PlayerLocalData local) => ref local.Skybox3D; + private bool GetSkyboxFogEnable() { + C_BasePlayer? pbp = C_BasePlayer.GetLocalPlayer(); + if (pbp == null) + return false; + + PlayerLocalData local = pbp.Local; + + if (fog_override.GetInt() != 0) + return fog_enableskybox.GetInt() != 0; + else + return local.Skybox3D.Fog.Enable; + } + + private void Enable3dSkyboxFog() { + C_BasePlayer? pbp = C_BasePlayer.GetLocalPlayer(); + if (pbp == null) + return; + + PlayerLocalData local = pbp.Local; + + using MatRenderContextPtr renderContext = new(mainView.materials); + + float scale = 1.0f; + if (local.Skybox3D.Scale > 0.0f) + scale = 1.0f / local.Skybox3D.Scale; + + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.SetupSkyboxFog)) { + g_Lua!.PushNumber(scale); + if (gGM.CallFinish(1)) + return; + } + + if (GetSkyboxFogEnable()) { + Span fogColor = stackalloc float[3]; + GetSkyboxFogColor(fogColor); + + renderContext.FogMode(MaterialFogMode.Linear); + renderContext.FogColor3fv(fogColor); + renderContext.FogStart(GetSkyboxFogStart() * scale); + renderContext.FogEnd(GetSkyboxFogEnd() * scale); + renderContext.FogMaxDensity(GetSkyboxFogMaxDensity()); + renderContext.FogRadial(GetSkyboxFogRadial()); + } + else + renderContext.FogMode(MaterialFogMode.None); + } + private SkyboxVisibility ComputeSkyboxVisibility() { return engine.IsSkyboxVisibleFromPoint(setup.Origin); } diff --git a/Game.Shared/PlayerNetVars.cs b/Game.Shared/PlayerNetVars.cs index 0d8c2b158..839cff236 100644 --- a/Game.Shared/PlayerNetVars.cs +++ b/Game.Shared/PlayerNetVars.cs @@ -61,7 +61,7 @@ public struct FogPlayerParams() [NetworkName("m_hCtrl")] public Handle Ctrl = new(); #endif - public float TransitionTime; + public TimeUnit_t TransitionTime = -1; public Color OldColor; public float OldStart; From 0536bcbdbd382dc41987c82d6e98635058fe09c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 04:57:38 +0300 Subject: [PATCH 48/57] Size water render targets to the frame buffer like GMod --- Source.Engine/MatSysInterface.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source.Engine/MatSysInterface.cs b/Source.Engine/MatSysInterface.cs index 87ff8a3ba..a6cab83e7 100644 --- a/Source.Engine/MatSysInterface.cs +++ b/Source.Engine/MatSysInterface.cs @@ -316,7 +316,7 @@ private void InitDebugMaterials() { private ITexture? CreateWaterReflectionTexture() { return materials.CreateNamedRenderTargetTextureEx2( "_rt_WaterReflection", - 1024, 1024, RenderTargetSizeMode.Picmip, + 512, 512, RenderTargetSizeMode.FullFrameBuffer, materials.GetBackBufferFormat(), MaterialRenderTargetDepth.Shared, TextureFlags.ClampS | TextureFlags.ClampT, @@ -326,7 +326,7 @@ private void InitDebugMaterials() { private ITexture? CreateWaterRefractionTexture() { return materials.CreateNamedRenderTargetTextureEx2( "_rt_WaterRefraction", - 1024, 1024, RenderTargetSizeMode.Picmip, + 512, 512, RenderTargetSizeMode.FullFrameBuffer, // This is different than reflection because it has to have alpha for fog factor. ImageFormat.RGBA8888, MaterialRenderTargetDepth.Shared, From a9f0b360da6be157ac25c4f15f4901c1f32b462f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 05:09:21 +0300 Subject: [PATCH 49/57] Fix ClearBuffers ignoring color writes and desyncing masks --- Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index ca785fdf0..ba723304e 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -140,6 +140,8 @@ public unsafe void ClearBuffers(bool clearColor, bool clearDepth, bool clearSten if (clearStencil) flags |= GL_STENCIL_BUFFER_BIT; + if (clearColor) + glColorMask(true, true, true, true); if (clearDepth) glDepthMask(true); if (clearStencil) @@ -172,6 +174,13 @@ public unsafe void ClearBuffers(bool clearColor, bool clearDepth, bool clearSten if (clearColor) glColorMask(colorMask[0], colorMask[1], colorMask[2], colorMask[3]); } + + if (boardStateValid) { + if (clearColor) + glColorMask(lastBoardState.ColorWrite, lastBoardState.ColorWrite, lastBoardState.ColorWrite, lastBoardState.AlphaWrite); + if (clearDepth) + glDepthMask(lastBoardState.DepthWrite); + } } public void ClearColor3ub(byte r, byte g, byte b) => glClearColor(r / 255f, g / 255f, b / 255f, 1); From af1285c03a9f0649ffc366809aed80a72ad56400 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 05:16:44 +0300 Subject: [PATCH 50/57] Fix water distortion going the wrong way vertically in GL --- Game.Assets/hl2/shaders/water_gl460.fs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Game.Assets/hl2/shaders/water_gl460.fs b/Game.Assets/hl2/shaders/water_gl460.fs index 0d069a50a..f3524fa54 100644 --- a/Game.Assets/hl2/shaders/water_gl460.fs +++ b/Game.Assets/hl2/shaders/water_gl460.fs @@ -88,9 +88,10 @@ void main() vec2 vRefractTexCoord; vec4 vN; - vN.xy = vNormal.xy; + vN.x = vNormal.x; + vN.y = -vNormal.y; vN.w = vNormal.x; - vN.z = vNormal.y; + vN.z = -vNormal.y; vec4 vDependentTexCoords = vN * vNormal.a * reflectRefractScale; vDependentTexCoords += (vs_ReflectXY_RefractYX * ooW); From 8dd3e61ebb4e3a5b5ca55cb1c437b5a53c1180e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 05:29:12 +0300 Subject: [PATCH 51/57] Port sky_camera so the 3D skybox gets networked --- Game.Server/PlayerLocalData.cs | 20 +++--- Game.Server/SkyCamera.cs | 125 ++++++++++++++++++++++++++++++++- 2 files changed, 135 insertions(+), 10 deletions(-) diff --git a/Game.Server/PlayerLocalData.cs b/Game.Server/PlayerLocalData.cs index c1a02be41..48caef76c 100644 --- a/Game.Server/PlayerLocalData.cs +++ b/Game.Server/PlayerLocalData.cs @@ -159,15 +159,19 @@ public void UpdateAreaBits(BasePlayer pl, ReadOnlySpan areaPortalBits) { } } + public SkyCamera? OldSkyCamera; + public static void ClientData_Update(BasePlayer pl) { - // TODO! - // SkyCamera skyCamera = GetCurrentSkyCamera(); - // if (skyCamera != pl.Local.OldSkyCamera) { - // pl.Local.OldSkyCamera = skyCamera; - // pl.Local.Skybox3D.CopyFrom(skyCamera.SkyboxData); - // } - // else if (skyCamera == null) - pl.Local.Skybox3D.Area = 255; + SkyCamera? skyCamera = SkyCamera.GetCurrentSkyCamera(); + + if (skyCamera == null) { + pl.Local.Skybox3D.Area = 255; + pl.Local.OldSkyCamera = null; + } + else if (skyCamera != pl.Local.OldSkyCamera) { + pl.Local.OldSkyCamera = skyCamera; + pl.Local.Skybox3D = skyCamera.SkyboxData; + } } public static void UpdateAllClientData() { diff --git a/Game.Server/SkyCamera.cs b/Game.Server/SkyCamera.cs index 66dbe40b0..613fed0be 100644 --- a/Game.Server/SkyCamera.cs +++ b/Game.Server/SkyCamera.cs @@ -1,8 +1,129 @@ using Game.Shared; +using Source; +using Source.Common; +using Source.Common.Mathematics; + namespace Game.Server; +using DEFINE = Source.DEFINE; + [LinkEntityToClass("sky_camera")] -class SkyCamera : BaseEntity // todo LogicalEntity +public class SkyCamera : LogicalEntity { -} \ No newline at end of file + public Sky3DParams SkyboxData = new(); + public bool UseAngles; + public SkyCamera? Next; + + static SkyCamera? ClassList; + + public static SkyCamera? GetCurrentSkyCamera() => ClassList; + public static SkyCamera? GetSkyCameraList() => ClassList; + + public static readonly new DataMap DataDesc = new(typeof(SkyCamera), BaseEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(UseAngles), FieldType.Boolean, "use_angles"), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + static readonly string[] BogusFogMaps = [ + "d1_canals_01", + "d1_canals_01a", + "d1_canals_02", + "d1_canals_03", + "d1_canals_09", + "d1_canals_10", + "d1_canals_11", + "d1_canals_12", + "d1_canals_13", + "d1_eli_01", + "d1_trainstation_01", + "d1_trainstation_03", + "d1_trainstation_04", + "d1_trainstation_05", + "d1_trainstation_06", + "d3_c17_04", + "d3_c17_11", + "d3_c17_12", + "d3_citadel_01", + ]; + + public SkyCamera() { + Next = ClassList; + ClassList = this; + SkyboxData.Fog.MaxDensity = 1.0f; + } + + public override void UpdateOnRemove() { + if (ClassList == this) + ClassList = Next; + else { + for (SkyCamera? prev = ClassList; prev != null; prev = prev.Next) { + if (prev.Next == this) { + prev.Next = Next; + break; + } + } + } + Next = null; + + base.UpdateOnRemove(); + } + + public override bool KeyValue(ReadOnlySpan keyName, ReadOnlySpan value) { + if (FStrEq(keyName, "scale")) + SkyboxData.Scale = atoi(value); + else if (FStrEq(keyName, "fogenable")) + SkyboxData.Fog.Enable = atoi(value) != 0; + else if (FStrEq(keyName, "fogblend")) + SkyboxData.Fog.Blend = atoi(value) != 0; + else if (FStrEq(keyName, "fogdir")) { + Span dir = stackalloc float[3]; + UTIL_StringToVector(dir, value); + SkyboxData.Fog.DirPrimary = new(dir[0], dir[1], dir[2]); + } + else if (FStrEq(keyName, "fogcolor")) + Util.StringToColor32(out SkyboxData.Fog.ColorPrimary, value); + else if (FStrEq(keyName, "fogcolor2")) + Util.StringToColor32(out SkyboxData.Fog.ColorSecondary, value); + else if (FStrEq(keyName, "fogstart")) + SkyboxData.Fog.Start = strtof(value, out _); + else if (FStrEq(keyName, "fogend")) + SkyboxData.Fog.End = strtof(value, out _); + else if (FStrEq(keyName, "fogmaxdensity")) + SkyboxData.Fog.MaxDensity = strtof(value, out _); + else + return base.KeyValue(keyName, value); + + return true; + } + + public override void Spawn() { + SkyboxData.Origin = GetLocalOrigin(); + SkyboxData.Area = engine.GetArea(SkyboxData.Origin); + + Precache(); + } + + public override void Activate() { + base.Activate(); + + if (UseAngles) { + MathLib.AngleVectors(GetAbsAngles(), out SkyboxData.Fog.DirPrimary); + SkyboxData.Fog.DirPrimary *= -1.0f; + } + +#if HL2_DLL + if (SkyboxData.Fog.Blend) { + for (int i = 0; i < BogusFogMaps.Length; ++i) { + if (string.Equals(BogusFogMaps[i], gpGlobals.MapName, StringComparison.OrdinalIgnoreCase)) { + SkyboxData.Fog.ColorPrimary.R = (byte)((SkyboxData.Fog.ColorPrimary.R + SkyboxData.Fog.ColorSecondary.R) * 0.5f); + SkyboxData.Fog.ColorPrimary.G = (byte)((SkyboxData.Fog.ColorPrimary.G + SkyboxData.Fog.ColorSecondary.G) * 0.5f); + SkyboxData.Fog.ColorPrimary.B = (byte)((SkyboxData.Fog.ColorPrimary.B + SkyboxData.Fog.ColorSecondary.B) * 0.5f); + SkyboxData.Fog.ColorPrimary.A = (byte)((SkyboxData.Fog.ColorPrimary.A + SkyboxData.Fog.ColorSecondary.A) * 0.5f); + SkyboxData.Fog.ColorSecondary = SkyboxData.Fog.ColorPrimary; + } + } + } +#endif + } +} From 07158d826ce174b0375d6d5e717f6f87c66f6580 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 05:38:57 +0300 Subject: [PATCH 52/57] Render the 3D skybox into water reflections --- Game.Client/View.cs | 2 +- Game.Client/ViewRender.cs | 247 +++++++++++++++++++++++++++----------- 2 files changed, 177 insertions(+), 72 deletions(-) diff --git a/Game.Client/View.cs b/Game.Client/View.cs index a66b7a1aa..22cb52b78 100644 --- a/Game.Client/View.cs +++ b/Game.Client/View.cs @@ -822,7 +822,7 @@ public static bool DoesViewPlaneIntersectWater(float waterZ, int leafWaterDataID public static bool RenderingView = false; public static ViewID g_CurrentViewID = ViewID.None; public virtual bool ShouldForceNoVis() => ForceNoVis; - private void SetupVis(in ViewSetup viewRender, out uint visFlags) { + internal void SetupVis(in ViewSetup viewRender, out uint visFlags) { // TODO: more logic here render.ViewSetupVisEx(ShouldForceNoVis(), new ReadOnlySpan(in viewRender.Origin), out visFlags); } diff --git a/Game.Client/ViewRender.cs b/Game.Client/ViewRender.cs index 557b85760..d952c04e9 100644 --- a/Game.Client/ViewRender.cs +++ b/Game.Client/ViewRender.cs @@ -23,6 +23,7 @@ public static class ViewRenderConVars internal readonly static ConVar r_drawopaqueworld = new("1", FCvar.Cheat); internal readonly static ConVar r_drawtranslucentworld = new("1", FCvar.Cheat); internal readonly static ConVar r_3dsky = new("1", 0, "Enable the rendering of 3d sky boxes"); + internal readonly static ConVar r_3dskyinreflection = new("1", 0, "Enable the rendering of 3d sky boxes in water reflection"); internal readonly static ConVar r_skybox = new("1", FCvar.Cheat, "Enable the rendering of sky boxes"); internal readonly static ConVar r_drawviewmodel = new("1", FCvar.Cheat); internal readonly static ConVar r_drawtranslucentrenderables = new("1", FCvar.Cheat); @@ -141,7 +142,7 @@ public BaseWorldView(ViewRender mainView) : base(mainView) { } static Vector3 SavedLinearLightMapScale = new(-1, -1, -1); - static void SetLightmapScaleForWater() { + protected static void SetLightmapScaleForWater() { if (Singleton().GetHDRType() == HDRType.Integer) { using MatRenderContextPtr renderContext = new(materials); SavedLinearLightMapScale = renderContext.GetToneMappingScaleLinear(); @@ -392,11 +393,13 @@ public class AboveWaterView : BaseWaterView readonly ReflectionView Reflection; readonly RefractionView Refraction; readonly IntersectionView Intersection; + readonly SkyboxReflectionView SkyboxReflection; public AboveWaterView(ViewRender mainView) : base(mainView) { Reflection = new(mainView, this); Refraction = new(mainView, this); Intersection = new(mainView, this); + SkyboxReflection = new(mainView, this); } public void Setup(in ViewSetup view, bool drawSkybox, in VisibleFogVolumeInfo fogInfo, in WaterRenderInfo waterInfo) { @@ -424,11 +427,20 @@ public override void ReleaseLists() { Reflection.ReleaseLists(); Refraction.ReleaseLists(); Intersection.ReleaseLists(); + SkyboxReflection.ReleaseLists(); } public override void Draw() { if (WaterInfo.Reflect) { - Reflection.Setup(WaterInfo.ReflectEntities); + bool drew3dSkybox = false; + if (r_3dskyinreflection.GetBool() && r_3dsky.GetInt() != 0 && SkyboxReflection.Setup()) { + mainView.AddViewToScene(SkyboxReflection); + drew3dSkybox = true; + + mainView.SetupVis(in setup, out _); + } + + Reflection.Setup(WaterInfo.ReflectEntities, drew3dSkybox); mainView.AddViewToScene(Reflection); } @@ -458,14 +470,15 @@ public override void Draw() { class ReflectionView(ViewRender mainView, AboveWaterView outer) : BaseWorldView(mainView) { - public void Setup(bool reflectEntities) { + public void Setup(bool reflectEntities, bool drew3dSkybox) { base.Setup(in outer.setup); ClearFlags = ClearFlags.ClearDepth; DrawFlags = DrawFlags.RenderReflection | DrawFlags.ClipZ | DrawFlags.ClipBelow | DrawFlags.RenderAbovewater; - DrawFlags |= DrawFlags.DrawSkybox; + if (!drew3dSkybox) + DrawFlags |= DrawFlags.DrawSkybox; if (reflectEntities) DrawFlags |= DrawFlags.DrawEntities; @@ -487,6 +500,98 @@ public override void Draw() { } } + class SkyboxReflectionView(ViewRender mainView, AboveWaterView outer) : BaseWorldView(mainView) + { + SafeFieldPointer Sky3dParams = new(); + + public bool Setup() { + base.Setup(in outer.setup); + + SkyboxVisibility skyboxVisible = SkyboxVisibility.Skybox3D; + Sky3dParams = PreRender3dSkyboxWorld(ref skyboxVisible); + + if (Sky3dParams.IsNull) + return false; + + ClearFlags = ClearFlags.ClearDepth; + ClearFlags |= ClearFlags.ClearColor; + + DrawFlags = DrawFlags.RenderReflection | DrawFlags.ClipZ | DrawFlags.ClipBelow | DrawFlags.RenderAbovewater; + DrawFlags |= DrawFlags.DrawSkybox; + return true; + } + + public override void Draw() { + if (Sky3dParams.IsNull) + return; + + ref Sky3DParams sky3dParams = ref Sky3dParams.Get(); + + Span areaBits = render.GetAreaBits(); + Span saveBits = stackalloc byte[Constants.MAX_AREA_STATE_BYTES]; + areaBits.CopyTo(saveBits); + areaBits.Clear(); + + areaBits[sky3dParams.Area >> 3] |= (byte)(1 << (sky3dParams.Area & 7)); + + setup.ZNear = 2.0f; + setup.ZFar = WorldSize.MAX_TRACE_LENGTH; + + float scale = (sky3dParams.Scale > 0) ? (1.0f / sky3dParams.Scale) : 1.0f; + Vector3 skyOrigin = sky3dParams.Origin; + setup.Origin *= scale; + setup.Origin += skyOrigin; + + float waterHeight = skyOrigin.Z + (scale * outer.FogInfo.WaterHeight); + AdjustView(waterHeight); + + Enable3dSkyboxFog(); + + render.ViewSetupVisEx(false, new(ref sky3dParams.Origin), out _); + + using MatRenderContextPtr renderContext = new(mainView.materials); + + ITexture? texture = RenderTexture.GetWaterReflectionTexture(); + + renderContext.SetHeightClipZ(waterHeight); + + MaterialHeightClipMode clipMode = MaterialHeightClipMode.Disable; + if ((DrawFlags & DrawFlags.ClipZ) != 0 && mat_clipz.GetBool()) + clipMode = MaterialHeightClipMode.RenderAboveHeight; + + renderContext.SetHeightClipMode(clipMode); + + SetLightmapScaleForWater(); + + render.Push3DView(in setup, ClearFlags, texture, GetFrustrum(), null); + + ViewID saveViewID = CurrentViewID(); + Vector3 oldOrigin = CurrentViewOrigin(); + QAngle oldAngles = CurrentViewAngles(); + SetupCurrentView(in setup.Origin, in setup.Angles, ViewID.Sky3D); + + render.BeginUpdateLightmaps(); + BuildWorldRenderLists(true, -1, true); + BuildRenderableRenderLists(ViewID.Sky3D); + render.EndUpdateLightmaps(); + + engine.Sound_ExtraUpdate(); + + DrawWorld(0.0f); + + DrawOpaqueRenderables(RenderDepthMode.Normal); + DrawTranslucentRenderables(RenderDepthMode.Normal); + mainView.DisableFog(); + + renderContext.Flush(); + saveBits.CopyTo(areaBits); + + PopView(); + + SetupCurrentView(in oldOrigin, in oldAngles, saveViewID); + } + } + class RefractionView(ViewRender mainView, AboveWaterView outer) : BaseWorldView(mainView) { public void Setup() { @@ -1272,6 +1377,73 @@ protected void EnableWorldFog() { protected void SetFogVolumeState(in VisibleFogVolumeInfo fogInfo, bool useHeightFog) { render.SetFogVolumeState(fogInfo.VisibleFogVolume, useHeightFog); } + + protected static SafeFieldPointer PreRender3dSkyboxWorld(ref SkyboxVisibility skyboxVisible) { + if ((skyboxVisible != SkyboxVisibility.Skybox3D) && r_3dsky.GetInt() != 2) + return SafeFieldPointer.Null; + + if (r_3dsky.GetInt() == 0) + return SafeFieldPointer.Null; + + C_BasePlayer? player = C_BasePlayer.GetLocalPlayer(); + if (player == null) + return SafeFieldPointer.Null; + + PlayerLocalData local = player.Local; + if (local.Skybox3D.Area == 255) + return SafeFieldPointer.Null; + + return new(local, GetSkybox3DRef); + } + + static ref Sky3DParams GetSkybox3DRef(PlayerLocalData local) => ref local.Skybox3D; + + protected static bool GetSkyboxFogEnable() { + C_BasePlayer? pbp = C_BasePlayer.GetLocalPlayer(); + if (pbp == null) + return false; + + PlayerLocalData local = pbp.Local; + + if (fog_override.GetInt() != 0) + return fog_enableskybox.GetInt() != 0; + else + return local.Skybox3D.Fog.Enable; + } + + protected void Enable3dSkyboxFog() { + C_BasePlayer? pbp = C_BasePlayer.GetLocalPlayer(); + if (pbp == null) + return; + + PlayerLocalData local = pbp.Local; + + using MatRenderContextPtr renderContext = new(mainView.materials); + + float scale = 1.0f; + if (local.Skybox3D.Scale > 0.0f) + scale = 1.0f / local.Skybox3D.Scale; + + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.SetupSkyboxFog)) { + g_Lua!.PushNumber(scale); + if (gGM.CallFinish(1)) + return; + } + + if (GetSkyboxFogEnable()) { + Span fogColor = stackalloc float[3]; + GetSkyboxFogColor(fogColor); + + renderContext.FogMode(MaterialFogMode.Linear); + renderContext.FogColor3fv(fogColor); + renderContext.FogStart(GetSkyboxFogStart() * scale); + renderContext.FogEnd(GetSkyboxFogEnd() * scale); + renderContext.FogMaxDensity(GetSkyboxFogMaxDensity()); + renderContext.FogRadial(GetSkyboxFogRadial()); + } + else + renderContext.FogMode(MaterialFogMode.None); + } protected void SetupRenderablesList(ViewID viewID) { // Clear the list. int i; @@ -1445,73 +1617,6 @@ private void DrawInternal(ViewID skyBoxViewID, bool invokePreAndPostRender, ITex Rendering3DSkybox = false; } - private SafeFieldPointer PreRender3dSkyboxWorld(ref SkyboxVisibility skyboxVisible) { - if ((skyboxVisible != SkyboxVisibility.Skybox3D) && r_3dsky.GetInt() != 2) - return SafeFieldPointer.Null; - - if (r_3dsky.GetInt() == 0) - return SafeFieldPointer.Null; - - C_BasePlayer? player = C_BasePlayer.GetLocalPlayer(); - if (player == null) - return SafeFieldPointer.Null; - - PlayerLocalData local = player.Local; - if (local.Skybox3D.Area == 255) - return SafeFieldPointer.Null; - - return new(local, GetSkybox3DRef); - } - - static ref Sky3DParams GetSkybox3DRef(PlayerLocalData local) => ref local.Skybox3D; - - private bool GetSkyboxFogEnable() { - C_BasePlayer? pbp = C_BasePlayer.GetLocalPlayer(); - if (pbp == null) - return false; - - PlayerLocalData local = pbp.Local; - - if (fog_override.GetInt() != 0) - return fog_enableskybox.GetInt() != 0; - else - return local.Skybox3D.Fog.Enable; - } - - private void Enable3dSkyboxFog() { - C_BasePlayer? pbp = C_BasePlayer.GetLocalPlayer(); - if (pbp == null) - return; - - PlayerLocalData local = pbp.Local; - - using MatRenderContextPtr renderContext = new(mainView.materials); - - float scale = 1.0f; - if (local.Skybox3D.Scale > 0.0f) - scale = 1.0f / local.Skybox3D.Scale; - - if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.SetupSkyboxFog)) { - g_Lua!.PushNumber(scale); - if (gGM.CallFinish(1)) - return; - } - - if (GetSkyboxFogEnable()) { - Span fogColor = stackalloc float[3]; - GetSkyboxFogColor(fogColor); - - renderContext.FogMode(MaterialFogMode.Linear); - renderContext.FogColor3fv(fogColor); - renderContext.FogStart(GetSkyboxFogStart() * scale); - renderContext.FogEnd(GetSkyboxFogEnd() * scale); - renderContext.FogMaxDensity(GetSkyboxFogMaxDensity()); - renderContext.FogRadial(GetSkyboxFogRadial()); - } - else - renderContext.FogMode(MaterialFogMode.None); - } - private SkyboxVisibility ComputeSkyboxVisibility() { return engine.IsSkyboxVisibleFromPoint(setup.Origin); } From c0e2d702180d1943a33599740c6cb57b5c45fe50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 05:52:31 +0300 Subject: [PATCH 53/57] Fix empty world node surface index reading past the end --- Source.Engine/GLRSurf.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source.Engine/GLRSurf.cs b/Source.Engine/GLRSurf.cs index d75ddef7b..dc1f624d7 100644 --- a/Source.Engine/GLRSurf.cs +++ b/Source.Engine/GLRSurf.cs @@ -1130,7 +1130,7 @@ static void R_RecursiveWorldNode(WorldRenderList renderList, BSPMNode node, int R_RecursiveWorldNode(renderList, node.Children[side]!, cullMask); SurfaceHandle_t surfID = node.FirstSurface; - int i = ModelLoader.MSurf_Index(ref ModelLoader.SurfaceHandleFromIndex(surfID)); + int i = surfID; int lastSurface = i + node.NumSurfaces; ref VarBitSet visitedSurfs = ref renderList.VisitedSurfs; for (; i < lastSurface; ++i, ++surfID) { From 68b0d3920654eac9ba3ad8d545bde4b10c58eddf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 06:07:48 +0300 Subject: [PATCH 54/57] Fix world render lists surviving level shutdown --- Source.Engine/GLRSurf.cs | 2 +- Source.Engine/Render.cs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Source.Engine/GLRSurf.cs b/Source.Engine/GLRSurf.cs index dc1f624d7..9f1a20f8f 100644 --- a/Source.Engine/GLRSurf.cs +++ b/Source.Engine/GLRSurf.cs @@ -1333,7 +1333,7 @@ public static void R_SceneEnd() { } public static void R_BrushBatchInit() => throw new NotImplementedException(); public static void R_Surface_LevelInit() => throw new NotImplementedException(); - public static void R_Surface_LevelShutdown() => throw new NotImplementedException(); + public static void R_Surface_LevelShutdown() => WorldRenderList.PurgeAll(); static void R_DrawBrushModel_Override(IClientEntity? baseEntity, Model? model, in Vector3 origin) => throw new NotImplementedException(); public static int R_MarkDlightsOnBrushModel(Model? model, IClientRenderable renderable) => throw new NotImplementedException(); diff --git a/Source.Engine/Render.cs b/Source.Engine/Render.cs index ff799c57f..34b0f3058 100644 --- a/Source.Engine/Render.cs +++ b/Source.Engine/Render.cs @@ -1418,6 +1418,7 @@ public void UnloadSkys() { } public void LevelShutdown() { + R_Surface_LevelShutdown(); R_Areaportal_LevelShutdown(); } From 949082cdbcbd798da441fe00b77dd82853f069d0 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:14:27 -0700 Subject: [PATCH 55/57] Fix g_hTonemapControllerInUse being readonly --- Game.Client/C_EnvTonemapController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Game.Client/C_EnvTonemapController.cs b/Game.Client/C_EnvTonemapController.cs index b65b5fe75..27d704773 100644 --- a/Game.Client/C_EnvTonemapController.cs +++ b/Game.Client/C_EnvTonemapController.cs @@ -35,7 +35,7 @@ public class C_EnvTonemapController : C_BaseEntity [NetworkName("m_flCustomBloomScaleMinimum")] public float CustomBloomScaleMinimum; - static readonly EHANDLE g_hTonemapControllerInUse = new(); + static EHANDLE g_hTonemapControllerInUse = new(); public override void UpdateOnRemove() { if (g_hTonemapControllerInUse.Get() == this) { @@ -59,4 +59,4 @@ public override void OnDataChanged(DataUpdateType updateType) { g_hTonemapControllerInUse.Set(this); } -} \ No newline at end of file +} From 7571a650cdb8b97293457317f2196bd0daf5fbb7 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:24:23 -0700 Subject: [PATCH 56/57] fix screenspace dx9 stub --- Source.StdShader.Gl46/Screenspace_General.cs | 275 +----------------- .../screenspace_general_dx9.cs | 249 ++++++++++------ 2 files changed, 159 insertions(+), 365 deletions(-) diff --git a/Source.StdShader.Gl46/Screenspace_General.cs b/Source.StdShader.Gl46/Screenspace_General.cs index c3cc1826b..794a440e3 100644 --- a/Source.StdShader.Gl46/Screenspace_General.cs +++ b/Source.StdShader.Gl46/Screenspace_General.cs @@ -1,282 +1,11 @@ -using Source.Common; using Source.Common.MaterialSystem; -using Source.Common.ShaderAPI; -using Source.Common.ShaderLib; namespace Source.StdShader.Gl46; public class Screenspace_General : BaseVSShader { public static string HelpString = "Help for screenspace_general"; - public static int Flags = (int)ShaderParamFlags.NotEditable; - public static List ShaderParams = []; - public static ShaderParam[] ShaderParamOverrides = new ShaderParam[(int)ShaderMaterialVars.Count]; + public static int Flags = 0; - public class ShaderParam - { - public readonly ShaderParamInfo Info; - public readonly int Index; - public ShaderParam(ShaderMaterialVars var, ShaderParamType type, ReadOnlySpan defaultParam, ReadOnlySpan help, int flags) { - Info.Name = "override"; - Info.Type = type; - Info.DefaultValue = new(defaultParam); - Info.Help = new(help); - Info.Flags = (ShaderParamFlags)flags; - - if (ShaderParamOverrides[(int)var] == null) { - - } - else { - AssertMsg(false, "ShaderParamOverrides at var index had null value"); - } - - ShaderParamOverrides[(int)var] = this; - Index = (int)var; - } - public ShaderParam(string name, ShaderParamType type, ReadOnlySpan defaultParam, ReadOnlySpan help, int flags = 0) { - Info.Name = name; - Info.Type = type; - Info.DefaultValue = new(defaultParam); - Info.Help = new(help); - Info.Flags = (ShaderParamFlags)flags; - Index = (int)ShaderMaterialVars.Count + ShaderParams.Count; - ShaderParams.Add(this); - } - public static implicit operator int(ShaderParam param) => param.Index; - public ReadOnlySpan GetName() => Info.Name; - public ShaderParamType GetType() => Info.Type; - public ReadOnlySpan GetDefaultValue() => Info.DefaultValue; - public int GetFlags() => (int)Info.Flags; - public ReadOnlySpan GetHelp() => Info.Help; - } - - public static readonly ShaderParam ALPHA_BLEND = new($"${nameof(ALPHA_BLEND)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam ALPHA_BLEND_COLOR_OVERLAY = new($"${nameof(ALPHA_BLEND_COLOR_OVERLAY)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam ALPHABLEND = new($"${nameof(ALPHABLEND)}", ShaderParamType.Integer, "0", "whether or not to enable alpha blend"); - public static readonly ShaderParam ALPHATESTED = new($"${nameof(ALPHATESTED)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam BLENDOPMIN = new($"${nameof(BLENDOPMIN)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam C0_W = new($"${nameof(C0_W)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C0_X = new($"${nameof(C0_X)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C0_Y = new($"${nameof(C0_Y)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C0_Z = new($"${nameof(C0_Z)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C1_W = new($"${nameof(C1_W)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C1_X = new($"${nameof(C1_X)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C1_Y = new($"${nameof(C1_Y)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C1_Z = new($"${nameof(C1_Z)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C2_W = new($"${nameof(C2_W)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C2_X = new($"${nameof(C2_X)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C2_Y = new($"${nameof(C2_Y)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C2_Z = new($"${nameof(C2_Z)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C3_W = new($"${nameof(C3_W)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C3_X = new($"${nameof(C3_X)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C3_Y = new($"${nameof(C3_Y)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C3_Z = new($"${nameof(C3_Z)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam COPYALPHA = new($"${nameof(COPYALPHA)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam CULL = new($"${nameof(CULL)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam DEPTHTEST = new($"${nameof(DEPTHTEST)}", ShaderParamType.Integer, "0", "Enable Depthtest"); - public static readonly ShaderParam DISABLE_COLOR_WRITES = new($"${nameof(DISABLE_COLOR_WRITES)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam INVVIEWPROJMAT = new($"${nameof(INVVIEWPROJMAT)}", ShaderParamType.Matrix, "0", ""); - public static readonly ShaderParam LINEARREAD_BASETEXTURE = new($"${nameof(LINEARREAD_BASETEXTURE)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam LINEARREAD_TEXTURE1 = new($"${nameof(LINEARREAD_TEXTURE1)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam LINEARREAD_TEXTURE2 = new($"${nameof(LINEARREAD_TEXTURE2)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam LINEARREAD_TEXTURE3 = new($"${nameof(LINEARREAD_TEXTURE3)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam LINEARWRITE = new($"${nameof(LINEARWRITE)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam MULTIPLYCOLOR = new($"${nameof(MULTIPLYCOLOR)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam PIXSHADER = new($"${nameof(PIXSHADER)}", ShaderParamType.String, "", ""); - public static readonly ShaderParam POINTSAMPLE_BASETEXTURE = new($"${nameof(POINTSAMPLE_BASETEXTURE)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam POINTSAMPLE_TEXTURE1 = new($"${nameof(POINTSAMPLE_TEXTURE1)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam POINTSAMPLE_TEXTURE2 = new($"${nameof(POINTSAMPLE_TEXTURE2)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam POINTSAMPLE_TEXTURE3 = new($"${nameof(POINTSAMPLE_TEXTURE3)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam TCSIZE0 = new($"${nameof(TCSIZE0)}", ShaderParamType.Integer, "2", ""); - public static readonly ShaderParam TCSIZE1 = new($"${nameof(TCSIZE1)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam TCSIZE2 = new($"${nameof(TCSIZE2)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam TCSIZE3 = new($"${nameof(TCSIZE3)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam TCSIZE4 = new($"${nameof(TCSIZE4)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam TCSIZE5 = new($"${nameof(TCSIZE5)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam TCSIZE6 = new($"${nameof(TCSIZE6)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam TCSIZE7 = new($"${nameof(TCSIZE7)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam TEXTURE1 = new($"${nameof(TEXTURE1)}", ShaderParamType.Texture, "", ""); - public static readonly ShaderParam TEXTURE2 = new($"${nameof(TEXTURE2)}", ShaderParamType.Texture, "", ""); - public static readonly ShaderParam TEXTURE3 = new($"${nameof(TEXTURE3)}", ShaderParamType.Texture, "", ""); - public static readonly ShaderParam VERTEXNORMAL = new($"${nameof(VERTEXNORMAL)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam VERTEXSHADER = new($"${nameof(VERTEXSHADER)}", ShaderParamType.String, "", ""); - public static readonly ShaderParam VERTEXTRANSFORM = new($"${nameof(VERTEXTRANSFORM)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam VIEWPROJMAT = new($"${nameof(VIEWPROJMAT)}", ShaderParamType.Matrix, "0", ""); - public static readonly ShaderParam WRITEALPHA = new($"${nameof(WRITEALPHA)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam WRITEDEPTH = new($"${nameof(WRITEDEPTH)}", ShaderParamType.Integer, "0", "whether or not to enable depth write"); - - static readonly ShaderParam[] TCSizes = [TCSIZE0, TCSIZE1, TCSIZE2, TCSIZE3, TCSIZE4, TCSIZE5, TCSIZE6, TCSIZE7]; - - protected override void OnInitShaderParams(IMaterialVar[] parms, ReadOnlySpan materialName) { - if (!parms[TCSIZE0].IsDefined()) - parms[TCSIZE0].SetIntValue(2); - } - - public override string? GetFallbackShader(IMaterialVar[] vars) => null; - public override int GetFlags() => Flags; - public override int GetNumParams() => base.GetNumParams() + ShaderParams.Count; - public override ReadOnlySpan GetParamName(int paramIndex) { - int baseClassParamCount = base.GetNumParams(); - if (paramIndex < baseClassParamCount) - return base.GetParamName(paramIndex); - else - return ShaderParams[paramIndex - baseClassParamCount].GetName(); - } - public override ReadOnlySpan GetParamHelp(int paramIndex) { - int baseClassParamCount = base.GetNumParams(); - if (paramIndex < baseClassParamCount) - return base.GetParamHelp(paramIndex); - else - return ShaderParams[paramIndex - baseClassParamCount].GetHelp(); - } - public override ShaderParamType GetParamType(int paramIndex) { - int baseClassParamCount = base.GetNumParams(); - if (paramIndex < baseClassParamCount) - return base.GetParamType(paramIndex); - else - return ShaderParams[paramIndex - baseClassParamCount].GetType(); - } - public override ReadOnlySpan GetParamDefault(int paramIndex) { - int baseClassParamCount = base.GetNumParams(); - if (paramIndex < baseClassParamCount) - return base.GetParamDefault(paramIndex); - else - return ShaderParams[paramIndex - baseClassParamCount].GetDefaultValue(); - } - - protected override void OnInitShaderInstance(IMaterialVar[] parms, ReadOnlySpan materialName) { - if (parms[(int)ShaderMaterialVars.BaseTexture].IsDefined()) - LoadTexture((int)ShaderMaterialVars.BaseTexture); - if (parms[TEXTURE1].IsDefined()) - LoadTexture(TEXTURE1); - if (parms[TEXTURE2].IsDefined()) - LoadTexture(TEXTURE2); - if (parms[TEXTURE3].IsDefined()) - LoadTexture(TEXTURE3); - } - - void EnableTextureSRGBRead(IMaterialVar[] parms, Sampler sampler, int textureVar, int linearReadVar) { - if (!parms[textureVar].IsDefined()) - return; - ShaderShadow!.EnableTexture(sampler, true); - ShaderShadow.EnableSRGBRead(sampler, !parms[linearReadVar].IsDefined() || parms[linearReadVar].GetIntValue() == 0); - } - - void SetPixelSize(IMaterialVar[] parms, Sampler sampler, int textureVar, int register) { - if (!parms[textureVar].IsDefined()) - return; - BindTexture(sampler, textureVar, -1); - - ITexture target = parms[textureVar].GetTextureValue()!; - Span pixelSize = [1.0f / target.GetActualWidth(), 1.0f / target.GetActualHeight(), 0.0f, 0.0f]; - ShaderAPI!.SetPixelShaderConstant(register, pixelSize, 1); - } - - protected override void OnDrawElements(IMaterialVar[] parms, IShaderDynamicAPI shaderAPI, VertexCompressionType vertexCompression) { - bool customVertexShader = parms[VERTEXSHADER].IsDefined(); - if (ShaderShadow != null) { - ShaderShadow.EnableDepthWrites(parms[WRITEDEPTH].GetIntValue() != 0); - if (parms[WRITEDEPTH].GetIntValue() != 0) { - ShaderShadow.EnableDepthTest(true); - ShaderShadow.DepthFunc(ShaderDepthFunc.Always); - } - ShaderShadow.EnableAlphaWrites(parms[WRITEALPHA].GetIntValue() != 0); - ShaderShadow.EnableDepthTest(parms[DEPTHTEST].GetIntValue() != 0); - ShaderShadow.EnableCulling(parms[CULL].GetIntValue() != 0); - - EnableTextureSRGBRead(parms, Sampler.Sampler0, (int)ShaderMaterialVars.BaseTexture, LINEARREAD_BASETEXTURE); - EnableTextureSRGBRead(parms, Sampler.Sampler1, TEXTURE1, LINEARREAD_TEXTURE1); - EnableTextureSRGBRead(parms, Sampler.Sampler2, TEXTURE2, LINEARREAD_TEXTURE2); - EnableTextureSRGBRead(parms, Sampler.Sampler3, TEXTURE3, LINEARREAD_TEXTURE3); - - int vertexColor = IsFlagSet(parms, MaterialVarFlags.VertexColor) ? 1 : 0; - VertexFormat fmt = VertexFormat.Position; - if (vertexColor != 0) - fmt |= VertexFormat.Color; - if (parms[VERTEXNORMAL].GetIntValue() != 0) - fmt |= VertexFormat.Normal; - - Span texCoordDimensions = stackalloc int[8]; - int texCoordCount = 0; - while (texCoordCount < 8 && parms[TCSizes[texCoordCount]].GetIntValue() != 0) { - texCoordDimensions[texCoordCount] = parms[TCSizes[texCoordCount]].GetIntValue(); - texCoordCount++; - } - ShaderShadow.VertexShaderVertexFormat(fmt, texCoordCount, texCoordDimensions[..texCoordCount], 0); - - if (IsFlagSet(parms, MaterialVarFlags.Additive)) - EnableAlphaBlending(ShaderBlendFactor.One, ShaderBlendFactor.One); - else if (parms[MULTIPLYCOLOR].GetIntValue() != 0) - EnableAlphaBlending(ShaderBlendFactor.Zero, ShaderBlendFactor.SrcColor); - else if (parms[ALPHABLEND].GetIntValue() != 0) - EnableAlphaBlending(ShaderBlendFactor.SrcAlpha, ShaderBlendFactor.OneMinusSrcAlpha); - else - ShaderShadow.EnableBlending(false); - - if (parms[BLENDOPMIN].GetIntValue() != 0) { - ShaderShadow.BlendOp(ShaderBlendOp.Min); - ShaderShadow.EnableBlending(true); - } - - ShaderShadow.EnableSRGBWrite(parms[LINEARWRITE].GetIntValue() == 0); - - if (!customVertexShader) - ShaderShadow.SetVertexShader("screenspaceeffect", vertexColor + parms[VERTEXTRANSFORM].GetIntValue() * 2); - else - ShaderShadow.SetVertexShader(parms[VERTEXSHADER].GetStringValue(), 0); - - if (parms[DISABLE_COLOR_WRITES].GetIntValue() != 0) - ShaderShadow.EnableColorWrites(false); - - ShaderShadow.EnableAlphaTest(true); - ShaderShadow.AlphaFunc(ShaderAlphaFunc.Greater, 0.0f); - - string pixelShader = parms[PIXSHADER].GetStringValue(); - if (HardwareConfig.SupportsPixelShaders_2_b() && pixelShader.Length > 6 && (pixelShader.EndsWith("_ps20", StringComparison.OrdinalIgnoreCase) || pixelShader.EndsWith("_vs20", StringComparison.OrdinalIgnoreCase))) - pixelShader += "b"; - ShaderShadow.SetPixelShader(pixelShader, 0); - - if (parms[ALPHA_BLEND_COLOR_OVERLAY].GetIntValue() != 0) - EnableAlphaBlending(ShaderBlendFactor.One, ShaderBlendFactor.OneMinusSrcAlpha); - if (parms[ALPHA_BLEND].GetIntValue() != 0) - EnableAlphaBlending(ShaderBlendFactor.SrcAlpha, ShaderBlendFactor.OneMinusSrcAlpha); - if (parms[COPYALPHA].GetIntValue() != 0) { - ShaderShadow.EnableBlending(false); - ShaderShadow.AlphaFunc(ShaderAlphaFunc.Always, 0.0f); - } - } - if (ShaderAPI != null) { - SetPixelSize(parms, Sampler.Sampler0, (int)ShaderMaterialVars.BaseTexture, 4); - SetPixelSize(parms, Sampler.Sampler1, TEXTURE1, 5); - SetPixelSize(parms, Sampler.Sampler2, TEXTURE2, 6); - SetPixelSize(parms, Sampler.Sampler3, TEXTURE3, 7); - - Span c0 = [ - parms[C0_X].GetFloatValue(), parms[C0_Y].GetFloatValue(), parms[C0_Z].GetFloatValue(), parms[C0_W].GetFloatValue(), - parms[C1_X].GetFloatValue(), parms[C1_Y].GetFloatValue(), parms[C1_Z].GetFloatValue(), parms[C1_W].GetFloatValue(), - parms[C2_X].GetFloatValue(), parms[C2_Y].GetFloatValue(), parms[C2_Z].GetFloatValue(), parms[C2_W].GetFloatValue(), - parms[C3_X].GetFloatValue(), parms[C3_Y].GetFloatValue(), parms[C3_Z].GetFloatValue(), parms[C3_W].GetFloatValue() - ]; - ShaderAPI.SetPixelShaderConstant(0, c0, 4); - - Span eyePos = stackalloc float[4]; - ShaderAPI.GetWorldSpaceCameraPosition(eyePos); - ShaderAPI.SetPixelShaderConstant(10, eyePos, 1); - - if (parms[VIEWPROJMAT].IsDefined()) { - System.Numerics.Matrix4x4 viewProj = parms[VIEWPROJMAT].GetMatrixValue(); - ShaderAPI.SetPixelShaderConstant(11, System.Runtime.InteropServices.MemoryMarshal.CreateReadOnlySpan(ref viewProj.M11, 16), 4); - } - if (parms[INVVIEWPROJMAT].IsDefined()) { - System.Numerics.Matrix4x4 invViewProj = parms[INVVIEWPROJMAT].GetMatrixValue(); - ShaderAPI.SetPixelShaderConstant(15, System.Runtime.InteropServices.MemoryMarshal.CreateReadOnlySpan(ref invViewProj.M11, 16), 4); - } - - ShaderAPI.SetVertexShaderIndex(0); - ShaderAPI.SetPixelShaderIndex(0); - if (!customVertexShader) - ShaderAPI.SetVertexShaderIndex(0); - } - Draw(); - } + public override string? GetFallbackShader(IMaterialVar[] vars) => "screenspace_general_dx9"; } diff --git a/Source.StdShader.Gl46/screenspace_general_dx9.cs b/Source.StdShader.Gl46/screenspace_general_dx9.cs index 92d72c8fc..fa0905603 100644 --- a/Source.StdShader.Gl46/screenspace_general_dx9.cs +++ b/Source.StdShader.Gl46/screenspace_general_dx9.cs @@ -1,4 +1,4 @@ -using Source.Common.Bitmap; +using Source.Common; using Source.Common.MaterialSystem; using Source.Common.ShaderAPI; using Source.Common.ShaderLib; @@ -10,11 +10,29 @@ public class screenspace_general_dx9 : BaseVSShader public static string HelpString = "Help for screenspace_general"; public static int Flags = (int)ShaderParamFlags.NotEditable; public static List ShaderParams = []; + public static ShaderParam[] ShaderParamOverrides = new ShaderParam[(int)ShaderMaterialVars.Count]; public class ShaderParam { public readonly ShaderParamInfo Info; public readonly int Index; + public ShaderParam(ShaderMaterialVars var, ShaderParamType type, ReadOnlySpan defaultParam, ReadOnlySpan help, int flags) { + Info.Name = "override"; + Info.Type = type; + Info.DefaultValue = new(defaultParam); + Info.Help = new(help); + Info.Flags = (ShaderParamFlags)flags; + + if (ShaderParamOverrides[(int)var] == null) { + + } + else { + AssertMsg(false, "ShaderParamOverrides at var index had null value"); + } + + ShaderParamOverrides[(int)var] = this; + Index = (int)var; + } public ShaderParam(string name, ShaderParamType type, ReadOnlySpan defaultParam, ReadOnlySpan help, int flags = 0) { Info.Name = name; Info.Type = type; @@ -32,36 +50,67 @@ public ShaderParam(string name, ShaderParamType type, ReadOnlySpan default public ReadOnlySpan GetHelp() => Info.Help; } + public static readonly ShaderParam ALPHA_BLEND = new($"${nameof(ALPHA_BLEND)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam ALPHA_BLEND_COLOR_OVERLAY = new($"${nameof(ALPHA_BLEND_COLOR_OVERLAY)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam ALPHABLEND = new($"${nameof(ALPHABLEND)}", ShaderParamType.Integer, "0", "whether or not to enable alpha blend"); + public static readonly ShaderParam ALPHATESTED = new($"${nameof(ALPHATESTED)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam BLENDOPMIN = new($"${nameof(BLENDOPMIN)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam C0_W = new($"${nameof(C0_W)}", ShaderParamType.Float, "0", ""); public static readonly ShaderParam C0_X = new($"${nameof(C0_X)}", ShaderParamType.Float, "0", ""); public static readonly ShaderParam C0_Y = new($"${nameof(C0_Y)}", ShaderParamType.Float, "0", ""); public static readonly ShaderParam C0_Z = new($"${nameof(C0_Z)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C0_W = new($"${nameof(C0_W)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C1_W = new($"${nameof(C1_W)}", ShaderParamType.Float, "0", ""); public static readonly ShaderParam C1_X = new($"${nameof(C1_X)}", ShaderParamType.Float, "0", ""); public static readonly ShaderParam C1_Y = new($"${nameof(C1_Y)}", ShaderParamType.Float, "0", ""); public static readonly ShaderParam C1_Z = new($"${nameof(C1_Z)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C1_W = new($"${nameof(C1_W)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C2_W = new($"${nameof(C2_W)}", ShaderParamType.Float, "0", ""); public static readonly ShaderParam C2_X = new($"${nameof(C2_X)}", ShaderParamType.Float, "0", ""); public static readonly ShaderParam C2_Y = new($"${nameof(C2_Y)}", ShaderParamType.Float, "0", ""); public static readonly ShaderParam C2_Z = new($"${nameof(C2_Z)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C2_W = new($"${nameof(C2_W)}", ShaderParamType.Float, "0", ""); + public static readonly ShaderParam C3_W = new($"${nameof(C3_W)}", ShaderParamType.Float, "0", ""); public static readonly ShaderParam C3_X = new($"${nameof(C3_X)}", ShaderParamType.Float, "0", ""); public static readonly ShaderParam C3_Y = new($"${nameof(C3_Y)}", ShaderParamType.Float, "0", ""); public static readonly ShaderParam C3_Z = new($"${nameof(C3_Z)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam C3_W = new($"${nameof(C3_W)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam PIXSHADER = new($"${nameof(PIXSHADER)}", ShaderParamType.String, "", "Name of the pixel shader to use"); + public static readonly ShaderParam COPYALPHA = new($"${nameof(COPYALPHA)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam CULL = new($"${nameof(CULL)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam DEPTHTEST = new($"${nameof(DEPTHTEST)}", ShaderParamType.Integer, "0", "Enable Depthtest"); public static readonly ShaderParam DISABLE_COLOR_WRITES = new($"${nameof(DISABLE_COLOR_WRITES)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam ALPHATESTED = new($"${nameof(ALPHATESTED)}", ShaderParamType.Float, "0", ""); - public static readonly ShaderParam ALPHA_BLEND_COLOR_OVERLAY = new($"${nameof(ALPHA_BLEND_COLOR_OVERLAY)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam ALPHA_BLEND = new($"${nameof(ALPHA_BLEND)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam TEXTURE1 = new($"${nameof(TEXTURE1)}", ShaderParamType.Texture, "", ""); - public static readonly ShaderParam TEXTURE2 = new($"${nameof(TEXTURE2)}", ShaderParamType.Texture, "", ""); - public static readonly ShaderParam TEXTURE3 = new($"${nameof(TEXTURE3)}", ShaderParamType.Texture, "", ""); + public static readonly ShaderParam INVVIEWPROJMAT = new($"${nameof(INVVIEWPROJMAT)}", ShaderParamType.Matrix, "0", ""); public static readonly ShaderParam LINEARREAD_BASETEXTURE = new($"${nameof(LINEARREAD_BASETEXTURE)}", ShaderParamType.Integer, "0", ""); public static readonly ShaderParam LINEARREAD_TEXTURE1 = new($"${nameof(LINEARREAD_TEXTURE1)}", ShaderParamType.Integer, "0", ""); public static readonly ShaderParam LINEARREAD_TEXTURE2 = new($"${nameof(LINEARREAD_TEXTURE2)}", ShaderParamType.Integer, "0", ""); public static readonly ShaderParam LINEARREAD_TEXTURE3 = new($"${nameof(LINEARREAD_TEXTURE3)}", ShaderParamType.Integer, "0", ""); public static readonly ShaderParam LINEARWRITE = new($"${nameof(LINEARWRITE)}", ShaderParamType.Integer, "0", ""); - public static readonly ShaderParam COPYALPHA = new($"${nameof(COPYALPHA)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam MULTIPLYCOLOR = new($"${nameof(MULTIPLYCOLOR)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam PIXSHADER = new($"${nameof(PIXSHADER)}", ShaderParamType.String, "", ""); + public static readonly ShaderParam POINTSAMPLE_BASETEXTURE = new($"${nameof(POINTSAMPLE_BASETEXTURE)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam POINTSAMPLE_TEXTURE1 = new($"${nameof(POINTSAMPLE_TEXTURE1)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam POINTSAMPLE_TEXTURE2 = new($"${nameof(POINTSAMPLE_TEXTURE2)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam POINTSAMPLE_TEXTURE3 = new($"${nameof(POINTSAMPLE_TEXTURE3)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam TCSIZE0 = new($"${nameof(TCSIZE0)}", ShaderParamType.Integer, "2", ""); + public static readonly ShaderParam TCSIZE1 = new($"${nameof(TCSIZE1)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam TCSIZE2 = new($"${nameof(TCSIZE2)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam TCSIZE3 = new($"${nameof(TCSIZE3)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam TCSIZE4 = new($"${nameof(TCSIZE4)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam TCSIZE5 = new($"${nameof(TCSIZE5)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam TCSIZE6 = new($"${nameof(TCSIZE6)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam TCSIZE7 = new($"${nameof(TCSIZE7)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam TEXTURE1 = new($"${nameof(TEXTURE1)}", ShaderParamType.Texture, "", ""); + public static readonly ShaderParam TEXTURE2 = new($"${nameof(TEXTURE2)}", ShaderParamType.Texture, "", ""); + public static readonly ShaderParam TEXTURE3 = new($"${nameof(TEXTURE3)}", ShaderParamType.Texture, "", ""); + public static readonly ShaderParam VERTEXNORMAL = new($"${nameof(VERTEXNORMAL)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam VERTEXSHADER = new($"${nameof(VERTEXSHADER)}", ShaderParamType.String, "", ""); + public static readonly ShaderParam VERTEXTRANSFORM = new($"${nameof(VERTEXTRANSFORM)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam VIEWPROJMAT = new($"${nameof(VIEWPROJMAT)}", ShaderParamType.Matrix, "0", ""); + public static readonly ShaderParam WRITEALPHA = new($"${nameof(WRITEALPHA)}", ShaderParamType.Integer, "0", ""); + public static readonly ShaderParam WRITEDEPTH = new($"${nameof(WRITEDEPTH)}", ShaderParamType.Integer, "0", "whether or not to enable depth write"); + + static readonly ShaderParam[] TCSizes = [TCSIZE0, TCSIZE1, TCSIZE2, TCSIZE3, TCSIZE4, TCSIZE5, TCSIZE6, TCSIZE7]; + + protected override void OnInitShaderParams(IMaterialVar[] parms, ReadOnlySpan materialName) { + if (!parms[TCSIZE0].IsDefined()) + parms[TCSIZE0].SetIntValue(2); + } public override string? GetFallbackShader(IMaterialVar[] vars) => null; public override int GetFlags() => Flags; @@ -95,122 +144,138 @@ public override ReadOnlySpan GetParamDefault(int paramIndex) { return ShaderParams[paramIndex - baseClassParamCount].GetDefaultValue(); } - protected override void OnInitShaderInstance(IMaterialVar[] vars, ReadOnlySpan materialName) { - if (vars[(int)ShaderMaterialVars.BaseTexture].IsDefined()) + protected override void OnInitShaderInstance(IMaterialVar[] parms, ReadOnlySpan materialName) { + if (parms[(int)ShaderMaterialVars.BaseTexture].IsDefined()) LoadTexture((int)ShaderMaterialVars.BaseTexture); - if (vars[TEXTURE1].IsDefined()) + if (parms[TEXTURE1].IsDefined()) LoadTexture(TEXTURE1); - if (vars[TEXTURE2].IsDefined()) + if (parms[TEXTURE2].IsDefined()) LoadTexture(TEXTURE2); - if (vars[TEXTURE3].IsDefined()) + if (parms[TEXTURE3].IsDefined()) LoadTexture(TEXTURE3); } - void SetupSamplerSRGBRead(IMaterialVar[] vars, Sampler sampler, int textureVar, int linearReadVar) { + void EnableTextureSRGBRead(IMaterialVar[] parms, Sampler sampler, int textureVar, int linearReadVar) { + if (!parms[textureVar].IsDefined()) + return; ShaderShadow!.EnableTexture(sampler, true); - ITexture txtr = vars[textureVar].GetTextureValue()!; - ImageFormat fmt = txtr.GetImageFormat(); - if ((fmt == ImageFormat.RGBA16161616F) || (fmt == ImageFormat.RGBA16161616)) - ShaderShadow.EnableSRGBRead(sampler, false); - else - ShaderShadow.EnableSRGBRead(sampler, !vars[linearReadVar].IsDefined() || vars[linearReadVar].GetIntValue() == 0); + ShaderShadow.EnableSRGBRead(sampler, !parms[linearReadVar].IsDefined() || parms[linearReadVar].GetIntValue() == 0); } - void BindTextureWithPixelSize(IShaderDynamicAPI shaderAPI, IMaterialVar[] vars, Sampler sampler, int textureVar, int constant) { + void SetPixelSize(IMaterialVar[] parms, Sampler sampler, int textureVar, int register) { + if (!parms[textureVar].IsDefined()) + return; BindTexture(sampler, textureVar, -1); - ITexture target = vars[textureVar].GetTextureValue()!; + ITexture target = parms[textureVar].GetTextureValue()!; Span pixelSize = [1.0f / target.GetActualWidth(), 1.0f / target.GetActualHeight(), 0.0f, 0.0f]; - shaderAPI.SetPixelShaderConstant(constant, pixelSize, 1); + ShaderAPI!.SetPixelShaderConstant(register, pixelSize, 1); } - static ReadOnlySpan PixelShaderFileName(ReadOnlySpan pixelShader) { - if (pixelShader.EndsWith("_ps20b", StringComparison.OrdinalIgnoreCase)) - return pixelShader[..^6]; - if (pixelShader.EndsWith("_ps20", StringComparison.OrdinalIgnoreCase)) - return pixelShader[..^5]; - return pixelShader; - } + protected override void OnDrawElements(IMaterialVar[] parms, IShaderDynamicAPI shaderAPI, VertexCompressionType vertexCompression) { + bool customVertexShader = parms[VERTEXSHADER].IsDefined(); + if (ShaderShadow != null) { + ShaderShadow.EnableDepthWrites(parms[WRITEDEPTH].GetIntValue() != 0); + if (parms[WRITEDEPTH].GetIntValue() != 0) { + ShaderShadow.EnableDepthTest(true); + ShaderShadow.DepthFunc(ShaderDepthFunc.Always); + } + ShaderShadow.EnableAlphaWrites(parms[WRITEALPHA].GetIntValue() != 0); + ShaderShadow.EnableDepthTest(parms[DEPTHTEST].GetIntValue() != 0); + ShaderShadow.EnableCulling(parms[CULL].GetIntValue() != 0); - protected override void OnDrawElements(IMaterialVar[] vars, IShaderDynamicAPI shaderAPI, VertexCompressionType vertexCompression) { - if (IsSnapshotting()) { - ShaderShadow.EnableDepthWrites(false); + EnableTextureSRGBRead(parms, Sampler.Sampler0, (int)ShaderMaterialVars.BaseTexture, LINEARREAD_BASETEXTURE); + EnableTextureSRGBRead(parms, Sampler.Sampler1, TEXTURE1, LINEARREAD_TEXTURE1); + EnableTextureSRGBRead(parms, Sampler.Sampler2, TEXTURE2, LINEARREAD_TEXTURE2); + EnableTextureSRGBRead(parms, Sampler.Sampler3, TEXTURE3, LINEARREAD_TEXTURE3); - if (vars[(int)ShaderMaterialVars.BaseTexture].IsDefined()) - SetupSamplerSRGBRead(vars, Sampler.Sampler0, (int)ShaderMaterialVars.BaseTexture, LINEARREAD_BASETEXTURE); - if (vars[TEXTURE1].IsDefined()) - SetupSamplerSRGBRead(vars, Sampler.Sampler1, TEXTURE1, LINEARREAD_TEXTURE1); - if (vars[TEXTURE2].IsDefined()) - SetupSamplerSRGBRead(vars, Sampler.Sampler2, TEXTURE2, LINEARREAD_TEXTURE2); - if (vars[TEXTURE3].IsDefined()) - SetupSamplerSRGBRead(vars, Sampler.Sampler3, TEXTURE3, LINEARREAD_TEXTURE3); + int vertexColor = IsFlagSet(parms, MaterialVarFlags.VertexColor) ? 1 : 0; + VertexFormat fmt = VertexFormat.Position; + if (vertexColor != 0) + fmt |= VertexFormat.Color; + if (parms[VERTEXNORMAL].GetIntValue() != 0) + fmt |= VertexFormat.Normal; - ShaderShadow.VertexShaderVertexFormat(VertexFormat.Position, 1, null, 0); + Span texCoordDimensions = stackalloc int[8]; + int texCoordCount = 0; + while (texCoordCount < 8 && parms[TCSizes[texCoordCount]].GetIntValue() != 0) { + texCoordDimensions[texCoordCount] = parms[TCSizes[texCoordCount]].GetIntValue(); + texCoordCount++; + } + ShaderShadow.VertexShaderVertexFormat(fmt, texCoordCount, texCoordDimensions[..texCoordCount], 0); - bool srgbWrite = true; - if (vars[LINEARWRITE].GetFloatValue() != 0) - srgbWrite = false; - ShaderShadow.EnableSRGBWrite(srgbWrite); + if (IsFlagSet(parms, MaterialVarFlags.Additive)) + EnableAlphaBlending(ShaderBlendFactor.One, ShaderBlendFactor.One); + else if (parms[MULTIPLYCOLOR].GetIntValue() != 0) + EnableAlphaBlending(ShaderBlendFactor.Zero, ShaderBlendFactor.SrcColor); + else if (parms[ALPHABLEND].GetIntValue() != 0) + EnableAlphaBlending(ShaderBlendFactor.SrcAlpha, ShaderBlendFactor.OneMinusSrcAlpha); + else + ShaderShadow.EnableBlending(false); + + if (parms[BLENDOPMIN].GetIntValue() != 0) { + ShaderShadow.BlendOp(ShaderBlendOp.Min); + ShaderShadow.EnableBlending(true); + } + + ShaderShadow.EnableSRGBWrite(parms[LINEARWRITE].GetIntValue() == 0); - ShaderShadow.SetVertexShader("screenspaceeffect", 0); + if (!customVertexShader) + ShaderShadow.SetVertexShader("screenspaceeffect", vertexColor + parms[VERTEXTRANSFORM].GetIntValue() * 2); + else + ShaderShadow.SetVertexShader(parms[VERTEXSHADER].GetStringValue(), 0); - if (vars[DISABLE_COLOR_WRITES].GetIntValue() != 0) + if (parms[DISABLE_COLOR_WRITES].GetIntValue() != 0) ShaderShadow.EnableColorWrites(false); ShaderShadow.EnableAlphaTest(true); ShaderShadow.AlphaFunc(ShaderAlphaFunc.Greater, 0.0f); - if (IsFlagSet(vars, MaterialVarFlags.Additive)) - EnableAlphaBlending(ShaderBlendFactor.One, ShaderBlendFactor.One); - if (vars[ALPHA_BLEND_COLOR_OVERLAY].GetIntValue() != 0) + string pixelShader = parms[PIXSHADER].GetStringValue(); + if (HardwareConfig.SupportsPixelShaders_2_b() && pixelShader.Length > 6 && (pixelShader.EndsWith("_ps20", StringComparison.OrdinalIgnoreCase) || pixelShader.EndsWith("_vs20", StringComparison.OrdinalIgnoreCase))) + pixelShader += "b"; + ShaderShadow.SetPixelShader(pixelShader, 0); + + if (parms[ALPHA_BLEND_COLOR_OVERLAY].GetIntValue() != 0) EnableAlphaBlending(ShaderBlendFactor.One, ShaderBlendFactor.OneMinusSrcAlpha); - if (vars[ALPHA_BLEND].GetIntValue() != 0) + if (parms[ALPHA_BLEND].GetIntValue() != 0) EnableAlphaBlending(ShaderBlendFactor.SrcAlpha, ShaderBlendFactor.OneMinusSrcAlpha); - - if (vars[COPYALPHA].GetIntValue() != 0) { + if (parms[COPYALPHA].GetIntValue() != 0) { ShaderShadow.EnableBlending(false); ShaderShadow.AlphaFunc(ShaderAlphaFunc.Always, 0.0f); } - - ShaderShadow.SetPixelShader(PixelShaderFileName(vars[PIXSHADER].GetStringValue()), 0); } - else { - if (vars[(int)ShaderMaterialVars.BaseTexture].IsDefined()) - BindTextureWithPixelSize(shaderAPI, vars, Sampler.Sampler0, (int)ShaderMaterialVars.BaseTexture, 4); - if (vars[TEXTURE1].IsDefined()) - BindTextureWithPixelSize(shaderAPI, vars, Sampler.Sampler1, TEXTURE1, 5); - if (vars[TEXTURE2].IsDefined()) - BindTextureWithPixelSize(shaderAPI, vars, Sampler.Sampler2, TEXTURE2, 6); - if (vars[TEXTURE3].IsDefined()) - BindTextureWithPixelSize(shaderAPI, vars, Sampler.Sampler3, TEXTURE3, 7); + if (ShaderAPI != null) { + SetPixelSize(parms, Sampler.Sampler0, (int)ShaderMaterialVars.BaseTexture, 4); + SetPixelSize(parms, Sampler.Sampler1, TEXTURE1, 5); + SetPixelSize(parms, Sampler.Sampler2, TEXTURE2, 6); + SetPixelSize(parms, Sampler.Sampler3, TEXTURE3, 7); Span c0 = [ - vars[C0_X].GetFloatValue(), - vars[C0_Y].GetFloatValue(), - vars[C0_Z].GetFloatValue(), - vars[C0_W].GetFloatValue(), - vars[C1_X].GetFloatValue(), - vars[C1_Y].GetFloatValue(), - vars[C1_Z].GetFloatValue(), - vars[C1_W].GetFloatValue(), - vars[C2_X].GetFloatValue(), - vars[C2_Y].GetFloatValue(), - vars[C2_Z].GetFloatValue(), - vars[C2_W].GetFloatValue(), - vars[C3_X].GetFloatValue(), - vars[C3_Y].GetFloatValue(), - vars[C3_Z].GetFloatValue(), - vars[C3_W].GetFloatValue() + parms[C0_X].GetFloatValue(), parms[C0_Y].GetFloatValue(), parms[C0_Z].GetFloatValue(), parms[C0_W].GetFloatValue(), + parms[C1_X].GetFloatValue(), parms[C1_Y].GetFloatValue(), parms[C1_Z].GetFloatValue(), parms[C1_W].GetFloatValue(), + parms[C2_X].GetFloatValue(), parms[C2_Y].GetFloatValue(), parms[C2_Z].GetFloatValue(), parms[C2_W].GetFloatValue(), + parms[C3_X].GetFloatValue(), parms[C3_Y].GetFloatValue(), parms[C3_Z].GetFloatValue(), parms[C3_W].GetFloatValue() ]; + ShaderAPI.SetPixelShaderConstant(0, c0, 4); - shaderAPI.SetPixelShaderConstant(0, c0, c0.Length / 4); + Span eyePos = stackalloc float[4]; + ShaderAPI.GetWorldSpaceCameraPosition(eyePos); + ShaderAPI.SetPixelShaderConstant(10, eyePos, 1); - Span eyePos = [0, 0, 0, 0]; - shaderAPI.GetWorldSpaceCameraPosition(eyePos); - shaderAPI.SetPixelShaderConstant(10, eyePos, 1); + if (parms[VIEWPROJMAT].IsDefined()) { + System.Numerics.Matrix4x4 viewProj = parms[VIEWPROJMAT].GetMatrixValue(); + ShaderAPI.SetPixelShaderConstant(11, System.Runtime.InteropServices.MemoryMarshal.CreateReadOnlySpan(ref viewProj.M11, 16), 4); + } + if (parms[INVVIEWPROJMAT].IsDefined()) { + System.Numerics.Matrix4x4 invViewProj = parms[INVVIEWPROJMAT].GetMatrixValue(); + ShaderAPI.SetPixelShaderConstant(15, System.Runtime.InteropServices.MemoryMarshal.CreateReadOnlySpan(ref invViewProj.M11, 16), 4); + } - shaderAPI.SetVertexShaderIndex(0); - shaderAPI.SetPixelShaderIndex(0); + ShaderAPI.SetVertexShaderIndex(0); + ShaderAPI.SetPixelShaderIndex(0); + if (!customVertexShader) + ShaderAPI.SetVertexShaderIndex(0); } Draw(); } From 459bca3f7f454e8ee2e3bede528fb8475eee7be4 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:41:41 -0700 Subject: [PATCH 57/57] fix alphatest not translating in VcsTranslator --- Source.ShaderAPI.Gl46/VcsTranslator.cs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/Source.ShaderAPI.Gl46/VcsTranslator.cs b/Source.ShaderAPI.Gl46/VcsTranslator.cs index ef6c3f289..10987fd8e 100644 --- a/Source.ShaderAPI.Gl46/VcsTranslator.cs +++ b/Source.ShaderAPI.Gl46/VcsTranslator.cs @@ -126,6 +126,18 @@ enum SamplerTextureType internal sealed class VcsTranslator { const string Xyzw = "xyzw"; + const string AlphaTest = + "if (isAlphaTesting) {\n" + + "switch (alphaTestFunc) {\n" + + "case 0: discard; break;\n" + + "case 1: if (oC0.a >= alphaTestRef) { discard; } break;\n" + + "case 2: if (oC0.a != alphaTestRef) { discard; } break;\n" + + "case 3: if (oC0.a > alphaTestRef) { discard; } break;\n" + + "case 4: if (oC0.a <= alphaTestRef) { discard; } break;\n" + + "case 5: if (oC0.a == alphaTestRef) { discard; } break;\n" + + "case 6: if (oC0.a < alphaTestRef) { discard; } break;\n" + + "}\n" + + "}\n"; static readonly string Temps = string.Concat(Enumerable.Range(0, 32).Select(i => $", r{i} = vec4(0.0)")); const int ShaderVcsVersion = 6; @@ -332,7 +344,7 @@ string Rows(uint vec, uint matrix, int rows, bool dot3) { StringBuilder head = new("#version 460\n"); if (pixel) - head.Append("layout(std140, binding = 6) uniform source_ps_constants { vec4 ps_const[256]; };\nlayout(location = 0) out vec4 oC0;\n"); + head.Append("layout(std140, binding = 3) uniform source_pixel_sharedUBO { bool isAlphaTesting; int alphaTestFunc; float alphaTestRef; };\nlayout(std140, binding = 6) uniform source_ps_constants { vec4 ps_const[256]; };\nlayout(location = 0) out vec4 oC0;\n"); else head.Append("layout(std140, binding = 0) uniform source_matrices { mat4 viewMatrix; mat4 projectionMatrix; mat4 modelMatrix; };\nlayout(std140, binding = 5) uniform source_vs_constants { vec4 vs_const[256]; };\n"); @@ -486,7 +498,9 @@ string Rows(uint vec, uint matrix, int rows, bool dot3) { body.Append($"{dst}{m} = ({expr}){m};\n"); } - if (!pixel) + if (pixel) + body.Append(AlphaTest); + else body.Append("gl_Position = oPos;\n"); foreach (string decl in io) head.Append(decl).Append('\n');