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
2 changes: 2 additions & 0 deletions Source.Common/GUI/ISurface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,8 @@ public interface ISurface
void DrawGetColor(out Color color);
void DrawGetTextColor(out Color color);
void DrawGetTranslate(out int x, out int y);
void GMOD_ClearFontCache();
void GMOD_FreeFontMaterials();
#endif
}

Expand Down
14 changes: 11 additions & 3 deletions Source.MaterialSystem/Material.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1204,7 +1204,12 @@ private void CleanUpMaterialProxy() {
}

private void CleanUpShaderParams() {
ShaderParams = null;
if (ShaderParams != null) {
for (int i = 0; i < VarCount; ++i)
MaterialVar.Destroy(ShaderParams[i]);

ShaderParams = null;
}
VarCount = 0;
}

Expand Down Expand Up @@ -1268,10 +1273,13 @@ public void SetNeedsWhiteLightmap(bool value) {
public void DecrementReferenceCount() => --RefCount;

public void DeleteIfUnreferenced() {
if (RefCount > 0)
if (RefCount > 0 || IsErrorMaterialInternal())
return;
// todo: this has more, but i'm not sure if its needed?

MaterialVar.DeleteUnreferencedTextures(true);
Uncache();
materials.MaterialDict.RemoveMaterial(this);
MaterialVar.DeleteUnreferencedTextures(false);
}

public IMaterialVar? FindVarFast(ReadOnlySpan<char> varName, ref TokenCache token) {
Expand Down
67 changes: 64 additions & 3 deletions Source.MaterialSystem/MaterialVar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,30 @@ public static void EnableThreadedMaterialVarAccess(bool enable) {
}
}

static bool DeleteUnreferencedTexturesEnabled = false;

public static void DeleteUnreferencedTextures(bool enable) => DeleteUnreferencedTexturesEnabled = enable;

public static void Destroy(IMaterialVar? var) => (var as MaterialVar)?.CleanUpData();

void CleanUpData() {
switch (Type) {
case MaterialVarType.String:
StringVal = "";
break;

case MaterialVarType.Texture:
// garymcthack
if (TextureValue != null && !ITextureInternal.IsTextureInternalEnvCubemap(TextureValue)) {
TextureValue.DecrementReferenceCount();
if (DeleteUnreferencedTexturesEnabled)
TextureValue.DeleteIfUnreferenced();
TextureValue = null;
}
break;
}
}

MatCallQueue? GetCallQueue() => FakeMaterialVar ? null : materials?.GetRenderCallQueue();

MaterialVar? GetThreadedTempVar() {
Expand Down Expand Up @@ -221,6 +245,7 @@ public override void SetFloatValue(float val) {

FlushIfCurrentMaterial();

CleanUpData();
VecVal[0] = VecVal[1] = VecVal[2] = VecVal[3] = val;
IntVal = (int)val;
Type = MaterialVarType.Float;
Expand All @@ -245,6 +270,7 @@ public override void SetIntValue(int val) {

FlushIfCurrentMaterial();

CleanUpData();
IntVal = val;
VecVal[0] = VecVal[1] = VecVal[2] = VecVal[3] = val;
Type = MaterialVarType.Int;
Expand All @@ -265,6 +291,7 @@ public override void SetMatrixValue(in Matrix4x4 matrix) {

FlushIfCurrentMaterial();

CleanUpData();
Matrix.Matrix = matrix;
Type = MaterialVarType.Matrix;
Matrix.IsIdent = matrix.IsIdentity;
Expand All @@ -284,16 +311,29 @@ public override void SetStringValue(ReadOnlySpan<char> val) {

FlushIfCurrentMaterial();

CleanUpData();
StringVal = new(val.SliceNullTerminatedString());
Type = MaterialVarType.String;
VarChanged();
}

public override void SetTextureValue(ITexture? texture) {
#if GMOD_DLL
if (texture == null) {
Warning("CMaterialVar::SetTextureValue is being set to NULL, falling back to error texture!\n");
texture = materials?.GetErrorTexture();
}
#endif

MatCallQueue? callQueue = GetCallQueue();
if (callQueue != null) {
AllocThreadedTempVar()?.SetTextureValue(texture);
callQueue.QueueCall(static s => s.Var.SetTextureValue(s.Val), (Var: this, Val: texture));

// Matches DecrementReferenceCount in SetTextureValueQueued
if (texture != null && !ITextureInternal.IsTextureInternalEnvCubemap(texture))
texture.IncrementReferenceCount();

callQueue.QueueCall(static s => s.Var.SetTextureValueQueued(s.Val), (Var: this, Val: texture));
return;
}

Expand All @@ -303,11 +343,25 @@ public override void SetTextureValue(ITexture? texture) {

FlushIfCurrentMaterial();

if (texture != null && !ITextureInternal.IsTextureInternalEnvCubemap(texture))
texture.IncrementReferenceCount();

CleanUpData();
Type = MaterialVarType.Texture;
TextureValue = texture;
IntVal = 0;
VecVal = default;
VarChanged();
}

void SetTextureValueQueued(ITexture? texture) {
SetTextureValue(texture);

// Matches IncrementReferenceCount in SetTextureValue
if (texture != null && !ITextureInternal.IsTextureInternalEnvCubemap(texture))
texture.DecrementReferenceCount();
}

public override void SetUndefined() {
MatCallQueue? callQueue = GetCallQueue();
if (callQueue != null) {
Expand All @@ -321,6 +375,7 @@ public override void SetUndefined() {

FlushIfCurrentMaterial();

CleanUpData();
Type = MaterialVarType.Undefined;
VarChanged();
}
Expand All @@ -342,7 +397,10 @@ public override void SetVecComponentValue(float val, int component) {

FlushIfCurrentMaterial();

Type = MaterialVarType.Vector;
if (Type != MaterialVarType.Vector) {
CleanUpData();
Type = MaterialVarType.Vector;
}
Assert(component <= 3);

if (NumVectorComps < component) {
Expand Down Expand Up @@ -371,7 +429,10 @@ void SetVecValueInternal(in Vector4 vec, int comps) {

FlushIfCurrentMaterial();

Type = MaterialVarType.Vector;
if (Type != MaterialVarType.Vector) {
CleanUpData();
Type = MaterialVarType.Vector;
}
Assert(comps <= 4);
NumVectorComps = (byte)comps;
VecVal = vec;
Expand Down
117 changes: 117 additions & 0 deletions Source.MaterialSystem/Surface/FontTextureCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ public class Page
public short Tall;
public short NextX;
public short NextY;
#if GMOD_DLL
public TexturePacker? PackedFontTextureCache;
#endif
}

public class FontTextureCache
Expand Down Expand Up @@ -202,19 +205,123 @@ public bool GetTextureForChars(IFont font, FontDrawType drawType, ReadOnlySpan<c
}

public void Clear() {
#if GMOD_DLL
for (int i = 0; i < PageList.Count; ++i) {
FreeTextureIDs.Add(PageList[i].TextureID[0]);
FreeTextureIDs.Add(PageList[i].TextureID[1]);
}
#endif

CharCache.Clear();
#if GMOD_DLL
for (int i = 0; i < PageList.Count; ++i)
PageList[i].PackedFontTextureCache = null;
#endif
PageList.Clear();

#if GMOD_DLL
CurrPage = -1;
#else
for (int i = 0; i < (int)FontPageSize.Count; ++i)
CurrPage[i] = -1;
#endif

FontPages.Clear();
}

#if GMOD_DLL
public void GMOD_FreeMaterials() {
if (FreeTextureIDs.Count == 0)
return;

surface.DrawSetTexture(-1);
for (int i = 0; i < FreeTextureIDs.Count; i++)
surface.DestroyTextureID(FreeTextureIDs[i]);

FreeTextureIDs.Clear();
}
#endif

const int TEXTURE_PAGE_WIDTH = 256;
const int TEXTURE_PAGE_HEIGHT = 256;

static int fontPageId = 0;
#if GMOD_DLL
bool AllocatePageForChar(int charWide, int charTall, out nint pageIndex, out int drawX, out int drawY, out int twide, out int ttall) {
pageIndex = 0;
drawX = 0; drawY = 0; twide = 0; ttall = 0;
if (charWide > TEXTURE_PAGE_WIDTH || charTall > TEXTURE_PAGE_HEIGHT)
return false;

pageIndex = CurrPage;

TexturePacker.Rect rect = new() { X = 0, Y = 0, Width = charWide, Height = charTall };
int nodeIndex = -1;
if (pageIndex >= 0)
nodeIndex = PageList[(int)pageIndex].PackedFontTextureCache!.InsertRect(rect);

if (nodeIndex == -1) {
// allocate a new page
pageIndex = PageList.Count;
Page newPage = new();
PageList.Add(newPage);

for (int i = 0; i < (int)FontDrawType.Count; ++i)
newPage.TextureID[i] = surface.CreateNewTextureID(true);

newPage.PackedFontTextureCache = new TexturePacker(TEXTURE_PAGE_WIDTH, TEXTURE_PAGE_HEIGHT, 1);
nodeIndex = newPage.PackedFontTextureCache.InsertRect(rect);
if (nodeIndex == -1) {
PageList.RemoveAt((int)pageIndex);
Warning("Failed to AllocatePageForChar!\n");
return false;
}

CurrPage = pageIndex;

Span<char> textureName = stackalloc char[64];
Span<char> finalName = sprintf(textureName, "%s__font_page_%d").S(FontPageName).D(fontPageId);
++fontPageId;

ITexture pTexture = materials.CreateProceduralTexture(
finalName,
TEXTURE_GROUP_VGUI,
TEXTURE_PAGE_WIDTH,
TEXTURE_PAGE_HEIGHT,
ImageFormat.RGBA8888,
TextureFlags.ClampS | TextureFlags.ClampT | TextureFlags.NoMip | TextureFlags.NoLOD | TextureFlags.Procedural | TextureFlags.SingleCopy
);

CreateFontMaterials(ref newPage, pTexture);
pTexture.DecrementReferenceCount();

int nByteCount = TEXTURE_PAGE_WIDTH * TEXTURE_PAGE_HEIGHT * 4;
Span<byte> rgba = stackalloc byte[nByteCount];
for (int i = 0; i < nByteCount; i += 4) {
rgba[i + 0] = 255;
rgba[i + 1] = 255;
rgba[i + 2] = 255;
rgba[i + 3] = 0;
}

int typePageNonAdditive = (int)FontDrawType.NonAdditive - 1;
surface.DrawSetTextureRGBA(newPage.TextureID[typePageNonAdditive], rgba, TEXTURE_PAGE_WIDTH, TEXTURE_PAGE_HEIGHT, 0, false);
}

TexturePacker packer = PageList[(int)pageIndex].PackedFontTextureCache!;
if (nodeIndex < 0 || nodeIndex > packer.MaxElementIndex) {
Warning("CTexturePacker::GetEntry Out of bounds!\n");
nodeIndex = 0;
}

TexturePacker.TreeEntry entry = packer.GetEntry(nodeIndex);
drawX = entry.Rc.X;
drawY = entry.Rc.Y;
twide = TEXTURE_PAGE_WIDTH;
ttall = TEXTURE_PAGE_HEIGHT;
return true;
}
#else
bool AllocatePageForChar(int charWide, int charTall, out nint pageIndex, out int drawX, out int drawY, out int twide, out int ttall) {
int nPageType = ComputePageType(charTall);
if (nPageType < 0) {
Expand Down Expand Up @@ -286,6 +393,8 @@ bool AllocatePageForChar(int charWide, int charTall, out nint pageIndex, out int

CreateFontMaterials(ref newPage, pTexture);

pTexture.DecrementReferenceCount();

// clear the texture from the inital checkerboard to black
// allocate for 32bpp format
int nByteCount = TEXTURE_PAGE_WIDTH * TEXTURE_PAGE_HEIGHT * 4;
Expand Down Expand Up @@ -313,6 +422,8 @@ bool AllocatePageForChar(int charWide, int charTall, out nint pageIndex, out int
page.NextX = (short)(nNextX + 1);
return true;
}
#endif

void CreateFontMaterials(ref Page page, ITexture fontTexture, bool bitmapFont = false) {
// The normal material
KeyValues vmtKeyValues = new KeyValues("UnlitGeneric");
Expand Down Expand Up @@ -357,6 +468,12 @@ int ComputePageType(int charTall) {
}
Dictionary<ulong, CacheEntry> CharCache = [];
List<Page> PageList = [];
#if GMOD_DLL
nint CurrPage = -1;
readonly List<TextureID> FreeTextureIDs = [];
readonly string FontPageName = "";
#else
nint[] CurrPage = new nint[(int)Surface.FontPageSize.Count];
#endif
Dictionary<IFont, Page> FontPages = [];
}
3 changes: 3 additions & 0 deletions Source.MaterialSystem/Surface/MatSystemSurface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2144,6 +2144,9 @@ public void DrawGetTranslate(out int x, out int y) {
x = TranslateX;
y = TranslateY;
}

public void GMOD_ClearFontCache() => FontTextureCache.Clear();
public void GMOD_FreeFontMaterials() => FontTextureCache.GMOD_FreeMaterials();
#endif

public void PushFullscreenViewport() {
Expand Down
3 changes: 3 additions & 0 deletions Source.MaterialSystem/Surface/TextureDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ public void SetMaterial(ReadOnlySpan<char> filename) {
if (Material!.TryFindVar("$basetexture", out IMaterialVar? var) && var.IsTexture()) {
Texture = var.GetTextureValue();
if (Texture != null) {
Texture.IncrementReferenceCount();
CreateRegen(Wide, Tall, Texture.GetImageFormat());
Texture.SetTextureRegenerator(Regen);
}
Expand Down Expand Up @@ -353,6 +354,7 @@ internal void SetTextureRGBA(Span<byte> rgba, int wide, int tall, ImageFormat fo

IMaterial pMaterial = materials.CreateMaterial(textureName, vmtTKeyValues);
pMaterial.Refresh();
pTexture.DecrementReferenceCount();

SetMaterial(pMaterial);
InputTall = tall;
Expand Down Expand Up @@ -397,6 +399,7 @@ internal void ReferenceOtherProcedural(MatSystemTexture texture, IMaterial mater
if (Material!.TryFindVar("$basetexture", out IMaterialVar? var) && var.IsTexture()) {
Texture = var.GetTextureValue();
if (Texture != null) {
Texture.IncrementReferenceCount();
Assert(Texture == texture.Texture);
Regen = texture.Regen;

Expand Down
Loading
Loading