From b0424dccc7866700eddeeddeeb7a26146e6f50c1 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Tue, 3 Nov 2026 19:03:31 +0000 Subject: [PATCH 1/3] Win32Font --- Source.MaterialSystem/Surface/FontEffects.cs | 163 +++++++ Source.MaterialSystem/Surface/FontManager.cs | 78 +++- .../Surface/FontTextureCache.cs | 12 + Source.MaterialSystem/Surface/FreeTypeFont.cs | 169 +------ Source.MaterialSystem/Surface/Win32Font.cs | 439 ++++++++++++++++++ 5 files changed, 695 insertions(+), 166 deletions(-) create mode 100644 Source.MaterialSystem/Surface/FontEffects.cs create mode 100644 Source.MaterialSystem/Surface/Win32Font.cs diff --git a/Source.MaterialSystem/Surface/FontEffects.cs b/Source.MaterialSystem/Surface/FontEffects.cs new file mode 100644 index 000000000..607d92b8c --- /dev/null +++ b/Source.MaterialSystem/Surface/FontEffects.cs @@ -0,0 +1,163 @@ +namespace Source.MaterialSystem.Surface; + +internal static class FontEffects +{ + internal static void ApplyDropShadowToTexture(int rgbaWide, int rgbaTall, Span rgba, uint dropShadowOffset) { + if (dropShadowOffset == 0) + return; + + for (int y = rgbaTall - 1; y >= dropShadowOffset; y--) { + for (int x = rgbaWide - 1; x >= dropShadowOffset; x--) { + Span dest = rgba[((x + (y * rgbaWide)) * 4)..]; + if (dest[3] == 0) { + Span src = rgba[(int)((x - dropShadowOffset + ((y - dropShadowOffset) * rgbaWide)) * 4)..]; + dest[0] = 0; + dest[1] = 0; + dest[2] = 0; + dest[3] = src[3]; + } + } + } + } + internal static void ApplyGaussianBlurToTexture(int rgbaWide, int rgbaTall, Span rgba, uint nBlur) { + if (nBlur == 0) + return; + + int filterWidth = (int)(nBlur * 2 + 1); + Span pGaussianDistribution = stackalloc float[filterWidth]; + float sigma = 0.683f * nBlur; + for (int x = 0; x <= nBlur * 2; x++) { + int val = x - (int)nBlur; + pGaussianDistribution[x] = (1.0f / MathF.Sqrt(2 * 3.14f * sigma * sigma)) * MathF.Pow(2.7f, -1.0f * (val * val) / (2 * sigma * sigma)); + } + + int totalBytes = rgbaWide * rgbaTall * 4; + Span src = new byte[totalBytes]; + rgba[..totalBytes].CopyTo(src); + + for (int x = 0; x < rgbaWide; x++) { + int distOffset = 0; + int nValues = filterWidth; + int nOffset = 0; + if (x < nBlur) { + nOffset += (int)nBlur - x; + distOffset += nOffset; + nValues -= nOffset; + } + if (x >= rgbaWide - nBlur) { + nValues = rgbaWide - (x - nOffset); + } + + for (int y = 0; y < rgbaTall; y++) { + int readIndex = (y * rgbaWide + x + nOffset - (int)nBlur) * 4 + 3; + float accum = 0.0f; + for (int n = 0; n < nValues; n++) { + accum += pGaussianDistribution[distOffset + n] * src[readIndex + n * 4]; + } + byte alpha = (byte)accum; + + int dstIndex = (y * rgbaWide + x) * 4; + rgba[dstIndex + 0] = rgba[dstIndex + 1] = rgba[dstIndex + 2] = alpha > 0 ? (byte)255 : (byte)0; + rgba[dstIndex + 3] = alpha; + } + } + + rgba[..totalBytes].CopyTo(src); + + for (int y = 0; y < rgbaTall; y++) { + int distOffset = 0; + int nValues = filterWidth; + int nOffset = 0; + if (y < nBlur) { + nOffset += (int)nBlur - y; + distOffset += nOffset; + nValues -= nOffset; + } + if (y >= rgbaTall - nBlur) { + nValues = rgbaTall - (y - nOffset); + } + + for (int x = 0; x < rgbaWide; x++) { + int readIndex = ((y + nOffset - (int)nBlur) * rgbaWide + x) * 4 + 3; + float accum = 0.0f; + for (int n = 0; n < nValues; n++) { + accum += pGaussianDistribution[distOffset + n] * src[readIndex + n * 4 * rgbaWide]; + } + byte alpha = (byte)accum; + + int dstIndex = (y * rgbaWide + x) * 4; + rgba[dstIndex + 0] = rgba[dstIndex + 1] = rgba[dstIndex + 2] = alpha > 0 ? (byte)255 : (byte)0; + rgba[dstIndex + 3] = alpha; + } + } + } + internal static void ApplyScanlineEffectToTexture(int rgbaWide, int rgbaTall, Span rgba, uint scanLines) { + if (scanLines < 2) + return; + + const float scale = 0.7f; + + for (int y = 0; y < rgbaTall; y++) { + if (y % scanLines == 0) + continue; + + Span pBits = rgba[((y * rgbaWide) * 4)..]; + + for (int x = 0; x < rgbaWide; x++, pBits = pBits[4..]) { + pBits[0] = (byte)(pBits[0] * scale); + pBits[1] = (byte)(pBits[1] * scale); + pBits[2] = (byte)(pBits[2] * scale); + } + } + } + internal static void ApplyRotaryEffectToTexture(int rgbaWide, int rgbaTall, Span rgba, bool rotary) { + if (!rotary) + return; + + int y = rgbaTall / 2; + + Span line = rgba[((y * rgbaWide) * 4)..]; + + for (int x = 0; x < rgbaWide; x++, line = line[4..]) { + line[0] = 127; + line[1] = 127; + line[2] = 127; + line[3] = 255; + } + } + internal static void ApplyOutlineToTexture(int rgbaWide, int rgbaTall, Span rgba, uint outlineSize) { + if (outlineSize == 0) + return; + + int x, y; + for (y = 0; y < rgbaTall; y++) { + for (x = 0; x < rgbaWide; x++) { + Span src = rgba[((x + (y * rgbaWide)) * 4)..]; + if (src[3] == 0) { + int shadowX, shadowY; + for (shadowX = -(int)outlineSize; shadowX <= (int)outlineSize; shadowX++) { + for (shadowY = -(int)outlineSize; shadowY <= (int)outlineSize; shadowY++) { + if (shadowX == 0 && shadowY == 0) { + continue; + } + int testX, testY; + testX = shadowX + x; + testY = shadowY + y; + if (testX < 0 || testX >= rgbaWide || + testY < 0 || testY >= rgbaTall) { + continue; + } + Span test = rgba[((testX + (testY * rgbaWide)) * 4)..]; + if (test[0] != 0 && test[1] != 0 && test[2] != 0 && test[3] != 0) { + src[0] = 0; + src[1] = 0; + src[2] = 0; + src[3] = 255; + } + } + } + } + } + } + } +} diff --git a/Source.MaterialSystem/Surface/FontManager.cs b/Source.MaterialSystem/Surface/FontManager.cs index 856247dbe..8ab515c93 100644 --- a/Source.MaterialSystem/Surface/FontManager.cs +++ b/Source.MaterialSystem/Surface/FontManager.cs @@ -162,7 +162,12 @@ public FontManager(IMaterialSystem materialSystem, IFileSystem fileSystem, ISyst } List FontAmalgams = []; +#if WIN32 + List Win32Fonts = []; + List CustomFontFileNames = []; +#else List FreeTypeFonts = []; +#endif static ulong FontHash(ReadOnlySpan name, int weight) => sprintf(stackalloc char[name.Length + 16], "%s-%i").S(name).I(weight).ToSpan().Hash(); @@ -171,7 +176,13 @@ public FontManager(IMaterialSystem materialSystem, IFileSystem fileSystem, ISyst Dictionary CustomFontFiles = []; public void ClearAllFonts() { +#if WIN32 + for (int i = 0; i < Win32Fonts.Count; i++) + Win32Fonts[i].Dispose(); + Win32Fonts.Clear(); +#else FreeTypeFonts.Clear(); +#endif for (int i = 0; i < FontAmalgams.Count; i++) FontAmalgams[i].RemoveAll(); @@ -192,7 +203,7 @@ internal bool SetFontGlyphSet(IFont font, ReadOnlySpan fontName, int tall, if (fontAmalgam.GetCount() > 0) fontAmalgam.RemoveAll(); - FreeTypeFont? baseFont = CreateOrFindFreeTypeFont(fontName, tall, weight, blur, scanlines, flags); + BaseFont? baseFont = CreateOrFindFont(fontName, tall, weight, blur, scanlines, flags); do { if (IsFontForeignLanguageCapable(fontName)) { @@ -208,7 +219,7 @@ internal bool SetFontGlyphSet(IFont font, ReadOnlySpan fontName, int tall, return true; } - FreeTypeFont? extendedFont = CreateOrFindFreeTypeFont(localizedFontName, tall, weight, blur, scanlines, flags); + BaseFont? extendedFont = CreateOrFindFont(localizedFontName, tall, weight, blur, scanlines, flags); if (baseFont != null && extendedFont != null) { int min = 0x0000, max = 0x00FF; @@ -300,6 +311,40 @@ private bool IsFontForeignLanguageCapable(ReadOnlySpan fontName) { return (byte*)binary; } + private BaseFont? CreateOrFindFont(ReadOnlySpan fontName, int tall, int weight, int blur, int scanlines, SurfaceFontFlags flags) { +#if WIN32 + return CreateOrFindWin32Font(fontName, tall, weight, blur, scanlines, flags); +#else + return CreateOrFindFreeTypeFont(fontName, tall, weight, blur, scanlines, flags); +#endif + } + +#if WIN32 + private Win32Font? CreateOrFindWin32Font(ReadOnlySpan windowsFontName, int tall, int weight, int blur, int scanlines, SurfaceFontFlags flags) { + Win32Font? winFont = null; + int i; + for (i = 0; i < Win32Fonts.Count; i++) { + if (Win32Fonts[i].IsEqualTo(windowsFontName, tall, weight, blur, scanlines, flags)) { + winFont = Win32Fonts[i]; + break; + } + } + + if (winFont == null) { + Win32Font font = new(); + if (font.Create(windowsFontName, tall, weight, blur, scanlines, flags)) { + Win32Fonts.Add(font); + winFont = font; + } + else { + font.Dispose(); + return null; + } + } + + return winFont; + } +#else private FreeTypeFont? CreateOrFindFreeTypeFont(ReadOnlySpan fontName, int tall, int weight, int blur, int scanlines, SurfaceFontFlags flags) { if (!FontsReady) InitFontSettings(); @@ -342,6 +387,7 @@ private bool IsFontForeignLanguageCapable(ReadOnlySpan fontName) { } return foundFont; } +#endif public struct FT_SfntName { @@ -354,6 +400,33 @@ public struct FT_SfntName } internal bool AddCustomFontFile(ReadOnlySpan fontName, ReadOnlySpan fontFileName) { +#if WIN32 + ReadOnlySpan fullPath = fileSystem.RelativePathToFullPath(fontFileName, null, stackalloc char[260]); + if (fullPath.IsEmpty) { + Warning($"Couldn't find custom font file '{fontFileName}'\n"); + return false; + } + + string path = new(fullPath); + int i; + for (i = 0; i < CustomFontFileNames.Count; i++) { + if (CustomFontFileNames[i] == path) + break; + } + if (i >= CustomFontFileNames.Count) { + CustomFontFileNames.Add(path); + fileSystem.GetLocalCopy(path); + } + + if (Win32Font.AddFontResourceExA(path, Win32Font.FR_PRIVATE, 0) > 0) + return true; + + if (Win32Font.AddFontResourceA(path) < 1) { + Warning($"Failed to load custom font file '{path}'\n"); + return false; + } + return true; +#else ReadOnlySpan fontFilepath = fileSystem.RelativePathToFullPath(fontFileName, null, stackalloc char[512]); if (fontFilepath.IsEmpty) { @@ -403,6 +476,7 @@ internal bool AddCustomFontFile(ReadOnlySpan fontName, ReadOnlySpan CustomFontFiles[fontName.Hash()] = new(fontFilepath); return true; +#endif } internal int GetFontTall(IFont? font) => ((FontAmalgam?)font)?.GetFontHeight() ?? 0; diff --git a/Source.MaterialSystem/Surface/FontTextureCache.cs b/Source.MaterialSystem/Surface/FontTextureCache.cs index 00418ac6c..0f4904707 100644 --- a/Source.MaterialSystem/Surface/FontTextureCache.cs +++ b/Source.MaterialSystem/Surface/FontTextureCache.cs @@ -276,7 +276,11 @@ bool AllocatePageForChar(int charWide, int charTall, out nint pageIndex, out int newPage.Wide, newPage.Tall, ImageFormat.RGBA8888, +#if GMOD_DLL + TextureFlags.ClampS | TextureFlags.ClampT | +#else TextureFlags.PointSample | TextureFlags.ClampS | TextureFlags.ClampT | +#endif TextureFlags.NoMip | TextureFlags.NoLOD | TextureFlags.Procedural | TextureFlags.SingleCopy ); @@ -286,6 +290,14 @@ bool AllocatePageForChar(int charWide, int charTall, out nint pageIndex, out int // allocate for 32bpp format int nByteCount = TEXTURE_PAGE_WIDTH * TEXTURE_PAGE_HEIGHT * 4; Span rgba = stackalloc byte[nByteCount]; +#if GMOD_DLL + for (int i = 0; i < nByteCount; i += 4) { + rgba[i + 0] = 255; + rgba[i + 1] = 255; + rgba[i + 2] = 255; + rgba[i + 3] = 0; + } +#endif int typePageNonAdditive = (int)FontDrawType.NonAdditive - 1; surface.DrawSetTextureRGBA(newPage.TextureID[typePageNonAdditive], rgba, newPage.Wide, newPage.Tall, 0, false); } diff --git a/Source.MaterialSystem/Surface/FreeTypeFont.cs b/Source.MaterialSystem/Surface/FreeTypeFont.cs index 0737cb189..033f38d8a 100644 --- a/Source.MaterialSystem/Surface/FreeTypeFont.cs +++ b/Source.MaterialSystem/Surface/FreeTypeFont.cs @@ -174,170 +174,11 @@ internal override void GetCharRGBA(char ch, int rgbaWide, int rgbaTall, Span rgba, uint dropShadowOffset) { - if (dropShadowOffset == 0) - return; - - for (int y = rgbaTall - 1; y >= dropShadowOffset; y--) { - for (int x = rgbaWide - 1; x >= dropShadowOffset; x--) { - Span dest = rgba[((x + (y * rgbaWide)) * 4)..]; - if (dest[3] == 0) { - Span src = rgba[(int)((x - dropShadowOffset + ((y - dropShadowOffset) * rgbaWide)) * 4)..]; - dest[0] = 0; - dest[1] = 0; - dest[2] = 0; - dest[3] = src[3]; - } - } - } - } - private void ApplyGaussianBlurToTexture(int rgbaWide, int rgbaTall, Span rgba, uint nBlur) { - if (nBlur == 0) - return; - - int filterWidth = (int)(nBlur * 2 + 1); - Span pGaussianDistribution = stackalloc float[filterWidth]; - float sigma = 0.683f * nBlur; - for (int x = 0; x <= nBlur * 2; x++) { - int val = x - (int)nBlur; - pGaussianDistribution[x] = (1.0f / MathF.Sqrt(2 * 3.14f * sigma * sigma)) * MathF.Pow(2.7f, -1.0f * (val * val) / (2 * sigma * sigma)); - } - - int totalBytes = rgbaWide * rgbaTall * 4; - Span src = new byte[totalBytes]; - rgba[..totalBytes].CopyTo(src); - - for (int x = 0; x < rgbaWide; x++) { - int distOffset = 0; - int nValues = filterWidth; - int nOffset = 0; - if (x < nBlur) { - nOffset += (int)nBlur - x; - distOffset += nOffset; - nValues -= nOffset; - } - if (x >= rgbaWide - nBlur) { - nValues = rgbaWide - (x - nOffset); - } - - for (int y = 0; y < rgbaTall; y++) { - int readIndex = (y * rgbaWide + x + nOffset - (int)nBlur) * 4 + 3; - float accum = 0.0f; - for (int n = 0; n < nValues; n++) { - accum += pGaussianDistribution[distOffset + n] * src[readIndex + n * 4]; - } - byte alpha = (byte)accum; - - int dstIndex = (y * rgbaWide + x) * 4; - rgba[dstIndex + 0] = rgba[dstIndex + 1] = rgba[dstIndex + 2] = alpha > 0 ? (byte)255 : (byte)0; - rgba[dstIndex + 3] = alpha; - } - } - - rgba[..totalBytes].CopyTo(src); - - for (int y = 0; y < rgbaTall; y++) { - int distOffset = 0; - int nValues = filterWidth; - int nOffset = 0; - if (y < nBlur) { - nOffset += (int)nBlur - y; - distOffset += nOffset; - nValues -= nOffset; - } - if (y >= rgbaTall - nBlur) { - nValues = rgbaTall - (y - nOffset); - } - - for (int x = 0; x < rgbaWide; x++) { - int readIndex = ((y + nOffset - (int)nBlur) * rgbaWide + x) * 4 + 3; - float accum = 0.0f; - for (int n = 0; n < nValues; n++) { - accum += pGaussianDistribution[distOffset + n] * src[readIndex + n * 4 * rgbaWide]; - } - byte alpha = (byte)accum; - - int dstIndex = (y * rgbaWide + x) * 4; - rgba[dstIndex + 0] = rgba[dstIndex + 1] = rgba[dstIndex + 2] = alpha > 0 ? (byte)255 : (byte)0; - rgba[dstIndex + 3] = alpha; - } - } - } - private void ApplyScanlineEffectToTexture(int rgbaWide, int rgbaTall, Span rgba, uint scanLines) { - if (scanLines < 2) - return; - - const float scale = 0.7f; - - for (int y = 0; y < rgbaTall; y++) { - if (y % scanLines == 0) - continue; - - Span pBits = rgba[((y * rgbaWide) * 4)..]; - - for (int x = 0; x < rgbaWide; x++, pBits = pBits[4..]) { - pBits[0] = (byte)(pBits[0] * scale); - pBits[1] = (byte)(pBits[1] * scale); - pBits[2] = (byte)(pBits[2] * scale); - } - } - } - private void ApplyRotaryEffectToTexture(int rgbaWide, int rgbaTall, Span rgba, bool rotary) { - if (!rotary) - return; - - int y = rgbaTall / 2; - - Span line = rgba[((y * rgbaWide) * 4)..]; - - for (int x = 0; x < rgbaWide; x++, line = line[4..]) { - line[0] = 127; - line[1] = 127; - line[2] = 127; - line[3] = 255; - } - } - private void ApplyOutlineToTexture(int rgbaWide, int rgbaTall, Span rgba, uint outlineSize) { - if (outlineSize == 0) - return; - - int x, y; - for (y = 0; y < rgbaTall; y++) { - for (x = 0; x < rgbaWide; x++) { - Span src = rgba[((x + (y * rgbaWide)) * 4)..]; - if (src[3] == 0) { - int shadowX, shadowY; - for (shadowX = -(int)outlineSize; shadowX <= (int)outlineSize; shadowX++) { - for (shadowY = -(int)outlineSize; shadowY <= (int)outlineSize; shadowY++) { - if (shadowX == 0 && shadowY == 0) { - continue; - } - int testX, testY; - testX = shadowX + x; - testY = shadowY + y; - if (testX < 0 || testX >= rgbaWide || - testY < 0 || testY >= rgbaTall) { - continue; - } - Span test = rgba[((testX + (testY * rgbaWide)) * 4)..]; - if (test[0] != 0 && test[1] != 0 && test[2] != 0 && test[3] != 0) { - src[0] = 0; - src[1] = 0; - src[2] = 0; - src[3] = 255; - } - } - } - } - } - } + FontEffects.ApplyDropShadowToTexture(rgbaWide, rgbaTall, rgba, DropShadowOffset); + FontEffects.ApplyOutlineToTexture(rgbaWide, rgbaTall, rgba, OutlineSize); + FontEffects.ApplyGaussianBlurToTexture(rgbaWide, rgbaTall, rgba, Blur); + FontEffects.ApplyScanlineEffectToTexture(rgbaWide, rgbaTall, rgba, ScanLines); + FontEffects.ApplyRotaryEffectToTexture(rgbaWide, rgbaTall, rgba, Rotary); } private unsafe void DrawBitmap(FT_GlyphSlotRec_* rec, int rgbaWide, int rgbaTall, Span rgba) { diff --git a/Source.MaterialSystem/Surface/Win32Font.cs b/Source.MaterialSystem/Surface/Win32Font.cs new file mode 100644 index 000000000..d74af5cdf --- /dev/null +++ b/Source.MaterialSystem/Surface/Win32Font.cs @@ -0,0 +1,439 @@ +#if WIN32 +using Source.Common.GUI; + +using System.Runtime.InteropServices; + +namespace Source.MaterialSystem.Surface; + +public unsafe class Win32Font : BaseFont, IDisposable +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + struct LOGFONTA + { + public int lfHeight; + public int lfWidth; + public int lfEscapement; + public int lfOrientation; + public int lfWeight; + public byte lfItalic; + public byte lfUnderline; + public byte lfStrikeOut; + public byte lfCharSet; + public byte lfOutPrecision; + public byte lfClipPrecision; + public byte lfQuality; + public byte lfPitchAndFamily; + public fixed byte lfFaceName[32]; + } + + [StructLayout(LayoutKind.Sequential)] + struct TEXTMETRICA + { + public int tmHeight; + public int tmAscent; + public int tmDescent; + public int tmInternalLeading; + public int tmExternalLeading; + public int tmAveCharWidth; + public int tmMaxCharWidth; + public int tmWeight; + public int tmOverhang; + public int tmDigitizedAspectX; + public int tmDigitizedAspectY; + public byte tmFirstChar; + public byte tmLastChar; + public byte tmDefaultChar; + public byte tmBreakChar; + public byte tmItalic; + public byte tmUnderlined; + public byte tmStruckOut; + public byte tmPitchAndFamily; + public byte tmCharSet; + } + + [StructLayout(LayoutKind.Sequential)] + struct BITMAPINFOHEADER + { + public uint biSize; + public int biWidth; + public int biHeight; + public ushort biPlanes; + public ushort biBitCount; + public uint biCompression; + public uint biSizeImage; + public int biXPelsPerMeter; + public int biYPelsPerMeter; + public uint biClrUsed; + public uint biClrImportant; + } + + [StructLayout(LayoutKind.Sequential)] + struct FIXED + { + public ushort fract; + public short value; + } + + [StructLayout(LayoutKind.Sequential)] + struct MAT2 + { + public FIXED eM11; + public FIXED eM12; + public FIXED eM21; + public FIXED eM22; + } + + [StructLayout(LayoutKind.Sequential)] + struct GLYPHMETRICS + { + public uint gmBlackBoxX; + public uint gmBlackBoxY; + public int gmptGlyphOriginX; + public int gmptGlyphOriginY; + public short gmCellIncX; + public short gmCellIncY; + } + + [StructLayout(LayoutKind.Sequential)] + struct ABC + { + public int abcA; + public uint abcB; + public int abcC; + } + + [StructLayout(LayoutKind.Sequential)] + struct SIZE + { + public int cx; + public int cy; + } + + const byte ANSI_CHARSET = 0; + const byte DEFAULT_CHARSET = 1; + const byte SYMBOL_CHARSET = 2; + const byte SHIFTJIS_CHARSET = 128; + const uint OUT_TT_ONLY_PRECIS = 7; + const uint CLIP_DEFAULT_PRECIS = 0; + const uint NONANTIALIASED_QUALITY = 3; + const uint ANTIALIASED_QUALITY = 4; + const uint DEFAULT_PITCH = 0; + const uint FF_DONTCARE = 0; + const int MM_TEXT = 1; + const uint TA_UPDATECP = 1; + const uint BI_RGB = 0; + const uint DIB_RGB_COLORS = 0; + const uint GGO_METRICS = 0; + const uint GGO_BITMAP = 1; + const uint GGO_GRAY8_BITMAP = 6; + const uint CP_ACP = 0; + internal const uint FR_PRIVATE = 16; + + [DllImport("gdi32")] static extern nint CreateCompatibleDC(nint hdc); + [DllImport("gdi32")] static extern int DeleteDC(nint hdc); + [DllImport("gdi32")] static extern int DeleteObject(nint ho); + [DllImport("gdi32")] static extern nint SelectObject(nint hdc, nint h); + [DllImport("gdi32")] static extern int EnumFontFamiliesExA(nint hdc, LOGFONTA* logfont, delegate* unmanaged[Stdcall] proc, nint lParam, uint flags); + [DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true)] static extern nint CreateFontA(int cHeight, int cWidth, int cEscapement, int cOrientation, int cWeight, uint bItalic, uint bUnderline, uint bStrikeOut, uint iCharSet, uint iOutPrecision, uint iClipPrecision, uint iQuality, uint iPitchAndFamily, string pszFaceName); + [DllImport("gdi32")] static extern int SetMapMode(nint hdc, int mode); + [DllImport("gdi32")] static extern uint SetTextAlign(nint hdc, uint align); + [DllImport("gdi32")] static extern int GetTextMetricsA(nint hdc, TEXTMETRICA* tm); + [DllImport("gdi32")] static extern nint CreateDIBSection(nint hdc, BITMAPINFOHEADER* pbmi, uint usage, byte** ppvBits, nint hSection, uint offset); + [DllImport("gdi32")] static extern uint GetGlyphOutlineW(nint hdc, uint uChar, uint fuFormat, GLYPHMETRICS* lpgm, uint cjBuffer, void* pvBuffer, MAT2* lpmat2); + [DllImport("gdi32")] static extern uint GetGlyphOutlineA(nint hdc, uint uChar, uint fuFormat, GLYPHMETRICS* lpgm, uint cjBuffer, void* pvBuffer, MAT2* lpmat2); + [DllImport("gdi32")] static extern int GetCharABCWidthsW(nint hdc, uint wFirst, uint wLast, ABC* lpABC); + [DllImport("gdi32")] static extern int GetCharABCWidthsA(nint hdc, uint wFirst, uint wLast, ABC* lpABC); + [DllImport("gdi32")] static extern int GetTextExtentPoint32A(nint hdc, byte* lpString, int c, SIZE* lpsz); + [DllImport("gdi32", CharSet = CharSet.Ansi)] internal static extern int AddFontResourceExA(string name, uint fl, nint res); + [DllImport("gdi32", CharSet = CharSet.Ansi)] internal static extern int AddFontResourceA(string name); + [DllImport("kernel32")] static extern int WideCharToMultiByte(uint codePage, uint flags, char* lpWideCharStr, int cchWideChar, byte* lpMultiByteStr, int cbMultiByte, byte* lpDefaultChar, int* lpUsedDefaultChar); + + struct ABCCache + { + public short B; + public sbyte A; + public sbyte C; + } + + nint Font; + nint DC; + nint DIB; + byte* Buf; + + string? Name; + + short Tall; + ushort Weight; + ushort Flags; + ushort ScanLines; + ushort Blur; + ushort[] BitmapSize = new ushort[2]; + bool Underlined; + + byte Height; + byte MaxCharWidth; + byte Ascent; + uint DropShadowOffset; + uint OutlineSize; + bool AntiAliased; + bool Rotary; + bool Additive; + + readonly Dictionary ExtendedABCWidthsCache = []; + + static bool FontFound; + + [UnmanagedCallersOnly(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvStdcall)])] + static int FontEnumProc(LOGFONTA* logfont, TEXTMETRICA* tm, uint fontType, nint lParam) { + FontFound = true; + return 0; + } + + public bool Create(ReadOnlySpan windowsFontName, int tall, int weight, int blur, int scanlines, SurfaceFontFlags flags) { + Name = new(windowsFontName); + Tall = (short)tall; + Weight = (ushort)weight; + Flags = (ushort)flags; + AntiAliased = (flags & SurfaceFontFlags.Antialias) != 0; + Underlined = (flags & SurfaceFontFlags.Underline) != 0; + DropShadowOffset = (flags & SurfaceFontFlags.DropShadow) != 0 ? 1u : 0u; + OutlineSize = (flags & SurfaceFontFlags.Outline) != 0 ? 1u : 0u; + Blur = (ushort)blur; + ScanLines = (ushort)scanlines; + Rotary = (flags & SurfaceFontFlags.Rotary) != 0; + Additive = (flags & SurfaceFontFlags.Additive) != 0; + + uint charset = (flags & SurfaceFontFlags.Symbol) != 0 ? SYMBOL_CHARSET : ANSI_CHARSET; + + if (stricmp(windowsFontName, "win98japanese") == 0) { + charset = SHIFTJIS_CHARSET; + Name = "Tahoma"; + } + + DC = CreateCompatibleDC(0); + + LOGFONTA logfont = default; + logfont.lfCharSet = DEFAULT_CHARSET; + logfont.lfPitchAndFamily = 0; + int nameLength = Math.Min(Name.Length, 31); + for (int i = 0; i < nameLength; i++) + logfont.lfFaceName[i] = (byte)Name[i]; + logfont.lfFaceName[nameLength] = 0; + FontFound = false; + EnumFontFamiliesExA(DC, &logfont, &FontEnumProc, 0, 0); + if (FontFound) { + Font = CreateFontA(tall, 0, 0, 0, Weight, (uint)flags & (uint)SurfaceFontFlags.Italic, (uint)flags & (uint)SurfaceFontFlags.Underline, (uint)flags & (uint)SurfaceFontFlags.Strikeout, charset, OUT_TT_ONLY_PRECIS, CLIP_DEFAULT_PRECIS, AntiAliased ? ANTIALIASED_QUALITY : NONANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, new(windowsFontName)); + if (Font == 0) + Warning($"Couldn't create windows font '{windowsFontName}' ({Marshal.GetLastPInvokeError()})\n"); + else { +#if false + DevMsg($"Creating Win32Font '{windowsFontName}' [{string.Join(';', new[] { $"tall {tall}", $"weight {weight}", $"blur {blur}", $"scanlines {scanlines}", $"flags {flags}" }.Where(x => !x.EndsWith(" 0") && !x.EndsWith(" None")))}]\n"); +#endif + SetMapMode(DC, MM_TEXT); + SelectObject(DC, Font); + SetTextAlign(DC, TA_UPDATECP); + + TEXTMETRICA tm = default; + if (GetTextMetricsA(DC, &tm) != 0) { + Height = (byte)(tm.tmHeight + DropShadowOffset + 2 * OutlineSize); + MaxCharWidth = (byte)tm.tmMaxCharWidth; + Ascent = (byte)tm.tmAscent; + + BitmapSize[0] = (ushort)(tm.tmMaxCharWidth + OutlineSize * 2); + BitmapSize[1] = (ushort)(tm.tmHeight + DropShadowOffset + OutlineSize * 2); + + BITMAPINFOHEADER header = default; + header.biSize = (uint)sizeof(BITMAPINFOHEADER); + header.biWidth = BitmapSize[0]; + header.biHeight = -BitmapSize[1]; + header.biPlanes = 1; + header.biBitCount = 32; + header.biCompression = BI_RGB; + + byte* buf; + DIB = CreateDIBSection(DC, &header, DIB_RGB_COLORS, &buf, 0, 0); + Buf = buf; + SelectObject(DC, DIB); + return true; + } + } + } + + Name = null; + return false; + } + + internal override void GetCharRGBA(char ch, int rgbaWide, int rgbaTall, Span rgba) { + GetCharABCwidths(ch, out _, out _, out _); + + SelectObject(DC, Font); + + uint fontHeight = Height; + MAT2 mat2 = default; + mat2.eM11.value = 1; + mat2.eM22.value = 1; + uint format = AntiAliased ? GGO_GRAY8_BITMAP : GGO_BITMAP; + + GLYPHMETRICS glyphMetrics; + uint bytesNeeded = GetGlyphOutlineW(DC, ch, format, &glyphMetrics, 0, null, &mat2); + if (bytesNeeded == 0) + return; + + byte* lpbuf = stackalloc byte[(int)bytesNeeded]; + if (GetGlyphOutlineW(DC, ch, format, &glyphMetrics, bytesNeeded, lpbuf, &mat2) == 0) + return; + + uint pitch = glyphMetrics.gmBlackBoxX; + if (!AntiAliased) + pitch = ((glyphMetrics.gmBlackBoxX + 31) >> 3) & 536870908; + while ((pitch & 3) != 0) + pitch++; + + uint xOffset = OutlineSize + Blur; + for (uint i = 0; i < glyphMetrics.gmBlackBoxX; i++) { + uint x = i + xOffset; + for (uint j = 0; j < glyphMetrics.gmBlackBoxY; j++) { + uint y = (uint)(j + (Ascent - glyphMetrics.gmptGlyphOriginY)); + if (x < (uint)rgbaWide && y < (uint)rgbaTall) { + byte value; + if (!AntiAliased) + value = (lpbuf[(i >> 3) + j * pitch] & (128 >> (int)(i & 7))) != 0 ? (byte)255 : (byte)0; + else { + double gray = lpbuf[j * pitch + i] * 4.0; + if (gray >= 0.0) { + if (gray >= 255.0) + gray = 255.0; + value = (byte)(int)gray; + } + else + value = 0; + } + + int dst = (int)((x + y * (uint)rgbaWide) * 4); + rgba[dst + 3] = ch != '\t' ? value : (byte)0; + rgba[dst + 0] = 255; + rgba[dst + 1] = 255; + rgba[dst + 2] = 255; + } + } + } + + if (Underlined) { + GLYPHMETRICS metrics; + MAT2 identity = default; + identity.eM11.value = 1; + identity.eM22.value = 1; + GetGlyphOutlineA(DC, 'a', GGO_METRICS, &metrics, 0, null, &identity); + + uint start = (uint)rgbaTall - fontHeight / 10; + if (start <= metrics.gmBlackBoxY - 1) + start = metrics.gmBlackBoxY - 1; + + uint end = fontHeight / 15 + start; + if (end >= (uint)rgbaTall) + end = (uint)rgbaTall; + if (start + 1 >= end) + end = start + 1; + + for (uint x = 0; x < (uint)rgbaWide; x++) { + for (uint y = start; y < end; y++) { + if (y < (uint)rgbaTall) { + int dst = (int)((y * (uint)rgbaWide + x) * 4); + rgba[dst + 0] = 255; + rgba[dst + 1] = 255; + rgba[dst + 2] = 255; + rgba[dst + 3] = 255; + } + } + } + } + + FontEffects.ApplyDropShadowToTexture(rgbaWide, rgbaTall, rgba, DropShadowOffset); + FontEffects.ApplyOutlineToTexture(rgbaWide, rgbaTall, rgba, OutlineSize); + FontEffects.ApplyGaussianBlurToTexture(rgbaWide, rgbaTall, rgba, Blur); + FontEffects.ApplyScanlineEffectToTexture(rgbaWide, rgbaTall, rgba, ScanLines); + FontEffects.ApplyRotaryEffectToTexture(rgbaWide, rgbaTall, rgba, Rotary); + } + + public override bool IsEqualTo(ReadOnlySpan windowsFontName, int tall, int weight, int blur, int scanlines, SurfaceFontFlags flags) { + return stricmp(windowsFontName, Name) == 0 + && Tall == tall + && Weight == weight + && Blur == blur + && ScanLines == scanlines + && Flags == (int)flags; + } + + public bool IsValid() => Name != null && Name.Length > 0; + + public void SetAsActiveFont(nint hdc) => SelectObject(hdc, Font); + + public override void GetCharABCwidths(char ch, out int a, out int b, out int c) { + if (ExtendedABCWidthsCache.TryGetValue(ch, out ABCCache cached)) { + a = cached.A; + b = cached.B; + c = cached.C; + return; + } + + ABC abc; + if (GetCharABCWidthsW(DC, ch, ch, &abc) != 0 || GetCharABCWidthsA(DC, ch, ch, &abc) != 0) { + a = abc.abcA; + b = (int)abc.abcB + 2; + c = abc.abcC - 2; + } + else { + byte* mbcs = stackalloc byte[6]; + new Span(mbcs, 6).Clear(); + char wch = ch; + WideCharToMultiByte(CP_ACP, 0, &wch, 1, mbcs, 6, null, null); + int length = 0; + while (mbcs[length] != 0) + length++; + SIZE size; + if (GetTextExtentPoint32A(DC, mbcs, length, &size) != 0) { + a = 0; + b = size.cx + 2; + c = -2; + } + else { + a = c = 0; + b = MaxCharWidth; + } + } + + ExtendedABCWidthsCache[ch] = new() { + A = (sbyte)(a - OutlineSize - Blur), + B = (short)((OutlineSize + Blur) * 2 + DropShadowOffset + b), + C = (sbyte)(c - DropShadowOffset - OutlineSize - Blur) + }; + } + + public override int GetCharYOffset(char ch) => 0; + + public override int GetHeight() => Height; + internal override int GetHeightRequested() => Tall; + public int GetAscent() => Ascent; + public override int GetMaxCharWidth() => MaxCharWidth; + public override SurfaceFontFlags GetFlags() => (SurfaceFontFlags)Flags; + public override bool GetUnderlined() => Underlined; + internal override ReadOnlySpan GetName() => Name; + internal override ReadOnlySpan GetFamilyName() => null; + + internal override void GetKernedCharWidth(char ch, char chBefore, char chAfter, out float wide, out float abcA, out float abcC) { + GetCharABCwidths(ch, out int a, out int b, out int c); + wide = a + b + c; + abcA = a; + abcC = 0; + } + + public void Dispose() { + if (Font != 0) + DeleteObject(Font); + if (DC != 0) + DeleteDC(DC); + if (DIB != 0) + DeleteObject(DIB); + } +} +#endif From 5909d2cb2eccbd5b77ba7dea775d2984815a2ff4 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Tue, 3 Nov 2026 19:03:43 +0000 Subject: [PATCH 2/3] Custom fonts --- Game.Shared/GarrysMod/GarrysMod.cs | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index 3b4f7e806..8d64a9c75 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -88,6 +88,29 @@ void AddLanguageFiles(ReadOnlySpan language) { } filesystem.FindClose(handle); } + + void AddCustomFontsFromFolder(string folder) { + HashSet workshopFonts = []; + ReadOnlySpan fileName = filesystem.FindFirstEx($"{folder}/*.ttf", "workshop", out ulong handle); + while (!fileName.IsEmpty) { + workshopFonts.Add(new(fileName)); + fileName = filesystem.FindNext(handle); + } + filesystem.FindClose(handle); + + fileName = filesystem.FindFirstEx($"{folder}/*.ttf", "GAME", out handle); + while (!fileName.IsEmpty) { + if (!workshopFonts.Contains(new(fileName))) + Surface.AddCustomFontFile(fileName, $"{folder}/{fileName}"); + fileName = filesystem.FindNext(handle); + } + filesystem.FindClose(handle); + } + + void AddCustomFonts() { + AddCustomFontsFromFolder("resource/fonts"); + AddCustomFontsFromFolder("cache/workshop/resource/fonts"); + } #endif public void InitializeMod(IServiceProvider services) { @@ -98,8 +121,9 @@ public void InitializeMod(IServiceProvider services) { #endif #if !SWDS get.IntroScreen()?.Update("Adding Custom Fonts", true); - // todo: AddCustomFonts #if CLIENT_DLL + AddCustomFonts(); + if (filesystem == null) Error("g_pFullFileSystem is NULL!?"); if (filesystem!.Language() == null) @@ -157,7 +181,7 @@ public void LevelInit(ReadOnlySpan mapName) { get.Audio()?.StopAllPlayback(); engine.ClientCmd("net_maxroutable 1260"); - // todo: AddCustomFonts(); + AddCustomFonts(); if (gpGlobals.MaxClients > 1) { // todo: ParseParticleEffects(true, false); From 5f11a1910766d8b35dfdf8868cef57263b529d84 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Tue, 3 Nov 2026 19:03:51 +0000 Subject: [PATCH 3/3] ClipRect fix --- Source.MaterialSystem/Surface/Clip2D.cs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Source.MaterialSystem/Surface/Clip2D.cs b/Source.MaterialSystem/Surface/Clip2D.cs index 981af941b..f30259f92 100644 --- a/Source.MaterialSystem/Surface/Clip2D.cs +++ b/Source.MaterialSystem/Surface/Clip2D.cs @@ -164,6 +164,13 @@ public unsafe static int ClipPolygon(in ScissorRectState state, Span outLR.Position.X || outUL.Position.Y > outLR.Position.Y) return false; - outUL.TexCoord = inUL.TexCoord; - outLR.TexCoord = inLR.TexCoord; + if (!StretchTexture) { + outUL.TexCoord.X = InterpTCoord(outUL.Position.X, inUL.Position.X, inLR.Position.X, inUL.TexCoord.X, inLR.TexCoord.X); + outUL.TexCoord.Y = InterpTCoord(outUL.Position.Y, inUL.Position.Y, inLR.Position.Y, inUL.TexCoord.Y, inLR.TexCoord.Y); + + outLR.TexCoord.X = InterpTCoord(outLR.Position.X, inUL.Position.X, inLR.Position.X, inUL.TexCoord.X, inLR.TexCoord.X); + outLR.TexCoord.Y = InterpTCoord(outLR.Position.Y, inUL.Position.Y, inLR.Position.Y, inUL.TexCoord.Y, inLR.TexCoord.Y); + } + else { + outUL.TexCoord = inUL.TexCoord; + outLR.TexCoord = inLR.TexCoord; + } } else { outUL = inUL;