Files
sbox-public/engine/Sandbox.Engine/Core/Interop/Interop.cs
Garry Newman d27c236689 UI additions and optimizations (#4968)
ADDED
css min(), max() and clamp() for lengths
css-wide keywords inherit, initial, unset, revert (incl. shorthands)
added currentColor keyword to css
colors can parse oklch(), lab() and hwb()
added css text-align: justify
css white-space: pre-wrap and break-spaces
added css word-break: break-word
parses css image-rendering: crisp-edges (point sampling)
added css inset shorthand
now parses 1–4 values in the css border-width shorthand
added css transition-duration, -delay, -property and -timing-function longhands
css :has() now supports descendant selectors
added css opacity percentages
added css overflow: auto (maps to scroll)
added css gap: normal
added css filter: none
css transform: scale() now takes comma-separated args
css animations now accept ms units
added more css justify-content, align-* and text-align keywords (start, end, …)
parses css dvh/svh/lvh/dvw viewport units (treated as vh/vw)
parses css object-fit: scale-down (treated as contain)
added css margin-block / margin-inline (+ the logical margin sides)
added css padding-block / padding-inline (+ the logical padding sides)
added css inset-block / inset-inline (+ the logical inset sides)
added the css flex-flow shorthand
added the css font shorthand
added css font-size keywords (xx-small … xxx-large)
css letter-spacing and word-spacing now accept normal
added css font-smooth: none
css aspect-ratio now accepts the auto form
css font-family now maps generic families (serif, sans-serif, monospace)
added css flex-flow
added css font

FIXED
fixed css !important dropping the whole declaration
css line-height without units is now a multiplier
fixed css calc() division and full-expression parsing
fixed the css flex shorthand for single-number and three-value forms
fixed the css transition shorthand when the property is omitted
css font-family now uses the first family in a comma stack
colors now parse fully in the css background shorthand
an unknown css @-rule no longer drops the whole stylesheet
css variables no longer match on partial tokens
injected css variables are kept across stylesheet hotloads
fixed css selector specificity overflowing when comparing rules
css background: none now resets the background (image and colour)
css filter: none now overrides a filter set by a base class
css transform: none now overrides a transform set by a base class

IMPROVED
css rule matching is ~3–5× faster on large stylesheets (rules indexed by class)
~2× fewer allocations in css transitions (snapshot styles once, not per property)
finished css animations no longer re-layout every frame
less GC in css sibling/child selector queries (no list copies or wrappers)
less GC diffing active css rules (no LINQ or hashsets)
faster, lower-GC Yoga layout wrapper
css stylesheet hotload now watches newly imported files
2026-06-02 19:19:23 +01:00

223 lines
5.5 KiB
C#

using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace Sandbox;
internal unsafe static partial class Interop
{
private static Logger log = Logging.GetLogger();
// Native can call back into managed (and thus allocate temporary return strings)
// from non-main threads, while Free() drains this at frame end on the main thread,
// so this has to be a concurrent collection.
[SkipHotload] static ConcurrentQueue<PassBackString> FrameAllocatedStrings = new();
public static int Free()
{
int i = 0;
while ( FrameAllocatedStrings.TryDequeue( out var entry ) )
{
entry.Free();
i++;
}
return i;
}
const int maxNativeString = 1024 * 1024 * 64; // a 64mb string sounds sensible!
/// <summary>
/// Convert a native utf pointer to a string
/// </summary>
public static string GetString( IntPtr pointer )
{
if ( pointer == IntPtr.Zero )
return null;
// Uses the runtime's vectorized strlen to find the null terminator
var span = MemoryMarshal.CreateReadOnlySpanFromNullTerminated( (byte*)pointer );
if ( span.Length >= maxNativeString )
{
Log.Warning( "Really long, or really invalid string detected" );
return null;
}
if ( span.IsEmpty )
return string.Empty;
return Encoding.UTF8.GetString( span );
}
/// <summary>
/// Convert a native utf pointer to a string
/// </summary>
public static string GetString( IntPtr pointer, int byteLen )
{
if ( pointer == IntPtr.Zero || byteLen < 0 )
return null;
if ( byteLen == 0 )
return string.Empty;
return Encoding.UTF8.GetString( (byte*)pointer, byteLen );
}
/// <summary>
/// Convert a native utf pointer to a string
/// </summary>
public static string GetWString( IntPtr pointer )
{
if ( pointer == IntPtr.Zero )
return null;
return Marshal.PtrToStringUni( pointer );
}
/// <summary>
/// Convert a native utf pointer to a string
/// </summary>
public static string GetWString( IntPtr pointer, int byteLen )
{
if ( pointer == IntPtr.Zero || byteLen <= 0 )
return null;
return Marshal.PtrToStringUni( pointer, byteLen );
}
public unsafe ref struct InteropString
{
public IntPtr Pointer;
public InteropString( string str )
{
if ( str is null )
return;
uint nb = (uint)Encoding.UTF8.GetByteCount( str );
byte* mem = (byte*)NativeMemory.Alloc( nb + 1 );
fixed ( char* src = str )
{
Encoding.UTF8.GetBytes( src, str.Length, mem, (int)nb );
}
mem[nb] = 0;
Pointer = (IntPtr)mem;
}
public void Free()
{
NativeMemory.Free( (void*)Pointer );
Pointer = default;
}
}
/// <summary>
/// Called by the binding system to log an exception when calling a binding
/// </summary>
public static void BindingException( string ClassName, string MethodName, Exception e )
{
try
{
log.Error( e, e.Message );
}
catch ( Exception e2 )
{
System.Diagnostics.Debug.WriteLine( "Exception thrown when logging exception: {0}", e2 );
System.Diagnostics.Debug.WriteLine( "Original exception: {0}", e );
}
}
internal static void NativeAssemblyLoadFailed( string libraryName )
{
string errorMessage = $"Failed to load native library '{libraryName}'. Error Code: {Marshal.GetLastWin32Error()}/{Marshal.GetLastSystemError()}";
throw new NativeAssemblyLoadException( errorMessage, Marshal.GetLastWin32Error() );
}
/// <summary>
/// Converts a base library name to its platform-specific filename.
/// e.g. "engine2" → "engine2.dll" (Windows), "libengine2.so" (Linux), "libengine2.dylib" (macOS)
/// </summary>
internal static string GetNativeLibraryName( string baseName )
{
var dir = System.IO.Path.GetDirectoryName( baseName ) ?? "";
var name = System.IO.Path.GetFileNameWithoutExtension( baseName );
var platformName = true switch
{
_ when OperatingSystem.IsWindows() => $"{name}.dll",
_ when OperatingSystem.IsLinux() => $"lib{name}.so",
_ when OperatingSystem.IsMacOS() => $"lib{name}.dylib",
_ => throw new PlatformNotSupportedException()
};
return string.IsNullOrEmpty( dir )
? platformName
: System.IO.Path.Combine( dir, platformName );
}
/// <summary>
/// used to pass a string back to native
/// </summary>
public unsafe struct PassBackString
{
public IntPtr Pointer;
public PassBackString( string str )
{
if ( str is null )
return;
uint nb = (uint)Encoding.UTF8.GetByteCount( str );
byte* mem = (byte*)NativeMemory.Alloc( nb + 1 );
fixed ( char* src = str )
{
Encoding.UTF8.GetBytes( src, str.Length, mem, (int)nb );
}
mem[nb] = 0;
Pointer = (IntPtr)mem;
}
public void Free()
{
NativeMemory.Free( (void*)Pointer );
Pointer = default;
}
}
/// <summary>
/// This is called when native calls a managed function and it returns a string. In this case
/// we can't free the string immediately, so we store it in a list and free it at the end of the frame.
/// This has potential to crash, if we free the string before the thread uses it but this would be super
/// rare and the other option is to never return strings like this.
/// </summary>
internal static IntPtr GetTemporaryStringPointerForNative( string str )
{
var f = new PassBackString( str );
FrameAllocatedStrings.Enqueue( f );
return f.Pointer;
}
}
internal class NativeAssemblyLoadException : Exception
{
public int ErrorCode { get; }
public NativeAssemblyLoadException( string message, int errorCode ) : base( message )
{
ErrorCode = errorCode;
}
public override string ToString()
{
return $"{base.ToString()}, ErrorCode: {ErrorCode}";
}
}