Merge commit '795cd93' into nibu/rtd-hud-target-box
This commit is contained in:
commit
ff9bca1c28
24 changed files with 3287 additions and 9 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -5,5 +5,7 @@ __pycache__/
|
|||
/dist/
|
||||
bin/
|
||||
obj/
|
||||
artifacts/
|
||||
build/
|
||||
.godot/
|
||||
.vs/
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
<Folder Name="/src/">
|
||||
<Project Path="src/RustToDust.Core/RustToDust.Core.csproj" />
|
||||
<Project Path="src/RustToDust.Ymir/RustToDust.Ymir.csproj" />
|
||||
<Project Path="src/RustToDust.HbGpu/RustToDust.HbGpu.csproj" />
|
||||
<Project Path="src/RustToDust.Net/RustToDust.Net.csproj" />
|
||||
<Project Path="src/RustToDust.Server/RustToDust.Server.csproj" />
|
||||
<Project Path="src/RustToDust.Directory/RustToDust.Directory.csproj" />
|
||||
|
|
|
|||
15
THIRD_PARTY_NOTICES.txt
Normal file
15
THIRD_PARTY_NOTICES.txt
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
|
||||
|
||||
This product incorporates or bundles the following third-party software and
|
||||
font assets under their respective licenses:
|
||||
|
||||
1. Monaspace Krypton (Krypton.ttf — Monaspace Krypton Var.ttf v1.400)
|
||||
Copyright (c) 2023, GitHub (https://github.com/githubnext/monaspace)
|
||||
Reserved Font Names: 'Monaspace', 'Argon', 'Neon', 'Xenon', 'Radon', 'Krypton'
|
||||
License: SIL Open Font License, Version 1.1
|
||||
Full license text: assets/fonts/OFL-1.1.txt
|
||||
|
||||
2. HarfBuzz (15.2.0) — shaping and hb-gpu shader/curve encoder (rtd_hbgpu)
|
||||
Copyright (C) HarfBuzz Authors (Behdad Esfahbod, Google Inc., Red Hat Inc., et al.)
|
||||
License: HarfBuzz "Old MIT" License
|
||||
Full license text: assets/fonts/HARFBUZZ-COPYING.txt
|
||||
42
assets/fonts/HARFBUZZ-COPYING.txt
Normal file
42
assets/fonts/HARFBUZZ-COPYING.txt
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
HarfBuzz is licensed under the so-called "Old MIT" license. Details follow.
|
||||
For parts of HarfBuzz that are licensed under different licenses see individual
|
||||
files names COPYING in subdirectories where applicable.
|
||||
|
||||
Copyright © 2010-2022 Google, Inc.
|
||||
Copyright © 2015-2020 Ebrahim Byagowi
|
||||
Copyright © 2019,2020 Facebook, Inc.
|
||||
Copyright © 2012,2015 Mozilla Foundation
|
||||
Copyright © 2011 Codethink Limited
|
||||
Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies)
|
||||
Copyright © 2009 Keith Stribley
|
||||
Copyright © 2011 Martin Hosken and SIL International
|
||||
Copyright © 2007 Chris Wilson
|
||||
Copyright © 2005,2006,2020,2021,2022,2023 Behdad Esfahbod
|
||||
Copyright © 2004,2007,2008,2009,2010,2013,2021,2022,2023 Red Hat, Inc.
|
||||
Copyright © 1998-2005 David Turner and Werner Lemberg
|
||||
Copyright © 2016 Igalia S.L.
|
||||
Copyright © 2022 Matthias Clasen
|
||||
Copyright © 2018,2021 Khaled Hosny
|
||||
Copyright © 2018,2019,2020 Adobe, Inc
|
||||
Copyright © 2013-2015 Alexei Podtelezhnikov
|
||||
|
||||
For full copyright notices consult the individual files in the package.
|
||||
|
||||
|
||||
Permission is hereby granted, without written agreement and without
|
||||
license or royalty fees, to use, copy, modify, and distribute this
|
||||
software and its documentation for any purpose, provided that the
|
||||
above copyright notice and the following two paragraphs appear in
|
||||
all copies of this software.
|
||||
|
||||
IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
|
||||
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
|
||||
ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
|
||||
IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGE.
|
||||
|
||||
THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
|
||||
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
|
||||
ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
|
||||
PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
|
||||
BIN
assets/fonts/Krypton.ttf
Normal file
BIN
assets/fonts/Krypton.ttf
Normal file
Binary file not shown.
94
assets/fonts/OFL-1.1.txt
Normal file
94
assets/fonts/OFL-1.1.txt
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
Copyright (c) 2023, GitHub (https://github.com/githubnext/monaspace)
|
||||
with Reserved Font Names 'Monaspace', 'Argon', 'Neon', 'Xenon', 'Radon', 'Krypton'.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSIONS & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to remain
|
||||
under this license does not apply to any document created using the fonts
|
||||
or their derivatives.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
933
client/HbGpuCanvas.cs
Normal file
933
client/HbGpuCanvas.cs
Normal file
|
|
@ -0,0 +1,933 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using Godot;
|
||||
using RustToDust.HbGpu;
|
||||
|
||||
namespace RustToDust.Client;
|
||||
|
||||
/// <summary>
|
||||
/// Single-draw-call HarfBuzz 15.2.0 hb-gpu GLSL renderer on Godot 4.7 Forward+ Vulkan RenderingDevice.
|
||||
/// Safe in --headless / null-RD mode: preserves CPU shaping/layout without allocating RD resources.
|
||||
/// </summary>
|
||||
public partial class HbGpuCanvas : Control
|
||||
{
|
||||
public const byte DefaultFontId = 0;
|
||||
private const int PushConstantBytes = 80; // mat4 (64) + vec2 viewport (8) + vec2 logicalSize (8)
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
private struct PushConstants
|
||||
{
|
||||
// Column-major mat4 for GLSL: col 0, col 1, col 2, col 3
|
||||
public float C0R0, C0R1, C0R2, C0R3;
|
||||
public float C1R0, C1R1, C1R2, C1R3;
|
||||
public float C2R0, C2R1, C2R2, C2R3;
|
||||
public float C3R0, C3R1, C3R2, C3R3;
|
||||
public float ViewportX, ViewportY;
|
||||
public float LogicalW, LogicalH;
|
||||
}
|
||||
|
||||
private readonly HbGpuFontCache _fontCache = new();
|
||||
private readonly HbGpuAtlasAllocator _atlas = new();
|
||||
private readonly HbGpuBlobCache _blobCache;
|
||||
private readonly HbGpuCommandWriter _writer = new();
|
||||
|
||||
private readonly object _syncLock = new();
|
||||
private readonly HbGpuQuadInstance[] _stagedQuads = new HbGpuQuadInstance[HbGpuCommandWriter.MaxQuads];
|
||||
private int _stagedQuadCount;
|
||||
private float _stagedLogicalW = 1280f;
|
||||
private float _stagedLogicalH = 720f;
|
||||
private int _stagedPhysW = 1280;
|
||||
private int _stagedPhysH = 720;
|
||||
private bool _hasStagedFrame;
|
||||
|
||||
private TextureRect? _outputRect;
|
||||
private Texture2Drd? _outputTexRd;
|
||||
private HbGpuVulkanBackend? _backend;
|
||||
private Callable _renderCallable;
|
||||
private Callable _disposeCallable;
|
||||
private bool _disposed;
|
||||
|
||||
public bool ProfilingEnabled { get; set; }
|
||||
public double LastHbGpuMs => _backend?.LastHbGpuMs ?? 0.0;
|
||||
public int LastDrawCallCount => _backend?.LastDrawCallCount ?? 0;
|
||||
public int LastQuadCount { get; private set; }
|
||||
public bool IsVulkanActive => RenderingServer.GetRenderingDevice() is not null;
|
||||
|
||||
public HbGpuFontCache Fonts => _fontCache;
|
||||
public HbGpuBlobCache Blobs => _blobCache;
|
||||
public HbGpuCommandWriter Writer => _writer;
|
||||
|
||||
public HbGpuCanvas()
|
||||
{
|
||||
_blobCache = new HbGpuBlobCache(_atlas);
|
||||
MouseFilter = MouseFilterEnum.Ignore;
|
||||
}
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
|
||||
MouseFilter = MouseFilterEnum.Ignore;
|
||||
|
||||
LoadDefaultKryptonFont();
|
||||
|
||||
if (RenderingServer.GetRenderingDevice() is not null)
|
||||
{
|
||||
_outputTexRd = new Texture2Drd();
|
||||
_outputRect = new TextureRect
|
||||
{
|
||||
Name = "HbGpuOutput",
|
||||
MouseFilter = MouseFilterEnum.Ignore,
|
||||
ExpandMode = TextureRect.ExpandModeEnum.IgnoreSize,
|
||||
StretchMode = TextureRect.StretchModeEnum.Scale,
|
||||
Texture = _outputTexRd,
|
||||
Material = new CanvasItemMaterial
|
||||
{
|
||||
BlendMode = CanvasItemMaterial.BlendModeEnum.PremultAlpha
|
||||
}
|
||||
};
|
||||
AddChild(_outputRect);
|
||||
_outputRect.SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
|
||||
|
||||
_backend = new HbGpuVulkanBackend(_outputTexRd, _atlas);
|
||||
_renderCallable = Callable.From(RenderOnRenderThread);
|
||||
_disposeCallable = Callable.From(DisposeOnRenderThread);
|
||||
}
|
||||
}
|
||||
|
||||
private void LoadDefaultKryptonFont()
|
||||
{
|
||||
if (_fontCache.TryGetMetrics(DefaultFontId, out _))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
string path = ResolveKryptonPath();
|
||||
_fontCache.RegisterFontFromFile(DefaultFontId, path);
|
||||
}
|
||||
|
||||
public static string ResolveKryptonPath()
|
||||
{
|
||||
ClientAssets.EnsureAssetsRootRegistered();
|
||||
string[] candidates =
|
||||
{
|
||||
Path.Combine(ClientAssets.LocateAssetsDirectory(), "fonts", "Krypton.ttf"),
|
||||
Path.GetFullPath(Path.Combine(ProjectSettings.GlobalizePath("res://"), "..", "assets", "fonts", "Krypton.ttf")),
|
||||
Path.Combine(AppContext.BaseDirectory, "assets", "fonts", "Krypton.ttf")
|
||||
};
|
||||
|
||||
foreach (string c in candidates)
|
||||
{
|
||||
if (File.Exists(c))
|
||||
{
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
throw new FileNotFoundException("Could not locate assets/fonts/Krypton.ttf.");
|
||||
}
|
||||
|
||||
public void BeginFrame()
|
||||
{
|
||||
_blobCache.EnsureBudgetOrReset();
|
||||
_writer.BeginFrame();
|
||||
}
|
||||
|
||||
public float DrawText(
|
||||
ReadOnlySpan<char> text,
|
||||
float x,
|
||||
float baselineY,
|
||||
float fontSizePx,
|
||||
Color color,
|
||||
float wght = 200f,
|
||||
float wdth = 100f,
|
||||
float slnt = 0f,
|
||||
HbGpuFeatureFlags features = HbGpuFeatureFlags.Default,
|
||||
bool stemDarken = true,
|
||||
uint clipMinPacked = 0,
|
||||
uint clipMaxPacked = HbGpuQuadInstance.Unclipped)
|
||||
{
|
||||
return _writer.DrawTextUtf16(
|
||||
text, x, baselineY, fontSizePx,
|
||||
color.R, color.G, color.B, color.A,
|
||||
_fontCache, _blobCache,
|
||||
DefaultFontId, wght, wdth, slnt,
|
||||
features, stemDarken, clipMinPacked, clipMaxPacked);
|
||||
}
|
||||
|
||||
public float MeasureTextWidth(
|
||||
ReadOnlySpan<char> text,
|
||||
float fontSizePx,
|
||||
float wght = 200f,
|
||||
float wdth = 100f,
|
||||
float slnt = 0f,
|
||||
HbGpuFeatureFlags features = HbGpuFeatureFlags.Default)
|
||||
{
|
||||
return _writer.MeasureTextWidth(text, fontSizePx, _fontCache, DefaultFontId, wght, wdth, slnt, features);
|
||||
}
|
||||
|
||||
public void DrawRectFilled(float x, float y, float w, float h, Color color,
|
||||
uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped)
|
||||
{
|
||||
CachedBlob blob = HbGpuVectorShapes.GetUnitFilledRect(_blobCache);
|
||||
float cx = x + w * 0.5f;
|
||||
float cy = y + h * 0.5f;
|
||||
_writer.DrawBlob(
|
||||
blob, cx, cy,
|
||||
w * 0.001f, 0f, 0f, -h * 0.001f,
|
||||
0f, 0f,
|
||||
color.R, color.G, color.B, color.A,
|
||||
stemDarken: false, clipMinPacked, clipMaxPacked);
|
||||
}
|
||||
|
||||
public void DrawLineSegment(float x0, float y0, float x1, float y1, float thicknessPx, Color color,
|
||||
uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped)
|
||||
{
|
||||
float dx = x1 - x0;
|
||||
float dy = y1 - y0;
|
||||
float len = MathF.Sqrt(dx * dx + dy * dy);
|
||||
if (len < 1e-4f || thicknessPx <= 0f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
CachedBlob blob = HbGpuVectorShapes.GetUnitFilledRect(_blobCache);
|
||||
float cos = dx / len;
|
||||
float sin = dy / len;
|
||||
float sx = len * 0.001f;
|
||||
float sy = thicknessPx * 0.001f;
|
||||
float cx = (x0 + x1) * 0.5f;
|
||||
float cy = (y0 + y1) * 0.5f;
|
||||
// Rotate unit rect (X along segment, Y perpendicular) in Y-down screen coords
|
||||
_writer.DrawBlob(
|
||||
blob, cx, cy,
|
||||
cos * sx, -sin * sy,
|
||||
sin * sx, cos * sy,
|
||||
0f, 0f,
|
||||
color.R, color.G, color.B, color.A,
|
||||
stemDarken: false, clipMinPacked, clipMaxPacked);
|
||||
}
|
||||
|
||||
public void DrawCircleFilled(float cx, float cy, float radiusPx, Color color,
|
||||
uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped)
|
||||
{
|
||||
CachedBlob blob = HbGpuVectorShapes.GetUnitFilledCircle(_blobCache);
|
||||
float s = radiusPx * 0.002f;
|
||||
_writer.DrawBlob(
|
||||
blob, cx, cy,
|
||||
s, 0f, 0f, -s,
|
||||
0f, 0f,
|
||||
color.R, color.G, color.B, color.A,
|
||||
stemDarken: false, clipMinPacked, clipMaxPacked);
|
||||
}
|
||||
|
||||
public void DrawCircleRing(float cx, float cy, float radiusPx, float strokePx, Color color,
|
||||
uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped)
|
||||
{
|
||||
if (radiusPx <= 0f || strokePx <= 0f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ushort strokeUnits = (ushort)Math.Clamp((int)MathF.Round(strokePx / radiusPx * 500f), 2, 480);
|
||||
CachedBlob blob = HbGpuVectorShapes.GetUnitRingStroke(_blobCache, strokeUnits);
|
||||
float s = radiusPx * 0.002f;
|
||||
_writer.DrawBlob(
|
||||
blob, cx, cy,
|
||||
s, 0f, 0f, -s,
|
||||
0f, 0f,
|
||||
color.R, color.G, color.B, color.A,
|
||||
stemDarken: false, clipMinPacked, clipMaxPacked);
|
||||
}
|
||||
|
||||
public void DrawTargetBracketCorner(float cornerX, float cornerY, float armPx, float thicknessPx, int quadrant, Color color)
|
||||
{
|
||||
if (armPx <= 0f || thicknessPx <= 0f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ushort thickUnits = (ushort)Math.Clamp((int)MathF.Round(thicknessPx / armPx * 1000f), 10, 450);
|
||||
CachedBlob blob = HbGpuVectorShapes.GetTargetBracketCorner(_blobCache, thickUnits);
|
||||
float s = armPx * 0.001f;
|
||||
// Design space: corner at (0,0), X in [0..1000], Y in [-1000..0] (so -emY points down in screen if m11 = -s -> +s).
|
||||
// Rotate per quadrant: 0=top-left (+X,+Y), 1=top-right (-X,+Y), 2=bottom-right (-X,-Y), 3=bottom-left (+X,-Y)
|
||||
float sx = (quadrant == 1 || quadrant == 2) ? -s : s;
|
||||
float sy = (quadrant == 2 || quadrant == 3) ? s : -s;
|
||||
_writer.DrawBlob(
|
||||
blob, cornerX, cornerY,
|
||||
sx, 0f, 0f, sy,
|
||||
0f, 0f,
|
||||
color.R, color.G, color.B, color.A);
|
||||
}
|
||||
|
||||
public void DrawDirectionalArrow(float cx, float cy, float sizePx, float angleRad, Color color)
|
||||
{
|
||||
CachedBlob blob = HbGpuVectorShapes.GetDirectionalArrow(_blobCache);
|
||||
float s = sizePx * 0.001f;
|
||||
float cos = MathF.Cos(angleRad);
|
||||
float sin = MathF.Sin(angleRad);
|
||||
// Angle 0 points right (+X) in screen space; design arrow points +Y, so rotate by angleRad - PI/2 with Y flip
|
||||
// Design (0, +500) -> screen (+cos, +sin) * sizePx * 0.5
|
||||
_writer.DrawBlob(
|
||||
blob, cx, cy,
|
||||
-sin * s, cos * s,
|
||||
cos * s, sin * s,
|
||||
0f, 0f,
|
||||
color.R, color.G, color.B, color.A);
|
||||
}
|
||||
|
||||
public void DrawArcStrokeDynamic(float cx, float cy, float radiusPx, float strokePx, float startRadScreen, float endRadScreen, Color color)
|
||||
{
|
||||
if (radiusPx <= 0f || strokePx <= 0f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
float halfThickDesign = Math.Clamp(strokePx / radiusPx * 250f, 2f, 200f);
|
||||
// Screen Y-down angles -> design Y-up angles (negate angles so screen clockwise matches -design angle)
|
||||
CachedBlob blob = HbGpuVectorShapes.EncodeArcStrokeDynamic(_blobCache, -endRadScreen, -startRadScreen, 500f, halfThickDesign);
|
||||
float s = radiusPx * 0.002f;
|
||||
_writer.DrawBlob(
|
||||
blob, cx, cy,
|
||||
s, 0f, 0f, -s,
|
||||
0f, 0f,
|
||||
color.R, color.G, color.B, color.A);
|
||||
}
|
||||
|
||||
public void EndFrameAndSubmit()
|
||||
{
|
||||
LastQuadCount = _writer.QuadCount;
|
||||
|
||||
if (_backend is null || _disposed)
|
||||
{
|
||||
_atlas.ClearPending();
|
||||
return;
|
||||
}
|
||||
|
||||
ComputeViewportSizes(out float logicalW, out float logicalH, out int physW, out int physH);
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
int count = _writer.QuadCount;
|
||||
if (count > 0)
|
||||
{
|
||||
Array.Copy(_writer.RawBuffer, 0, _stagedQuads, 0, count);
|
||||
}
|
||||
_stagedQuadCount = count;
|
||||
_stagedLogicalW = logicalW;
|
||||
_stagedLogicalH = logicalH;
|
||||
_stagedPhysW = physW;
|
||||
_stagedPhysH = physH;
|
||||
_hasStagedFrame = true;
|
||||
_backend.ProfilingEnabled = ProfilingEnabled;
|
||||
}
|
||||
|
||||
RenderingServer.CallOnRenderThread(_renderCallable);
|
||||
}
|
||||
|
||||
private void ComputeViewportSizes(out float logicalW, out float logicalH, out int physW, out int physH)
|
||||
{
|
||||
Viewport? vp = GetViewport();
|
||||
if (vp is null)
|
||||
{
|
||||
logicalW = MathF.Max(2f, Size.X);
|
||||
logicalH = MathF.Max(2f, Size.Y);
|
||||
physW = Math.Max(2, Mathf.RoundToInt(logicalW));
|
||||
physH = Math.Max(2, Mathf.RoundToInt(logicalH));
|
||||
return;
|
||||
}
|
||||
|
||||
Vector2 vis = vp.GetVisibleRect().Size;
|
||||
if (vis.X < 2f || vis.Y < 2f)
|
||||
{
|
||||
vis = Size;
|
||||
}
|
||||
|
||||
logicalW = MathF.Max(2f, vis.X);
|
||||
logicalH = MathF.Max(2f, vis.Y);
|
||||
|
||||
if (vp is SubViewport sv)
|
||||
{
|
||||
physW = Math.Max(2, sv.Size.X);
|
||||
physH = Math.Max(2, sv.Size.Y);
|
||||
}
|
||||
else
|
||||
{
|
||||
Vector2 stretchScale = vp.GetStretchTransform().Scale;
|
||||
physW = Math.Max(2, Mathf.RoundToInt(logicalW * stretchScale.X));
|
||||
physH = Math.Max(2, Mathf.RoundToInt(logicalH * stretchScale.Y));
|
||||
}
|
||||
}
|
||||
|
||||
private void RenderOnRenderThread()
|
||||
{
|
||||
if (_backend is null || _disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int quadCount;
|
||||
float logicalW, logicalH;
|
||||
int physW, physH;
|
||||
lock (_syncLock)
|
||||
{
|
||||
if (!_hasStagedFrame)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_hasStagedFrame = false;
|
||||
quadCount = _stagedQuadCount;
|
||||
logicalW = _stagedLogicalW;
|
||||
logicalH = _stagedLogicalH;
|
||||
physW = _stagedPhysW;
|
||||
physH = _stagedPhysH;
|
||||
_backend.RenderFrame(_stagedQuads, quadCount, logicalW, logicalH, physW, physH);
|
||||
}
|
||||
}
|
||||
|
||||
private void DisposeOnRenderThread()
|
||||
{
|
||||
_backend?.DisposeRdResources();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Synchronously reads back the current offscreen RGBA8 render target from RenderingDevice.
|
||||
/// Intended strictly for verification probes/tests.
|
||||
/// </summary>
|
||||
public bool TryReadbackRgba8(out byte[] data, out int width, out int height)
|
||||
{
|
||||
byte[]? captured = null;
|
||||
int w = 0, h = 0;
|
||||
|
||||
if (_backend is null || RenderingServer.GetRenderingDevice() is null)
|
||||
{
|
||||
data = Array.Empty<byte>();
|
||||
width = 0;
|
||||
height = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
RenderingServer.CallOnRenderThread(Callable.From(() =>
|
||||
{
|
||||
_backend.TryReadbackOnRenderThread(out captured, out w, out h);
|
||||
}));
|
||||
RenderingServer.ForceSync();
|
||||
|
||||
if (captured is null || w <= 0 || h <= 0)
|
||||
{
|
||||
data = Array.Empty<byte>();
|
||||
width = 0;
|
||||
height = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
data = captured;
|
||||
width = w;
|
||||
height = h;
|
||||
return true;
|
||||
}
|
||||
|
||||
public override void _ExitTree()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_disposed = true;
|
||||
|
||||
if (_outputTexRd is not null)
|
||||
{
|
||||
_outputTexRd.TextureRdRid = new Rid();
|
||||
}
|
||||
|
||||
if (_backend is not null && RenderingServer.GetRenderingDevice() is not null)
|
||||
{
|
||||
RenderingServer.CallOnRenderThread(_disposeCallable);
|
||||
RenderingServer.ForceSync();
|
||||
}
|
||||
|
||||
_fontCache.Dispose();
|
||||
}
|
||||
|
||||
private sealed class HbGpuVulkanBackend
|
||||
{
|
||||
private readonly Texture2Drd _outputTexRd;
|
||||
private readonly HbGpuAtlasAllocator _atlas;
|
||||
|
||||
private readonly byte[] _atlasMirrorBytes = new byte[HbGpuAtlasAllocator.TotalBytes];
|
||||
private readonly byte[] _quadUploadBytes = new byte[HbGpuCommandWriter.MaxQuads * 80];
|
||||
private readonly byte[] _pushConstantBytes = new byte[PushConstantBytes];
|
||||
private static readonly Color[] ClearColors = { new Color(0f, 0f, 0f, 0f) };
|
||||
|
||||
private RenderingDevice? _rd;
|
||||
private bool _initialized;
|
||||
private bool _failed;
|
||||
|
||||
private Rid _shaderRid;
|
||||
private Rid _pipelineRid;
|
||||
private Rid _atlasBufRid;
|
||||
private Rid _quadSsboRid;
|
||||
private Rid _uniformSetRid;
|
||||
private Rid _colorTexRid;
|
||||
private Rid _framebufferRid;
|
||||
private int _fbWidth;
|
||||
private int _fbHeight;
|
||||
|
||||
private ulong _frameIndex;
|
||||
private ulong _lastSampledTimestampFrame = ulong.MaxValue;
|
||||
|
||||
public bool ProfilingEnabled { get; set; }
|
||||
public double LastHbGpuMs { get; private set; }
|
||||
public int LastDrawCallCount { get; private set; }
|
||||
|
||||
public HbGpuVulkanBackend(Texture2Drd outputTexRd, HbGpuAtlasAllocator atlas)
|
||||
{
|
||||
_outputTexRd = outputTexRd;
|
||||
_atlas = atlas;
|
||||
}
|
||||
|
||||
public void RenderFrame(
|
||||
HbGpuQuadInstance[] quads,
|
||||
int quadCount,
|
||||
float logicalW,
|
||||
float logicalH,
|
||||
int physW,
|
||||
int physH)
|
||||
{
|
||||
if (_failed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
RenderingDevice? rd = RenderingServer.GetRenderingDevice();
|
||||
if (rd is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
bool atlasDirty = _atlas.PendingChunkCount > 0;
|
||||
if (atlasDirty)
|
||||
{
|
||||
_atlas.DrainToMirror(_atlasMirrorBytes);
|
||||
}
|
||||
|
||||
if (!_initialized)
|
||||
{
|
||||
if (!TryInitialize(rd, physW, physH))
|
||||
{
|
||||
_failed = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (atlasDirty)
|
||||
{
|
||||
RebuildAtlasBufferAndUniformSet(rd);
|
||||
}
|
||||
if (physW != _fbWidth || physH != _fbHeight)
|
||||
{
|
||||
RecreateRenderTarget(rd, physW, physH);
|
||||
}
|
||||
}
|
||||
|
||||
_rd = rd;
|
||||
_frameIndex++;
|
||||
|
||||
// Upload quad instances into SSBO
|
||||
if (quadCount > 0)
|
||||
{
|
||||
uint byteLen = (uint)(quadCount * 80);
|
||||
ReadOnlySpan<byte> srcBytes = MemoryMarshal.AsBytes(quads.AsSpan(0, quadCount));
|
||||
srcBytes.CopyTo(_quadUploadBytes);
|
||||
rd.BufferUpdate(_quadSsboRid, 0, byteLen, _quadUploadBytes);
|
||||
}
|
||||
|
||||
bool captureTs = ProfilingEnabled && rd.GetCapturedTimestampsCount() < 180;
|
||||
if (ProfilingEnabled)
|
||||
{
|
||||
SamplePreviousTimestamps(rd);
|
||||
}
|
||||
if (captureTs)
|
||||
{
|
||||
rd.CaptureTimestamp("HbGpu_Start");
|
||||
}
|
||||
|
||||
long dl = rd.DrawListBegin(_framebufferRid, RenderingDevice.DrawFlags.ClearColorAll, ClearColors);
|
||||
if (quadCount > 0)
|
||||
{
|
||||
var pc = new PushConstants
|
||||
{
|
||||
C0R0 = 2.0f / logicalW,
|
||||
C1R1 = 2.0f / logicalH,
|
||||
C2R2 = 1.0f,
|
||||
C3R0 = -1.0f,
|
||||
C3R1 = -1.0f,
|
||||
C3R3 = 1.0f,
|
||||
ViewportX = physW,
|
||||
ViewportY = physH,
|
||||
LogicalW = logicalW,
|
||||
LogicalH = logicalH
|
||||
};
|
||||
MemoryMarshal.Write(_pushConstantBytes, in pc);
|
||||
|
||||
rd.DrawListBindRenderPipeline(dl, _pipelineRid);
|
||||
rd.DrawListBindUniformSet(dl, _uniformSetRid, 0);
|
||||
rd.DrawListSetPushConstant(dl, _pushConstantBytes, PushConstantBytes);
|
||||
rd.DrawListDraw(dl, useIndices: false, instances: (uint)quadCount, proceduralVertexCount: 6u);
|
||||
LastDrawCallCount = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
LastDrawCallCount = 0;
|
||||
}
|
||||
rd.DrawListEnd();
|
||||
|
||||
if (captureTs)
|
||||
{
|
||||
rd.CaptureTimestamp("HbGpu_End");
|
||||
}
|
||||
}
|
||||
|
||||
private void RebuildAtlasBufferAndUniformSet(RenderingDevice rd)
|
||||
{
|
||||
if (_uniformSetRid.IsValid)
|
||||
{
|
||||
rd.FreeRid(_uniformSetRid);
|
||||
_uniformSetRid = new Rid();
|
||||
}
|
||||
if (_atlasBufRid.IsValid)
|
||||
{
|
||||
rd.FreeRid(_atlasBufRid);
|
||||
_atlasBufRid = new Rid();
|
||||
}
|
||||
|
||||
_atlasBufRid = rd.TextureBufferCreate(
|
||||
HbGpuAtlasAllocator.TotalTexels,
|
||||
RenderingDevice.DataFormat.R16G16B16A16Sint,
|
||||
_atlasMirrorBytes);
|
||||
|
||||
var u0 = new RDUniform
|
||||
{
|
||||
UniformType = RenderingDevice.UniformType.TextureBuffer,
|
||||
Binding = 0
|
||||
};
|
||||
u0.AddId(_atlasBufRid);
|
||||
|
||||
var u1 = new RDUniform
|
||||
{
|
||||
UniformType = RenderingDevice.UniformType.StorageBuffer,
|
||||
Binding = 1
|
||||
};
|
||||
u1.AddId(_quadSsboRid);
|
||||
|
||||
_uniformSetRid = rd.UniformSetCreate(new Godot.Collections.Array<RDUniform> { u0, u1 }, _shaderRid, 0);
|
||||
}
|
||||
|
||||
private void SamplePreviousTimestamps(RenderingDevice rd)
|
||||
{
|
||||
uint count = rd.GetCapturedTimestampsCount();
|
||||
if (count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ulong tsFrame = rd.GetCapturedTimestampsFrame();
|
||||
if (tsFrame == _lastSampledTimestampFrame)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_lastSampledTimestampFrame = tsFrame;
|
||||
|
||||
ulong tStart = 0, tEnd = 0;
|
||||
for (uint i = 0; i < count; i++)
|
||||
{
|
||||
string name = rd.GetCapturedTimestampName(i);
|
||||
if (name == "HbGpu_Start")
|
||||
{
|
||||
tStart = rd.GetCapturedTimestampGpuTime(i);
|
||||
}
|
||||
else if (name == "HbGpu_End")
|
||||
{
|
||||
tEnd = rd.GetCapturedTimestampGpuTime(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (tStart > 0 && tEnd >= tStart)
|
||||
{
|
||||
LastHbGpuMs = (tEnd - tStart) / 1_000_000.0;
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryInitialize(RenderingDevice rd, int physW, int physH)
|
||||
{
|
||||
_rd = rd;
|
||||
|
||||
string vertSrc = BuildVertexShaderSource();
|
||||
string fragSrc = BuildFragmentShaderSource();
|
||||
|
||||
using var rdSrc = new RDShaderSource
|
||||
{
|
||||
Language = RenderingDevice.ShaderLanguage.Glsl,
|
||||
SourceVertex = vertSrc,
|
||||
SourceFragment = fragSrc
|
||||
};
|
||||
|
||||
using RDShaderSpirV spirv = rd.ShaderCompileSpirVFromSource(rdSrc, allowCache: true);
|
||||
if (!string.IsNullOrEmpty(spirv.CompileErrorVertex))
|
||||
{
|
||||
GD.PrintErr($"HbGpuCanvas vertex SPIR-V error: {spirv.CompileErrorVertex}");
|
||||
return false;
|
||||
}
|
||||
if (!string.IsNullOrEmpty(spirv.CompileErrorFragment))
|
||||
{
|
||||
GD.PrintErr($"HbGpuCanvas fragment SPIR-V error: {spirv.CompileErrorFragment}");
|
||||
return false;
|
||||
}
|
||||
|
||||
_shaderRid = rd.ShaderCreateFromSpirV(spirv, "HbGpuCanvas");
|
||||
if (!_shaderRid.IsValid)
|
||||
{
|
||||
GD.PrintErr("HbGpuCanvas: ShaderCreateFromSpirV failed.");
|
||||
return false;
|
||||
}
|
||||
|
||||
_quadSsboRid = rd.StorageBufferCreate((uint)(HbGpuCommandWriter.MaxQuads * 80));
|
||||
RebuildAtlasBufferAndUniformSet(rd);
|
||||
|
||||
RecreateRenderTarget(rd, physW, physH);
|
||||
|
||||
long fbFormat = rd.FramebufferGetFormat(_framebufferRid);
|
||||
|
||||
var rasterState = new RDPipelineRasterizationState
|
||||
{
|
||||
CullMode = RenderingDevice.PolygonCullMode.Disabled
|
||||
};
|
||||
var msState = new RDPipelineMultisampleState
|
||||
{
|
||||
SampleCount = RenderingDevice.TextureSamples.Samples1
|
||||
};
|
||||
var dsState = new RDPipelineDepthStencilState();
|
||||
var blendAttachment = new RDPipelineColorBlendStateAttachment
|
||||
{
|
||||
EnableBlend = true,
|
||||
SrcColorBlendFactor = RenderingDevice.BlendFactor.One,
|
||||
DstColorBlendFactor = RenderingDevice.BlendFactor.OneMinusSrcAlpha,
|
||||
ColorBlendOp = RenderingDevice.BlendOperation.Add,
|
||||
SrcAlphaBlendFactor = RenderingDevice.BlendFactor.One,
|
||||
DstAlphaBlendFactor = RenderingDevice.BlendFactor.OneMinusSrcAlpha,
|
||||
AlphaBlendOp = RenderingDevice.BlendOperation.Add
|
||||
};
|
||||
var blendState = new RDPipelineColorBlendState();
|
||||
blendState.Attachments.Add(blendAttachment);
|
||||
|
||||
_pipelineRid = rd.RenderPipelineCreate(
|
||||
_shaderRid,
|
||||
fbFormat,
|
||||
RenderingDevice.InvalidFormatId,
|
||||
RenderingDevice.RenderPrimitive.Triangles,
|
||||
rasterState,
|
||||
msState,
|
||||
dsState,
|
||||
blendState);
|
||||
|
||||
if (!_pipelineRid.IsValid)
|
||||
{
|
||||
GD.PrintErr("HbGpuCanvas: RenderPipelineCreate failed.");
|
||||
return false;
|
||||
}
|
||||
|
||||
_initialized = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void RecreateRenderTarget(RenderingDevice rd, int physW, int physH)
|
||||
{
|
||||
if (_framebufferRid.IsValid)
|
||||
{
|
||||
rd.FreeRid(_framebufferRid);
|
||||
_framebufferRid = new Rid();
|
||||
}
|
||||
if (_colorTexRid.IsValid)
|
||||
{
|
||||
_outputTexRd.TextureRdRid = new Rid();
|
||||
rd.FreeRid(_colorTexRid);
|
||||
_colorTexRid = new Rid();
|
||||
}
|
||||
|
||||
var fmt = new RDTextureFormat
|
||||
{
|
||||
TextureType = RenderingDevice.TextureType.Type2D,
|
||||
Format = RenderingDevice.DataFormat.R8G8B8A8Unorm,
|
||||
Width = (uint)physW,
|
||||
Height = (uint)physH,
|
||||
Depth = 1,
|
||||
ArrayLayers = 1,
|
||||
Mipmaps = 1,
|
||||
Samples = RenderingDevice.TextureSamples.Samples1,
|
||||
UsageBits = RenderingDevice.TextureUsageBits.ColorAttachmentBit
|
||||
| RenderingDevice.TextureUsageBits.SamplingBit
|
||||
| RenderingDevice.TextureUsageBits.CanCopyFromBit
|
||||
};
|
||||
_colorTexRid = rd.TextureCreate(fmt, new RDTextureView());
|
||||
_framebufferRid = rd.FramebufferCreate(new Godot.Collections.Array<Rid> { _colorTexRid });
|
||||
_fbWidth = physW;
|
||||
_fbHeight = physH;
|
||||
_outputTexRd.TextureRdRid = _colorTexRid;
|
||||
}
|
||||
|
||||
public void TryReadbackOnRenderThread(out byte[]? data, out int width, out int height)
|
||||
{
|
||||
if (_rd is null || !_initialized || !_colorTexRid.IsValid)
|
||||
{
|
||||
data = null;
|
||||
width = 0;
|
||||
height = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
data = _rd.TextureGetData(_colorTexRid, 0);
|
||||
width = _fbWidth;
|
||||
height = _fbHeight;
|
||||
}
|
||||
|
||||
public void DisposeRdResources()
|
||||
{
|
||||
if (_rd is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_outputTexRd.TextureRdRid = new Rid();
|
||||
|
||||
if (_framebufferRid.IsValid) { _rd.FreeRid(_framebufferRid); _framebufferRid = new Rid(); }
|
||||
if (_colorTexRid.IsValid) { _rd.FreeRid(_colorTexRid); _colorTexRid = new Rid(); }
|
||||
if (_uniformSetRid.IsValid) { _rd.FreeRid(_uniformSetRid); _uniformSetRid = new Rid(); }
|
||||
if (_quadSsboRid.IsValid) { _rd.FreeRid(_quadSsboRid); _quadSsboRid = new Rid(); }
|
||||
if (_atlasBufRid.IsValid) { _rd.FreeRid(_atlasBufRid); _atlasBufRid = new Rid(); }
|
||||
if (_pipelineRid.IsValid) { _rd.FreeRid(_pipelineRid); _pipelineRid = new Rid(); }
|
||||
if (_shaderRid.IsValid) { _rd.FreeRid(_shaderRid); _shaderRid = new Rid(); }
|
||||
|
||||
_initialized = false;
|
||||
_rd = null;
|
||||
}
|
||||
|
||||
private static string BuildVertexShaderSource()
|
||||
{
|
||||
string sharedVert = HbGpuNative.GetShaderSource(HbGpuShaderStage.Vertex, HbGpuShaderKind.Shared);
|
||||
return $@"#version 450
|
||||
{sharedVert}
|
||||
|
||||
struct QuadInstance {{
|
||||
vec4 em_box;
|
||||
vec4 pos_anchor;
|
||||
vec4 xform;
|
||||
vec4 color;
|
||||
uvec4 meta;
|
||||
}};
|
||||
|
||||
layout(set = 0, binding = 1, std430) readonly buffer Quads {{
|
||||
QuadInstance quads[];
|
||||
}};
|
||||
|
||||
layout(push_constant, std430) uniform Push {{
|
||||
mat4 u_mvp;
|
||||
vec2 u_viewport;
|
||||
vec2 u_logicalSize;
|
||||
}} pc;
|
||||
|
||||
layout(location = 0) out vec2 v_em;
|
||||
layout(location = 1) out vec4 v_color;
|
||||
layout(location = 2) flat out uint v_blob_loc;
|
||||
layout(location = 3) flat out uint v_flags;
|
||||
layout(location = 4) flat out uvec2 v_clip_packed;
|
||||
|
||||
void main() {{
|
||||
QuadInstance q = quads[gl_InstanceIndex];
|
||||
const uint idxMap[6] = uint[6](0u, 1u, 2u, 0u, 2u, 3u);
|
||||
uint c = idxMap[gl_VertexIndex];
|
||||
vec2 uv = vec2((c == 1u || c == 2u) ? 1.0 : 0.0, (c >= 2u) ? 1.0 : 0.0);
|
||||
vec2 em = mix(q.em_box.xy, q.em_box.zw, uv);
|
||||
vec2 emSgn = uv * 2.0 - 1.0;
|
||||
|
||||
vec2 dEm = em - q.pos_anchor.xy;
|
||||
float m00 = q.xform.x;
|
||||
float m01 = q.xform.y;
|
||||
float m10 = q.xform.z;
|
||||
float m11 = q.xform.w;
|
||||
vec2 pos = q.pos_anchor.zw + vec2(m00 * dEm.x + m01 * dEm.y, m10 * dEm.x + m11 * dEm.y);
|
||||
|
||||
vec2 ax = vec2(m00, m10);
|
||||
vec2 ay = vec2(m01, m11);
|
||||
float lx = length(ax);
|
||||
float ly = length(ay);
|
||||
vec2 axisX = lx > 1e-8 ? ax / lx : vec2(1.0, 0.0);
|
||||
vec2 axisY = ly > 1e-8 ? ay / ly : vec2(0.0, 1.0);
|
||||
vec2 normal = axisX * emSgn.x + axisY * emSgn.y;
|
||||
|
||||
float det = m00 * m11 - m01 * m10;
|
||||
float invDet = abs(det) > 1e-12 ? (1.0 / det) : 0.0;
|
||||
vec4 jac = vec4(m11, -m01, -m10, m00) * invDet;
|
||||
|
||||
hb_gpu_dilate(pos, em, normal, jac, pc.u_mvp, pc.u_viewport);
|
||||
|
||||
gl_Position = pc.u_mvp * vec4(pos, 0.0, 1.0);
|
||||
v_em = em;
|
||||
v_color = q.color;
|
||||
v_blob_loc = q.meta.x;
|
||||
v_flags = q.meta.y;
|
||||
v_clip_packed = q.meta.zw;
|
||||
}}
|
||||
";
|
||||
}
|
||||
|
||||
private static string BuildFragmentShaderSource()
|
||||
{
|
||||
string sharedFrag = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Shared);
|
||||
string drawFrag = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Draw);
|
||||
return $@"#version 450
|
||||
#define uniform layout(set = 0, binding = 0) uniform
|
||||
{sharedFrag}
|
||||
#undef uniform
|
||||
{drawFrag}
|
||||
|
||||
layout(push_constant, std430) uniform Push {{
|
||||
mat4 u_mvp;
|
||||
vec2 u_viewport;
|
||||
vec2 u_logicalSize;
|
||||
}} pc;
|
||||
|
||||
layout(location = 0) in vec2 v_em;
|
||||
layout(location = 1) in vec4 v_color;
|
||||
layout(location = 2) flat in uint v_blob_loc;
|
||||
layout(location = 3) flat in uint v_flags;
|
||||
layout(location = 4) flat in uvec2 v_clip_packed;
|
||||
|
||||
layout(location = 0) out vec4 frag_color;
|
||||
|
||||
void main() {{
|
||||
float cov = hb_gpu_draw(v_em, v_blob_loc);
|
||||
float ppem = hb_gpu_ppem(v_em, v_blob_loc);
|
||||
|
||||
if ((v_flags & 1u) != 0u && cov > 0.0 && cov < 1.0) {{
|
||||
float brightness = dot(v_color.rgb, vec3(1.0 / 3.0));
|
||||
cov = hb_gpu_stem_darken(cov, brightness, ppem);
|
||||
}}
|
||||
|
||||
if (v_clip_packed.y != 0xFFFFFFFFu) {{
|
||||
vec2 logicalPos = gl_FragCoord.xy * (pc.u_logicalSize / pc.u_viewport);
|
||||
vec2 cMin = vec2(float(v_clip_packed.x & 0xFFFFu), float(v_clip_packed.x >> 16u));
|
||||
vec2 cMax = vec2(float(v_clip_packed.y & 0xFFFFu), float(v_clip_packed.y >> 16u));
|
||||
if (logicalPos.x < cMin.x || logicalPos.y < cMin.y || logicalPos.x > cMax.x || logicalPos.y > cMax.y) {{
|
||||
cov = 0.0;
|
||||
}}
|
||||
}}
|
||||
|
||||
float a = clamp(v_color.a * cov, 0.0, 1.0);
|
||||
frag_color = vec4(v_color.rgb * a, a);
|
||||
}}
|
||||
";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -4,28 +4,41 @@ using System.Reflection;
|
|||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using Godot;
|
||||
using RustToDust.HbGpu;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace RustToDust.Client;
|
||||
|
||||
/// <summary>
|
||||
/// Finds ymir_box3d for Ymir.Box3D's DllImports. Godot loads game assemblies into its own load context, so the
|
||||
/// default probing does not look beside them. A run from the editor or <c>--path</c> loads the library from the
|
||||
/// project's build directory; an exported run from the data folder Godot puts beside the executable.
|
||||
/// Resolves native libraries (ymir_box3d, rtd_hbgpu) for Godot's AssemblyLoadContext.
|
||||
/// </summary>
|
||||
internal static class NativeLibraries
|
||||
{
|
||||
private const string Library = "ymir_box3d";
|
||||
private const string YmirLibrary = "ymir_box3d";
|
||||
private const string HbGpuLibrary = "rtd_hbgpu";
|
||||
|
||||
#pragma warning disable CA2255 // application code: the resolver must exist before the first DllImport
|
||||
[ModuleInitializer]
|
||||
internal static void Register() =>
|
||||
internal static void Register()
|
||||
{
|
||||
NativeLibrary.SetDllImportResolver(typeof(Box3DSoaWorld).Assembly, Resolve);
|
||||
NativeLibrary.SetDllImportResolver(typeof(HbGpuNative).Assembly, Resolve);
|
||||
}
|
||||
|
||||
private static IntPtr Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath)
|
||||
{
|
||||
if (name != Library) return IntPtr.Zero;
|
||||
string fileName = FileName();
|
||||
string? stem = name switch
|
||||
{
|
||||
YmirLibrary => YmirLibrary,
|
||||
HbGpuLibrary => HbGpuLibrary,
|
||||
_ => null
|
||||
};
|
||||
if (stem is null)
|
||||
{
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
string fileName = FileName(stem);
|
||||
|
||||
if (OS.HasFeature("template"))
|
||||
{
|
||||
|
|
@ -65,8 +78,8 @@ internal static class NativeLibraries
|
|||
: IntPtr.Zero;
|
||||
}
|
||||
|
||||
private static string FileName() =>
|
||||
OperatingSystem.IsWindows() ? "ymir_box3d.dll" : OperatingSystem.IsMacOS() ? "libymir_box3d.dylib" : "libymir_box3d.so";
|
||||
private static string FileName(string stem) =>
|
||||
OperatingSystem.IsWindows() ? $"{stem}.dll" : OperatingSystem.IsMacOS() ? $"lib{stem}.dylib" : $"lib{stem}.so";
|
||||
|
||||
private static string Platform() =>
|
||||
OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linuxbsd";
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@
|
|||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\src\RustToDust.Ymir\RustToDust.Ymir.csproj" />
|
||||
<ProjectReference Include="..\src\RustToDust.HbGpu\RustToDust.HbGpu.csproj" AdditionalProperties="HbGpuNativeConfiguration=$(YmirNativeConfiguration)" />
|
||||
<ProjectReference Include="..\src\RustToDust.Net\RustToDust.Net.csproj" />
|
||||
<ProjectReference Include="$(YmirRoot)/src/Ymir.Box3D/Ymir.Box3D.csproj" AdditionalProperties="YmirNativeConfiguration=$(YmirNativeConfiguration)" />
|
||||
</ItemGroup>
|
||||
|
|
|
|||
233
client/tests/HbGpuProbe.cs
Normal file
233
client/tests/HbGpuProbe.cs
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Godot;
|
||||
using RustToDust.HbGpu;
|
||||
|
||||
namespace RustToDust.Client.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Cut 14a visual & headless verification probe for HbGpuCanvas (1 Vulkan draw call).
|
||||
/// Run headless: Godot --headless --audio-driver Dummy --path client res://tests/HbGpuProbe.tscn
|
||||
/// Run Vulkan: Godot --audio-driver Dummy --windowed --path client res://tests/HbGpuProbe.tscn -- --capture-proof=path.png
|
||||
/// </summary>
|
||||
public partial class HbGpuProbe : Control
|
||||
{
|
||||
private HbGpuCanvas _canvas = null!;
|
||||
private bool _done;
|
||||
private int _frameCount;
|
||||
private string? _capturePath;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
foreach (string arg in OS.GetCmdlineUserArgs())
|
||||
{
|
||||
if (arg.StartsWith("--capture-proof=", StringComparison.Ordinal))
|
||||
{
|
||||
_capturePath = arg["--capture-proof=".Length..];
|
||||
}
|
||||
}
|
||||
_capturePath ??= System.Environment.GetEnvironmentVariable("RTD_HBGPU_PROOF_PNG");
|
||||
|
||||
var bg = new ColorRect
|
||||
{
|
||||
Color = new Color(0.05f, 0.065f, 0.085f, 1.0f),
|
||||
MouseFilter = MouseFilterEnum.Ignore
|
||||
};
|
||||
AddChild(bg);
|
||||
bg.SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
|
||||
|
||||
_canvas = new HbGpuCanvas
|
||||
{
|
||||
Name = "HbGpuCanvas",
|
||||
ProfilingEnabled = true
|
||||
};
|
||||
AddChild(_canvas);
|
||||
_canvas.SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
|
||||
|
||||
_ = RunVerificationAsync();
|
||||
}
|
||||
|
||||
private async Task RunVerificationAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Render enough frames to warm Vulkan pipeline & collect RD GPU timestamps
|
||||
int targetFrames = _canvas.IsVulkanActive ? 24 : 3;
|
||||
for (int i = 0; i < targetFrames; i++)
|
||||
{
|
||||
SubmitShowcaseFrame(i);
|
||||
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
|
||||
_frameCount++;
|
||||
}
|
||||
|
||||
if (_canvas.LastQuadCount <= 0)
|
||||
{
|
||||
Fail("Expected LastQuadCount > 0 after submitting HbGpu showcase frame.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_canvas.IsVulkanActive)
|
||||
{
|
||||
GD.Print($"HBGPU_PROBE PASS (headless null-RD): quads={_canvas.LastQuadCount}, frames={_frameCount}");
|
||||
Finish(0);
|
||||
return;
|
||||
}
|
||||
|
||||
if (_canvas.LastDrawCallCount != 1)
|
||||
{
|
||||
Fail($"Expected LastDrawCallCount == 1 on Vulkan, got {_canvas.LastDrawCallCount}.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_canvas.TryReadbackRgba8(out byte[] rgba, out int w, out int h))
|
||||
{
|
||||
Fail("HbGpuCanvas.TryReadbackRgba8 returned false on active Vulkan device.");
|
||||
return;
|
||||
}
|
||||
|
||||
int nonZero = 0;
|
||||
int premulViolations = 0;
|
||||
for (int i = 0; i + 3 < rgba.Length; i += 4)
|
||||
{
|
||||
byte r = rgba[i];
|
||||
byte g = rgba[i + 1];
|
||||
byte b = rgba[i + 2];
|
||||
byte a = rgba[i + 3];
|
||||
if (a > 0)
|
||||
{
|
||||
nonZero++;
|
||||
}
|
||||
if (r > a || g > a || b > a)
|
||||
{
|
||||
premulViolations++;
|
||||
}
|
||||
}
|
||||
|
||||
if (nonZero < 1500)
|
||||
{
|
||||
Fail($"Expected >= 1500 rendered pixels in HbGpu Texture2Drd, got {nonZero} ({w}x{h}).");
|
||||
return;
|
||||
}
|
||||
|
||||
if (premulViolations != 0)
|
||||
{
|
||||
Fail($"Premultiplied alpha invariant violated on {premulViolations} pixels.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(_capturePath))
|
||||
{
|
||||
SubmitShowcaseFrame(_frameCount);
|
||||
await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
Image? vpImg = GetViewport().GetTexture()?.GetImage();
|
||||
if (vpImg is null)
|
||||
{
|
||||
Fail("Viewport capture returned null Image.");
|
||||
return;
|
||||
}
|
||||
string? dir = Path.GetDirectoryName(_capturePath);
|
||||
if (!string.IsNullOrEmpty(dir))
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
Error saveErr = vpImg.SavePng(_capturePath);
|
||||
if (saveErr != Error.Ok)
|
||||
{
|
||||
Fail($"Failed to save proof PNG '{_capturePath}': {saveErr}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
GD.Print(
|
||||
$"HBGPU_PROBE PASS (Vulkan): size={w}x{h}, quads={_canvas.LastQuadCount}, " +
|
||||
$"draw_calls={_canvas.LastDrawCallCount}, gpu_ms={_canvas.LastHbGpuMs:F4}, " +
|
||||
$"non_zero_px={nonZero}, premul_violations={premulViolations}");
|
||||
Finish(0);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Fail(ex.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
private void SubmitShowcaseFrame(int frameIndex)
|
||||
{
|
||||
Color amber = new(0.95f, 0.72f, 0.22f, 1.0f);
|
||||
Color cyan = new(0.32f, 0.86f, 0.96f, 1.0f);
|
||||
Color slate = new(0.78f, 0.84f, 0.90f, 1.0f);
|
||||
Color panelBg = new(0.06f, 0.09f, 0.12f, 0.78f);
|
||||
Color alert = new(0.96f, 0.28f, 0.22f, 1.0f);
|
||||
Color emerald = new(0.28f, 0.90f, 0.56f, 1.0f);
|
||||
|
||||
_canvas.BeginFrame();
|
||||
|
||||
// Top-left panel backdrop + crisp Krypton typography across weights/slants/sizes
|
||||
_canvas.DrawRectFilled(40f, 36f, 680f, 224f, panelBg);
|
||||
_canvas.DrawLineSegment(40f, 36f, 720f, 36f, 2f, amber);
|
||||
_canvas.DrawLineSegment(40f, 260f, 720f, 260f, 1.5f, new Color(amber, 0.5f));
|
||||
|
||||
_canvas.DrawText("RUST TO DUST // HB-GPU VULKAN", 60f, 84f, 32f, amber, wght: 700f);
|
||||
_canvas.DrawText("CHASSIS: RAPTOR-7 | ALT: 142.8m | SPD: 28.4m/s", 60f, 124f, 20f, slate, wght: 550f);
|
||||
_canvas.DrawText("CALT / LIGA: -> ==> != <= >= // 0x4F2A", 60f, 158f, 18f, cyan, wght: 350f);
|
||||
_canvas.DrawText("SLANT -9 DEG // STEM DARKENED ANALYTIC SLUG", 60f, 192f, 15f, emerald, wght: 400f, slnt: -9f);
|
||||
_canvas.DrawText("11PX MICRO TELEMETRY: 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ", 60f, 226f, 11f, slate, wght: 250f);
|
||||
|
||||
// Center crosshair reticle + dynamic cubic Bezier thermal heat arc
|
||||
float cx = 640f;
|
||||
float cy = 400f;
|
||||
_canvas.DrawCircleFilled(cx, cy, 3.5f, amber);
|
||||
_canvas.DrawLineSegment(cx - 28f, cy, cx - 10f, cy, 2.0f, cyan);
|
||||
_canvas.DrawLineSegment(cx + 10f, cy, cx + 28f, cy, 2.0f, cyan);
|
||||
_canvas.DrawLineSegment(cx, cy - 28f, cx, cy - 10f, 2.0f, cyan);
|
||||
_canvas.DrawLineSegment(cx, cy + 10f, cx, cy + 28f, 2.0f, cyan);
|
||||
|
||||
float heatSweep = -2.356f + (0.65f + 0.1f * MathF.Sin(frameIndex * 0.1f)) * 4.712f;
|
||||
_canvas.DrawArcStrokeDynamic(cx, cy, 62f, 5.5f, -2.356f, heatSweep, amber);
|
||||
_canvas.DrawArcStrokeDynamic(cx, cy, 82f, 4.0f, -0.34f, 0.34f, alert);
|
||||
|
||||
// Target lock corner brackets (all 4 quadrants)
|
||||
float bx0 = 860f, by0 = 280f, bx1 = 1040f, by1 = 460f;
|
||||
_canvas.DrawTargetBracketCorner(bx0, by0, 26f, 3.5f, 0, alert);
|
||||
_canvas.DrawTargetBracketCorner(bx1, by0, 26f, 3.5f, 1, alert);
|
||||
_canvas.DrawTargetBracketCorner(bx1, by1, 26f, 3.5f, 2, alert);
|
||||
_canvas.DrawTargetBracketCorner(bx0, by1, 26f, 3.5f, 3, alert);
|
||||
_canvas.DrawText("LOCK: SPECTATOR-02 [318m]", bx0, by0 - 12f, 14f, alert, wght: 600f);
|
||||
|
||||
// Offscreen directional arrows
|
||||
_canvas.DrawDirectionalArrow(1160f, 560f, 28f, 0.55f, amber);
|
||||
_canvas.DrawDirectionalArrow(120f, 560f, 28f, -2.45f, alert);
|
||||
|
||||
// Radar circle, safe ring, LOS lock line, diamond blip & chevron
|
||||
float rx = 1080f, ry = 160f, rr = 96f;
|
||||
_canvas.DrawCircleFilled(rx, ry, rr, new Color(0.04f, 0.07f, 0.09f, 0.85f));
|
||||
_canvas.DrawCircleRing(rx, ry, rr, 2.5f, cyan);
|
||||
_canvas.DrawCircleRing(rx, ry, rr * 0.58f, 1.5f, new Color(emerald, 0.75f));
|
||||
_canvas.DrawLineSegment(rx, ry, rx + 44f, ry - 52f, 1.5f, new Color(alert, 0.85f));
|
||||
_canvas.Writer.DrawBlob(
|
||||
HbGpuVectorShapes.GetDiamondBlip(_canvas.Blobs),
|
||||
rx + 44f, ry - 52f,
|
||||
0.012f, 0f, 0f, -0.012f, 0f, 0f,
|
||||
alert.R, alert.G, alert.B, alert.A);
|
||||
_canvas.Writer.DrawBlob(
|
||||
HbGpuVectorShapes.GetChevronTriangle(_canvas.Blobs),
|
||||
rx, ry,
|
||||
0.014f, 0f, 0f, -0.014f, 0f, 0f,
|
||||
emerald.R, emerald.G, emerald.B, emerald.A);
|
||||
|
||||
_canvas.EndFrameAndSubmit();
|
||||
}
|
||||
|
||||
private void Fail(string msg)
|
||||
{
|
||||
GD.PrintErr("HBGPU_PROBE FAIL: " + msg);
|
||||
Finish(1);
|
||||
}
|
||||
|
||||
private void Finish(int code)
|
||||
{
|
||||
if (_done) return;
|
||||
_done = true;
|
||||
GetTree().Quit(code);
|
||||
}
|
||||
}
|
||||
12
client/tests/HbGpuProbe.tscn
Normal file
12
client/tests/HbGpuProbe.tscn
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
[gd_scene load_steps=2 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://tests/HbGpuProbe.cs" id="1"]
|
||||
|
||||
[node name="HbGpuProbe" type="Control"]
|
||||
layout_mode = 3
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
script = ExtResource("1")
|
||||
89
native/rtd_hbgpu/CMakeLists.txt
Normal file
89
native/rtd_hbgpu/CMakeLists.txt
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
cmake_minimum_required(VERSION 3.22)
|
||||
|
||||
project(rtd_hbgpu VERSION 0.1.0 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
if(MSVC)
|
||||
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
endif()
|
||||
|
||||
# Resolve pinned HarfBuzz 15.2.0 source
|
||||
set(RTD_HARFBUZZ_DIR "" CACHE PATH "Path to HarfBuzz 15.2.0 source directory")
|
||||
if(NOT RTD_HARFBUZZ_DIR AND DEFINED ENV{RTD_HARFBUZZ_DIR} AND EXISTS "$ENV{RTD_HARFBUZZ_DIR}/CMakeLists.txt")
|
||||
set(RTD_HARFBUZZ_DIR "$ENV{RTD_HARFBUZZ_DIR}")
|
||||
elseif(NOT RTD_HARFBUZZ_DIR AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../../extern/harfbuzz/CMakeLists.txt")
|
||||
set(RTD_HARFBUZZ_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../extern/harfbuzz")
|
||||
elseif(NOT RTD_HARFBUZZ_DIR AND EXISTS "F:/aeth-wt/text-probe-gpu-build2/src/harfbuzz/CMakeLists.txt")
|
||||
set(RTD_HARFBUZZ_DIR "F:/aeth-wt/text-probe-gpu-build2/src/harfbuzz")
|
||||
endif()
|
||||
|
||||
# Minimal HarfBuzz configuration: zero ICU/FreeType/Cairo/Glib/Subset/Raster/Vector bloat
|
||||
set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
|
||||
set(HB_HAVE_CAIRO OFF CACHE BOOL "" FORCE)
|
||||
set(HB_HAVE_FREETYPE OFF CACHE BOOL "" FORCE)
|
||||
set(HB_HAVE_GRAPHITE2 OFF CACHE BOOL "" FORCE)
|
||||
set(HB_HAVE_GLIB OFF CACHE BOOL "" FORCE)
|
||||
set(HB_HAVE_ICU OFF CACHE BOOL "" FORCE)
|
||||
set(HB_HAVE_GOBJECT OFF CACHE BOOL "" FORCE)
|
||||
set(HB_HAVE_INTROSPECTION OFF CACHE BOOL "" FORCE)
|
||||
set(HB_HAVE_CORETEXT OFF CACHE BOOL "" FORCE)
|
||||
set(HB_HAVE_UNISCRIBE OFF CACHE BOOL "" FORCE)
|
||||
set(HB_HAVE_GDI OFF CACHE BOOL "" FORCE)
|
||||
set(HB_HAVE_DIRECTWRITE OFF CACHE BOOL "" FORCE)
|
||||
set(HB_BUILD_UTILS OFF CACHE BOOL "" FORCE)
|
||||
set(HB_BUILD_SUBSET OFF CACHE BOOL "" FORCE)
|
||||
set(HB_BUILD_RASTER OFF CACHE BOOL "" FORCE)
|
||||
set(HB_BUILD_VECTOR OFF CACHE BOOL "" FORCE)
|
||||
set(HB_BUILD_GPU ON CACHE BOOL "" FORCE)
|
||||
set(HB_BUILD_GPU_DEMO OFF CACHE STRING "" FORCE)
|
||||
|
||||
if(RTD_HARFBUZZ_DIR AND EXISTS "${RTD_HARFBUZZ_DIR}/CMakeLists.txt")
|
||||
add_subdirectory("${RTD_HARFBUZZ_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/harfbuzz" EXCLUDE_FROM_ALL)
|
||||
else()
|
||||
include(FetchContent)
|
||||
FetchContent_Declare(
|
||||
harfbuzz
|
||||
URL "https://github.com/harfbuzz/harfbuzz/releases/download/15.2.0/harfbuzz-15.2.0.tar.xz"
|
||||
URL_HASH SHA256=e2ec49090744383cdbe7df808c1cedaafba06a97be8dc4211fe546ba585f12cb
|
||||
)
|
||||
FetchContent_MakeAvailable(harfbuzz)
|
||||
endif()
|
||||
|
||||
add_library(rtd_hbgpu SHARED rtd_hbgpu.c)
|
||||
target_link_libraries(rtd_hbgpu PRIVATE harfbuzz-gpu harfbuzz)
|
||||
target_include_directories(rtd_hbgpu
|
||||
PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
PRIVATE "${harfbuzz_SOURCE_DIR}/src"
|
||||
)
|
||||
if(RTD_HARFBUZZ_DIR)
|
||||
target_include_directories(rtd_hbgpu PRIVATE "${RTD_HARFBUZZ_DIR}/src")
|
||||
endif()
|
||||
|
||||
target_compile_features(rtd_hbgpu PRIVATE c_std_17)
|
||||
target_compile_definitions(rtd_hbgpu PRIVATE RTD_HBGPU_EXPORTS)
|
||||
|
||||
if(MSVC)
|
||||
set_property(TARGET rtd_hbgpu PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
target_compile_options(harfbuzz PRIVATE $<$<CONFIG:Release>:/O2 /GL /Gy>)
|
||||
target_compile_options(harfbuzz-gpu PRIVATE $<$<CONFIG:Release>:/O2 /GL /Gy>)
|
||||
target_compile_options(rtd_hbgpu PRIVATE $<$<CONFIG:Release>:/O2 /GL /Gy>)
|
||||
target_link_options(rtd_hbgpu PRIVATE $<$<CONFIG:Release>:/OPT:REF /OPT:ICF /LTCG>)
|
||||
elseif(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang")
|
||||
target_compile_options(rtd_hbgpu PRIVATE $<$<CONFIG:Release>:-O2 -ffunction-sections -fdata-sections>)
|
||||
if(NOT APPLE)
|
||||
target_link_options(rtd_hbgpu PRIVATE $<$<CONFIG:Release>:-Wl,--gc-sections>)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
set_target_properties(rtd_hbgpu PROPERTIES
|
||||
C_VISIBILITY_PRESET hidden
|
||||
CXX_VISIBILITY_PRESET hidden
|
||||
VISIBILITY_INLINES_HIDDEN ON
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$<CONFIG>"
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$<CONFIG>"
|
||||
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
|
||||
)
|
||||
if(MINGW)
|
||||
set_property(TARGET rtd_hbgpu PROPERTY PREFIX "")
|
||||
endif()
|
||||
124
native/rtd_hbgpu/include/rtd_hbgpu.h
Normal file
124
native/rtd_hbgpu/include/rtd_hbgpu.h
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
#ifndef RTD_HBGPU_H
|
||||
#define RTD_HBGPU_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#ifdef RTD_HBGPU_EXPORTS
|
||||
#define RTD_HBGPU_API __declspec(dllexport)
|
||||
#else
|
||||
#define RTD_HBGPU_API __declspec(dllimport)
|
||||
#endif
|
||||
#else
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
#define RTD_HBGPU_API __attribute__((visibility("default")))
|
||||
#else
|
||||
#define RTD_HBGPU_API
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct rtd_hb_font rtd_hb_font;
|
||||
|
||||
typedef struct rtd_hb_font_metrics {
|
||||
int32_t upem;
|
||||
int32_t ascender;
|
||||
int32_t descender;
|
||||
int32_t line_gap;
|
||||
} rtd_hb_font_metrics;
|
||||
|
||||
typedef struct rtd_hb_shaped_glyph {
|
||||
uint32_t glyph_id;
|
||||
uint32_t cluster;
|
||||
int32_t x_advance;
|
||||
int32_t y_advance;
|
||||
int32_t x_offset;
|
||||
int32_t y_offset;
|
||||
} rtd_hb_shaped_glyph;
|
||||
|
||||
typedef struct rtd_hb_extents {
|
||||
int32_t min_x;
|
||||
int32_t min_y;
|
||||
int32_t max_x;
|
||||
int32_t max_y;
|
||||
} rtd_hb_extents;
|
||||
|
||||
enum {
|
||||
RTD_HB_STAGE_VERTEX = 0,
|
||||
RTD_HB_STAGE_FRAGMENT = 1
|
||||
};
|
||||
|
||||
enum {
|
||||
RTD_HB_SHADER_SHARED = 0,
|
||||
RTD_HB_SHADER_DRAW = 1
|
||||
};
|
||||
|
||||
enum {
|
||||
RTD_HB_FEAT_NONE = 0,
|
||||
RTD_HB_FEAT_CALT = 1u << 0,
|
||||
RTD_HB_FEAT_LIGA = 1u << 1,
|
||||
RTD_HB_FEAT_DEFAULT = RTD_HB_FEAT_CALT | RTD_HB_FEAT_LIGA
|
||||
};
|
||||
|
||||
enum {
|
||||
RTD_HB_VERB_MOVE = 0, /* 2 args: x, y */
|
||||
RTD_HB_VERB_LINE_TO = 1, /* 2 args: x, y */
|
||||
RTD_HB_VERB_QUAD_TO = 2, /* 4 args: cx, cy, x, y */
|
||||
RTD_HB_VERB_CUBIC_TO = 3, /* 6 args: c1x, c1y, c2x, c2y, x, y */
|
||||
RTD_HB_VERB_CLOSE = 4, /* 0 args */
|
||||
RTD_HB_VERB_LINE = 5, /* 7 args: x0, y0, w0, x1, y1, w1, cap (0=butt,1=square) */
|
||||
RTD_HB_VERB_RECT = 6, /* 5 args: x, y, w, h, stroke_width (NaN or <0 = filled) */
|
||||
RTD_HB_VERB_CIRCLE = 7 /* 4 args: cx, cy, r, stroke_width (NaN or <0 = filled) */
|
||||
};
|
||||
|
||||
RTD_HBGPU_API const char* rtd_hb_version_string(void);
|
||||
|
||||
RTD_HBGPU_API const char* rtd_hb_shader_source(uint32_t stage, uint32_t kind);
|
||||
|
||||
RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create(
|
||||
const uint8_t* ttf,
|
||||
uint32_t len,
|
||||
uint32_t face_index,
|
||||
rtd_hb_font_metrics* out_metrics);
|
||||
|
||||
RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create_variant(
|
||||
const rtd_hb_font* base_font,
|
||||
float wght,
|
||||
float wdth,
|
||||
float slnt);
|
||||
|
||||
RTD_HBGPU_API void rtd_hb_font_destroy(rtd_hb_font* f);
|
||||
|
||||
RTD_HBGPU_API uint32_t rtd_hb_shape_utf16(
|
||||
rtd_hb_font* f,
|
||||
const uint16_t* utf16,
|
||||
uint32_t char_len,
|
||||
uint32_t feature_flags,
|
||||
rtd_hb_shaped_glyph* out,
|
||||
uint32_t cap);
|
||||
|
||||
RTD_HBGPU_API int32_t rtd_hb_encode_glyph(
|
||||
rtd_hb_font* f,
|
||||
uint32_t glyph_id,
|
||||
int16_t* out_rgba16i,
|
||||
uint32_t cap_texels,
|
||||
rtd_hb_extents* out_ext);
|
||||
|
||||
RTD_HBGPU_API int32_t rtd_hb_encode_path(
|
||||
uint32_t design_upem,
|
||||
const uint8_t* verbs,
|
||||
uint32_t n_verbs,
|
||||
const float* args,
|
||||
uint32_t n_args,
|
||||
int16_t* out_rgba16i,
|
||||
uint32_t cap_texels,
|
||||
rtd_hb_extents* out_ext);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* RTD_HBGPU_H */
|
||||
348
native/rtd_hbgpu/rtd_hbgpu.c
Normal file
348
native/rtd_hbgpu/rtd_hbgpu.c
Normal file
|
|
@ -0,0 +1,348 @@
|
|||
#include "rtd_hbgpu.h"
|
||||
|
||||
#include "hb.h"
|
||||
#include "hb-gpu.h"
|
||||
#include "hb-ot.h"
|
||||
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
struct rtd_hb_font {
|
||||
hb_face_t* face;
|
||||
hb_font_t* font;
|
||||
hb_buffer_t* buf;
|
||||
hb_gpu_draw_t* draw;
|
||||
};
|
||||
|
||||
static void fill_extents(const hb_glyph_extents_t* ext, rtd_hb_extents* out_ext) {
|
||||
if (!out_ext) return;
|
||||
out_ext->min_x = ext->x_bearing;
|
||||
out_ext->max_y = ext->y_bearing;
|
||||
out_ext->max_x = ext->x_bearing + ext->width;
|
||||
out_ext->min_y = ext->y_bearing + ext->height;
|
||||
}
|
||||
|
||||
static int32_t finalize_draw_blob(
|
||||
hb_gpu_draw_t* draw,
|
||||
int16_t* out_rgba16i,
|
||||
uint32_t cap_texels,
|
||||
rtd_hb_extents* out_ext)
|
||||
{
|
||||
hb_glyph_extents_t hb_ext;
|
||||
memset(&hb_ext, 0, sizeof(hb_ext));
|
||||
|
||||
hb_blob_t* blob = hb_gpu_draw_encode(draw, &hb_ext);
|
||||
if (!blob) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
unsigned int byte_len = 0;
|
||||
const char* data = hb_blob_get_data(blob, &byte_len);
|
||||
fill_extents(&hb_ext, out_ext);
|
||||
|
||||
if (byte_len == 0) {
|
||||
hb_gpu_draw_recycle_blob(draw, blob);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if ((byte_len & 7u) != 0u) {
|
||||
hb_gpu_draw_recycle_blob(draw, blob);
|
||||
return -1;
|
||||
}
|
||||
|
||||
uint32_t texels = byte_len >> 3u;
|
||||
if (texels > cap_texels || !out_rgba16i) {
|
||||
hb_gpu_draw_recycle_blob(draw, blob);
|
||||
return -(int32_t)texels;
|
||||
}
|
||||
|
||||
memcpy(out_rgba16i, data, byte_len);
|
||||
hb_gpu_draw_recycle_blob(draw, blob);
|
||||
return (int32_t)texels;
|
||||
}
|
||||
|
||||
RTD_HBGPU_API const char* rtd_hb_version_string(void) {
|
||||
return hb_version_string();
|
||||
}
|
||||
|
||||
RTD_HBGPU_API const char* rtd_hb_shader_source(uint32_t stage, uint32_t kind) {
|
||||
hb_gpu_shader_stage_t hb_stage;
|
||||
if (stage == RTD_HB_STAGE_VERTEX) {
|
||||
hb_stage = HB_GPU_SHADER_STAGE_VERTEX;
|
||||
} else if (stage == RTD_HB_STAGE_FRAGMENT) {
|
||||
hb_stage = HB_GPU_SHADER_STAGE_FRAGMENT;
|
||||
} else {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (kind == RTD_HB_SHADER_SHARED) {
|
||||
return hb_gpu_shader_source(hb_stage, HB_GPU_SHADER_LANG_GLSL);
|
||||
}
|
||||
if (kind == RTD_HB_SHADER_DRAW) {
|
||||
return hb_gpu_draw_shader_source(hb_stage, HB_GPU_SHADER_LANG_GLSL);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create(
|
||||
const uint8_t* ttf,
|
||||
uint32_t len,
|
||||
uint32_t face_index,
|
||||
rtd_hb_font_metrics* out_metrics)
|
||||
{
|
||||
if (!ttf || len == 0) return NULL;
|
||||
|
||||
hb_blob_t* blob = hb_blob_create((const char*)ttf, len, HB_MEMORY_MODE_DUPLICATE, NULL, NULL);
|
||||
if (!blob || hb_blob_get_length(blob) == 0) {
|
||||
if (blob) hb_blob_destroy(blob);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
hb_face_t* face = hb_face_create(blob, face_index);
|
||||
hb_blob_destroy(blob);
|
||||
if (!face || face == hb_face_get_empty()) {
|
||||
if (face) hb_face_destroy(face);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
hb_font_t* font = hb_font_create(face);
|
||||
hb_buffer_t* buf = hb_buffer_create();
|
||||
hb_gpu_draw_t* draw = hb_gpu_draw_create_or_fail();
|
||||
if (!font || !buf || !draw) {
|
||||
if (draw) hb_gpu_draw_destroy(draw);
|
||||
if (buf) hb_buffer_destroy(buf);
|
||||
if (font) hb_font_destroy(font);
|
||||
hb_face_destroy(face);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
rtd_hb_font* out = (rtd_hb_font*)calloc(1, sizeof(rtd_hb_font));
|
||||
if (!out) {
|
||||
hb_gpu_draw_destroy(draw);
|
||||
hb_buffer_destroy(buf);
|
||||
hb_font_destroy(font);
|
||||
hb_face_destroy(face);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
out->face = face;
|
||||
out->font = font;
|
||||
out->buf = buf;
|
||||
out->draw = draw;
|
||||
|
||||
if (out_metrics) {
|
||||
hb_font_extents_t fe;
|
||||
memset(&fe, 0, sizeof(fe));
|
||||
hb_font_get_h_extents(font, &fe);
|
||||
out_metrics->upem = (int32_t)hb_face_get_upem(face);
|
||||
out_metrics->ascender = fe.ascender;
|
||||
out_metrics->descender = fe.descender;
|
||||
out_metrics->line_gap = fe.line_gap;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create_variant(
|
||||
const rtd_hb_font* base_font,
|
||||
float wght,
|
||||
float wdth,
|
||||
float slnt)
|
||||
{
|
||||
if (!base_font || !base_font->face) return NULL;
|
||||
|
||||
hb_face_t* face = hb_face_reference(base_font->face);
|
||||
hb_font_t* font = hb_font_create(face);
|
||||
hb_buffer_t* buf = hb_buffer_create();
|
||||
hb_gpu_draw_t* draw = hb_gpu_draw_create_or_fail();
|
||||
if (!font || !buf || !draw) {
|
||||
if (draw) hb_gpu_draw_destroy(draw);
|
||||
if (buf) hb_buffer_destroy(buf);
|
||||
if (font) hb_font_destroy(font);
|
||||
hb_face_destroy(face);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
hb_variation_t vars[3] = {
|
||||
{ HB_TAG('w', 'g', 'h', 't'), wght },
|
||||
{ HB_TAG('w', 'd', 't', 'h'), wdth },
|
||||
{ HB_TAG('s', 'l', 'n', 't'), slnt }
|
||||
};
|
||||
hb_font_set_variations(font, vars, 3);
|
||||
|
||||
rtd_hb_font* out = (rtd_hb_font*)calloc(1, sizeof(rtd_hb_font));
|
||||
if (!out) {
|
||||
hb_gpu_draw_destroy(draw);
|
||||
hb_buffer_destroy(buf);
|
||||
hb_font_destroy(font);
|
||||
hb_face_destroy(face);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
out->face = face;
|
||||
out->font = font;
|
||||
out->buf = buf;
|
||||
out->draw = draw;
|
||||
return out;
|
||||
}
|
||||
|
||||
RTD_HBGPU_API void rtd_hb_font_destroy(rtd_hb_font* f) {
|
||||
if (!f) return;
|
||||
if (f->draw) hb_gpu_draw_destroy(f->draw);
|
||||
if (f->buf) hb_buffer_destroy(f->buf);
|
||||
if (f->font) hb_font_destroy(f->font);
|
||||
if (f->face) hb_face_destroy(f->face);
|
||||
free(f);
|
||||
}
|
||||
|
||||
RTD_HBGPU_API uint32_t rtd_hb_shape_utf16(
|
||||
rtd_hb_font* f,
|
||||
const uint16_t* utf16,
|
||||
uint32_t char_len,
|
||||
uint32_t feature_flags,
|
||||
rtd_hb_shaped_glyph* out,
|
||||
uint32_t cap)
|
||||
{
|
||||
if (!f || !f->font || !f->buf) return 0;
|
||||
if (char_len == 0 || !utf16) return 0;
|
||||
|
||||
hb_buffer_clear_contents(f->buf);
|
||||
hb_buffer_add_utf16(f->buf, utf16, (int)char_len, 0, (int)char_len);
|
||||
hb_buffer_guess_segment_properties(f->buf);
|
||||
|
||||
hb_feature_t feats[2] = {
|
||||
{ HB_TAG('c', 'a', 'l', 't'), (feature_flags & RTD_HB_FEAT_CALT) ? 1u : 0u, HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END },
|
||||
{ HB_TAG('l', 'i', 'g', 'a'), (feature_flags & RTD_HB_FEAT_LIGA) ? 1u : 0u, HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END }
|
||||
};
|
||||
hb_shape(f->font, f->buf, feats, 2);
|
||||
|
||||
unsigned int count = 0;
|
||||
const hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(f->buf, &count);
|
||||
const hb_glyph_position_t* pos = hb_buffer_get_glyph_positions(f->buf, &count);
|
||||
|
||||
if (out && cap > 0) {
|
||||
uint32_t to_copy = count < cap ? count : cap;
|
||||
for (uint32_t i = 0; i < to_copy; i++) {
|
||||
out[i].glyph_id = infos[i].codepoint;
|
||||
out[i].cluster = infos[i].cluster;
|
||||
out[i].x_advance = pos[i].x_advance;
|
||||
out[i].y_advance = pos[i].y_advance;
|
||||
out[i].x_offset = pos[i].x_offset;
|
||||
out[i].y_offset = pos[i].y_offset;
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
RTD_HBGPU_API int32_t rtd_hb_encode_glyph(
|
||||
rtd_hb_font* f,
|
||||
uint32_t glyph_id,
|
||||
int16_t* out_rgba16i,
|
||||
uint32_t cap_texels,
|
||||
rtd_hb_extents* out_ext)
|
||||
{
|
||||
if (!f || !f->font || !f->draw) return -1;
|
||||
|
||||
hb_gpu_draw_clear(f->draw);
|
||||
hb_gpu_draw_glyph(f->draw, f->font, glyph_id);
|
||||
return finalize_draw_blob(f->draw, out_rgba16i, cap_texels, out_ext);
|
||||
}
|
||||
|
||||
RTD_HBGPU_API int32_t rtd_hb_encode_path(
|
||||
uint32_t design_upem,
|
||||
const uint8_t* verbs,
|
||||
uint32_t n_verbs,
|
||||
const float* args,
|
||||
uint32_t n_args,
|
||||
int16_t* out_rgba16i,
|
||||
uint32_t cap_texels,
|
||||
rtd_hb_extents* out_ext)
|
||||
{
|
||||
if (!verbs || n_verbs == 0 || design_upem == 0) return -1;
|
||||
|
||||
hb_gpu_draw_t* draw = hb_gpu_draw_create_or_fail();
|
||||
if (!draw) return -1;
|
||||
|
||||
hb_gpu_draw_set_scale(draw, (int)design_upem, (int)design_upem);
|
||||
hb_draw_funcs_t* dfuncs = hb_gpu_draw_get_funcs(draw);
|
||||
hb_draw_state_t st = HB_DRAW_STATE_DEFAULT;
|
||||
|
||||
uint32_t arg_idx = 0;
|
||||
for (uint32_t i = 0; i < n_verbs; i++) {
|
||||
switch (verbs[i]) {
|
||||
case RTD_HB_VERB_MOVE:
|
||||
if (arg_idx + 2u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; }
|
||||
hb_draw_move_to(dfuncs, draw, &st, args[arg_idx], args[arg_idx + 1]);
|
||||
arg_idx += 2u;
|
||||
break;
|
||||
|
||||
case RTD_HB_VERB_LINE_TO:
|
||||
if (arg_idx + 2u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; }
|
||||
hb_draw_line_to(dfuncs, draw, &st, args[arg_idx], args[arg_idx + 1]);
|
||||
arg_idx += 2u;
|
||||
break;
|
||||
|
||||
case RTD_HB_VERB_QUAD_TO:
|
||||
if (arg_idx + 4u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; }
|
||||
hb_draw_quadratic_to(dfuncs, draw, &st,
|
||||
args[arg_idx], args[arg_idx + 1],
|
||||
args[arg_idx + 2], args[arg_idx + 3]);
|
||||
arg_idx += 4u;
|
||||
break;
|
||||
|
||||
case RTD_HB_VERB_CUBIC_TO:
|
||||
if (arg_idx + 6u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; }
|
||||
hb_draw_cubic_to(dfuncs, draw, &st,
|
||||
args[arg_idx], args[arg_idx + 1],
|
||||
args[arg_idx + 2], args[arg_idx + 3],
|
||||
args[arg_idx + 4], args[arg_idx + 5]);
|
||||
arg_idx += 6u;
|
||||
break;
|
||||
|
||||
case RTD_HB_VERB_CLOSE:
|
||||
hb_draw_close_path(dfuncs, draw, &st);
|
||||
break;
|
||||
|
||||
case RTD_HB_VERB_LINE:
|
||||
if (arg_idx + 7u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; }
|
||||
hb_draw_line(dfuncs, draw, &st,
|
||||
args[arg_idx], args[arg_idx + 1], args[arg_idx + 2],
|
||||
args[arg_idx + 3], args[arg_idx + 4], args[arg_idx + 5],
|
||||
args[arg_idx + 6] >= 0.5f ? HB_DRAW_LINE_CAP_SQUARE : HB_DRAW_LINE_CAP_BUTT);
|
||||
arg_idx += 7u;
|
||||
break;
|
||||
|
||||
case RTD_HB_VERB_RECT: {
|
||||
if (arg_idx + 5u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; }
|
||||
float sw = args[arg_idx + 4];
|
||||
if (sw < 0.0f) sw = NAN;
|
||||
hb_draw_rectangle(dfuncs, draw, &st,
|
||||
args[arg_idx], args[arg_idx + 1],
|
||||
args[arg_idx + 2], args[arg_idx + 3], sw);
|
||||
arg_idx += 5u;
|
||||
break;
|
||||
}
|
||||
|
||||
case RTD_HB_VERB_CIRCLE: {
|
||||
if (arg_idx + 4u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; }
|
||||
float sw = args[arg_idx + 3];
|
||||
if (sw < 0.0f) sw = NAN;
|
||||
hb_draw_circle(dfuncs, draw, &st,
|
||||
args[arg_idx], args[arg_idx + 1],
|
||||
args[arg_idx + 2], sw);
|
||||
arg_idx += 4u;
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
hb_gpu_draw_destroy(draw);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
int32_t res = finalize_draw_blob(draw, out_rgba16i, cap_texels, out_ext);
|
||||
hb_gpu_draw_destroy(draw);
|
||||
return res;
|
||||
}
|
||||
175
src/RustToDust.HbGpu/HbGpuAtlasAllocator.cs
Normal file
175
src/RustToDust.HbGpu/HbGpuAtlasAllocator.cs
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RustToDust.HbGpu;
|
||||
|
||||
/// <summary>
|
||||
/// Manages texel offsets inside the single 262,144-texel (2.0 MiB) RGBA16I GPU atlas:
|
||||
/// - Persistent zone: [0 .. 229,376) with a 75% (172,032) watermark reset trigger.
|
||||
/// - Dynamic scratch ring: [229,376 .. 262,144).
|
||||
/// Queues uploads into pre-allocated staging storage for zero-GC render-thread commits.
|
||||
/// </summary>
|
||||
public sealed class HbGpuAtlasAllocator
|
||||
{
|
||||
public const uint TotalTexels = 262_144;
|
||||
public const uint PersistentCapacity = 229_376;
|
||||
public const uint PersistentResetWatermark = 172_032; // 75% of PersistentCapacity
|
||||
public const uint DynamicBase = PersistentCapacity;
|
||||
public const uint DynamicCapacity = TotalTexels - PersistentCapacity; // 32,768
|
||||
public const int BytesPerTexel = 8;
|
||||
public const int TotalBytes = (int)(TotalTexels * BytesPerTexel);
|
||||
|
||||
public struct UploadChunk
|
||||
{
|
||||
public uint AtlasTexelOffset;
|
||||
public uint ShortOffset;
|
||||
public uint TexelCount;
|
||||
}
|
||||
|
||||
private readonly short[] _pendingShorts = new short[TotalTexels * 4];
|
||||
private readonly UploadChunk[] _pendingChunks = new UploadChunk[2048];
|
||||
private uint _pendingShortCursor;
|
||||
private int _pendingChunkCount;
|
||||
|
||||
public uint PersistentCursor { get; private set; }
|
||||
public uint DynamicCursor { get; private set; }
|
||||
public uint Epoch { get; private set; } = 1;
|
||||
|
||||
public bool NeedsPersistentReset => PersistentCursor > PersistentResetWatermark;
|
||||
|
||||
public int PendingChunkCount => _pendingChunkCount;
|
||||
|
||||
public ReadOnlySpan<short> PendingShortPool => _pendingShorts;
|
||||
|
||||
public ReadOnlySpan<UploadChunk> PendingChunks => _pendingChunks.AsSpan(0, _pendingChunkCount);
|
||||
|
||||
public void ResetPersistent()
|
||||
{
|
||||
PersistentCursor = 0;
|
||||
Epoch++;
|
||||
}
|
||||
|
||||
public uint AllocatePersistent(ReadOnlySpan<short> rgba16iShorts)
|
||||
{
|
||||
if (rgba16iShorts.IsEmpty || (rgba16iShorts.Length & 3) != 0)
|
||||
{
|
||||
throw new ArgumentException("Texel data must be a non-empty multiple of 4 shorts.", nameof(rgba16iShorts));
|
||||
}
|
||||
|
||||
uint texels = (uint)(rgba16iShorts.Length >> 2);
|
||||
if (PersistentCursor + texels > PersistentCapacity)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Persistent atlas overflow: cursor={PersistentCursor}, needed={texels}, cap={PersistentCapacity}.");
|
||||
}
|
||||
|
||||
uint atlasOffset = PersistentCursor;
|
||||
PersistentCursor += texels;
|
||||
QueueUpload(atlasOffset, rgba16iShorts, texels);
|
||||
return atlasOffset;
|
||||
}
|
||||
|
||||
public uint AllocateDynamic(ReadOnlySpan<short> rgba16iShorts)
|
||||
{
|
||||
if (rgba16iShorts.IsEmpty || (rgba16iShorts.Length & 3) != 0)
|
||||
{
|
||||
throw new ArgumentException("Texel data must be a non-empty multiple of 4 shorts.", nameof(rgba16iShorts));
|
||||
}
|
||||
|
||||
uint texels = (uint)(rgba16iShorts.Length >> 2);
|
||||
if (texels > DynamicCapacity)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Dynamic blob ({texels} texels) exceeds DynamicCapacity ({DynamicCapacity}).");
|
||||
}
|
||||
|
||||
if (DynamicCursor + texels > DynamicCapacity)
|
||||
{
|
||||
DynamicCursor = 0;
|
||||
}
|
||||
|
||||
uint atlasOffset = DynamicBase + DynamicCursor;
|
||||
DynamicCursor += texels;
|
||||
QueueUpload(atlasOffset, rgba16iShorts, texels);
|
||||
return atlasOffset;
|
||||
}
|
||||
|
||||
private void QueueUpload(uint atlasOffset, ReadOnlySpan<short> rgba16iShorts, uint texels)
|
||||
{
|
||||
if (_pendingChunkCount >= _pendingChunks.Length ||
|
||||
_pendingShortCursor + (uint)rgba16iShorts.Length > (uint)_pendingShorts.Length)
|
||||
{
|
||||
// Should never happen in normal HUD usage; reset pending ring head safely if overwhelmed without draining.
|
||||
throw new InvalidOperationException("Atlas pending upload staging buffer full before render-thread drain.");
|
||||
}
|
||||
|
||||
rgba16iShorts.CopyTo(_pendingShorts.AsSpan((int)_pendingShortCursor));
|
||||
_pendingChunks[_pendingChunkCount++] = new UploadChunk
|
||||
{
|
||||
AtlasTexelOffset = atlasOffset,
|
||||
ShortOffset = _pendingShortCursor,
|
||||
TexelCount = texels
|
||||
};
|
||||
_pendingShortCursor += (uint)rgba16iShorts.Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies all pending upload chunks into a caller-owned staging byte[] at index 0
|
||||
/// and invokes uploadCallback(atlasByteOffset, byteCount). Zero allocations when callback is cached.
|
||||
/// </summary>
|
||||
public int DrainChunks(byte[] stagingBuffer, Action<uint, uint> uploadCallback)
|
||||
{
|
||||
int count = _pendingChunkCount;
|
||||
if (count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
UploadChunk c = _pendingChunks[i];
|
||||
uint byteCount = c.TexelCount * BytesPerTexel;
|
||||
if (byteCount > (uint)stagingBuffer.Length)
|
||||
{
|
||||
throw new InvalidOperationException($"Upload chunk ({byteCount} B) exceeds staging buffer ({stagingBuffer.Length} B).");
|
||||
}
|
||||
Buffer.BlockCopy(_pendingShorts, (int)(c.ShortOffset * sizeof(short)), stagingBuffer, 0, (int)byteCount);
|
||||
uploadCallback(c.AtlasTexelOffset * BytesPerTexel, byteCount);
|
||||
}
|
||||
|
||||
_pendingChunkCount = 0;
|
||||
_pendingShortCursor = 0;
|
||||
return count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies all pending upload chunks into a full 2 MiB mirror buffer at their atlas byte offsets.
|
||||
/// Returns how many chunks were drained. Zero allocations.
|
||||
/// </summary>
|
||||
public int DrainToMirror(byte[] atlasMirrorBytes)
|
||||
{
|
||||
int count = _pendingChunkCount;
|
||||
if (count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
UploadChunk c = _pendingChunks[i];
|
||||
int dstOffset = (int)(c.AtlasTexelOffset * BytesPerTexel);
|
||||
int byteCount = (int)(c.TexelCount * BytesPerTexel);
|
||||
Buffer.BlockCopy(_pendingShorts, (int)(c.ShortOffset * sizeof(short)), atlasMirrorBytes, dstOffset, byteCount);
|
||||
}
|
||||
|
||||
_pendingChunkCount = 0;
|
||||
_pendingShortCursor = 0;
|
||||
return count;
|
||||
}
|
||||
|
||||
public void ClearPending()
|
||||
{
|
||||
_pendingChunkCount = 0;
|
||||
_pendingShortCursor = 0;
|
||||
}
|
||||
}
|
||||
192
src/RustToDust.HbGpu/HbGpuBlobCache.cs
Normal file
192
src/RustToDust.HbGpu/HbGpuBlobCache.cs
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RustToDust.HbGpu;
|
||||
|
||||
/// <summary>
|
||||
/// Encodes and caches RGBA16I Slug blobs for font glyphs and static/dynamic vector shapes
|
||||
/// using a pre-allocated 65,536-short (128 KiB) scratch buffer.
|
||||
/// </summary>
|
||||
public sealed unsafe class HbGpuBlobCache
|
||||
{
|
||||
public const int ScratchShortsCapacity = 65_536;
|
||||
public const uint ScratchTexelsCapacity = ScratchShortsCapacity / 4; // 16,384 texels
|
||||
|
||||
private readonly HbGpuAtlasAllocator _atlas;
|
||||
private readonly Dictionary<GlyphBlobKey, CachedBlob> _glyphBlobs = new(512);
|
||||
private readonly Dictionary<VectorBlobKey, CachedBlob> _vectorBlobs = new(64);
|
||||
private readonly short[] _scratchShorts = new short[ScratchShortsCapacity];
|
||||
|
||||
public HbGpuBlobCache(HbGpuAtlasAllocator atlas)
|
||||
{
|
||||
_atlas = atlas ?? throw new ArgumentNullException(nameof(atlas));
|
||||
}
|
||||
|
||||
public HbGpuAtlasAllocator Atlas => _atlas;
|
||||
|
||||
public int CachedGlyphCount => _glyphBlobs.Count;
|
||||
|
||||
public int CachedVectorCount => _vectorBlobs.Count;
|
||||
|
||||
public bool EnsureBudgetOrReset()
|
||||
{
|
||||
if (!_atlas.NeedsPersistentReset)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_atlas.ResetPersistent();
|
||||
_glyphBlobs.Clear();
|
||||
_vectorBlobs.Clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
public CachedBlob GetOrEncodeGlyph(
|
||||
HbGpuFontCache fonts,
|
||||
byte fontId,
|
||||
uint glyphId,
|
||||
ushort qWght,
|
||||
ushort qWdth,
|
||||
short qSlnt)
|
||||
{
|
||||
var key = new GlyphBlobKey(fontId, glyphId, qWght, qWdth, qSlnt);
|
||||
if (_glyphBlobs.TryGetValue(key, out CachedBlob cached))
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
|
||||
IntPtr fontHandle = fonts.GetOrCreateStyle(new HbGpuStyleKey(fontId, qWght, qWdth, qSlnt));
|
||||
int texelCount;
|
||||
RtdHbExtents ext;
|
||||
fixed (short* dst = _scratchShorts)
|
||||
{
|
||||
texelCount = HbGpuNative.EncodeGlyph(fontHandle, glyphId, dst, ScratchTexelsCapacity, out ext);
|
||||
}
|
||||
|
||||
if (texelCount < 0)
|
||||
{
|
||||
throw new InvalidOperationException($"rtd_hb_encode_glyph failed for glyph {glyphId} (code {texelCount}).");
|
||||
}
|
||||
|
||||
CachedBlob blob;
|
||||
if (texelCount == 0)
|
||||
{
|
||||
blob = new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_atlas.PersistentCursor + (uint)texelCount > HbGpuAtlasAllocator.PersistentCapacity)
|
||||
{
|
||||
_atlas.ResetPersistent();
|
||||
_glyphBlobs.Clear();
|
||||
_vectorBlobs.Clear();
|
||||
}
|
||||
|
||||
uint offset = _atlas.AllocatePersistent(_scratchShorts.AsSpan(0, texelCount * 4));
|
||||
blob = new CachedBlob(
|
||||
offset,
|
||||
checked((short)ext.MinX),
|
||||
checked((short)ext.MinY),
|
||||
checked((short)ext.MaxX),
|
||||
checked((short)ext.MaxY),
|
||||
(uint)texelCount,
|
||||
IsEmpty: false);
|
||||
}
|
||||
|
||||
_glyphBlobs[key] = blob;
|
||||
return blob;
|
||||
}
|
||||
|
||||
public CachedBlob GetOrEncodeStaticPath(
|
||||
VectorBlobKey key,
|
||||
uint designUpem,
|
||||
ReadOnlySpan<byte> verbs,
|
||||
ReadOnlySpan<float> args)
|
||||
{
|
||||
if (_vectorBlobs.TryGetValue(key, out CachedBlob cached))
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
|
||||
int texelCount = EncodePathIntoScratch(designUpem, verbs, args, out RtdHbExtents ext);
|
||||
CachedBlob blob;
|
||||
if (texelCount == 0)
|
||||
{
|
||||
blob = new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_atlas.PersistentCursor + (uint)texelCount > HbGpuAtlasAllocator.PersistentCapacity)
|
||||
{
|
||||
_atlas.ResetPersistent();
|
||||
_glyphBlobs.Clear();
|
||||
_vectorBlobs.Clear();
|
||||
}
|
||||
|
||||
uint offset = _atlas.AllocatePersistent(_scratchShorts.AsSpan(0, texelCount * 4));
|
||||
blob = new CachedBlob(
|
||||
offset,
|
||||
checked((short)ext.MinX),
|
||||
checked((short)ext.MinY),
|
||||
checked((short)ext.MaxX),
|
||||
checked((short)ext.MaxY),
|
||||
(uint)texelCount,
|
||||
IsEmpty: false);
|
||||
}
|
||||
|
||||
_vectorBlobs[key] = blob;
|
||||
return blob;
|
||||
}
|
||||
|
||||
public CachedBlob EncodeDynamicPath(
|
||||
uint designUpem,
|
||||
ReadOnlySpan<byte> verbs,
|
||||
ReadOnlySpan<float> args)
|
||||
{
|
||||
int texelCount = EncodePathIntoScratch(designUpem, verbs, args, out RtdHbExtents ext);
|
||||
if (texelCount == 0)
|
||||
{
|
||||
return new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true);
|
||||
}
|
||||
|
||||
uint offset = _atlas.AllocateDynamic(_scratchShorts.AsSpan(0, texelCount * 4));
|
||||
return new CachedBlob(
|
||||
offset,
|
||||
checked((short)ext.MinX),
|
||||
checked((short)ext.MinY),
|
||||
checked((short)ext.MaxX),
|
||||
checked((short)ext.MaxY),
|
||||
(uint)texelCount,
|
||||
IsEmpty: false);
|
||||
}
|
||||
|
||||
private int EncodePathIntoScratch(
|
||||
uint designUpem,
|
||||
ReadOnlySpan<byte> verbs,
|
||||
ReadOnlySpan<float> args,
|
||||
out RtdHbExtents ext)
|
||||
{
|
||||
int texelCount;
|
||||
fixed (byte* vPtr = verbs)
|
||||
fixed (float* aPtr = args)
|
||||
fixed (short* dst = _scratchShorts)
|
||||
{
|
||||
texelCount = HbGpuNative.EncodePath(
|
||||
designUpem,
|
||||
vPtr,
|
||||
(uint)verbs.Length,
|
||||
aPtr,
|
||||
(uint)args.Length,
|
||||
dst,
|
||||
ScratchTexelsCapacity,
|
||||
out ext);
|
||||
}
|
||||
|
||||
if (texelCount < 0)
|
||||
{
|
||||
throw new InvalidOperationException($"rtd_hb_encode_path failed (code {texelCount}).");
|
||||
}
|
||||
|
||||
return texelCount;
|
||||
}
|
||||
}
|
||||
246
src/RustToDust.HbGpu/HbGpuCommandWriter.cs
Normal file
246
src/RustToDust.HbGpu/HbGpuCommandWriter.cs
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
using System;
|
||||
|
||||
namespace RustToDust.HbGpu;
|
||||
|
||||
/// <summary>
|
||||
/// Zero-allocation CPU quad builder and text shaper writing 80-byte HbGpuQuadInstance records.
|
||||
/// </summary>
|
||||
public sealed unsafe class HbGpuCommandWriter
|
||||
{
|
||||
public const int MaxQuads = 4096;
|
||||
public const int ShapingScratchCapacity = 1024;
|
||||
|
||||
private readonly HbGpuQuadInstance[] _quads = new HbGpuQuadInstance[MaxQuads];
|
||||
private readonly RtdHbShapedGlyph[] _shapedScratch = new RtdHbShapedGlyph[ShapingScratchCapacity];
|
||||
|
||||
public int QuadCount { get; private set; }
|
||||
|
||||
public ReadOnlySpan<HbGpuQuadInstance> Quads => _quads.AsSpan(0, QuadCount);
|
||||
|
||||
public HbGpuQuadInstance[] RawBuffer => _quads;
|
||||
|
||||
public void BeginFrame()
|
||||
{
|
||||
QuadCount = 0;
|
||||
}
|
||||
|
||||
public static uint PackClipCoord(float minVal, float maxVal)
|
||||
{
|
||||
ushort lo = (ushort)Math.Clamp((int)MathF.Floor(minVal), 0, 65535);
|
||||
ushort hi = (ushort)Math.Clamp((int)MathF.Ceiling(maxVal), 0, 65535);
|
||||
return (uint)lo | ((uint)hi << 16);
|
||||
}
|
||||
|
||||
public static void PackClipRect(
|
||||
float x, float y, float w, float h,
|
||||
out uint clipMinPacked,
|
||||
out uint clipMaxPacked)
|
||||
{
|
||||
ushort x0 = (ushort)Math.Clamp((int)MathF.Floor(x), 0, 65535);
|
||||
ushort y0 = (ushort)Math.Clamp((int)MathF.Floor(y), 0, 65535);
|
||||
ushort x1 = (ushort)Math.Clamp((int)MathF.Ceiling(x + w), 0, 65535);
|
||||
ushort y1 = (ushort)Math.Clamp((int)MathF.Ceiling(y + h), 0, 65535);
|
||||
clipMinPacked = (uint)x0 | ((uint)y0 << 16);
|
||||
clipMaxPacked = (uint)x1 | ((uint)y1 << 16);
|
||||
}
|
||||
|
||||
public bool TryAddQuad(in HbGpuQuadInstance quad)
|
||||
{
|
||||
if (QuadCount >= MaxQuads)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_quads[QuadCount++] = quad;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void DrawBlob(
|
||||
in CachedBlob blob,
|
||||
float screenX,
|
||||
float screenY,
|
||||
float m00,
|
||||
float m01,
|
||||
float m10,
|
||||
float m11,
|
||||
float anchorEmX,
|
||||
float anchorEmY,
|
||||
float r,
|
||||
float g,
|
||||
float b,
|
||||
float a,
|
||||
bool stemDarken = false,
|
||||
uint clipMinPacked = 0,
|
||||
uint clipMaxPacked = HbGpuQuadInstance.Unclipped)
|
||||
{
|
||||
if (!blob.IsValid || QuadCount >= MaxQuads)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_quads[QuadCount++] = new HbGpuQuadInstance
|
||||
{
|
||||
EmMinX = blob.MinX,
|
||||
EmMinY = blob.MinY,
|
||||
EmMaxX = blob.MaxX,
|
||||
EmMaxY = blob.MaxY,
|
||||
AnchorEmX = anchorEmX,
|
||||
AnchorEmY = anchorEmY,
|
||||
ScreenX = screenX,
|
||||
ScreenY = screenY,
|
||||
M00 = m00,
|
||||
M01 = m01,
|
||||
M10 = m10,
|
||||
M11 = m11,
|
||||
ColorR = r,
|
||||
ColorG = g,
|
||||
ColorB = b,
|
||||
ColorA = a,
|
||||
AtlasTexelOffset = blob.AtlasOffset,
|
||||
Flags = stemDarken ? HbGpuQuadInstance.FlagStemDarken : 0u,
|
||||
ClipMinPacked = clipMinPacked,
|
||||
ClipMaxPacked = clipMaxPacked
|
||||
};
|
||||
}
|
||||
|
||||
public float MeasureTextWidth(
|
||||
ReadOnlySpan<char> text,
|
||||
float fontSizePx,
|
||||
HbGpuFontCache fonts,
|
||||
byte fontId = 0,
|
||||
float wght = 200f,
|
||||
float wdth = 100f,
|
||||
float slnt = 0f,
|
||||
HbGpuFeatureFlags features = HbGpuFeatureFlags.Default)
|
||||
{
|
||||
if (text.IsEmpty)
|
||||
{
|
||||
return 0f;
|
||||
}
|
||||
|
||||
HbGpuStyleKey styleKey = HbGpuStyleKey.FromAxes(fontId, wght, wdth, slnt);
|
||||
IntPtr fontHandle = fonts.GetOrCreateStyle(styleKey);
|
||||
int upem = fonts.GetMetrics(fontId).Upem;
|
||||
float scale = fontSizePx / upem;
|
||||
|
||||
uint glyphCount;
|
||||
fixed (char* textPtr = text)
|
||||
fixed (RtdHbShapedGlyph* outPtr = _shapedScratch)
|
||||
{
|
||||
glyphCount = HbGpuNative.ShapeUtf16(
|
||||
fontHandle,
|
||||
textPtr,
|
||||
(uint)text.Length,
|
||||
(uint)features,
|
||||
outPtr,
|
||||
(uint)_shapedScratch.Length);
|
||||
}
|
||||
|
||||
int count = (int)Math.Min(glyphCount, (uint)_shapedScratch.Length);
|
||||
int adv = 0;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
adv += _shapedScratch[i].XAdvance;
|
||||
}
|
||||
|
||||
return adv * scale;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shapes UTF-16 text directly and appends glyph quads. (x, baselineY) is the pen baseline origin in logical pixels (Y-down).
|
||||
/// Returns the total horizontal advance in logical pixels.
|
||||
/// </summary>
|
||||
public float DrawTextUtf16(
|
||||
ReadOnlySpan<char> text,
|
||||
float x,
|
||||
float baselineY,
|
||||
float fontSizePx,
|
||||
float r,
|
||||
float g,
|
||||
float b,
|
||||
float a,
|
||||
HbGpuFontCache fonts,
|
||||
HbGpuBlobCache blobs,
|
||||
byte fontId = 0,
|
||||
float wght = 200f,
|
||||
float wdth = 100f,
|
||||
float slnt = 0f,
|
||||
HbGpuFeatureFlags features = HbGpuFeatureFlags.Default,
|
||||
bool stemDarken = true,
|
||||
uint clipMinPacked = 0,
|
||||
uint clipMaxPacked = HbGpuQuadInstance.Unclipped)
|
||||
{
|
||||
if (text.IsEmpty)
|
||||
{
|
||||
return 0f;
|
||||
}
|
||||
|
||||
HbGpuStyleKey styleKey = HbGpuStyleKey.FromAxes(fontId, wght, wdth, slnt);
|
||||
IntPtr fontHandle = fonts.GetOrCreateStyle(styleKey);
|
||||
int upem = fonts.GetMetrics(fontId).Upem;
|
||||
float scale = fontSizePx / upem;
|
||||
|
||||
uint glyphCount;
|
||||
fixed (char* textPtr = text)
|
||||
fixed (RtdHbShapedGlyph* outPtr = _shapedScratch)
|
||||
{
|
||||
glyphCount = HbGpuNative.ShapeUtf16(
|
||||
fontHandle,
|
||||
textPtr,
|
||||
(uint)text.Length,
|
||||
(uint)features,
|
||||
outPtr,
|
||||
(uint)_shapedScratch.Length);
|
||||
}
|
||||
|
||||
int count = (int)Math.Min(glyphCount, (uint)_shapedScratch.Length);
|
||||
float penX = x;
|
||||
float penY = baselineY;
|
||||
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
RtdHbShapedGlyph sg = _shapedScratch[i];
|
||||
CachedBlob blob = blobs.GetOrEncodeGlyph(
|
||||
fonts,
|
||||
fontId,
|
||||
sg.GlyphId,
|
||||
styleKey.QWght,
|
||||
styleKey.QWdth,
|
||||
styleKey.QSlnt);
|
||||
|
||||
if (blob.IsValid && QuadCount < MaxQuads)
|
||||
{
|
||||
float gx = penX + sg.XOffset * scale;
|
||||
float gy = penY - sg.YOffset * scale; // Y-up font offset -> Y-down screen
|
||||
_quads[QuadCount++] = new HbGpuQuadInstance
|
||||
{
|
||||
EmMinX = blob.MinX,
|
||||
EmMinY = blob.MinY,
|
||||
EmMaxX = blob.MaxX,
|
||||
EmMaxY = blob.MaxY,
|
||||
AnchorEmX = 0f,
|
||||
AnchorEmY = 0f,
|
||||
ScreenX = gx,
|
||||
ScreenY = gy,
|
||||
M00 = scale,
|
||||
M01 = 0f,
|
||||
M10 = 0f,
|
||||
M11 = -scale,
|
||||
ColorR = r,
|
||||
ColorG = g,
|
||||
ColorB = b,
|
||||
ColorA = a,
|
||||
AtlasTexelOffset = blob.AtlasOffset,
|
||||
Flags = stemDarken ? HbGpuQuadInstance.FlagStemDarken : 0u,
|
||||
ClipMinPacked = clipMinPacked,
|
||||
ClipMaxPacked = clipMaxPacked
|
||||
};
|
||||
}
|
||||
|
||||
penX += sg.XAdvance * scale;
|
||||
penY -= sg.YAdvance * scale;
|
||||
}
|
||||
|
||||
return penX - x;
|
||||
}
|
||||
}
|
||||
111
src/RustToDust.HbGpu/HbGpuFontCache.cs
Normal file
111
src/RustToDust.HbGpu/HbGpuFontCache.cs
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace RustToDust.HbGpu;
|
||||
|
||||
/// <summary>
|
||||
/// Owns loaded font faces and lazy quantized-axis (wght, wdth, slnt) hb_font_t* handles.
|
||||
/// Avoids per-frame hb_font_set_variations thrash.
|
||||
/// </summary>
|
||||
public sealed unsafe class HbGpuFontCache : IDisposable
|
||||
{
|
||||
private readonly Dictionary<byte, IntPtr> _baseFaces = new();
|
||||
private readonly Dictionary<byte, RtdHbFontMetrics> _metrics = new();
|
||||
private readonly Dictionary<HbGpuStyleKey, IntPtr> _styles = new();
|
||||
private bool _disposed;
|
||||
|
||||
public byte RegisterFontFromFile(byte fontId, string path, uint faceIndex = 0)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
byte[] bytes = File.ReadAllBytes(path);
|
||||
return RegisterFont(fontId, bytes, faceIndex);
|
||||
}
|
||||
|
||||
public byte RegisterFont(byte fontId, ReadOnlySpan<byte> ttfBytes, uint faceIndex = 0)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (ttfBytes.IsEmpty)
|
||||
{
|
||||
throw new ArgumentException("Font bytes cannot be empty.", nameof(ttfBytes));
|
||||
}
|
||||
|
||||
if (_baseFaces.TryGetValue(fontId, out IntPtr existing) && existing != IntPtr.Zero)
|
||||
{
|
||||
throw new InvalidOperationException($"FontId {fontId} is already registered.");
|
||||
}
|
||||
|
||||
fixed (byte* ptr = ttfBytes)
|
||||
{
|
||||
IntPtr baseHandle = HbGpuNative.FontCreate(ptr, (uint)ttfBytes.Length, faceIndex, out RtdHbFontMetrics metrics);
|
||||
if (baseHandle == IntPtr.Zero)
|
||||
{
|
||||
throw new InvalidOperationException($"rtd_hb_font_create failed for FontId {fontId}.");
|
||||
}
|
||||
|
||||
_baseFaces[fontId] = baseHandle;
|
||||
_metrics[fontId] = metrics;
|
||||
}
|
||||
|
||||
return fontId;
|
||||
}
|
||||
|
||||
public RtdHbFontMetrics GetMetrics(byte fontId) => _metrics[fontId];
|
||||
|
||||
public bool TryGetMetrics(byte fontId, out RtdHbFontMetrics metrics) =>
|
||||
_metrics.TryGetValue(fontId, out metrics);
|
||||
|
||||
public IntPtr GetOrCreateStyle(HbGpuStyleKey key)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_styles.TryGetValue(key, out IntPtr handle))
|
||||
{
|
||||
return handle;
|
||||
}
|
||||
|
||||
if (!_baseFaces.TryGetValue(key.FontId, out IntPtr baseHandle))
|
||||
{
|
||||
throw new KeyNotFoundException($"FontId {key.FontId} is not registered in HbGpuFontCache.");
|
||||
}
|
||||
|
||||
float wght = key.QWght;
|
||||
float wdth = key.QWdth * 0.1f;
|
||||
float slnt = key.QSlnt * 0.1f;
|
||||
IntPtr variant = HbGpuNative.FontCreateVariant(baseHandle, wght, wdth, slnt);
|
||||
if (variant == IntPtr.Zero)
|
||||
{
|
||||
throw new InvalidOperationException($"rtd_hb_font_create_variant failed for {key}.");
|
||||
}
|
||||
|
||||
_styles[key] = variant;
|
||||
return variant;
|
||||
}
|
||||
|
||||
public IntPtr GetOrCreateStyle(byte fontId, float wght, float wdth, float slnt) =>
|
||||
GetOrCreateStyle(HbGpuStyleKey.FromAxes(fontId, wght, wdth, slnt));
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
|
||||
foreach (IntPtr handle in _styles.Values)
|
||||
{
|
||||
if (handle != IntPtr.Zero)
|
||||
{
|
||||
HbGpuNative.FontDestroy(handle);
|
||||
}
|
||||
}
|
||||
_styles.Clear();
|
||||
|
||||
foreach (IntPtr baseHandle in _baseFaces.Values)
|
||||
{
|
||||
if (baseHandle != IntPtr.Zero)
|
||||
{
|
||||
HbGpuNative.FontDestroy(baseHandle);
|
||||
}
|
||||
}
|
||||
_baseFaces.Clear();
|
||||
_metrics.Clear();
|
||||
}
|
||||
}
|
||||
66
src/RustToDust.HbGpu/HbGpuNative.cs
Normal file
66
src/RustToDust.HbGpu/HbGpuNative.cs
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RustToDust.HbGpu;
|
||||
|
||||
public static unsafe class HbGpuNative
|
||||
{
|
||||
public const string LibraryName = "rtd_hbgpu";
|
||||
|
||||
[DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_version_string")]
|
||||
private static extern IntPtr NativeVersionString();
|
||||
|
||||
[DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_shader_source")]
|
||||
private static extern IntPtr NativeShaderSource(uint stage, uint kind);
|
||||
|
||||
[DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_font_create")]
|
||||
public static extern IntPtr FontCreate(
|
||||
byte* ttf,
|
||||
uint len,
|
||||
uint faceIndex,
|
||||
out RtdHbFontMetrics outMetrics);
|
||||
|
||||
[DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_font_create_variant")]
|
||||
public static extern IntPtr FontCreateVariant(
|
||||
IntPtr baseFont,
|
||||
float wght,
|
||||
float wdth,
|
||||
float slnt);
|
||||
|
||||
[DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_font_destroy")]
|
||||
public static extern void FontDestroy(IntPtr font);
|
||||
|
||||
[DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_shape_utf16")]
|
||||
public static extern uint ShapeUtf16(
|
||||
IntPtr font,
|
||||
char* utf16,
|
||||
uint charLen,
|
||||
uint featureFlags,
|
||||
RtdHbShapedGlyph* outGlyphs,
|
||||
uint cap);
|
||||
|
||||
[DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_encode_glyph")]
|
||||
public static extern int EncodeGlyph(
|
||||
IntPtr font,
|
||||
uint glyphId,
|
||||
short* outRgba16i,
|
||||
uint capTexels,
|
||||
out RtdHbExtents outExt);
|
||||
|
||||
[DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_encode_path")]
|
||||
public static extern int EncodePath(
|
||||
uint designUpem,
|
||||
byte* verbs,
|
||||
uint nVerbs,
|
||||
float* args,
|
||||
uint nArgs,
|
||||
short* outRgba16i,
|
||||
uint capTexels,
|
||||
out RtdHbExtents outExt);
|
||||
|
||||
public static string GetVersionString() =>
|
||||
Marshal.PtrToStringUTF8(NativeVersionString()) ?? string.Empty;
|
||||
|
||||
public static string GetShaderSource(HbGpuShaderStage stage, HbGpuShaderKind kind) =>
|
||||
Marshal.PtrToStringUTF8(NativeShaderSource((uint)stage, (uint)kind)) ?? string.Empty;
|
||||
}
|
||||
151
src/RustToDust.HbGpu/HbGpuTypes.cs
Normal file
151
src/RustToDust.HbGpu/HbGpuTypes.cs
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RustToDust.HbGpu;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct RtdHbFontMetrics
|
||||
{
|
||||
public int Upem;
|
||||
public int Ascender;
|
||||
public int Descender;
|
||||
public int LineGap;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct RtdHbShapedGlyph
|
||||
{
|
||||
public uint GlyphId;
|
||||
public uint Cluster;
|
||||
public int XAdvance;
|
||||
public int YAdvance;
|
||||
public int XOffset;
|
||||
public int YOffset;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct RtdHbExtents
|
||||
{
|
||||
public int MinX;
|
||||
public int MinY;
|
||||
public int MaxX;
|
||||
public int MaxY;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 80-byte GPU quad instance matching the std430 SSBO layout in HbGpuCanvas.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
public struct HbGpuQuadInstance
|
||||
{
|
||||
public float EmMinX;
|
||||
public float EmMinY;
|
||||
public float EmMaxX;
|
||||
public float EmMaxY;
|
||||
|
||||
public float AnchorEmX;
|
||||
public float AnchorEmY;
|
||||
public float ScreenX;
|
||||
public float ScreenY;
|
||||
|
||||
public float M00;
|
||||
public float M01;
|
||||
public float M10;
|
||||
public float M11;
|
||||
|
||||
public float ColorR;
|
||||
public float ColorG;
|
||||
public float ColorB;
|
||||
public float ColorA;
|
||||
|
||||
public uint AtlasTexelOffset;
|
||||
public uint Flags;
|
||||
public uint ClipMinPacked;
|
||||
public uint ClipMaxPacked;
|
||||
|
||||
public const uint FlagStemDarken = 1u;
|
||||
public const uint Unclipped = 0xFFFFFFFFu;
|
||||
}
|
||||
|
||||
[Flags]
|
||||
public enum HbGpuFeatureFlags : uint
|
||||
{
|
||||
None = 0u,
|
||||
Calt = 1u << 0,
|
||||
Liga = 1u << 1,
|
||||
Default = Calt | Liga
|
||||
}
|
||||
|
||||
public enum HbGpuPathVerb : byte
|
||||
{
|
||||
Move = 0,
|
||||
LineTo = 1,
|
||||
QuadTo = 2,
|
||||
CubicTo = 3,
|
||||
Close = 4,
|
||||
Line = 5,
|
||||
Rect = 6,
|
||||
Circle = 7
|
||||
}
|
||||
|
||||
public enum HbGpuShaderStage : uint
|
||||
{
|
||||
Vertex = 0,
|
||||
Fragment = 1
|
||||
}
|
||||
|
||||
public enum HbGpuShaderKind : uint
|
||||
{
|
||||
Shared = 0,
|
||||
Draw = 1
|
||||
}
|
||||
|
||||
public enum VectorShapeKind : ushort
|
||||
{
|
||||
UnitFilledRect = 1,
|
||||
UnitCircleFill = 2,
|
||||
UnitRingStroke = 3,
|
||||
CornerLBracket = 4,
|
||||
TargetBracketCorner = 5,
|
||||
DirectionalArrow = 6,
|
||||
ChevronTriangle = 7,
|
||||
DiamondBlip = 8,
|
||||
HitMarkerArm = 9,
|
||||
StrippedHatchX = 10,
|
||||
PanelFrame = 11,
|
||||
HardpointBracket = 12,
|
||||
ThermalHeatArc = 13,
|
||||
IncomingHitArc = 14,
|
||||
Custom = 100
|
||||
}
|
||||
|
||||
public readonly record struct HbGpuStyleKey(byte FontId, ushort QWght, ushort QWdth, short QSlnt)
|
||||
{
|
||||
public static ushort QuantizeWeight(float wght) =>
|
||||
(ushort)Math.Clamp((int)MathF.Round(wght), 100, 1000);
|
||||
|
||||
public static ushort QuantizeWidth(float wdth) =>
|
||||
(ushort)Math.Clamp((int)MathF.Round(wdth * 10f), 500, 2000);
|
||||
|
||||
public static short QuantizeSlant(float slnt) =>
|
||||
(short)Math.Clamp((int)MathF.Round(slnt * 10f), -200, 200);
|
||||
|
||||
public static HbGpuStyleKey FromAxes(byte fontId, float wght, float wdth, float slnt) =>
|
||||
new(fontId, QuantizeWeight(wght), QuantizeWidth(wdth), QuantizeSlant(slnt));
|
||||
}
|
||||
|
||||
public readonly record struct GlyphBlobKey(byte FontId, uint GlyphId, ushort QWght, ushort QWdth, short QSlnt);
|
||||
|
||||
public readonly record struct VectorBlobKey(VectorShapeKind Kind, ushort ParamA, ushort ParamB, uint ParamC = 0);
|
||||
|
||||
public readonly record struct CachedBlob(
|
||||
uint AtlasOffset,
|
||||
short MinX,
|
||||
short MinY,
|
||||
short MaxX,
|
||||
short MaxY,
|
||||
uint TexelCount,
|
||||
bool IsEmpty)
|
||||
{
|
||||
public bool IsValid => TexelCount > 0 && !IsEmpty;
|
||||
}
|
||||
209
src/RustToDust.HbGpu/HbGpuVectorShapes.cs
Normal file
209
src/RustToDust.HbGpu/HbGpuVectorShapes.cs
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
using System;
|
||||
|
||||
namespace RustToDust.HbGpu;
|
||||
|
||||
/// <summary>
|
||||
/// Encodes canonical UI/HUD vector primitives into HarfBuzz hb-gpu RGBA16I blobs
|
||||
/// in a 1000-unit design space ([-500 .. +500] or [0 .. 1000]).
|
||||
/// </summary>
|
||||
public static class HbGpuVectorShapes
|
||||
{
|
||||
public const uint DesignUpem = 1000u;
|
||||
|
||||
private static readonly byte[] RectVerbs = { (byte)HbGpuPathVerb.Rect };
|
||||
private static readonly float[] UnitFilledRectArgs = { -500f, -500f, 1000f, 1000f, float.NaN };
|
||||
|
||||
private static readonly byte[] CircleVerbs = { (byte)HbGpuPathVerb.Circle };
|
||||
private static readonly float[] UnitFilledCircleArgs = { 0f, 0f, 500f, float.NaN };
|
||||
|
||||
// L-corner bracket centered around (0,0) pointing into (+X, +Y), design space 1000x1000
|
||||
// Thickness paramB in thousandths (e.g. 100 = 10% of arm length)
|
||||
private static readonly byte[] CornerBracketVerbs =
|
||||
{
|
||||
(byte)HbGpuPathVerb.Move,
|
||||
(byte)HbGpuPathVerb.LineTo,
|
||||
(byte)HbGpuPathVerb.LineTo,
|
||||
(byte)HbGpuPathVerb.LineTo,
|
||||
(byte)HbGpuPathVerb.LineTo,
|
||||
(byte)HbGpuPathVerb.LineTo,
|
||||
(byte)HbGpuPathVerb.Close
|
||||
};
|
||||
|
||||
// Equilateral/tactical chevron pointing +Y (Y-up in design space -> -Y in Y-down screen)
|
||||
private static readonly byte[] ChevronVerbs =
|
||||
{
|
||||
(byte)HbGpuPathVerb.Move,
|
||||
(byte)HbGpuPathVerb.LineTo,
|
||||
(byte)HbGpuPathVerb.LineTo,
|
||||
(byte)HbGpuPathVerb.LineTo,
|
||||
(byte)HbGpuPathVerb.Close
|
||||
};
|
||||
private static readonly float[] ChevronArgs =
|
||||
{
|
||||
0f, 500f,
|
||||
420f, -380f,
|
||||
0f, -140f,
|
||||
-420f, -380f
|
||||
};
|
||||
|
||||
// Solid directional arrow pointing +Y in design space
|
||||
private static readonly float[] ArrowArgs =
|
||||
{
|
||||
0f, 520f,
|
||||
400f, -360f,
|
||||
0f, -180f,
|
||||
-400f, -360f
|
||||
};
|
||||
|
||||
// Diamond blip centered at (0,0)
|
||||
private static readonly float[] DiamondArgs =
|
||||
{
|
||||
0f, 500f,
|
||||
500f, 0f,
|
||||
0f, -500f,
|
||||
-500f, 0f
|
||||
};
|
||||
|
||||
public static CachedBlob GetUnitFilledRect(HbGpuBlobCache cache) =>
|
||||
cache.GetOrEncodeStaticPath(
|
||||
new VectorBlobKey(VectorShapeKind.UnitFilledRect, 0, 0),
|
||||
DesignUpem,
|
||||
RectVerbs,
|
||||
UnitFilledRectArgs);
|
||||
|
||||
public static CachedBlob GetUnitFilledCircle(HbGpuBlobCache cache) =>
|
||||
cache.GetOrEncodeStaticPath(
|
||||
new VectorBlobKey(VectorShapeKind.UnitCircleFill, 0, 0),
|
||||
DesignUpem,
|
||||
CircleVerbs,
|
||||
UnitFilledCircleArgs);
|
||||
|
||||
public static CachedBlob GetUnitRingStroke(HbGpuBlobCache cache, ushort strokeUnits = 24)
|
||||
{
|
||||
Span<float> args = stackalloc float[] { 0f, 0f, 500f, strokeUnits };
|
||||
return cache.GetOrEncodeStaticPath(
|
||||
new VectorBlobKey(VectorShapeKind.UnitRingStroke, strokeUnits, 0),
|
||||
DesignUpem,
|
||||
CircleVerbs,
|
||||
args);
|
||||
}
|
||||
|
||||
public static CachedBlob GetTargetBracketCorner(HbGpuBlobCache cache, ushort thicknessUnits = 120)
|
||||
{
|
||||
float t = Math.Clamp((float)thicknessUnits, 10f, 450f);
|
||||
Span<float> args = stackalloc float[]
|
||||
{
|
||||
0f, 0f,
|
||||
1000f, 0f,
|
||||
1000f, -t,
|
||||
t, -t,
|
||||
t, -1000f,
|
||||
0f, -1000f
|
||||
};
|
||||
return cache.GetOrEncodeStaticPath(
|
||||
new VectorBlobKey(VectorShapeKind.TargetBracketCorner, thicknessUnits, 0),
|
||||
DesignUpem,
|
||||
CornerBracketVerbs,
|
||||
args);
|
||||
}
|
||||
|
||||
public static CachedBlob GetChevronTriangle(HbGpuBlobCache cache) =>
|
||||
cache.GetOrEncodeStaticPath(
|
||||
new VectorBlobKey(VectorShapeKind.ChevronTriangle, 0, 0),
|
||||
DesignUpem,
|
||||
ChevronVerbs,
|
||||
ChevronArgs);
|
||||
|
||||
public static CachedBlob GetDirectionalArrow(HbGpuBlobCache cache) =>
|
||||
cache.GetOrEncodeStaticPath(
|
||||
new VectorBlobKey(VectorShapeKind.DirectionalArrow, 0, 0),
|
||||
DesignUpem,
|
||||
ChevronVerbs,
|
||||
ArrowArgs);
|
||||
|
||||
public static CachedBlob GetDiamondBlip(HbGpuBlobCache cache) =>
|
||||
cache.GetOrEncodeStaticPath(
|
||||
new VectorBlobKey(VectorShapeKind.DiamondBlip, 0, 0),
|
||||
DesignUpem,
|
||||
ChevronVerbs,
|
||||
DiamondArgs);
|
||||
|
||||
/// <summary>
|
||||
/// Encodes a stroked circular arc in design space (radius=500, Y-up) using cubic Bezier segments.
|
||||
/// Useful for thermal heat arcs and directional incoming-hit arcs.
|
||||
/// Angles are in radians counter-clockwise from +X (Y-up).
|
||||
/// </summary>
|
||||
public static CachedBlob EncodeArcStrokeDynamic(
|
||||
HbGpuBlobCache cache,
|
||||
float startRad,
|
||||
float endRad,
|
||||
float radius = 500f,
|
||||
float halfThickness = 32f)
|
||||
{
|
||||
float sweep = endRad - startRad;
|
||||
if (MathF.Abs(sweep) < 1e-4f)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
int segs = Math.Clamp((int)MathF.Ceiling(MathF.Abs(sweep) / (MathF.PI * 0.4f)), 1, 8);
|
||||
float rOut = radius + halfThickness;
|
||||
float rIn = MathF.Max(1f, radius - halfThickness);
|
||||
float dt = sweep / segs;
|
||||
float k = (4f / 3f) * MathF.Tan(dt * 0.25f);
|
||||
|
||||
// 1 Move + segs CubicTo + 1 LineTo + segs CubicTo + 1 Close
|
||||
int nVerbs = 1 + segs + 1 + segs + 1;
|
||||
int nArgs = 2 + segs * 6 + 2 + segs * 6;
|
||||
Span<byte> verbs = stackalloc byte[nVerbs];
|
||||
Span<float> args = stackalloc float[nArgs];
|
||||
|
||||
int v = 0;
|
||||
int a = 0;
|
||||
|
||||
float ca0 = MathF.Cos(startRad);
|
||||
float sa0 = MathF.Sin(startRad);
|
||||
verbs[v++] = (byte)HbGpuPathVerb.Move;
|
||||
args[a++] = rOut * ca0;
|
||||
args[a++] = rOut * sa0;
|
||||
|
||||
for (int i = 0; i < segs; i++)
|
||||
{
|
||||
float t0 = startRad + i * dt;
|
||||
float t1 = t0 + dt;
|
||||
float c0 = MathF.Cos(t0), s0 = MathF.Sin(t0);
|
||||
float c1 = MathF.Cos(t1), s1 = MathF.Sin(t1);
|
||||
verbs[v++] = (byte)HbGpuPathVerb.CubicTo;
|
||||
args[a++] = rOut * (c0 - k * s0);
|
||||
args[a++] = rOut * (s0 + k * c0);
|
||||
args[a++] = rOut * (c1 + k * s1);
|
||||
args[a++] = rOut * (s1 - k * c1);
|
||||
args[a++] = rOut * c1;
|
||||
args[a++] = rOut * s1;
|
||||
}
|
||||
|
||||
float ce = MathF.Cos(endRad);
|
||||
float se = MathF.Sin(endRad);
|
||||
verbs[v++] = (byte)HbGpuPathVerb.LineTo;
|
||||
args[a++] = rIn * ce;
|
||||
args[a++] = rIn * se;
|
||||
|
||||
for (int i = segs - 1; i >= 0; i--)
|
||||
{
|
||||
float t1 = startRad + (i + 1) * dt;
|
||||
float t0 = startRad + i * dt;
|
||||
float c1 = MathF.Cos(t1), s1 = MathF.Sin(t1);
|
||||
float c0 = MathF.Cos(t0), s0 = MathF.Sin(t0);
|
||||
verbs[v++] = (byte)HbGpuPathVerb.CubicTo;
|
||||
args[a++] = rIn * (c1 + k * s1);
|
||||
args[a++] = rIn * (s1 - k * c1);
|
||||
args[a++] = rIn * (c0 - k * s0);
|
||||
args[a++] = rIn * (s0 + k * c0);
|
||||
args[a++] = rIn * c0;
|
||||
args[a++] = rIn * s0;
|
||||
}
|
||||
|
||||
verbs[v++] = (byte)HbGpuPathVerb.Close;
|
||||
return cache.EncodeDynamicPath(DesignUpem, verbs[..v], args[..a]);
|
||||
}
|
||||
}
|
||||
42
src/RustToDust.HbGpu/RustToDust.HbGpu.csproj
Normal file
42
src/RustToDust.HbGpu/RustToDust.HbGpu.csproj
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>RustToDust.HbGpu</RootNamespace>
|
||||
<AssemblyName>RustToDust.HbGpu</AssemblyName>
|
||||
<HbGpuNativeConfiguration Condition="'$(HbGpuNativeConfiguration)' == ''">Release</HbGpuNativeConfiguration>
|
||||
<NativeSourceDir>$(MSBuildThisFileDirectory)..\..\native\rtd_hbgpu</NativeSourceDir>
|
||||
<NativeBuildDir>$(MSBuildThisFileDirectory)..\..\artifacts\hbgpu-native\$(HbGpuNativeConfiguration)</NativeBuildDir>
|
||||
<CMakeExe Condition="'$(CMakeExe)' == '' and '$(OS)' == 'Windows_NT' and Exists('C:\Program Files\CMake\bin\cmake.exe')">C:\Program Files\CMake\bin\cmake.exe</CMakeExe>
|
||||
<CMakeExe Condition="'$(CMakeExe)' == ''">cmake</CMakeExe>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(NativeBuildDir)\bin\$(HbGpuNativeConfiguration)\rtd_hbgpu.dll"
|
||||
Link="rtd_hbgpu.dll"
|
||||
CopyToOutputDirectory="Always"
|
||||
CopyToPublishDirectory="Always"
|
||||
Condition="'$(OS)' == 'Windows_NT'" />
|
||||
<None Include="$(NativeBuildDir)\bin\$(HbGpuNativeConfiguration)\librtd_hbgpu.so"
|
||||
Link="librtd_hbgpu.so"
|
||||
CopyToOutputDirectory="Always"
|
||||
CopyToPublishDirectory="Always"
|
||||
Condition="'$(OS)' != 'Windows_NT' and !$([MSBuild]::IsOSPlatform('OSX'))" />
|
||||
<None Include="$(NativeBuildDir)\bin\$(HbGpuNativeConfiguration)\librtd_hbgpu.dylib"
|
||||
Link="librtd_hbgpu.dylib"
|
||||
CopyToOutputDirectory="Always"
|
||||
CopyToPublishDirectory="Always"
|
||||
Condition="$([MSBuild]::IsOSPlatform('OSX'))" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="BuildHbGpuNative"
|
||||
BeforeTargets="PrepareForBuild;GetCopyToOutputDirectoryItems;GetCopyToPublishDirectoryItems"
|
||||
Condition="'$(DesignTimeBuild)' != 'true'">
|
||||
<Exec Command=""$(CMakeExe)" -S "$(NativeSourceDir)" -B "$(NativeBuildDir)" -DCMAKE_BUILD_TYPE=$(HbGpuNativeConfiguration)" />
|
||||
<Exec Command=""$(CMakeExe)" --build "$(NativeBuildDir)" --config $(HbGpuNativeConfiguration) --target rtd_hbgpu --parallel" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
178
tests/RustToDust.Tests/HbGpuNativeTests.cs
Normal file
178
tests/RustToDust.Tests/HbGpuNativeTests.cs
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using RustToDust.HbGpu;
|
||||
using Xunit;
|
||||
|
||||
namespace RustToDust.Tests;
|
||||
|
||||
public sealed class HbGpuNativeTests
|
||||
{
|
||||
private static string RepoRoot
|
||||
{
|
||||
get
|
||||
{
|
||||
string? dir = AppContext.BaseDirectory;
|
||||
while (dir is not null)
|
||||
{
|
||||
if (File.Exists(Path.Combine(dir, "RustToDust.slnx")))
|
||||
{
|
||||
return dir;
|
||||
}
|
||||
dir = Directory.GetParent(dir)?.FullName;
|
||||
}
|
||||
throw new DirectoryNotFoundException("Could not locate RustToDust.slnx from test output directory.");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NativeDllExistsAndMeetsSizeBudget()
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
string dllPath = Path.Combine(AppContext.BaseDirectory, "rtd_hbgpu.dll");
|
||||
Assert.True(File.Exists(dllPath), $"Expected rtd_hbgpu.dll at '{dllPath}'.");
|
||||
long size = new FileInfo(dllPath).Length;
|
||||
Assert.InRange(size, 100_000, 2_621_440); // < 2.5 MiB
|
||||
}
|
||||
|
||||
string ver = HbGpuNative.GetVersionString();
|
||||
Assert.Equal("15.2.0", ver);
|
||||
|
||||
string vertShared = HbGpuNative.GetShaderSource(HbGpuShaderStage.Vertex, HbGpuShaderKind.Shared);
|
||||
string fragShared = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Shared);
|
||||
string fragDraw = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Draw);
|
||||
Assert.Contains("hb_gpu_dilate", vertShared);
|
||||
Assert.Contains("uniform isamplerBuffer hb_gpu_atlas;", fragShared);
|
||||
Assert.Contains("hb_gpu_draw", fragDraw);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void KryptonFontAndLicensesAreCompliant()
|
||||
{
|
||||
string root = RepoRoot;
|
||||
string fontPath = Path.Combine(root, "assets", "fonts", "Krypton.ttf");
|
||||
string oflPath = Path.Combine(root, "assets", "fonts", "OFL-1.1.txt");
|
||||
string hbCopyPath = Path.Combine(root, "assets", "fonts", "HARFBUZZ-COPYING.txt");
|
||||
string noticesPath = Path.Combine(root, "THIRD_PARTY_NOTICES.txt");
|
||||
|
||||
Assert.True(File.Exists(fontPath));
|
||||
Assert.True(File.Exists(oflPath));
|
||||
Assert.True(File.Exists(hbCopyPath));
|
||||
Assert.True(File.Exists(noticesPath));
|
||||
|
||||
byte[] fontBytes = File.ReadAllBytes(fontPath);
|
||||
Assert.Equal(1_363_340, fontBytes.Length);
|
||||
string sha = Convert.ToHexString(SHA256.HashData(fontBytes)).ToLowerInvariant();
|
||||
Assert.Equal("6462cae55b336ae6ffb7c8f1932177960510a4207e65803f527b276d42c8a240", sha);
|
||||
|
||||
string oflText = File.ReadAllText(oflPath);
|
||||
Assert.Contains("Copyright (c) 2023, GitHub", oflText);
|
||||
Assert.Contains("Krypton", oflText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void QuadInstanceStructIs80Bytes()
|
||||
{
|
||||
Assert.Equal(80, Unsafe.SizeOf<HbGpuQuadInstance>());
|
||||
Assert.Equal(80, Marshal.SizeOf<HbGpuQuadInstance>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ShapingAndGlyphEncodingWorkAcrossKryptonAxes()
|
||||
{
|
||||
string fontPath = Path.Combine(RepoRoot, "assets", "fonts", "Krypton.ttf");
|
||||
using var fonts = new HbGpuFontCache();
|
||||
fonts.RegisterFontFromFile(0, fontPath);
|
||||
|
||||
RtdHbFontMetrics metrics = fonts.GetMetrics(0);
|
||||
Assert.Equal(2000, metrics.Upem);
|
||||
|
||||
var atlas = new HbGpuAtlasAllocator();
|
||||
var blobs = new HbGpuBlobCache(atlas);
|
||||
var writer = new HbGpuCommandWriter();
|
||||
|
||||
writer.BeginFrame();
|
||||
float wReg = writer.DrawTextUtf16("RAPTOR -> 142.8m", 10f, 40f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 200f);
|
||||
float wBold = writer.DrawTextUtf16("CHASSIS", 10f, 80f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 700f);
|
||||
float wSlnt = writer.DrawTextUtf16("SLANT", 10f, 120f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 400f, slnt: -9f);
|
||||
|
||||
Assert.True(wReg > 50f);
|
||||
Assert.True(wBold > 20f);
|
||||
Assert.True(wSlnt > 20f);
|
||||
Assert.True(writer.QuadCount >= 18); // spaces omit quads, visible glyphs emit quads
|
||||
Assert.True(blobs.CachedGlyphCount >= 15);
|
||||
Assert.True(atlas.PersistentCursor > 0);
|
||||
Assert.True(atlas.PendingChunkCount > 0);
|
||||
|
||||
// Space glyph encodes cleanly as empty
|
||||
CachedBlob spaceBlob = blobs.GetOrEncodeGlyph(fonts, 0, 1 /* glyph or verify space */, 200, 1000, 0);
|
||||
Assert.True(spaceBlob.TexelCount >= 0);
|
||||
|
||||
// Hot steady-state loop allocates zero managed bytes once glyphs/styles are cached
|
||||
writer.BeginFrame();
|
||||
atlas.ClearPending();
|
||||
ReadOnlySpan<char> hotText = "RAPTOR -> 142.8m";
|
||||
long before = GC.GetAllocatedBytesForCurrentThread();
|
||||
for (int i = 0; i < 64; i++)
|
||||
{
|
||||
writer.BeginFrame();
|
||||
writer.DrawTextUtf16(hotText, 10f, 40f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 200f);
|
||||
}
|
||||
long after = GC.GetAllocatedBytesForCurrentThread();
|
||||
Assert.Equal(0, after - before);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void VectorPathsAndAtlasBudgetResetWork()
|
||||
{
|
||||
var atlas = new HbGpuAtlasAllocator();
|
||||
var blobs = new HbGpuBlobCache(atlas);
|
||||
|
||||
CachedBlob rect = HbGpuVectorShapes.GetUnitFilledRect(blobs);
|
||||
CachedBlob circle = HbGpuVectorShapes.GetUnitFilledCircle(blobs);
|
||||
CachedBlob ring = HbGpuVectorShapes.GetUnitRingStroke(blobs, 24);
|
||||
CachedBlob bracket = HbGpuVectorShapes.GetTargetBracketCorner(blobs, 120);
|
||||
CachedBlob arrow = HbGpuVectorShapes.GetDirectionalArrow(blobs);
|
||||
CachedBlob chevron = HbGpuVectorShapes.GetChevronTriangle(blobs);
|
||||
CachedBlob diamond = HbGpuVectorShapes.GetDiamondBlip(blobs);
|
||||
CachedBlob arc = HbGpuVectorShapes.EncodeArcStrokeDynamic(blobs, -2.356f, 0.785f);
|
||||
|
||||
Assert.True(rect.IsValid && rect.TexelCount > 2);
|
||||
Assert.True(circle.IsValid && circle.TexelCount > 2);
|
||||
Assert.True(ring.IsValid && ring.TexelCount > 4);
|
||||
Assert.True(bracket.IsValid && bracket.TexelCount > 2);
|
||||
Assert.True(arrow.IsValid && arrow.TexelCount > 2);
|
||||
Assert.True(chevron.IsValid && chevron.TexelCount > 2);
|
||||
Assert.True(diamond.IsValid && diamond.TexelCount > 2);
|
||||
Assert.True(arc.IsValid && arc.TexelCount > 4);
|
||||
Assert.True(arc.AtlasOffset >= HbGpuAtlasAllocator.DynamicBase);
|
||||
|
||||
// Also test tapered line verb directly
|
||||
Span<byte> lineVerb = stackalloc byte[] { (byte)HbGpuPathVerb.Line };
|
||||
Span<float> lineArgs = stackalloc float[] { -400f, 0f, 20f, 400f, 0f, 60f, 1f };
|
||||
CachedBlob lineBlob = blobs.GetOrEncodeStaticPath(
|
||||
new VectorBlobKey(VectorShapeKind.Custom, 1, 0), 1000u, lineVerb, lineArgs);
|
||||
Assert.True(lineBlob.IsValid);
|
||||
|
||||
// Drain uploads with zero allocations
|
||||
byte[] staging = new byte[HbGpuBlobCache.ScratchShortsCapacity * sizeof(short)];
|
||||
int drainedBytes = 0;
|
||||
Action<uint, uint> cb = (_, len) => drainedBytes += (int)len;
|
||||
int chunks = atlas.DrainChunks(staging, cb);
|
||||
Assert.True(chunks >= 9);
|
||||
Assert.True(drainedBytes > 0);
|
||||
Assert.Equal(0, atlas.PendingChunkCount);
|
||||
|
||||
// Verify dynamic ring wrap-around
|
||||
for (int i = 0; i < 600; i++)
|
||||
{
|
||||
CachedBlob dyn = HbGpuVectorShapes.EncodeArcStrokeDynamic(blobs, -1.5f, 1.5f);
|
||||
Assert.True(dyn.AtlasOffset >= HbGpuAtlasAllocator.DynamicBase);
|
||||
Assert.True(dyn.AtlasOffset + dyn.TexelCount <= HbGpuAtlasAllocator.TotalTexels);
|
||||
atlas.ClearPending();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -23,6 +23,7 @@
|
|||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\RustToDust.Core\RustToDust.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\RustToDust.Ymir\RustToDust.Ymir.csproj" />
|
||||
<ProjectReference Include="..\..\src\RustToDust.HbGpu\RustToDust.HbGpu.csproj" AdditionalProperties="HbGpuNativeConfiguration=$(YmirNativeConfiguration)" />
|
||||
<ProjectReference Include="..\..\src\RustToDust.Net\RustToDust.Net.csproj" />
|
||||
<ProjectReference Include="..\..\src\RustToDust.Directory\RustToDust.Directory.csproj" />
|
||||
<ProjectReference Include="$(YmirRoot)/src/Ymir.Box3D/Ymir.Box3D.csproj" AdditionalProperties="YmirNativeConfiguration=$(YmirNativeConfiguration)" />
|
||||
|
|
|
|||
Loading…
Reference in a new issue