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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Source.Common/MaterialSystem/IMaterial.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 21 additions & 2 deletions Source.Common/MaterialSystem/IMesh.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<float> 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<float> 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<float> 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<float> st, ReadOnlySpan<float> offset, ReadOnlySpan<float> scale) => throw new NotImplementedException();
Expand Down
8 changes: 2 additions & 6 deletions Source.MaterialSystem/MatRenderContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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");
Expand Down
6 changes: 5 additions & 1 deletion Source.MaterialSystem/MatRenderContextBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
1 change: 1 addition & 0 deletions Source.MaterialSystem/MatStub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions Source.MaterialSystem/Material.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
3 changes: 3 additions & 0 deletions Source.MaterialSystem/MaterialSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1053,6 +1053,9 @@ public ReadOnlySpan<char> 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)
Expand Down
32 changes: 27 additions & 5 deletions Source.MaterialSystem/Texture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,26 @@ public int GetNumAnimationFrames() {
return FrameCount;
}

public Span<byte> GetResourceData(uint type) {
throw new NotImplementedException();
readonly Dictionary<ResourceEntryType, byte[]> ResourceData = [];

public Span<byte> 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<ResourceEntryType> types = stackalloc ResourceEntryType[(int)count];
vtfTexture.GetResourceTypes(types);
foreach (ResourceEntryType type in types) {
if (type == ResourceEntryType.LowResThumbnail || type == ResourceEntryType.HighResImageData)
continue;

Span<byte> data = vtfTexture.GetResourceData(type);
if (!data.IsEmpty)
ResourceData.TryAdd(type, data.ToArray());
}
}

public void IncrementReferenceCount() => ++RefCount;
Expand Down Expand Up @@ -699,6 +717,8 @@ private void MigrateShaderAPITextures() {

Reflectivity = vtfTexture.Reflectivity();

StoreResourceData(vtfTexture);

// TODO: How does Source stream textures?
if (ConvertToActualFormat(vtfTexture)) {

Expand All @@ -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(),
Expand All @@ -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;
Expand Down Expand Up @@ -1198,6 +1218,8 @@ public void OnRestore() {
}

private void Shutdown() {
ResourceData.Clear();

// Frees the texture regen class
TextureRegenerator = null;

Expand Down
53 changes: 41 additions & 12 deletions Source.ShaderAPI.Gl46/ShaderAPIGl46.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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);

Expand Down Expand Up @@ -1214,15 +1217,19 @@ void ConfigureAttribute(Span<uint> 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<VertexElement> 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)
Expand All @@ -1249,15 +1256,25 @@ void ConfigureAttribute(Span<uint> 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);
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down
53 changes: 34 additions & 19 deletions Source.VTF/VTFTexture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public sealed class VTFTexture : IVTFTexture
int CoarsestMipmapLevel;

List<ResourceEntryInfo> ResourcesInfo = [];
readonly Dictionary<ResourceEntryType, byte[]> ResourcesData = [];
float IVTFTexture.BumpScale() => BumpScale;

public void ComputeAlphaFlags() {
Expand Down Expand Up @@ -224,15 +225,10 @@ public void GenerateMipmaps() {
throw new NotImplementedException();
}

public unsafe Span<byte> GetResourceData(ResourceEntryType type) {
ref ResourceEntryInfo info = ref FindResourceEntryInfo(type);
public Span<byte> 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;

Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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)) {
Expand All @@ -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();
Comment thread
Earu marked this conversation as resolved.
Resolved
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) {
Expand Down Expand Up @@ -616,16 +641,6 @@ private bool LoadImageData(Stream stream, VTFFileHeader header, int skipMipLevel
int firstAvailableMip = 0;
int lastAvailableMip = MipCount - 1;

Span<byte> data = GetResourceData(ResourceEntryType.TextureLOD);
Comment thread
Earu marked this conversation as resolved.
Resolved
if (!data.IsEmpty) {
ref TextureStreamSettings_t streamSettings = ref MemoryMarshal.Cast<byte, TextureStreamSettings_t>(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;
Expand Down
Loading