diff --git a/Source.Common/MaterialSystem/IMaterial.cs b/Source.Common/MaterialSystem/IMaterial.cs index 10153053..8bff7862 100644 --- a/Source.Common/MaterialSystem/IMaterial.cs +++ b/Source.Common/MaterialSystem/IMaterial.cs @@ -484,6 +484,7 @@ public interface IMaterial bool NeedsPowerOfTwoFrameBufferTexture(bool checkSpecificToThisFrame); bool NeedsFullFrameBufferTexture(bool checkSpecificToThisFrame); bool NeedsLightmapBlendAlpha(); + bool IsSpriteCard(); } // Intended to only be used by the material system and not other components diff --git a/Source.Common/MaterialSystem/IMesh.cs b/Source.Common/MaterialSystem/IMesh.cs index 625c4827..8d2651bd 100644 --- a/Source.Common/MaterialSystem/IMesh.cs +++ b/Source.Common/MaterialSystem/IMesh.cs @@ -420,6 +420,25 @@ internal void TexCoord3f(int stage, float s, float t, float u) { *pDst = u; } + internal void TexCoord4f(int stage, float s, float t, float u, float w) { + float* pDst = stage switch { + 0 => CurrTexCoord0, + 1 => CurrTexCoord1, + 2 => CurrTexCoord2, + 3 => CurrTexCoord3, + 4 => CurrTexCoord4, + 5 => CurrTexCoord5, + 6 => CurrTexCoord6, + 7 => CurrTexCoord7, + _ => null + }; + if (pDst == null) return; + *pDst++ = s; + *pDst++ = t; + *pDst++ = u; + *pDst = w; + } + public void AdvanceVertex() { if (++CurrentVertex > VertexCount) VertexCount = CurrentVertex; @@ -988,8 +1007,8 @@ public unsafe void Color4ubv(in Color rgba) { public void TexCoord2fv(int stage, in Vector2 vec) => VertexBuilder.TexCoord2f(stage, vec.X, vec.Y); public void TexCoord3f(int stage, float s, float t, float u) => VertexBuilder.TexCoord3f(stage, s, t, u); public void TexCoord3fv(int stage, ReadOnlySpan stu) => VertexBuilder.TexCoord3f(stage, stu[0], stu[1], stu[2]); - public void TexCoord4f(int stage, float s, float t, float u, float w) => throw new NotImplementedException(); - public void TexCoord4fv(int stage, ReadOnlySpan stuv) => throw new NotImplementedException(); + public void TexCoord4f(int stage, float s, float t, float u, float w) => VertexBuilder.TexCoord4f(stage, s, t, u, w); + public void TexCoord4fv(int stage, ReadOnlySpan stuv) => VertexBuilder.TexCoord4f(stage, stuv[0], stuv[1], stuv[2], stuv[3]); public void TexCoordSubRect2f(int stage, float s, float t, float offsetS, float offsetT, float scaleS, float scaleT) => throw new NotImplementedException(); public void TexCoordSubRect2fv(int stage, ReadOnlySpan st, ReadOnlySpan offset, ReadOnlySpan scale) => throw new NotImplementedException(); diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index 2731bbe3..ed54b074 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -673,9 +673,7 @@ public void EnableNonInteractiveMode(MaterialNonInteractiveMode mode) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void EnableUserClipTransformOverride(bool enable) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void EnableUserClipTransformOverride(bool enable) => shaderAPI.EnableUserClipTransformOverride(enable); public void EndMorphAccumulation() { throw new NotImplementedException("Incomplete port of IMatRenderContext"); @@ -902,9 +900,7 @@ public void UnlockLookup(ColorCorrectionHandle_t handle) { throw new NotImplementedException("Incomplete port of IMatRenderContext"); } - public void UserClipTransform(in Matrix4x4 worldToView) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void UserClipTransform(in Matrix4x4 worldToView) => shaderAPI.UserClipTransform(worldToView); public void DrawClearBufferQuad(byte r, byte g, byte b, byte a, bool clearColor, bool clearAlpha, bool clearDepth) { throw new NotImplementedException("Incomplete port of IMatRenderContextInternal"); diff --git a/Source.MaterialSystem/MatRenderContextBase.cs b/Source.MaterialSystem/MatRenderContextBase.cs index ec60b66a..f3a42cf1 100644 --- a/Source.MaterialSystem/MatRenderContextBase.cs +++ b/Source.MaterialSystem/MatRenderContextBase.cs @@ -404,11 +404,15 @@ public float ComputePixelWidthOfSphere(in Vector3 origin, float radius) { } public virtual void GetWorldSpaceCameraPosition(out Vector3 vecCameraPos) { + RecomputeViewState(); vecCameraPos = VecViewOrigin; } public virtual void GetWorldSpaceCameraVectors(out Vector3 forward, out Vector3 right, out Vector3 up) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); + RecomputeViewState(); + forward = VecViewForward; + right = VecViewRight; + up = VecViewUp; } public virtual Vector3 GetToneMappingScaleLinear() { diff --git a/Source.MaterialSystem/MatStub.cs b/Source.MaterialSystem/MatStub.cs index 791ab786..1f147e7e 100644 --- a/Source.MaterialSystem/MatStub.cs +++ b/Source.MaterialSystem/MatStub.cs @@ -327,6 +327,7 @@ public void SetUseFixedFunctionBakedLighting(bool enable) { } public bool NeedsPowerOfTwoFrameBufferTexture(bool checkSpecificToThisFrame) => false; public bool NeedsFullFrameBufferTexture(bool checkSpecificToThisFrame) => false; public bool NeedsLightmapBlendAlpha() => false; + public bool IsSpriteCard() => false; } public class DummyMorph : IMorph diff --git a/Source.MaterialSystem/Material.cs b/Source.MaterialSystem/Material.cs index 9502c2f8..57d49666 100644 --- a/Source.MaterialSystem/Material.cs +++ b/Source.MaterialSystem/Material.cs @@ -1425,6 +1425,13 @@ public bool IsTwoSided() { return GetMaterialVarFlag(MaterialVarFlags.NoCull); } + public bool IsSpriteCard() { + Precache(); + if (IsValidRenderState()) + return (GetMaterialVarFlags2() & MaterialVarFlags2.IsSpritecard) != 0; + return false; + } + public bool IsAlphaTested() { Precache(); if (Shader != null && IsValidRenderState()) diff --git a/Source.MaterialSystem/MaterialSystem.cs b/Source.MaterialSystem/MaterialSystem.cs index 5b64d1c8..0b9fbebd 100644 --- a/Source.MaterialSystem/MaterialSystem.cs +++ b/Source.MaterialSystem/MaterialSystem.cs @@ -1053,6 +1053,9 @@ public ReadOnlySpan GetForcedTextureLoadPathID() { char c = materialName[i]; tempNameBuffer[i] = c == '\\' ? '/' : c; } + int extension = tempNameBuffer.LastIndexOfAny('.', '/'); + if (extension > 0 && tempNameBuffer[extension] == '.') + tempNameBuffer = tempNameBuffer[..extension]; IMaterialInternal? existingMaterial = MaterialDict.FindMaterial(tempNameBuffer, false); if (existingMaterial != null) diff --git a/Source.MaterialSystem/Texture.cs b/Source.MaterialSystem/Texture.cs index 80987b0f..1e566536 100644 --- a/Source.MaterialSystem/Texture.cs +++ b/Source.MaterialSystem/Texture.cs @@ -93,8 +93,26 @@ public int GetNumAnimationFrames() { return FrameCount; } - public Span GetResourceData(uint type) { - throw new NotImplementedException(); + readonly Dictionary ResourceData = []; + + public Span GetResourceData(uint type) + => ResourceData.TryGetValue(ResourceEntryInfo.ParseTag((byte)type, (byte)(type >> 8), (byte)(type >> 16)), out byte[]? data) ? data : default; + + void StoreResourceData(IVTFTexture vtfTexture) { + uint count = vtfTexture.GetResourceTypes([]); + if (count == 0) + return; + + Span types = stackalloc ResourceEntryType[(int)count]; + vtfTexture.GetResourceTypes(types); + foreach (ResourceEntryType type in types) { + if (type == ResourceEntryType.LowResThumbnail || type == ResourceEntryType.HighResImageData) + continue; + + Span data = vtfTexture.GetResourceData(type); + if (!data.IsEmpty) + ResourceData.TryAdd(type, data.ToArray()); + } } public void IncrementReferenceCount() => ++RefCount; @@ -699,6 +717,8 @@ private void MigrateShaderAPITextures() { Reflectivity = vtfTexture.Reflectivity(); + StoreResourceData(vtfTexture); + // TODO: How does Source stream textures? if (ConvertToActualFormat(vtfTexture)) { @@ -713,9 +733,9 @@ private bool SLoadTextureBitsFromFile(ref IVTFTexture vtfTexture, IFileHandle fi out TexDimensions dimsMapping, out TexDimensions dimsActual, out TexDimensions dimsAllocated, out uint stripFlags) { // TODO; finish the complexities of texture loading - if (!vtfTexture!.Unserialize(fileHandle.Stream, false)) { + bool loaded = vtfTexture!.Unserialize(fileHandle.Stream, false); + if (!loaded) Warning($"VTF texture '{fileHandle.GetPath()}' failed to load!\n"); - } dimsMapping = new() { Width = (ushort)vtfTexture.Width(), @@ -729,7 +749,7 @@ private bool SLoadTextureBitsFromFile(ref IVTFTexture vtfTexture, IFileHandle fi int nMipSkipCount = ComputeMipSkipCount(name, dimsMapping, false, vtfTexture, fullFlags, DesiredDimensionLimit, ref StreamingMips, out settings, out dimsActual, out dimsAllocated, out stripFlags); - return true; + return loaded; } unsafe byte* ImageData; @@ -1198,6 +1218,8 @@ public void OnRestore() { } private void Shutdown() { + ResourceData.Clear(); + // Frees the texture regen class TextureRegenerator = null; diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index c7867e0c..f1eb550d 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -268,6 +268,8 @@ private unsafe void CreateMatrixStacks() { int UserClipPlaneChanged; readonly Vector4[] UserClipPlaneWorld = new Vector4[Gl46.HardwareConfig.MAXUSERCLIPPLANES]; readonly Vector4[] UserClipPlaneProj = new Vector4[Gl46.HardwareConfig.MAXUSERCLIPPLANES]; + bool UserClipTransformOverride; + Matrix4x4 UserClipTransform_ = Matrix4x4.Identity; float FogZ; private void MarkAllUserClipPlanesDirty() { @@ -278,7 +280,8 @@ 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 worldToView = UserClipTransformOverride ? UserClipTransform_ : Matrices[(int)MaterialMatrixMode.View]; + Matrix4x4 worldToProjectionInvTrans = worldToView * Matrices[(int)MaterialMatrixMode.Projection]; Matrix4x4.Invert(worldToProjectionInvTrans, out worldToProjectionInvTrans); worldToProjectionInvTrans = Matrix4x4.Transpose(worldToProjectionInvTrans); @@ -1214,15 +1217,19 @@ void ConfigureAttribute(Span bindings, OpenGL_ShaderInputAttribute attr, V else glDisableVertexArrayAttrib(vao, (uint)OpenGL_ShaderInputAttribute.Specular); + Assert(format.GetTexCoordDimensionSize(6) == 0 || (format & VertexFormat.Wrinkle) == 0); + Assert(format.GetTexCoordDimensionSize(7) == 0 || ((format & VertexFormat.Specular) == 0 && !staticLit)); + Span texCoordElements = [VertexElement.TexCoord1D_0, VertexElement.TexCoord2D_0, VertexElement.TexCoord3D_0, VertexElement.TexCoord4D_0]; for (int i = 0; i < IMesh.VERTEX_MAX_TEXTURE_COORDINATES; i++) { + OpenGL_ShaderInputAttribute location = TexCoordLocation(i); int texCoordSize = format.GetTexCoordDimensionSize(i); if (texCoordSize > 0) { VertexElement element = (VertexElement)((int)texCoordElements[texCoordSize - 1] + i); - ConfigureAttribute(bindings, (OpenGL_ShaderInputAttribute)((int)OpenGL_ShaderInputAttribute.TexCoord0 + i), element, texCoordSize); + ConfigureAttribute(bindings, location, element, texCoordSize); } - else - glDisableVertexArrayAttrib(vao, (uint)((int)OpenGL_ShaderInputAttribute.TexCoord0 + i)); + else if (location >= OpenGL_ShaderInputAttribute.TexCoord0) + glDisableVertexArrayAttrib(vao, (uint)location); } if ((format & VertexFormat.TangentS) != 0) @@ -1249,15 +1256,25 @@ void ConfigureAttribute(Span bindings, OpenGL_ShaderInputAttribute attr, V int normalOffset = (int)(VertexElement.Position.GetSize() + VertexElement.Wrinkle.GetSize()); - glEnableVertexArrayAttrib(vao, (uint)OpenGL_ShaderInputAttribute.FlexPosition); - glVertexArrayAttribFormat(vao, (uint)OpenGL_ShaderInputAttribute.FlexPosition, 4, GL_FLOAT, false, 0); - glVertexArrayAttribBinding(vao, (uint)OpenGL_ShaderInputAttribute.FlexPosition, 2); + if (format.GetTexCoordDimensionSize(OpenGL_ShaderInputAttribute.FlexPosition - OpenGL_ShaderInputAttribute.TexCoord0) == 0) { + glEnableVertexArrayAttrib(vao, (uint)OpenGL_ShaderInputAttribute.FlexPosition); + glVertexArrayAttribFormat(vao, (uint)OpenGL_ShaderInputAttribute.FlexPosition, 4, GL_FLOAT, false, 0); + glVertexArrayAttribBinding(vao, (uint)OpenGL_ShaderInputAttribute.FlexPosition, 2); + } - glEnableVertexArrayAttrib(vao, (uint)OpenGL_ShaderInputAttribute.FlexNormal); - glVertexArrayAttribFormat(vao, (uint)OpenGL_ShaderInputAttribute.FlexNormal, 3, GL_FLOAT, false, (uint)normalOffset); - glVertexArrayAttribBinding(vao, (uint)OpenGL_ShaderInputAttribute.FlexNormal, 2); + if (format.GetTexCoordDimensionSize(OpenGL_ShaderInputAttribute.FlexNormal - OpenGL_ShaderInputAttribute.TexCoord0) == 0) { + glEnableVertexArrayAttrib(vao, (uint)OpenGL_ShaderInputAttribute.FlexNormal); + glVertexArrayAttribFormat(vao, (uint)OpenGL_ShaderInputAttribute.FlexNormal, 3, GL_FLOAT, false, (uint)normalOffset); + glVertexArrayAttribBinding(vao, (uint)OpenGL_ShaderInputAttribute.FlexNormal, 2); + } } + static OpenGL_ShaderInputAttribute TexCoordLocation(int index) => index switch { + 6 => OpenGL_ShaderInputAttribute.Wrinkle, + 7 => OpenGL_ShaderInputAttribute.Specular, + _ => OpenGL_ShaderInputAttribute.TexCoord0 + index + }; + public IMesh GetDynamicMesh(IMaterial material, int hwSkinBoneCount, bool buffered, IMesh? vertexOverride, IMesh? indexOverride) { Assert(material == null || material.IsRealTimeVersion()); return MeshMgr.GetDynamicMesh(material, 0, hwSkinBoneCount, buffered, vertexOverride, indexOverride); @@ -3471,7 +3488,12 @@ public void EnableHWMorphing(bool enable) { public void EnableShaderShaderMutex(bool enable) { } public void EnableUserClipTransformOverride(bool enable) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + if (UserClipTransformOverride == enable) + return; + + FlushBufferedPrimitives(); + UserClipTransformOverride = enable; + MarkAllUserClipPlanesDirty(); } public void EndOcclusionQueryDrawing(ShaderAPIOcclusionQuery_t query) { @@ -3847,7 +3869,14 @@ public void TexSetPriority(int priority) { } public void UserClipTransform(in Matrix4x4 worldToView) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + Matrix4x4 transform = Matrix4x4.Transpose(worldToView); + if (UserClipTransform_ == transform) + return; + UserClipTransform_ = transform; + if (UserClipTransformOverride) { + FlushBufferedPrimitives(); + MarkAllUserClipPlanesDirty(); + } } public void BindStandardVertexTexture(VertexTextureSampler sampler, StandardTextureId id) { diff --git a/Source.VTF/VTFTexture.cs b/Source.VTF/VTFTexture.cs index 3aa80abd..8ce31ef0 100644 --- a/Source.VTF/VTFTexture.cs +++ b/Source.VTF/VTFTexture.cs @@ -44,6 +44,7 @@ public sealed class VTFTexture : IVTFTexture int CoarsestMipmapLevel; List ResourcesInfo = []; + readonly Dictionary ResourcesData = []; float IVTFTexture.BumpScale() => BumpScale; public void ComputeAlphaFlags() { @@ -224,15 +225,10 @@ public void GenerateMipmaps() { throw new NotImplementedException(); } - public unsafe Span GetResourceData(ResourceEntryType type) { - ref ResourceEntryInfo info = ref FindResourceEntryInfo(type); + public Span GetResourceData(ResourceEntryType type) + => ResourcesData.TryGetValue(type & ~ResourceEntryType.Flag_Mask, out byte[]? data) ? data : default; - return null; - } - - public bool HasResourceEntry(ResourceEntryType type) { - throw new NotImplementedException(); - } + public bool HasResourceEntry(ResourceEntryType type) => !Unsafe.IsNullRef(ref FindResourceEntryInfo(type)); int IVTFTexture.Height() => Height; @@ -479,6 +475,9 @@ public bool UnserializeEx(Stream stream, bool headerOnly, int forceFlags, int sk if (!ReadHeader(stream, out header)) return false; + ResourcesInfo.Clear(); + ResourcesData.Clear(); + header.Flags |= (uint)forceFlags; var flags = (TextureFlags)header.Flags; @@ -573,7 +572,8 @@ public bool UnserializeEx(Stream stream, bool headerOnly, int forceFlags, int sk return false; } - // TODO: LoadNewResources + if (!LoadNewResources(stream)) + return false; ref ResourceEntryInfo imageDataInfo = ref FindResourceEntryInfo(ResourceEntryType.HighResImageData); if (!Unsafe.IsNullRef(ref imageDataInfo)) { @@ -587,6 +587,31 @@ public bool UnserializeEx(Stream stream, bool headerOnly, int forceFlags, int sk return true; } + private bool LoadNewResources(Stream stream) { + using BinaryReader reader = new(stream, Encoding.ASCII, true); + foreach (ResourceEntryInfo resource in ResourcesInfo) { + ResourceEntryType type = resource.Tag & ~ResourceEntryType.Flag_Mask; + if (type == ResourceEntryType.LowResThumbnail || type == ResourceEntryType.HighResImageData) + continue; + + if ((resource.Flags & ((uint)ResourceEntryType.Flag_HasNoDataChunk >> 24)) != 0) { + ResourcesData[type] = BitConverter.GetBytes(resource.Offset); + continue; + } + + if (resource.Offset > stream.Length - sizeof(int)) + return false; + + stream.Seek(resource.Offset, SeekOrigin.Begin); + int numBytes = reader.ReadInt32(); + if (numBytes < 0 || numBytes > stream.Length - stream.Position) + return false; + + ResourcesData[type] = reader.ReadBytes(numBytes); + } + return true; + } + private bool LoadImageData(Stream stream, VTFFileHeader header, int skipMipLevels) { if (skipMipLevels > 0) { if (header.NumMipLevels < skipMipLevels) { @@ -616,16 +641,6 @@ private bool LoadImageData(Stream stream, VTFFileHeader header, int skipMipLevel int firstAvailableMip = 0; int lastAvailableMip = MipCount - 1; - Span data = GetResourceData(ResourceEntryType.TextureLOD); - if (!data.IsEmpty) { - ref TextureStreamSettings_t streamSettings = ref MemoryMarshal.Cast(data)[0]; - firstAvailableMip = Math.Max(0, streamSettings.FirstAvailableMip - skipMipLevels); - lastAvailableMip = Math.Max(0, streamSettings.LastAvailableMip - skipMipLevels); - mipDataPresent = false; - } - - // Not doing streamable textures right now - Assert(firstAvailableMip >= 0 && firstAvailableMip <= lastAvailableMip && lastAvailableMip < MipCount); FinestMipmapLevel = firstAvailableMip;