diff --git a/.gitignore b/.gitignore index 621a8decd..d53e382d3 100644 --- a/.gitignore +++ b/.gitignore @@ -387,6 +387,7 @@ FodyWeavers.xsd !.vscode/launch.json !.vscode/extensions.json *.code-workspace +.forge/* # Local History for Visual Studio Code .history/ diff --git a/Dependencies/LuaJIT b/Dependencies/LuaJIT index 3546dbfbd..d8b530c2a 160000 --- a/Dependencies/LuaJIT +++ b/Dependencies/LuaJIT @@ -1 +1 @@ -Subproject commit 3546dbfbde5f90dee4defe303258dc3e1d71c5dc +Subproject commit d8b530c2a356a0020d466029fd58a2047bea052e diff --git a/Directory.Build.props b/Directory.Build.props index a19062318..5fe02657b 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -73,6 +73,7 @@ AnyCPU + $(NoWarn);RS2008 diff --git a/Directory.Packages.props b/Directory.Packages.props index cee916b17..295980a01 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -15,6 +15,7 @@ + diff --git a/Game.Assets/runtimes/osx/native/libbass.dylib b/Game.Assets/runtimes/osx/native/libbass.dylib new file mode 100644 index 000000000..c8197de61 Binary files /dev/null and b/Game.Assets/runtimes/osx/native/libbass.dylib differ diff --git a/Game.BASS/BassAudioStream.cs b/Game.BASS/BassAudioStream.cs new file mode 100644 index 000000000..f1aceacd5 --- /dev/null +++ b/Game.BASS/BassAudioStream.cs @@ -0,0 +1,91 @@ +using ManagedBass; + +using Source.Common.Audio; +using Source.Common.GarrysMod; + +using System.Runtime.InteropServices; + +namespace Game.BASS; + +public class BassAudioStream : IBassAudioStream, IDisposable +{ + int Handle; + IAudioStreamEvent? Event; + uint Offset; + GCHandle Self; + + static readonly FileProcedures StreamProcs = new() { + Close = static user => { }, + Length = static user => 0, + Read = StreamRead, + Seek = StreamSeek, + }; + + static BassAudioStream Get(nint user) => (BassAudioStream)GCHandle.FromIntPtr(user).Target!; + + static unsafe int StreamRead(nint buffer, int length, nint user) { + BassAudioStream stream = Get(user); + int read = stream.Event!.StreamRequestData(new Span((void*)buffer, length), length, (int)stream.Offset); + stream.Offset += (uint)read; + return read; + } + + static bool StreamSeek(long offset, nint user) { + if ((ulong)offset > 0x4000000) + return false; + Get(user).Offset = (uint)offset; + return true; + } + + public bool Init(IAudioStreamEvent? eventHandler) { + Event = eventHandler; + Self = GCHandle.Alloc(this); + Handle = Bass.CreateStream(StreamSystem.NoBuffer, BassFlags.Decode | BassFlags.StreamDownloadBlocks | BassFlags.RestrictDownloadRate, StreamProcs, GCHandle.ToIntPtr(Self)); + if (Handle == 0) { + Warning($"Couldn't create BASS audio stream ({GMod_Audio.BassErrorDescription(Bass.LastError)})\n"); + return false; + } + return true; + } + + public void Dispose() { + if (Handle != 0) + Bass.StreamFree(Handle); + if (Self.IsAllocated) + Self.Free(); + } + + public unsafe int Decode(Span buffer) { + if (Handle == 0) + return 0; + int ret; + fixed (byte* ptr = buffer) + ret = Bass.ChannelGetData(Handle, (nint)ptr, buffer.Length); + return ret < 0 ? 0 : ret; + } + + public int GetOutputBits() { + Error("Not used"); + return 0; + } + + public int GetOutputRate() { + Bass.ChannelGetInfo(Handle, out ChannelInfo info); + return info.Frequency == 0 ? 44100 : info.Frequency; + } + + public int GetOutputChannels() { + Bass.ChannelGetInfo(Handle, out ChannelInfo info); + return info.Channels == 0 ? 2 : info.Channels; + } + + public uint GetPosition() { + if (Handle == 0) + return 0; + return (uint)Bass.StreamGetFilePosition(Handle, FileStreamPosition.Current); + } + + public void SetPosition(uint distance) { } + + public uint GetHandle() => (uint)Handle; +} diff --git a/Game.BASS/GModAudioChannel.cs b/Game.BASS/GModAudioChannel.cs new file mode 100644 index 000000000..f826a3183 --- /dev/null +++ b/Game.BASS/GModAudioChannel.cs @@ -0,0 +1,226 @@ +using ManagedBass; + +using Source.Common.GarrysMod; + +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Game.BASS; + +public class GModAudioChannel(int handle, bool isFile, int type, string? fileName) : IGModAudioChannel +{ + int Handle = handle; + readonly bool IsFile = isFile; + readonly int Type = type; + readonly string? FileName = fileName; + + public void Destroy() { + if (Bass.ChannelIsActive(Handle) == PlaybackState.Playing && !IsLooping() && Bass.ChannelGetLength(Handle, PositionFlags.Bytes) >= 0) { + Bass.ChannelFlags(Handle, BassFlags.AutoFree, BassFlags.AutoFree); + Handle = 0; + return; + } + + if (Type == 0) + Bass.StreamFree(Handle); + else if (Type == 1) + Bass.MusicFree(Handle); + + Handle = 0; + } + + public void Stop() => Bass.ChannelStop(Handle); + public void Pause() => Bass.ChannelPause(Handle); + public void Play() => Bass.ChannelPlay(Handle, false); + + public void SetVolume(float volume) => Bass.ChannelSetAttribute(Handle, ChannelAttribute.Volume, volume); + + public float GetVolume() { + Bass.ChannelGetAttribute(Handle, ChannelAttribute.Volume, out float volume); + return volume; + } + + public void SetPlaybackRate(float rate) => Bass.ChannelSetAttribute(Handle, ChannelAttribute.Frequency, rate * GetSamplingRate()); + + public float GetPlaybackRate() { + Bass.ChannelGetAttribute(Handle, ChannelAttribute.Frequency, out float frequency); + if (frequency <= 0.0f) + return 1.0f; + return frequency / GetSamplingRate(); + } + + public void SetPos(in Vector3 position, in Vector3 direction, in Vector3 velocity) { + Bass.ChannelSet3DPosition(Handle, GMod_Audio.ToBass(position), GMod_Audio.ToBass(direction), GMod_Audio.ToBass(velocity)); + Bass.Apply3D(); + } + + public void GetPos(out Vector3 position, out Vector3 direction, out Vector3 velocity) { + Vector3D pos = new(), dir = new(), vel = new(); + Bass.ChannelGet3DPosition(Handle, ref pos, ref dir, ref vel); + position = GMod_Audio.FromBass(pos); + direction = GMod_Audio.FromBass(dir); + velocity = GMod_Audio.FromBass(vel); + } + + public void SetTime(TimeUnit_t time, bool dontDecode) { + long target = Bass.ChannelSeconds2Bytes(Handle, time); + long current = Bass.ChannelGetPosition(Handle, PositionFlags.Bytes); + PositionFlags flags = PositionFlags.Bytes; + if (current < target && !dontDecode) + flags = PositionFlags.DecodeTo; + Bass.ChannelSetPosition(Handle, target, flags); + } + + public TimeUnit_t GetTime() => Bass.ChannelBytes2Seconds(Handle, Bass.ChannelGetPosition(Handle, PositionFlags.Bytes)); + + public TimeUnit_t GetBufferedTime() { + if (IsFile) + return GetLength(); + + long length = Bass.ChannelGetLength(Handle, PositionFlags.Bytes); + long download = Bass.StreamGetFilePosition(Handle, FileStreamPosition.Download); + long start = Bass.StreamGetFilePosition(Handle, FileStreamPosition.Start); + long size = Bass.StreamGetFilePosition(Handle, (FileStreamPosition)8); + double buffered = (double)(ulong)download / (double)(ulong)(size - start) * (double)(ulong)length; + return Bass.ChannelBytes2Seconds(Handle, (long)(ulong)buffered); + } + + public void Set3DFadeDistance(float min, float max) { + Bass.ChannelSet3DAttributes(Handle, Mode3D.LeaveCurrent, min, max, -1, -1, -1.0f); + Bass.Apply3D(); + } + + public void Get3DFadeDistance(out float min, out float max) { + Mode3D mode = 0; + int iangle = 0, oangle = 0; + float outvol = 0; + min = 0; + max = 0; + Bass.ChannelGet3DAttributes(Handle, ref mode, ref min, ref max, ref iangle, ref oangle, ref outvol); + } + + public void Set3DCone(int innerAngle, int outerAngle, float outerVolume) { + if (innerAngle < 0 || outerAngle < 0) { + innerAngle = -1; + outerAngle = -1; + } + Bass.ChannelSet3DAttributes(Handle, Mode3D.LeaveCurrent, -1.0f, -1.0f, innerAngle, outerAngle, outerVolume); + Bass.Apply3D(); + } + + public void Get3DCone(out int innerAngle, out int outerAngle, out float outerVolume) { + Mode3D mode = 0; + float min = 0, max = 0; + innerAngle = 0; + outerAngle = 0; + outerVolume = 0; + Bass.ChannelGet3DAttributes(Handle, ref mode, ref min, ref max, ref innerAngle, ref outerAngle, ref outerVolume); + } + + public int GetState() => Bass.ChannelIsActive(Handle) switch { + PlaybackState.Playing => 1, + PlaybackState.Stalled => 3, + PlaybackState.Paused => 2, + _ => 0, + }; + + public void SetLooping(bool looping) => Bass.ChannelFlags(Handle, looping ? BassFlags.Loop : BassFlags.Default, BassFlags.Loop); + public bool IsLooping() => (Bass.ChannelFlags(Handle, BassFlags.Default, BassFlags.Default) & BassFlags.Loop) != 0; + public bool IsOnline() => !IsFile; + public bool Is3D() => (Bass.ChannelFlags(Handle, BassFlags.Default, BassFlags.Default) & BassFlags.Bass3D) != 0; + public bool IsBlockStreamed() => (Bass.ChannelFlags(Handle, BassFlags.Default, BassFlags.Default) & BassFlags.StreamDownloadBlocks) != 0; + public bool IsValid() => Handle != 0; + + public double GetLength() => Bass.ChannelBytes2Seconds(Handle, Bass.ChannelGetLength(Handle, PositionFlags.Bytes)); + + public ReadOnlySpan GetFileName() { + if (FileName != null) + return FileName; + Bass.ChannelGetInfo(Handle, out ChannelInfo info); + ChannelInfoRaw raw = Unsafe.As(ref info); + if (raw.FileName == 0) + return ""; + return ((raw.Flags & BassFlags.Unicode) != 0 ? Marshal.PtrToStringUni(raw.FileName) : Marshal.PtrToStringAnsi(raw.FileName)) ?? ""; + } + + [StructLayout(LayoutKind.Sequential)] + struct ChannelInfoRaw + { + public int Frequency; + public int Channels; + public BassFlags Flags; + public ChannelType ChannelType; + public int OriginalResolution; + public int Plugin; + public int Sample; + public nint FileName; + } + + public int GetSamplingRate() { + Bass.ChannelGetInfo(Handle, out ChannelInfo info); + return info.Frequency; + } + + public int GetBitsPerSample() { + Bass.ChannelGetInfo(Handle, out ChannelInfo info); + return info.OriginalResolution; + } + + public float GetAverageBitRate() { + Bass.ChannelGetAttribute(Handle, ChannelAttribute.Bitrate, out float bitrate); + return bitrate; + } + + public void GetLevel(out float left, out float right) { + int level = Bass.ChannelIsActive(Handle) == PlaybackState.Playing ? Bass.ChannelGetLevel(Handle) : 0; + left = ((uint)level >> 16) * 3.0517578e-05f; + right = (level & 0xffff) * 3.0517578e-05f; + } + + public int FFT(float[] data, GModChannelFFT size) { + if (Bass.ChannelIsActive(Handle) != PlaybackState.Playing) + return 0; + + (int count, DataFlags flags) = size switch { + GModChannelFFT.FFT_256 => (128, DataFlags.FFT256), + GModChannelFFT.FFT_512 => (256, DataFlags.FFT512), + GModChannelFFT.FFT_2048 => (1024, DataFlags.FFT2048), + GModChannelFFT.FFT_4096 => (2048, DataFlags.FFT4096), + GModChannelFFT.FFT_8192 => (4096, DataFlags.FFT8192), + GModChannelFFT.FFT_16384 => (8192, DataFlags.FFT16384), + GModChannelFFT.FFT_32768 => (16384, DataFlags.FFT32768), + _ => (512, DataFlags.FFT1024), + }; + Bass.ChannelGetData(Handle, data, (int)(flags | DataFlags.Float | DataFlags.FFTRemoveDC)); + return count; + } + + public void SetChannelPan(float pan) => Bass.ChannelSetAttribute(Handle, ChannelAttribute.Pan, pan); + + public float GetChannelPan() { + Bass.ChannelGetAttribute(Handle, ChannelAttribute.Pan, out float pan); + return pan; + } + + public nint GetTags(int type) => Bass.ChannelGetTags(Handle, (TagType)type); + + public void Set3DEnabled(bool enabled) { + if (!Is3D()) + return; + Bass.ChannelSet3DAttributes(Handle, enabled ? Mode3D.Normal : Mode3D.Off, -1.0f, -1.0f, -1, -1, -1.0f); + Bass.Apply3D(); + } + + public bool Get3DEnabled() { + if (!Is3D()) + return false; + Mode3D mode = 0; + float min = 0, max = 0, outvol = 0; + int iangle = 0, oangle = 0; + Bass.ChannelGet3DAttributes(Handle, ref mode, ref min, ref max, ref iangle, ref oangle, ref outvol); + return mode != Mode3D.Off; + } + + public void Restart() => Bass.ChannelPlay(Handle, true); +} diff --git a/Game.BASS/GMod_Audio.cs b/Game.BASS/GMod_Audio.cs new file mode 100644 index 000000000..ad3951620 --- /dev/null +++ b/Game.BASS/GMod_Audio.cs @@ -0,0 +1,269 @@ +using ManagedBass; + +using Microsoft.Extensions.DependencyInjection; + +using Source.Common.Audio; +using Source.Common.Filesystem; +using Source.Common.GarrysMod; + +using System.Numerics; +using System.Runtime.InteropServices; + +namespace Game.BASS; + +public class GMod_Audio : IGMod_Audio +{ + public static readonly GMod_Audio g_GModAudio = new(); + + internal static IFileSystem? filesystem; + + static readonly string[] ErrorStrings = [ + "BASS_OK", "BASS_ERROR_MEM", "BASS_ERROR_FILEOPEN", "BASS_ERROR_DRIVER", "BASS_ERROR_BUFLOST", "BASS_ERROR_HANDLE", "BASS_ERROR_FORMAT", "BASS_ERROR_POSITION", + "BASS_ERROR_INIT", "BASS_ERROR_START", "BASS_ERROR_SSL", "BASS_ERROR_", "BASS_ERROR_", "BASS_ERROR_", "BASS_ERROR_ALREADY", "BASS_ERROR_NOTAUDIO", + "BASS_ERROR_", "BASS_ERROR_", "BASS_ERROR_NOCHAN", "BASS_ERROR_ILLTYPE", "BASS_ERROR_ILLPARAM", "BASS_ERROR_NO3D", "BASS_ERROR_NOEAX", "BASS_ERROR_DEVICE", + "BASS_ERROR_NOPLAY", "BASS_ERROR_FREQ", "BASS_ERROR_", "BASS_ERROR_NOTFILE", "BASS_ERROR_", "BASS_ERROR_NOHW", "BASS_ERROR_", "BASS_ERROR_EMPTY", + "BASS_ERROR_NONET", "BASS_ERROR_CREATE", "BASS_ERROR_NOFX", "BASS_ERROR_", "BASS_ERROR_", "BASS_ERROR_NOTAVAIL", "BASS_ERROR_DECODE", "BASS_ERROR_DX", + "BASS_ERROR_TIMEOUT", "BASS_ERROR_FILEFORM", "BASS_ERROR_SPEAKER", "BASS_ERROR_VERSION", "BASS_ERROR_CODEC", "BASS_ERROR_ENDED", "BASS_ERROR_BUSY", "BASS_ERROR_UNSTREAMABLE", + ]; + + internal static string BassErrorDescription(Errors error) => (int)error switch { + 0 => "success", + 1 => "out of memory", + 2 => "can't open file", + 3 => "can't find free/valid driver", + 4 => "sample buffer lost", + 5 => "invalid handle", + 6 => "unsupported sample format", + 7 => "invalid position", + 8 => "BASS_Init has not been successfully called", + 9 => "BASS_Start has not been successfully called", + 10 => "SSL/HTTPS support not available", + 14 => "already initialized/paused/whatever", + 17 => "not audio", + 18 => "no free channels available", + 19 => "illegal type specified", + 20 => "illegal parameter specified", + 21 => "no 3D support", + 22 => "no EAX support", + 23 => "illegal device number", + 24 => "not playing", + 25 => "illegal sample rate", + 27 => "invalid file stream", + 29 => "no hardware voices available", + 31 => "MOD music has no sequence data", + 32 => "no internet connection could be opened", + 33 => "couldn't create file", + 34 => "effects are not available", + 37 => "requested data is not available", + 38 => "this is not a decoding channel", + 39 => "sufficient DirectX version not installed", + 40 => "connection timed out", + 41 => "unsupported file format", + 42 => "unavailable speaker", + 43 => "invalid BASS version", + 44 => "codec not available/supported", + 45 => "channel/file has already ended", + 46 => "device is busy", + 47 => "unstreamable", + _ => "unknown error", + }; + + internal static Vector3D ToBass(in Vector3 vec) => new(vec.X, -vec.Y, vec.Z); + internal static Vector3 FromBass(Vector3D vec) => new(vec.X, -vec.Y, vec.Z); + + static readonly (int Device, DeviceInitFlags Flags)[] InitAttempts = [ + (-1, DeviceInitFlags.Device3D), + (1, DeviceInitFlags.Device3D), + (-1, DeviceInitFlags.Device3D | DeviceInitFlags.Mono), + (1, DeviceInitFlags.Device3D | DeviceInitFlags.Mono), + (-1, 0), + (1, 0) + ]; + + public bool Init(IServiceProvider services) { + filesystem = services.GetService(); + + Shutdown(); + + Bass.Configure(Configuration.IncludeDefaultDevice, 1); + bool initialized = false; + for (int i = 0; i < InitAttempts.Length; i++) { + if (Bass.Init(InitAttempts[i].Device, 44100, InitAttempts[i].Flags, 0, 0)) { + initialized = true; + break; + } + Warning($"BASS_Init failed ({GetErrorString((int)Bass.LastError)})! Attempt {i + 1}.\n"); + } + + if (!initialized && !Bass.Init(0, 44100, 0, 0, 0) && Bass.LastError != Errors.Already) + Error($"Couldn't Init Bass ({GetErrorString((int)Bass.LastError)})!"); + + Bass.Configure((Configuration)60, 1); + Bass.Configure(Configuration.NetPlaylist, 1); + Bass.Configure(Configuration.FileVerificationBytes, 0x100000); + Bass.Set3DFactors(29.527559f, 7.0f, 0.02f); + return true; + } + + public void Shutdown() { + Bass.Free(); + Bass.PluginFree(0); + } + + public void Update(uint time) => Bass.Update((int)time); + + public IBassAudioStream? CreateAudioStream(IAudioStreamEvent? eventHandler) { + BassAudioStream stream = new(); + if (stream.Init(eventHandler)) + return stream; + stream.Dispose(); + return null; + } + + public void SetEar(ref Vector3 position, ref Vector3 velocity, ref Vector3 forward, ref Vector3 up) { + Bass.Set3DPosition(ToBass(position), ToBass(velocity), ToBass(forward), ToBass(up)); + Bass.Set3DFactors(29.527559f, 7.0f, 0.02f); + Bass.Apply3D(); + } + + internal static BassFlags ParseFlags(string flags) { + BassFlags ret = 0; + if (flags.Contains("3d")) + ret = BassFlags.Bass3D | BassFlags.Mono; + if (flags.Contains("mono")) + ret |= BassFlags.Mono; + if (!flags.Contains("noblock")) + ret |= BassFlags.StreamDownloadBlocks; + return ret; + } + + internal static void StartChannel(int handle, string flags) { + if (!flags.Contains("noplay")) + Bass.ChannelPlay(handle, false); + + if (flags.Contains("3d")) { + Bass.ChannelSet3DAttributes(handle, Mode3D.Normal, 200.0f, 0.0f, 360, 360, 0.0f); + Vector3D zero = new(); + Bass.ChannelSet3DPosition(handle, zero, zero, zero); + Bass.Apply3D(); + } + } + + public IGModAudioChannel? PlayURL(ReadOnlySpan url, ReadOnlySpan flags, Span error) { + string flagStr = flags.ToString().ToLowerInvariant(); + + int handle = Bass.CreateStream(url.ToString(), 0, ParseFlags(flagStr), null, 0); + if (handle == 0) { + Errors code = Bass.LastError; + if (error.IsEmpty) + Warning($"BASS_StreamCreateURL failed ({BassErrorDescription(code)})\n"); + else + error[0] = (int)code; + return null; + } + + StartChannel(handle, flagStr); + return new GModAudioChannel(handle, false, 0, null); + } + + static readonly FileProcedures FileProcs = new() { + Close = FileClose, + Length = FileLength, + Read = FileRead, + Seek = FileSeek, + }; + + static void FileClose(nint user) { + if (filesystem != null && user != 0) { + GCHandle handle = GCHandle.FromIntPtr(user); + ((IFileHandle)handle.Target!).Dispose(); + handle.Free(); + } + } + + static long FileLength(nint user) { + if (filesystem == null || user == 0) + return 0; + return ((IFileHandle)GCHandle.FromIntPtr(user).Target!).Stream.Length; + } + + static unsafe int FileRead(nint buffer, int length, nint user) { + if (filesystem != null && user != 0) { + Stream stream = ((IFileHandle)GCHandle.FromIntPtr(user).Target!).Stream; + if (stream.Position < stream.Length) + return stream.Read(new Span((void*)buffer, length)); + } + return -1; + } + + static bool FileSeek(long offset, nint user) { + if (filesystem == null || user == 0) + return false; + Stream stream = ((IFileHandle)GCHandle.FromIntPtr(user).Target!).Stream; + stream.Seek(offset, SeekOrigin.Begin); + return stream.Position == offset; + } + + public IGModAudioChannel? PlayFile(ReadOnlySpan path, ReadOnlySpan flags, Span error) { + string flagStr = flags.ToString().ToLowerInvariant(); + string pathStr = path.ToString(); + + if (pathStr.StartsWith(' ') || pathStr.StartsWith('/') || pathStr.Contains("..") || pathStr.Contains("./") || pathStr.Contains(':')) { + if (!error.IsEmpty) + error[0] = 2; + return null; + } + + IFileHandle? file = filesystem!.Open(pathStr, FileOpenOptions.Read | FileOpenOptions.Binary, "GAME"); + if (file == null) { + if (!error.IsEmpty) + error[0] = 2; + return null; + } + + BassFlags bassFlags = ParseFlags(flagStr); + GCHandle fileHandle = GCHandle.Alloc(file); + int handle = Bass.CreateStream(StreamSystem.NoBuffer, bassFlags, FileProcs, GCHandle.ToIntPtr(fileHandle)); + int type = 0; + if (handle == 0) { + if (Bass.LastError != Errors.FileFormat) { + if (!error.IsEmpty) + error[0] = (int)Bass.LastError; + return null; + } + + using IFileHandle? musicFile = filesystem.Open(pathStr, FileOpenOptions.Read | FileOpenOptions.Binary, "GAME"); + int size = (int)musicFile!.Stream.Length; + byte[] data = new byte[size]; + int read = musicFile.Stream.Read(data, 0, size); + type = 1; + handle = Bass.MusicLoad(data, 0, read, (bassFlags & ~BassFlags.StreamDownloadBlocks) | BassFlags.Prescan, 0); + if (handle == 0) { + if (!error.IsEmpty) + error[0] = (int)Bass.LastError; + return null; + } + } + + StartChannel(handle, flagStr); + return new GModAudioChannel(handle, true, type, pathStr); + } + + public void SetGlobalVolume(float volume) { + int value = (int)(volume * 10000.0f); + Bass.Configure(Configuration.GlobalMusicVolume, value); + Bass.Configure(Configuration.GlobalSampleVolume, value); + Bass.Configure(Configuration.GlobalStreamVolume, value); + } + + public void StopAllPlayback() { + Bass.Stop(); + Bass.Start(); + } + + public ReadOnlySpan GetErrorString(int error) { + if (error < 0 || error >= 48) + return "BASS_ERROR_UNKNOWN"; + return ErrorStrings[error]; + } +} diff --git a/Game.BASS/Game.BASS.csproj b/Game.BASS/Game.BASS.csproj new file mode 100644 index 000000000..d5df2ea6d --- /dev/null +++ b/Game.BASS/Game.BASS.csproj @@ -0,0 +1,18 @@ + + + True + + + + + + + + + + + + + + + diff --git a/Game.Client/C_BaseAnimating.cs b/Game.Client/C_BaseAnimating.cs index c6ff6d8d9..2d92fe250 100644 --- a/Game.Client/C_BaseAnimating.cs +++ b/Game.Client/C_BaseAnimating.cs @@ -290,8 +290,8 @@ public void Dispose() { long MostRecentModelBoneCounter; long MostRecentBoneSetupRequest; int PrevBoneMask; - protected int AccumulatedBoneMask; - readonly BoneAccessor BoneAccessor = new(); + protected internal int AccumulatedBoneMask; + internal readonly BoneAccessor BoneAccessor = new(); // Note that Handle is not a pointer in this case so we need to initialize // each member in the bone attachments (when we get to this part). readonly List> BoneAttachments = []; @@ -680,6 +680,8 @@ public override bool SetupBones(Span boneToWorldOut, int maxBones, in if (hdr == null || !hdr.SequencesAvailable()) return false; + C_BoneManipulate? boneManipulator = GetBoneManipulator(false) as C_BoneManipulate; + Matrix3x4 parentTransform = default; MathLib.AngleMatrix(GetRenderAngles(), GetRenderOrigin(), out parentTransform); // MathLib.AngleMatrix(new(19.56f, -145.89f, 0), new(-767, 143.9f, -12650), ref parentTransform); @@ -715,6 +717,11 @@ public override bool SetupBones(Span boneToWorldOut, int maxBones, in StandardBlendingRules(hdr, pos, q, currentTime, bonesMaskNeedRecalc); + if (boneManipulator != null) { + for (int i = 0; i < hdr.NumBones(); i++) + boneManipulator.ManipulateBone(i, ref pos[i], ref q[i]); + } + BoneBitList boneComputed = new(); if (Ik != null && !IsRagdoll()) SolveIK(pos, q, BoneAccessor.GetBoneArrayForWrite(), ref boneComputed, currentTime); @@ -730,6 +737,8 @@ public override bool SetupBones(Span boneToWorldOut, int maxBones, in return false; } } + + boneManipulator?.PostBuildTransformations(this, hdr); } if (!boneToWorldOut.IsEmpty) { @@ -1946,7 +1955,7 @@ public override bool GetAttachment(int number, out Vector3 origin, out QAngle an } public override int DrawModel(StudioFlags flags) { - if (!ReadyToDraw) + if (!ReadyToDraw || !ShouldDrawInView()) return 0; int drawn = 0; @@ -2077,6 +2086,32 @@ public override void GetAimEntOrigin(C_BaseEntity attachedTo, out Vector3 origin public EHANDLE LightingOriginRelative = new(); [NetworkVar("m_pBoneManipulator")] public EHANDLE BoneManipulator = new(); + public EHANDLE ClientBoneManipulator = new(); + + public virtual C_BaseEntity? GetBoneManipulator(bool create) { + if (BoneManipulator.IsValid()) + return BoneManipulator.Get(); + + if (ClientBoneManipulator.Get() != null) + return ClientBoneManipulator.Get(); + + if (create) { + C_BoneManipulate manipulator = new(); + if (!manipulator.InitializeAsClientEntity(null, RenderGroup.OpaqueEntity)) + return null; + + manipulator.SetParent(this, 0); + manipulator.SetOwnerEntity(this); + manipulator.SetLocalOrigin(default); + manipulator.Spawn(); + RemoveFromPreviousBoneSetups(); + ClientBoneManipulator.Set(manipulator); + return ClientBoneManipulator.Get(); + } + + return null; + } + [NetworkVar("m_pFlexManipulator")] public EHANDLE FlexManipulator = new(); public EHANDLE ClientFlexManipulator = new(); diff --git a/Game.Client/C_BaseCombatWeapon.cs b/Game.Client/C_BaseCombatWeapon.cs index ee088128a..05615c98f 100644 --- a/Game.Client/C_BaseCombatWeapon.cs +++ b/Game.Client/C_BaseCombatWeapon.cs @@ -52,6 +52,60 @@ public bool IsCarriedByLocalPlayer() { return owner == C_BasePlayer.GetLocalPlayer(); } + int OldState; + bool JustRestored; + + public override void OnDataChanged(DataUpdateType updateType) { + base.OnDataChanged(updateType); + + C_BasePlayer? player = C_BasePlayer.GetLocalPlayer(); + C_BaseCombatCharacter? owner = GetOwner(); + + if (player != null && player == owner && ShouldDrawLocalPlayerViewModel()) { + if (State != (int)WeaponState.NotCarried && OldState == (int)WeaponState.NotCarried) { + if (ShouldDrawPickup()) + BaseHudWeaponSelection.GetHudWeaponSelection()?.OnWeaponPickup(this); + } + } + else { + int overrideModelIndex = CalcOverrideModelIndex(); + if (overrideModelIndex != -1 && overrideModelIndex != GetModelIndex()) + SetModelIndex(overrideModelIndex); + } + + UpdateVisibility(); + + OldState = State; + JustRestored = false; + } + + public virtual int GetWorldModelIndex() { + if (g_pGameRules != null) { + ReadOnlySpan baseName = modelinfo.GetModelName(modelinfo.GetModel(WorldModelIndex)); + ReadOnlySpan translatedName = g_pGameRules.TranslateEffectForVisionFilter("weapons", baseName); + if (translatedName != baseName) + return modelinfo.GetModelIndex(translatedName); + } + return WorldModelIndex; + } + + public override int CalcOverrideModelIndex() { + C_BasePlayer? localPlayer = C_BasePlayer.GetLocalPlayer(); + if (localPlayer != null && localPlayer == GetOwner() && ShouldDrawLocalPlayerViewModel()) + return base.CalcOverrideModelIndex(); + return GetWorldModelIndex(); + } + + public bool ShouldDrawPickup() { + if ((GetWeaponFlags() & WeaponFlags.NoItemPickup) != 0) + return false; + + if (JustRestored) + return false; + + return true; + } + public bool ShouldDrawUsingViewModel() => IsCarriedByLocalPlayer() && !C_BasePlayer.ShouldDrawLocalPlayer(); public void Redraw() { @@ -60,7 +114,7 @@ public void Redraw() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool ShouldDrawLocalPlayerViewModel() => C_BasePlayer.ShouldDrawLocalPlayer(); + public static bool ShouldDrawLocalPlayerViewModel() => !C_BasePlayer.ShouldDrawLocalPlayer(); public override bool ShouldDraw() { if (WorldModelIndex == 0) diff --git a/Game.Client/C_BaseEntity.cs b/Game.Client/C_BaseEntity.cs index a34dd59b8..620889933 100644 --- a/Game.Client/C_BaseEntity.cs +++ b/Game.Client/C_BaseEntity.cs @@ -3,6 +3,7 @@ using CommunityToolkit.HighPerformance; +using Game.Client.GarrysMod; using Game.Shared; using Source; @@ -11,6 +12,7 @@ using Source.Common.Bitbuffers; using Source.Common.Commands; using Source.Common.Engine; +using Source.Common.MaterialSystem; using Source.Common.Mathematics; using Source.Common.Networking; @@ -870,8 +872,60 @@ public C_BaseEntity() { public ushort RealClassName; [NetworkVar("m_OverrideMaterial")] public ushort OverrideMaterial; + IMaterial? MaterialOverridePointer; + + public virtual void SetMaterialOverride(ReadOnlySpan name) { + if (name.IsEmpty || name[0] == '\0') { + SetMaterialOverridePointer(null); + return; + } + + IMaterial? material = materials.FindMaterial(name, MaterialDefines.TEXTURE_GROUP_OTHER, true, null); + if (material == null || material.IsErrorMaterial()) + material = null; + SetMaterialOverridePointer(material); + } + + public virtual void SetMaterialOverridePointer(IMaterial? material) { + MaterialOverridePointer?.DecrementReferenceCount(); + MaterialOverridePointer = material; + material?.IncrementReferenceCount(); + } + + public virtual ReadOnlySpan GetMaterialOverride() => NetworkString.Convert(OverrideMaterial) ?? ""; [NetworkVar("m_OverrideSubMaterials")] public InlineArray32 OverrideSubMaterials; + InlineArray32 SubMaterialOverridePointers; + + public void ClearSubMaterialOverrides() { + for (int i = 0; i < 32; i++) { + SubMaterialOverridePointers[i]?.DecrementReferenceCount(); + SubMaterialOverridePointers[i] = null; + } + } + + public void SetSubMaterialOverride(int index, ReadOnlySpan name) { + if ((uint)index >= 32) + return; + + if (name.IsEmpty || name[0] == '\0') { + SubMaterialOverridePointers[index]?.DecrementReferenceCount(); + SubMaterialOverridePointers[index] = null; + return; + } + + IMaterial? material = materials.FindMaterial(name, MaterialDefines.TEXTURE_GROUP_OTHER, true, null); + if (material == null || material.IsErrorMaterial()) + material = null; + SubMaterialOverridePointers[index]?.DecrementReferenceCount(); + SubMaterialOverridePointers[index] = material; + material?.IncrementReferenceCount(); + } + public ReadOnlySpan GetSubMaterialOverride(int index) { + if ((uint)index < 32 && NetworkString.Convert(OverrideSubMaterials[index]) is string name) + return name; + return ""; + } [NetworkVar("m_iHealth")] public int Health; [NetworkVar("m_iMaxHealth")] @@ -955,6 +1009,24 @@ public C_BaseEntity() { public int GetTeamNumber() => TeamNum; + public ref readonly Vector3 WorldAlignMins() { + Assert(!CollisionProp().IsBoundsDefinedInEntitySpace()); + Assert(CollisionProp().GetCollisionAngles() == vec3_angle); + return ref CollisionProp().OBBMins(); + } + + public ref readonly Vector3 WorldAlignMaxs() { + Assert(!CollisionProp().IsBoundsDefinedInEntitySpace()); + Assert(CollisionProp().GetCollisionAngles() == vec3_angle); + return ref CollisionProp().OBBMaxs(); + } + + public virtual bool InSameTeam(C_BaseEntity? entity) { + if (entity == null) + return false; + return entity.GetTeamNumber() == GetTeamNumber(); + } + IPhysicsObject? PhysicsObject = null!; public void VPhysicsUpdate(IPhysicsObject physics) { } public IPhysicsObject? VPhysicsGetObject() => PhysicsObject; @@ -1049,6 +1121,7 @@ public void SetParent(C_BaseEntity? parentEntity, int parentAttachment = 0) { [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AddSolidFlags(SolidFlags flags) => CollisionProp().AddSolidFlags(flags); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RemoveSolidFlags(SolidFlags flags) => CollisionProp().RemoveSolidFlags(flags); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsSolid() => CollisionProp().IsSolid(); + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsPointSized() => CollisionProp().BoundingRadius() == 0.0f; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetSolid(SolidType val) => CollisionProp().SetSolid(val); [MethodImpl(MethodImplOptions.AggressiveInlining)] public SolidType GetSolid() => CollisionProp().GetSolid(); @@ -1060,6 +1133,19 @@ public void GetColorModulation(Span color) { } public virtual void ClientThink() { } + public virtual bool ShouldDrawInView() { + C_BasePlayer? localPlayer = C_BasePlayer.GetLocalPlayer(); + if (localPlayer == null) + return true; + + if (render.GetViewEntity() == Index && localPlayer != this && (LuaRender.DrawViewerStack.Count == 0 || !LuaRender.DrawViewerStack[^1])) { + Shared.ObserverMode mode = localPlayer.GetObserverMode(); + return mode != Shared.ObserverMode.None && mode != Shared.ObserverMode.InEye; + } + + return true; + } + public bool ReadyToDraw; public virtual int DrawModel(StudioFlags flags) { if (!ReadyToDraw) @@ -1220,7 +1306,7 @@ public void SetModelPointer(Model? model) { protected virtual StudioHdr? OnNewModel() { return null; // what the hell????????????????? } - void SetModelIndex(int index) { + public void SetModelIndex(int index) { ModelIndex = index; #if GMOD_DLL if (index != -1) @@ -1666,7 +1752,7 @@ public virtual void PostDataUpdate(DataUpdateType updateType) { // Make sure player is driving simulation (field is only ever sent to local player) SetPlayerSimulated(local); - // TODO: Partition/leaf stuff + UpdatePartitionListEntry(); if (!IsClientCreated()) if (Teleported() || IsNoInterpolationFrame()) @@ -2089,6 +2175,8 @@ public virtual void NotifyShouldTransmit(ShouldTransmiteState state) { case ShouldTransmiteState.Start: { SetDormant(false); + UpdatePartitionListEntry(); + if (PredictableID.IsActive()) { PredictableID.SetAcknowledged(true); @@ -2219,7 +2307,22 @@ public void SetBlocksLOS(bool blocksLOS) { AddEFlags(EFL.DontBlockLOS); } - public virtual CollideType GetCollideType() => CollideType.ShouldNotCollide; + public virtual CollideType GetCollideType() { + if (ModelIndex == 0 || Model == null) + return CollideType.ShouldNotCollide; + + if (!IsSolid()) + return CollideType.ShouldNotCollide; + + ModelType type = modelinfo.GetModelType(Model); + if (type != ModelType.Brush && type != ModelType.Studio) + return CollideType.ShouldNotCollide; + + if (ModelIndex != 1 && IsPointSized()) + return CollideType.ShouldNotCollide; + + return CollideType.ShouldCollide; + } public void UpdatePartitionListEntry() { PartitionListMask list = PartitionListMask.ClientNonStaticEdicts; diff --git a/Game.Client/C_BasePlayer.cs b/Game.Client/C_BasePlayer.cs index 814b7e053..abbdc70c0 100644 --- a/Game.Client/C_BasePlayer.cs +++ b/Game.Client/C_BasePlayer.cs @@ -1,4 +1,5 @@ -using Game.Shared; +using Game.Client.GarrysMod; +using Game.Shared; using Source; using Source.Common; @@ -129,8 +130,38 @@ public ReadOnlySpan GetNetworkIDString() { } public bool IsHLTV() => IsLocalPlayer() && engine.IsHLTV(); public bool IsBot() => (GetFlags() & EntityFlags.FakeClient) != 0; + public virtual void OverrideView(ref ViewSetup setup) { } + public static bool ShouldDrawLocalPlayer() { - return input.CAM_IsThirdPerson(); // todo + if (LuaRender.DrawViewerStack.Count != 0) + return LuaRender.DrawViewerStack[^1]; + + C_BasePlayer? localPlayer = GetLocalPlayer(); + if (localPlayer == null) + return true; + + if ((render.GetViewEntity() != localPlayer.Index || !ClientModeShared.DrawViewer) && !input.CAM_IsThirdPerson()) { + if (ToolsEnabled() && ToolFramework_IsThirdPersonCamera()) + return true; + + if (render.GetViewEntity() == localPlayer.Index) { + if (LuaCam.FrameStateChecked) + return LuaCam.ShouldDrawLocalPlayerCache; + + LuaCam.FrameStateChecked = true; + LuaCam.ShouldDrawLocalPlayerCache = false; + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.ShouldDrawLocalPlayer)) { + LuaEntity.Push_Entity(localPlayer); + if (gGM.CallFinish(1)) { + LuaCam.ShouldDrawLocalPlayerCache = true; + return true; + } + } + return false; + } + } + + return true; } public override bool ShouldDraw() { diff --git a/Game.Client/C_BoneManipulate.cs b/Game.Client/C_BoneManipulate.cs index 7d74d4313..1e704ed39 100644 --- a/Game.Client/C_BoneManipulate.cs +++ b/Game.Client/C_BoneManipulate.cs @@ -2,6 +2,7 @@ using Source; using Game.Shared; using System.Numerics; +using Source.Common.Mathematics; namespace Game.Client; [LinkEntityToClass("manipulate_bone")] @@ -24,4 +25,82 @@ public partial class C_BoneManipulate : C_BaseEntity public InlineArrayMaxStudioBones BoneScale; [NetworkVar("m_BoneJiggle")] public InlineArrayMaxStudioBones BoneJiggle; + + public Vector3 RenderMins; + public Vector3 RenderMaxs; + + public C_BoneManipulate() { + for (int i = 0; i < Studio.MAXSTUDIOBONES; i++) { + BoneScale[i] = new(1.0f, 1.0f, 1.0f); + BoneJiggle[i] = 0; + BonePos[i] = default; + BoneAng[i] = default; + } + } + + public void SetBonePosition(byte index, Vector3 pos, bool networkUpdate) { + if (pos.Length() > 128.0f) + pos = Vector3.Normalize(pos) * 128.0f; + + if (BonePos[index] != pos) + BonePos[index] = pos; + } + + public void SetBoneAngles(byte index, in Vector3 ang, bool networkUpdate) { + if (BoneAng[index] != ang) + BoneAng[index] = ang; + } + + public void SetBoneScale(byte index, Vector3 scale, bool networkUpdate) { + if (scale.Length() > 512.0f) + scale = Vector3.Normalize(scale) * 512.0f; + + if (BoneScale[index] != scale) + BoneScale[index] = scale; + } + + public void ScaleBone(int index, ref Matrix3x4 bone) { + if ((uint)index < Studio.MAXSTUDIOBONES) { + MathLib.SetScaleMatrix(BoneScale[index].X, BoneScale[index].Y, BoneScale[index].Z, out Matrix3x4 scale); + MathLib.ConcatTransforms(bone, scale, out bone); + } + } + + public void PostBuildTransformations(C_BaseAnimating animating, StudioHdr hdr) { + for (int i = 0; i < hdr.NumBones(); i++) + ScaleBone(i, ref animating.GetBoneForWrite(i)); + + modelinfo.GetModelRenderBounds(animating.GetModel(), out Vector3 mins, out Vector3 maxs); + for (int i = 0; i < hdr.NumBones(); i++) { + if ((animating.BoneAccessor.GetReadableBones() & hdr.Bone(i).Flags) == 0) + continue; + + MathLib.MatrixGetColumn(animating.GetBone(i), 3, out Vector3 origin); + if (origin.X <= -0.01f || origin.X >= 0.01f || origin.Y <= -0.01f || origin.Y >= 0.01f || origin.Z <= -0.01f || origin.Z >= 0.01f) { + Vector3 local; + if (animating.GetAbsAngles() == vec3_angle) + local = origin - animating.GetAbsOrigin(); + else + MathLib.VectorITransform(origin, animating.EntityToWorldTransform(), out local); + + float pad = 32.0f; + if (IsPlayer() || IsNPC()) + pad = 4.0f; + + mins = Vector3.Min(mins, local - new Vector3(pad)); + maxs = Vector3.Max(maxs, local + new Vector3(pad)); + } + } + RenderMins = mins; + RenderMaxs = maxs; + } + + public void ManipulateBone(int index, ref Vector3 pos, ref Quaternion q) { + if ((uint)index < Studio.MAXSTUDIOBONES) { + pos += BonePos[index]; + Vector3 ang = BoneAng[index]; + MathLib.AngleQuaternion(new QAngle(ang.X, ang.Y, ang.Z), out Quaternion angQ); + MathLib.QuaternionMult(q, angQ, out q); + } + } } diff --git a/Game.Client/ClientModeShared.cs b/Game.Client/ClientModeShared.cs index c9a872192..f39772428 100644 --- a/Game.Client/ClientModeShared.cs +++ b/Game.Client/ClientModeShared.cs @@ -1,3 +1,4 @@ +using Game.Client.GarrysMod; using Game.Client.HUD; using Game.Shared; @@ -6,6 +7,7 @@ using Source.Common.Bitbuffers; using Source.Common.Commands; using Source.Common.Formats.Keyvalues; +using Source.Common.GarrysMod.Lua; using Source.Common.GUI; using Source.Common.Input; using Source.Common.MaterialSystem; @@ -213,12 +215,27 @@ public float GetViewModelFOV() { return v_viewmodel_fov.GetFloat(); } + public static bool DrawViewer; + public virtual void OverrideView(ref ViewSetup setup) { + DrawViewer = false; C_BasePlayer? player = C_BasePlayer.GetLocalPlayer(); if (player == null) return; - if (input.CAM_IsThirdPerson()) { + player.OverrideView(ref setup); + + if (!input.CAM_IsThirdPerson()) { + if (input.CAM_IsOrthographic()) { + setup.Ortho = true; + input.CAM_OrthographicSize(out float w, out float h); + setup.OrthoRight = w * 0.5f; + setup.OrthoLeft = -(w * 0.5f); + setup.OrthoTop = -(h * 0.5f); + setup.OrthoBottom = h * 0.5f; + } + } + else { Vector3 camOfs = g_ThirdPersonManager.GetCameraOffsetAngles(); Vector3 camOfsDist = g_ThirdPersonManager.GetFinalCameraOffset(); @@ -238,7 +255,39 @@ public virtual void OverrideView(ref ViewSetup setup) { setup.Angles = camAngles; } - // todo ortho + Vector3 eyeOrigin = setup.Origin; + QAngle eyeAngles = setup.Angles; + + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.CalcView)) { + LuaEntity.Push_Entity(player); + LuaVector.Push_Vector(setup.Origin); + LuaAngle.Push_Angle(setup.Angles); + g_Lua!.PushNumber(setup.FOV); + g_Lua!.PushNumber(setup.ZNear); + g_Lua!.PushNumber(setup.ZFar); + if (gGM.CallReturns(6, 1)) { + ILuaObject ret = g_Lua!.GetReturn(0); + setup.Origin = ret.GetMemberVector("origin", setup.Origin); + setup.Angles = ret.GetMemberAngle("angles", setup.Angles); + setup.FOV = ret.GetMemberFloat("fov", setup.FOV); + setup.ZNear = ret.GetMemberFloat("znear", setup.ZNear); + setup.ZFar = ret.GetMemberFloat("zfar", setup.ZFar); + + LuaObject ortho = new(); + ret.GetMember("ortho", ortho); + if (ortho.isTable()) { + setup.Ortho = true; + setup.OrthoLeft = ortho.GetMemberFloat("left", setup.OrthoLeft); + setup.OrthoRight = ortho.GetMemberFloat("right", setup.OrthoRight); + setup.OrthoTop = ortho.GetMemberFloat("top", setup.OrthoTop); + setup.OrthoBottom = ortho.GetMemberFloat("bottom", setup.OrthoBottom); + } + DrawViewer = ret.GetMemberBool("drawviewer", false); + ortho.UnReference(); + } + } + + player.CalcViewModelView(in eyeOrigin, in eyeAngles); } public void Layout() { diff --git a/Game.Client/GarrysMod/C_GMOD_Player.cs b/Game.Client/GarrysMod/C_GMOD_Player.cs index 307415749..5c27ec45b 100644 --- a/Game.Client/GarrysMod/C_GMOD_Player.cs +++ b/Game.Client/GarrysMod/C_GMOD_Player.cs @@ -1,4 +1,5 @@ using Game.Client.HL2MP; +using Game.Client.HUD; using Game.Shared; using Source; @@ -6,7 +7,9 @@ using Source.Common.Commands; using Source.Common.GarrysMod.Lua; using Source.Common.Hashing; +using Source.Common.Input; using Source.Common.Mathematics; +using Source.GUI.Controls; using System.Numerics; @@ -203,6 +206,53 @@ protected override bool OnPostInternalDrawModel(ref ClientModelRenderInfo info) return true; } + public override void UpdateLookAt() { + if (HeadYawPoseParam < 0 || HeadPitchPoseParam < 0) + return; + + ViewTarget = LookAtTarget; + + if (BlinkTimer.IsElapsed()) { + BlinkToggle = BlinkToggle == 0 ? 1 : 0; + BlinkTimer.Start(RandomFloat(1.5f, 4.0f)); + } + + QAngle eyeAngles = EyeAngles(); + + float bodyYaw; + IClientVehicle? vehicle = GetVehicle(); + if (vehicle == null) + bodyYaw = GetRenderAngles()[YAW]; + else { + float vehicleYaw = vehicle.GetVehicleEnt()!.GetAbsAngles()[YAW]; + C_BaseEntity vehicleEnt = GetVehicle()!.GetVehicleEnt()!; + bodyYaw = vehicleYaw + 90.0f; + if (stricmp(modelinfo.GetModelName(vehicleEnt.GetModel()), "models/vehicles/prisoner_pod_inner.mdl") == 0) + bodyYaw = vehicleYaw; + } + + float lastBodyYaw = LastBodyYaw; + LastBodyYaw = bodyYaw; + + float desired = MathLib.AngleNormalize(eyeAngles[YAW] - bodyYaw); + if (GetVehicle() != null) { + float absDesired = MathF.Abs(desired); + if (absDesired > 90.0f) + desired = MathLib.AngleNormalize((90.0f - (absDesired - 90.0f)) * (int)(desired / absDesired)); + } + + desired = Math.Clamp(desired, HeadYawMin, HeadYawMax); + CurrentHeadYaw = MathLib.AngleNormalize(desired - (bodyYaw - lastBodyYaw)); + SetPoseParameter(HeadYawPoseParam, desired); + + float pitch = MathLib.AngleNormalize(eyeAngles[PITCH]); + pitch = Math.Clamp(pitch, HeadPitchMin, HeadPitchMax); + CurrentHeadPitch = MathLib.AngleNormalize(pitch); + SetPoseParameter(HeadPitchPoseParam, CurrentHeadPitch); + + SetPoseParameter(GetModelPtr(), "breathing", 1.0f); + } + public override void UpdateClientSideAnimation() { if (Driving.Get() != null) { if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerDriveAnimate)) { @@ -217,4 +267,219 @@ public override void UpdateClientSideAnimation() { UpdateBaseClientSideAnimation(); } + + class CreateMoveCmdRef + { + public UserCmd Cmd; + public AnonymousSafeFieldPointer Ptr => new(this, static o => ref ((CreateMoveCmdRef)o).Cmd); + } + + static readonly CreateMoveCmdRef CreateMoveCmd = new(); + + static void CreateMoveSWEPThink() { + if (gpGlobals.MaxClients >= 2) + return; + C_BasePlayer? player = GetLocalPlayer(); + if (player == null) + return; + if (player.GetActiveWeapon() is not C_WeaponSWEP swep) + return; + if (player.NextAttack <= gpGlobals.CurTime) + swep.CreateMoveThink(); + } + + public override bool CreateMove(TimeUnit_t inputSampleTime, ref UserCmd cmd) { + CreateMoveCmd.Cmd = cmd; + bool ret = CreateMoveInternal(inputSampleTime, ref CreateMoveCmd.Cmd); + cmd = CreateMoveCmd.Cmd; + return ret; + } + + bool CreateMoveInternal(TimeUnit_t inputSampleTime, ref UserCmd cmd) { + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.StartCommand)) { + LuaEntity.Push_Entity(GetLocalPlayer()); + LuaUserCmd.Push_UserCmd(CreateMoveCmd.Ptr); + LuaDisposable disposable = new(g_Lua!.Top(), LuaType.None); + gGM.CallNoReturns(2); + disposable.Dispose(); + } + + CreateMoveSWEPThink(); + + cmd.IsTyping = false; + BaseHudChat? chat = (BaseHudChat?)gHUD.FindElement("CHudChat"); + if (chat != null && chat.IsVisible() && chat.GetChatInput() != null && chat.GetChatInput().IsVisible()) + cmd.IsTyping = chat.GetChatInput().GetInputPanel() == vguiInput.GetFocus(); + + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.CreateMove)) { + LuaUserCmd.Push_UserCmd(CreateMoveCmd.Ptr); + LuaDisposable disposable = new(g_Lua!.Top(), LuaType.None); + bool handled = gGM.CallFinish(1); + disposable.Dispose(); + if (handled) + return true; + } + + bool ret = base.CreateMove(inputSampleTime, ref cmd); + + if ((GModPlayerFlags & 8) != 0) + AvoidPlayers(ref cmd); + + cmd.WorldClickDirection = default; + cmd.WorldClicking = false; + + if (surface.IsCursorVisible()) { + Panel? panel = vguiInput.GetMouseFocus() as Panel; + if (panel == null) + panel = vguiInput.GetMouseOver() as Panel; + + if (panel != null && panel.IsWorldClicker() && panel.IsVisible()) { + vguiInput.GetCursorPos(out int x, out int y); + cmd.WorldClickDirection = LuaGui.ScreenToVector(x, y); + cmd.WorldClicking = true; + } + } + + if (cmd.WorldClicking && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PreventScreenClicks) && !gGM.CallFinish(0)) { + cmd.Buttons &= ~(InButtons.Attack | InButtons.Attack2); + for (int i = 0; i < 5; i++) { + if (inputsystem.IsButtonDown(ButtonCode.MouseLeft)) + cmd.Buttons |= InButtons.Attack; + if (inputsystem.IsButtonDown(ButtonCode.MouseRight)) + cmd.Buttons |= InButtons.Attack2; + } + } + + if (gpGlobals.MaxClients == 1) { + WorldClicking = cmd.WorldClicking; + WorldClickVector = cmd.WorldClickDirection; + } + + return ret; + } + + public override void Simulate() { + if (gpGlobals.MaxClients == 1 && IsLocalPlayer()) + UpdateButtonState(input.GetButtonBits(1)); + base.Simulate(); + } + + public override void UpdateButtonState(InButtons userCmdButtonMask) { + base.UpdateButtonState(userCmdButtonMask); + if (gGM == null) + return; + + uint bit = 1; + for (int i = 0; i < 32; i++) { + if (((uint)AfButtonPressed & bit) != 0) { + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.KeyPress)) { + LuaEntity.Push_Entity(this); + g_Lua!.PushNumber((int)bit); + gGM.CallNoReturns(2); + } + } + else if (((uint)AfButtonReleased & bit) != 0 && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.KeyRelease)) { + LuaEntity.Push_Entity(this); + g_Lua!.PushNumber((int)bit); + gGM.CallNoReturns(2); + } + bit = BitOperations.RotateLeft(bit, 1); + } + } + + void AvoidPlayers(ref UserCmd cmd) { + if (!IsAlive() || GetMoveType() == Source.MoveType.Noclip) + return; + + Vector3 playerCenter = GetAbsOrigin(); + Vector3 playerMin = GetPlayerMins(); + Vector3 playerMax = GetPlayerMaxs(); + float zHeight = playerMax.Z - playerMin.Z; + playerCenter.Z += 0.5f * zHeight; + playerMin += playerCenter; + playerMax += playerCenter; + + for (int i = 0; i < gpGlobals.MaxClients; i++) { + C_BasePlayer? avoidPlayer = Util.PlayerByIndex(i); + if (avoidPlayer == null || !avoidPlayer.IsPlayer() || avoidPlayer == this) + continue; + if (!InSameTeam(avoidPlayer) || avoidPlayer.IsDormant()) + continue; + if (avoidPlayer.IsSolidFlagSet(SolidFlags.NotSolid) || avoidPlayer.GetMoveType() == Source.MoveType.Noclip) + continue; + + Vector3 avoidCenter = avoidPlayer.GetAbsOrigin(); + Vector3 avoidMin = avoidPlayer.GetPlayerMins(); + Vector3 avoidMax = avoidPlayer.GetPlayerMaxs(); + zHeight = avoidMax.Z - avoidMin.Z; + avoidCenter.Z += 0.5f * zHeight; + avoidMin += avoidCenter; + avoidMax += avoidCenter; + + if (!CollisionUtils.IsBoxIntersectingBox(playerMin, playerMax, avoidMin, avoidMax)) + continue; + + Vector3 delta = avoidPlayer.WorldSpaceCenter() - playerCenter; + Vector3 rad = avoidPlayer.WorldAlignMaxs() - avoidPlayer.WorldAlignMins(); + rad.Z = 0; + float avoidRadius = rad.Length(); + + float pushStrength = (float)MathLib.RemapValClamped(delta.Length(), avoidRadius, 0, 0, 256); + if (pushStrength < 0.01f) + return; + + Vector3 push; + if (GetAbsVelocity().Length2DSqr() > 0.1f) { + Vector3 velocity = GetAbsVelocity(); + velocity.Z = 0.0f; + MathLib.CrossProduct(new Vector3(0.0f, 0.0f, 1.0f), velocity, out push); + MathLib.VectorNormalize(ref push); + } + else { + QAngle view = cmd.ViewAngles; + view.X = 0.0f; + MathLib.AngleVectors(view, out _, out push, out _); + } + + Vector3 separationVelocity; + if (Vector3.Dot(delta, push) < 0) + separationVelocity = push * pushStrength; + else + separationVelocity = push * -pushStrength; + + float maxPlayerSpeed = MaxSpeed(); + if ((GetFlags() & EntityFlags.Ducking) != 0 && GetGroundEntity() != null) + maxPlayerSpeed *= 1.3333334f; + + if (separationVelocity.LengthSquared() > maxPlayerSpeed * maxPlayerSpeed) { + separationVelocity.NormalizeInPlace(); + separationVelocity *= maxPlayerSpeed; + } + + QAngle angles = cmd.ViewAngles; + angles.X = 0; + MathLib.AngleVectors(angles, out Vector3 currentDir, out Vector3 rightDir, out _); + + Vector3 direction = separationVelocity; + MathLib.VectorNormalize(ref direction); + + cmd.ForwardMove += Vector3.Dot(currentDir, direction) * pushStrength; + cmd.SideMove += Vector3.Dot(rightDir, direction) * pushStrength; + + float forwardScale = 1.0f; + if (cmd.ForwardMove > 400.0f) + forwardScale = 400.0f / cmd.ForwardMove; + else if (cmd.ForwardMove < -400.0f) + forwardScale = 400.0f / MathF.Abs(cmd.ForwardMove); + + float sideScale = 1.0f; + if (MathF.Abs(cmd.SideMove) > 400.0f) + sideScale = 400.0f / MathF.Abs(cmd.SideMove); + + float scale = MathF.Min(forwardScale, sideScale); + cmd.ForwardMove *= scale; + cmd.SideMove *= scale; + return; + } + } } diff --git a/Game.Client/GarrysMod/LuaAchievements.cs b/Game.Client/GarrysMod/LuaAchievements.cs index 8d52f5813..7859c47da 100644 --- a/Game.Client/GarrysMod/LuaAchievements.cs +++ b/Game.Client/GarrysMod/LuaAchievements.cs @@ -19,7 +19,7 @@ public static partial class LuaAchievements static readonly LuaLibrary LL_Factory_achievements = new("achievements"); #if !MENU_DLL - static bool UnsetIncrementFlag; + internal static bool UnsetIncrementFlag; #endif static IAchievement? GetAchievement(int index) { diff --git a/Game.Client/GarrysMod/LuaAudioChannel.cs b/Game.Client/GarrysMod/LuaAudioChannel.cs new file mode 100644 index 000000000..c2f60cafd --- /dev/null +++ b/Game.Client/GarrysMod/LuaAudioChannel.cs @@ -0,0 +1,463 @@ +using Source.Common.GarrysMod; +using Source.Common.GarrysMod.Lua; + +using System.Numerics; +using System.Runtime.InteropServices; + +namespace Game.Client.GarrysMod; + +public static partial class LuaAudioChannel +{ + [LuaClass(typeof(IGModAudioChannel), NullError = "Tried to use a NULL IGModAudioChannel!")] + public static readonly LuaClass LC_IGModAudioChannel = new("IGModAudioChannel", LuaType.SoundHandle, null, null); + + public static void Push_IGModAudioChannel(IGModAudioChannel channel) => LC_IGModAudioChannel.Push(channel); + + static IGModAudioChannel? Get_IGModAudioChannel(ILuaInterface lua) { + IGModAudioChannel? channel = (IGModAudioChannel?)LC_IGModAudioChannel.Get(1); + if (channel == null) + lua.Error("Tried to use a NULL IGModAudioChannel!"); + return channel; + } + + [LuaMethod] + static int IGModAudioChannel__EnableLooping(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + bool loop = lua.GetBool(2); + if (loop && channel.IsBlockStreamed()) { + lua.Error("Cannot use EnableLooping on a block streamed audio channel. Use the 'noblock' flag when creating the channel to disable block streaming."); + return 0; + } + channel.SetLooping(loop); + return 0; + } + + [LuaMethod] + static int IGModAudioChannel__FFT(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + + LuaObject table = new(); + table.SetFromStack(2); + if (!table.isTable()) { + lua.TypeError("table", 2); + table.UnReference(); + return 0; + } + + int size = Math.Clamp((int)lua.CheckNumberOpt(3, 2), 0, 7); + float[] data = new float[16384]; + int count = channel.FFT(data, (GModChannelFFT)size); + for (int i = 0; i < count; i++) + table.SetMember((float)(i + 1), data[i]); + lua.PushNumber(count); + table.UnReference(); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__Get3DCone(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + channel.Get3DCone(out int innerAngle, out int outerAngle, out float outerVolume); + lua.PushNumber(innerAngle); + lua.PushNumber(outerAngle); + lua.PushNumber(outerVolume); + return 3; + } + + [LuaMethod] + static int IGModAudioChannel__Get3DEnabled(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushBool(channel.Get3DEnabled()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__Get3DFadeDistance(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + channel.Get3DFadeDistance(out float min, out float max); + lua.PushNumber(min); + lua.PushNumber(max); + return 2; + } + + [LuaMethod] + static int IGModAudioChannel__GetAverageBitRate(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushNumber(channel.GetAverageBitRate()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__GetBitsPerSample(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushNumber(channel.GetBitsPerSample()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__GetBufferedTime(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushNumber(channel.GetBufferedTime()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__GetFileName(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushString(channel.GetFileName()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__GetLength(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushNumber(channel.GetLength()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__GetLevel(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + channel.GetLevel(out float left, out float right); + lua.PushNumber(left); + lua.PushNumber(right); + return 2; + } + + [LuaMethod] + static int IGModAudioChannel__GetPan(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushNumber(channel.GetChannelPan()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__GetPlaybackRate(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushNumber(channel.GetPlaybackRate()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__GetPos(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + channel.GetPos(out Vector3 position, out Vector3 direction, out _); + LuaVector.Push_Vector(position); + LuaVector.Push_Vector(direction); + return 2; + } + + [LuaMethod] + static int IGModAudioChannel__GetSamplingRate(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushNumber(channel.GetSamplingRate()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__GetState(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushNumber(channel.GetState()); + return 1; + } + + static unsafe int PushTagList(ILuaInterface lua, int type) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + + byte* tags = (byte*)channel.GetTags(type); + if (tags == null) + return 0; + + LuaTable table = new(); + int index = 1; + while (*tags != 0) { + ReadOnlySpan tag = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(tags); + lua.PushString(tag); + LuaObject value = new(-1, LuaType.None); + table.SetMember((float)index++, value); + value.UnReference(); + lua.Pop(1); + tags += tag.Length + 1; + } + table.Push(); + table.UnReference(); + return 1; + } + + static unsafe int PushTagString(ILuaInterface lua, int type) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + + byte* tags = (byte*)channel.GetTags(type); + if (tags == null) + return 0; + + lua.PushString(MemoryMarshal.CreateReadOnlySpanFromNullTerminated(tags)); + return 1; + } + + [LuaMethod] static int IGModAudioChannel__GetTagsHTTP(ILuaInterface lua) => PushTagList(lua, 3); + [LuaMethod] static int IGModAudioChannel__GetTagsMP4(ILuaInterface lua) => PushTagList(lua, 7); + [LuaMethod] static int IGModAudioChannel__GetTagsOGG(ILuaInterface lua) => PushTagList(lua, 2); + [LuaMethod] static int IGModAudioChannel__GetTagsWMA(ILuaInterface lua) => PushTagList(lua, 8); + [LuaMethod] static int IGModAudioChannel__GetTagsMeta(ILuaInterface lua) => PushTagString(lua, 5); + [LuaMethod] static int IGModAudioChannel__GetTagsVendor(ILuaInterface lua) => PushTagString(lua, 9); + + static unsafe string ID3Field(byte* src, int size) { + int length = 0; + while (length < size - 1 && src[length] != 0) + length++; + return System.Text.Encoding.Latin1.GetString(src, length); + } + + [LuaMethod] + static unsafe int IGModAudioChannel__GetTagsID3(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + + byte* tag = (byte*)channel.GetTags(0); + if (tag == null) + return 0; + + LuaTable table = new(); + table.SetMember("id", ID3Field(tag, 4)); + table.SetMember("title", ID3Field(tag + 3, 31)); + table.SetMember("artist", ID3Field(tag + 33, 31)); + table.SetMember("album", ID3Field(tag + 63, 31)); + table.SetMember("year", ID3Field(tag + 93, 5)); + table.SetMember("comment", ID3Field(tag + 97, 31)); + table.SetMember("genre", (float)tag[127]); + table.Push(); + table.UnReference(); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__GetTime(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushNumber(channel.GetTime()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__GetVolume(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushNumber(channel.GetVolume()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__Is3D(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushBool(channel.Is3D()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__IsBlockStreamed(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushBool(channel.IsBlockStreamed()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__IsLooping(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushBool(channel.IsLooping()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__IsOnline(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + lua.PushBool(channel.IsOnline()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__IsValid(ILuaInterface lua) { + IGModAudioChannel? channel = (IGModAudioChannel?)LC_IGModAudioChannel.Get(1); + lua.PushBool(channel != null && channel.IsValid()); + return 1; + } + + [LuaMethod] + static int IGModAudioChannel__Pause(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel != null && channel.IsValid()) + channel.Pause(); + return 0; + } + + [LuaMethod] + static int IGModAudioChannel__Play(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel != null && channel.IsValid()) + channel.Play(); + return 0; + } + + [LuaMethod] + static int IGModAudioChannel__Set3DCone(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + float outerVolume = (float)lua.CheckNumber(4); + int outerAngle = (int)lua.CheckNumber(3); + int innerAngle = (int)lua.CheckNumber(2); + channel.Set3DCone(innerAngle, outerAngle, outerVolume); + return 0; + } + + [LuaMethod] + static int IGModAudioChannel__Set3DEnabled(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel != null && channel.IsValid()) + channel.Set3DEnabled(lua.GetBool(2)); + return 0; + } + + [LuaMethod] + static int IGModAudioChannel__Set3DFadeDistance(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + float max = (float)lua.CheckNumber(3); + float min = (float)lua.CheckNumber(2); + channel.Set3DFadeDistance(min, max); + return 0; + } + + [LuaMethod] + static int IGModAudioChannel__SetPan(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel != null && channel.IsValid()) + channel.SetChannelPan((float)lua.CheckNumber(2)); + return 0; + } + + [LuaMethod] + static int IGModAudioChannel__SetPlaybackRate(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel != null && channel.IsValid()) + channel.SetPlaybackRate((float)lua.CheckNumber(2)); + return 0; + } + + [LuaMethod] + static int IGModAudioChannel__SetPos(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + Vector3 position = LuaVector.Get_Vector(2); + Vector3 direction = default; + if (lua.GetType(3) == LuaType.Vector) + direction = LuaVector.Get_Vector(3); + channel.SetPos(position, direction, default); + return 0; + } + + [LuaMethod] + static int IGModAudioChannel__SetTime(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + if (channel.IsBlockStreamed()) { + lua.Error("Cannot use SetTime on a block streamed audio channel. Use the 'noblock' flag when creating the channel to disable block streaming."); + return 0; + } + bool dontDecode = lua.GetType(3) != LuaType.Nil && lua.GetBool(3); + channel.SetTime((float)lua.CheckNumber(2), dontDecode); + return 0; + } + + [LuaMethod] + static int IGModAudioChannel__SetVolume(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel != null && channel.IsValid()) + channel.SetVolume((float)lua.CheckNumber(2)); + return 0; + } + + [LuaMethod] + static int IGModAudioChannel__Stop(ILuaInterface lua) { + IGModAudioChannel? channel = Get_IGModAudioChannel(lua); + if (channel == null || !channel.IsValid()) + return 0; + channel.Stop(); + channel.Destroy(); + lua.ReleaseUserTypeObject(channel); + lua.SetUserType(1, 0); + return 0; + } + + [LuaMethod] + static int IGModAudioChannel____gc(ILuaInterface lua) { + IGModAudioChannel? channel = (IGModAudioChannel?)LC_IGModAudioChannel.Get(1); + if (channel != null) { + channel.Destroy(); + lua.ReleaseUserTypeObject(channel); + lua.SetUserType(1, 0); + } + return 0; + } + + [LuaMethod] + static int IGModAudioChannel____tostring(ILuaInterface lua) { + IGModAudioChannel? channel = (IGModAudioChannel?)LC_IGModAudioChannel.Get(1); + if (channel != null && channel.IsValid()) { + lua.PushString($"IGModAudioChannel [{channel.GetFileName()}]"); + return 1; + } + lua.PushString("IGModAudioChannel [NULL]"); + return 1; + } +} diff --git a/Game.Client/GarrysMod/LuaCam.cs b/Game.Client/GarrysMod/LuaCam.cs index cbb2aed17..8de6359d9 100644 --- a/Game.Client/GarrysMod/LuaCam.cs +++ b/Game.Client/GarrysMod/LuaCam.cs @@ -81,6 +81,7 @@ public static void CheckMissingEnds() { public static bool InSurface3D; public static void SetInSurface3D(bool value) => InSurface3D = value; + public static bool ShouldDrawLocalPlayerCache; public static bool FrameStateChecked; public static void ResetFrameStateChecked() => FrameStateChecked = false; diff --git a/Game.Client/GarrysMod/LuaMesh.cs b/Game.Client/GarrysMod/LuaMesh.cs new file mode 100644 index 000000000..0c9706a11 --- /dev/null +++ b/Game.Client/GarrysMod/LuaMesh.cs @@ -0,0 +1,680 @@ +using CommunityToolkit.HighPerformance; + +using Source; +using Source.Common; +using Source.Common.GarrysMod.Lua; +using Source.Common.MaterialSystem; +using Source.Common.Mathematics; + +using System.Numerics; + +namespace Game.Client.GarrysMod; + +public class LuaMeshObject +{ + public int Refs; + public IMesh? Mesh; +} + +public static partial class LuaMesh +{ + [LuaLibrary] + static readonly LuaLibrary LL_Factory_mesh = new("mesh"); + + [LuaClass(typeof(LuaMeshObject))] + public static readonly LuaClass LC_IMesh = new("IMesh", LuaType.IMesh, null, null); + + static readonly List PendingDestroy = []; + + static MeshBuilder Builder = new(); + static IMesh? CurrentMesh; + static bool IsStatic; + static int MaxVertices; + static int VerticesAdded; + + static IMesh? GetMesh(ILuaInterface lua, int stackPos) { + LuaMeshObject? obj = (LuaMeshObject?)LC_IMesh.Get(stackPos); + if (obj == null || obj.Mesh == null) { + lua.Error("Tried to use a NULL IMesh!"); + return null; + } + return obj.Mesh; + } + + static bool CanWriteVertex() => VerticesAdded < MaxVertices; + + static void EndMesh() { + if (CurrentMesh == null) + return; + CurrentMesh = null; + Builder.End(false, !IsStatic); + } + + public static void FlushPendingDestroy() { + for (int i = 0; i < PendingDestroy.Count; i++) { + LuaMeshObject obj = PendingDestroy[i]; + if (CurrentMesh == obj.Mesh) + EndMesh(); + obj.Refs--; + if (obj.Refs < 1 && obj.Mesh != null) { + using MatRenderContextPtr renderContext = new(materials); + renderContext.DestroyStaticMesh(obj.Mesh); + obj.Mesh = null; + } + } + PendingDestroy.Clear(); + } + + static void QueueDestroy(ILuaInterface lua) { + LuaMeshObject? obj = (LuaMeshObject?)LC_IMesh.Get(1); + if (obj == null) + return; + if (!PendingDestroy.Contains(obj)) + PendingDestroy.Add(obj); + lua.SetUserType(1, 0); + } + + [LuaGlobal("Mesh")] + static int CreateMesh(ILuaInterface lua) { + IMaterial? material = null; + if (lua.GetType(1) == LuaType.Material) + material = (IMaterial?)LuaMaterial.LC_IMaterial.Get(1); + int boneWeights = (int)lua.CheckNumberOpt(2, 0); + + VertexFormat format = MaterialVertexFormat.Model; + if (material != null) { + if (material.GetVertexFormat() != 0) + format = material.GetVertexFormat(); + else { + Warning($"Global.Mesh Warning! Attempted to use a material '{material.GetName()}' with vertex format 0!\n"); + material = null; + } + } + + if (boneWeights > 0) { + if ((uint)(boneWeights - 2) > 1) { + lua.Error("Invalid bone weight count! Allowed values are 0, 2, or 3.\n"); + return 0; + } + format |= VertexExts.GetBoneWeight(boneWeights) | VertexFormat.BoneIndex; + } + + using MatRenderContextPtr renderContext = new(materials); + IMesh? mesh = renderContext.CreateStaticMesh(format, "Model Verts", material!); + if (mesh == null) { + Warning("Mesh(): Error creating a new mesh!\n"); + return 0; + } + + LC_IMesh.Push(new LuaMeshObject() { Refs = 1, Mesh = mesh }); + return 1; + } + + [LuaMethod] + static int IMesh__BuildFromTriangles(ILuaInterface lua) { + IMesh? mesh = GetMesh(lua, 1); + if (!lua.IsType(2, LuaType.Table)) { + lua.TypeError("table", 2); + return 0; + } + BuildFromTriangles(3, MaterialPrimitiveType.Triangles, mesh!, lua.GetObject(2)); + return 0; + } + + static void BuildFromTriangles(int vertsPerPrimitive, MaterialPrimitiveType type, IMesh mesh, ILuaObject table) { + int count = 1; + LuaObject vert = new(); + table.GetMember(count, vert); + while (!vert.isNil()) { + vert.UnReference(); + count++; + vert = new(); + table.GetMember(count, vert); + } + vert.UnReference(); + count--; + if (count < 3) + return; + + int primitiveVerts = count / vertsPerPrimitive * vertsPerPrimitive; + VertexFormat format = mesh.GetVertexFormat(); + int texCoordSize = format.GetTexCoordDimensionSize(0); + int numBoneWeights = format.GetBoneWeightsSize(); + int userDataSize = format.GetUserDataSize(); + bool modify = mesh.IndexCount() > 0; + + MeshBuilder builder = new(); + if (!modify) + builder.Begin(mesh, type, count / vertsPerPrimitive); + else { + if (mesh.VertexCount() < count) { + g_Lua!.ErrorNoHalt("When modifying a mesh, you must match vertex count!"); + return; + } + builder.BeginModify(mesh, 0, -1, 0, 0); + } + + if (count < primitiveVerts) + primitiveVerts = count; + + for (int i = 1; i <= primitiveVerts; i++) { + vert = new(); + table.GetMember(i, vert); + if (vert.isNil()) { + vert.UnReference(); + break; + } + + if ((format & VertexFormat.Position) != 0) + builder.Position3fv(vert.GetMemberVector("pos", vec3_origin)); + if ((format & VertexFormat.Normal) != 0) + builder.Normal3fv(vert.GetMemberVector("normal", vec3_origin)); + if (texCoordSize > 1) { + builder.TexCoord2f(0, vert.GetMemberFloat("u", 0), vert.GetMemberFloat("v", 0)); + builder.TexCoord2f(1, vert.GetMemberFloat("u1", 0), vert.GetMemberFloat("v1", 0)); + } + if ((format & VertexFormat.Color) != 0) { + LuaObject color = new(); + vert.GetMember("color", color); + Color col = LuaRender.GetColor(color); + builder.Color4ub(col.R, col.G, col.B, col.A); + color.UnReference(); + } + if ((format & VertexFormat.TangentT) != 0) + builder.TangentT3fv(vert.GetMemberVector("tangent", vec3_origin)); + if ((format & VertexFormat.TangentS) != 0) + builder.TangentS3fv(vert.GetMemberVector("binormal", vec3_origin)); + if (numBoneWeights != 0) { + LuaObject weights = new(); + vert.GetMember("weights", weights); + int weightCount = Math.Min(numBoneWeights, 3); + for (int w = 0; w < weightCount; w++) { + LuaObject weight = new(); + weights.GetMember(w + 1, weight); + if (weight.isTable()) { + int bone = weight.GetMemberInt("bone", 0); + if ((uint)(bone - 1) > 51) { + g_Lua!.ErrorNoHalt($"BuildFromTriangles: Too many model transform matrices! ({53} max)\n"); + weight.UnReference(); + break; + } + builder.BoneMatrix(w, bone); + if (w < 2) + builder.BoneWeight(w, weight.GetMemberFloat("weight", 1.0f)); + } + weight.UnReference(); + } + weights.UnReference(); + } + if (userDataSize > 3) { + Vector4 userData = default; + LuaObject data = new(); + vert.GetMember("userdata", data); + if (data.isTable()) { + userData.X = (float)data.GetMemberDouble(1, 0); + userData.Y = (float)data.GetMemberDouble(2, 0); + userData.Z = (float)data.GetMemberDouble(3, 0); + userData.W = (float)data.GetMemberDouble(4, 0); + } + data.UnReference(); + builder.UserData(userData); + } + vert.UnReference(); + builder.AdvanceVertex(); + } + + if (!modify) + builder.End(); + else + builder.EndModify(); + } + + [LuaMethod] + static int IMesh__Destroy(ILuaInterface lua) { + if (LC_IMesh.Get(1) == null) { + lua.Error("Tried to use a NULL LuaMesh!"); + return 0; + } + QueueDestroy(lua); + return 0; + } + + [LuaMethod] + static int IMesh__Draw(ILuaInterface lua) { + IMesh? mesh = GetMesh(lua, 1); + if (mesh == null) + return 0; + if (mesh.GetVertexFormat().GetBoneWeightsSize() != 0) { + lua.Error("Trying to render skinned mesh without skinning!\n"); + return 0; + } + mesh.Draw(); + return 0; + } + + static bool IsMatrixMember(ILuaObject table, int key) { + LuaObject member = new(); + table.GetMember(key, member); + bool isMatrix = member.GetType() == LuaType.Matrix; + member.UnReference(); + return isMatrix; + } + + [LuaMethod] + static int IMesh__DrawSkinned(ILuaInterface lua) { + LuaMeshObject? obj = (LuaMeshObject?)LC_IMesh.Get(1); + if (obj == null || obj.Mesh == null) { + lua.Error("Tried to use a NULL IMesh!"); + return 0; + } + IMesh mesh = obj.Mesh; + + int numBoneWeights = mesh.GetVertexFormat().GetBoneWeightsSize(); + if (numBoneWeights == 0) { + mesh.Draw(); + return 0; + } + + ILuaObject table = lua.GetObject(2); + if (!table.isTable()) { + lua.TypeError("table", 2); + return 0; + } + + bool transform = lua.GetType(3) != LuaType.Nil && lua.GetBool(3); + + using MatRenderContextPtr renderContext = new(materials); + Matrix4x4 model = Matrix4x4.Identity; + renderContext.GetMatrix(MaterialMatrixMode.Model, out model); + + int bone = 1; + while (IsMatrixMember(table, bone)) { + Matrix4x4 bind = table.GetMemberMatrix(bone, default); + if (bone > 52) { + lua.ErrorNoHalt($"Too many model transform matrices! ({53} max)\n"); + break; + } + if (transform) + MathLib.MatrixMultiply(model, bind, out bind); + renderContext.LoadBoneMatrix(bone, new ReadOnlySpan(in bind).Cast()[0]); + bone++; + } + + Matrix4x4 fill = Matrix4x4.Identity; + if (transform) + MathLib.MatrixMultiply(fill, model, out fill); + for (; bone < 53; bone++) + renderContext.LoadBoneMatrix(bone, new ReadOnlySpan(in fill).Cast()[0]); + + int oldBones = renderContext.GetCurrentNumBones(); + renderContext.SetNumBoneWeights(numBoneWeights); + renderContext.MatrixMode(MaterialMatrixMode.Model); + renderContext.PushMatrix(); + mesh.Draw(); + renderContext.MatrixMode(MaterialMatrixMode.Model); + renderContext.PopMatrix(); + renderContext.SetNumBoneWeights(oldBones); + return 0; + } + + [LuaMethod] + static int IMesh__IsValid(ILuaInterface lua) { + LuaMeshObject? obj = (LuaMeshObject?)LC_IMesh.Get(1); + lua.PushBool(obj != null && obj.Mesh != null); + return 1; + } + + [LuaMethod] + static int IMesh____gc(ILuaInterface lua) { + QueueDestroy(lua); + return 0; + } + + [LuaMethod] + static int IMesh____tostring(ILuaInterface lua) { + LuaMeshObject? obj = (LuaMeshObject?)LC_IMesh.Get(1); + if (obj == null || obj.Mesh == null) { + lua.PushString("IMesh [NULL]"); + return 1; + } + lua.PushString($"IMesh [{obj.Mesh.VertexCount()} verts, {obj.Mesh.IndexCount()} indices]"); + return 1; + } + + [LuaFunction] + static int Begin(ILuaInterface lua) { + if (CurrentMesh != null) { + EndMesh(); + lua.Error("mesh.End must be called before calling mesh.Begin again"); + return 0; + } + + using MatRenderContextPtr renderContext = new(materials); + int maxVertices = 32768; + IMesh? mesh; + bool isStatic; + int type; + int count; + if (lua.GetType(1) == LuaType.IMesh) { + LuaMeshObject? obj = (LuaMeshObject?)LC_IMesh.Get(1); + if (obj == null || obj.Mesh == null) + lua.Error("Tried to use a NULL IMesh!"); + mesh = obj?.Mesh; + type = (int)lua.CheckNumber(2); + count = (int)lua.CheckNumber(3); + isStatic = true; + maxVertices = 65535; + } + else { + mesh = renderContext.GetDynamicMesh(true); + type = (int)lua.CheckNumber(1); + count = (int)lua.CheckNumber(2); + isStatic = false; + } + + if (count < 1) { + lua.Error($"called mesh.Begin with a bad primitive type ({type}) or count ({count})"); + return 0; + } + + VerticesAdded = 0; + IsStatic = isStatic; + switch ((MaterialPrimitiveType)type) { + case MaterialPrimitiveType.Lines: + MaxVertices = count * 2; + break; + case MaterialPrimitiveType.Triangles: + MaxVertices = count * 3; + break; + case MaterialPrimitiveType.TriangleStrip: + MaxVertices = count + 2; + break; + case MaterialPrimitiveType.LineStrip: + MaxVertices = count + 1; + break; + case MaterialPrimitiveType.Polygon: + if (count < 3) + goto default; + MaxVertices = count; + break; + case MaterialPrimitiveType.Points: + case MaterialPrimitiveType.LineLoop: + MaxVertices = count; + break; + case MaterialPrimitiveType.Quads: + MaxVertices = count * 4; + break; + default: + CurrentMesh = null; + lua.Error($"called mesh.Begin with a bad primitive type ({type}) or count ({count})"); + return 0; + } + + if (maxVertices < MaxVertices) { + CurrentMesh = null; + lua.Error($"called mesh.Begin with a primitive count which results in too many vertices ({MaxVertices}, maximum={maxVertices})"); + return 0; + } + + CurrentMesh = mesh; + Builder.Begin(mesh!, (MaterialPrimitiveType)type, count); + return 0; + } + + [LuaFunction] + static int End(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.End if no mesh was started using mesh.Begin"); + return 0; + } + EndMesh(); + return 0; + } + + [LuaFunction] + static int AdvanceVertex(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.AdvanceVertex if no mesh was started using mesh.Begin"); + return 0; + } + if (CanWriteVertex()) { + Builder.AdvanceVertex(); + VerticesAdded++; + } + return 0; + } + + [LuaFunction] + static int BoneData(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.BoneData if no mesh was started using mesh.Begin"); + return 0; + } + if (!CanWriteVertex()) + return 0; + + uint index = (uint)lua.CheckNumber(1); + uint bone = (uint)lua.CheckNumber(2); + if (index >= 3) { + lua.Error($"Invalid bone matrix index. Must be integer [0,{index - 1}]\n"); + return 0; + } + if (bone >= 53) { + lua.Error($"Invalid bone matrix bone. Must be integer [1,{52}]\n"); + return 0; + } + + int numBoneWeights = CurrentMesh.GetVertexFormat().GetBoneWeightsSize(); + if (numBoneWeights <= (int)index) { + lua.Error($"Invalid bone matrix index {index}. Mesh only has {numBoneWeights} weights!\n"); + return 0; + } + + if (index == 2) { + Builder.BoneMatrix((int)index, (int)bone); + return 0; + } + + float weight = (float)lua.CheckNumber(3); + if (weight < 0.0f || weight > 1.0f) { + lua.Error("Invalid bone matrix weight. Must be float [0,1]\n"); + return 0; + } + Builder.BoneMatrix((int)index, (int)bone); + Builder.BoneWeight((int)index, weight); + return 0; + } + + [LuaFunction("Color")] + static int MeshColor(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.Color if no mesh was started using mesh.Begin"); + return 0; + } + if (CanWriteVertex()) + Builder.Color4ub((byte)(int)lua.CheckNumber(1), (byte)(int)lua.CheckNumber(2), (byte)(int)lua.CheckNumber(3), (byte)(int)lua.CheckNumber(4)); + return 0; + } + + [LuaFunction] + static int Normal(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.Normal if no mesh was started using mesh.Begin"); + return 0; + } + if (!CanWriteVertex()) + return 0; + if (lua.GetType(1) == LuaType.Number) + Builder.Normal3f((float)lua.CheckNumber(1), (float)lua.CheckNumber(2), (float)lua.CheckNumber(3)); + else + Builder.Normal3fv(LuaVector.Get_Vector(1)); + return 0; + } + + [LuaFunction] + static int Position(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.Position if no mesh was started using mesh.Begin"); + return 0; + } + if (!CanWriteVertex()) + return 0; + if (lua.GetType(1) == LuaType.Number) + Builder.Position3f((float)lua.CheckNumber(1), (float)lua.CheckNumber(2), (float)lua.CheckNumber(3)); + else + Builder.Position3fv(LuaVector.Get_Vector(1)); + return 0; + } + + static void QuadVertex(in Vector3 position, in Vector3 normal, float s, float t, in Color color) { + if (!CanWriteVertex()) + return; + Builder.Position3fv(position); + Builder.Normal3fv(normal); + Builder.TexCoord2f(0, s, t); + Builder.Color4ub(color.R, color.G, color.B, color.A); + Builder.AdvanceVertex(); + VerticesAdded++; + } + + [LuaFunction] + static int Quad(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.Quad if no mesh was started using mesh.Begin"); + return 0; + } + Vector3 p1 = LuaVector.Get_Vector(1); + Vector3 p2 = LuaVector.Get_Vector(2); + Vector3 p3 = LuaVector.Get_Vector(3); + Vector3 p4 = LuaVector.Get_Vector(4); + Color color = LuaRender.GetColor(lua.GetObject(5)); + + Vector3 normal = Vector3.Cross(p1 - p2, p1 - p3); + MathLib.VectorNormalize(ref normal); + + QuadVertex(p1, normal, 1, 1, color); + QuadVertex(p2, normal, 0, 1, color); + QuadVertex(p3, normal, 0, 0, color); + QuadVertex(p4, normal, 1, 0, color); + return 0; + } + + [LuaFunction] + static int QuadEasy(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.QuadEasy if no mesh was started using mesh.Begin"); + return 0; + } + Vector3 position = LuaVector.Get_Vector(1); + Vector3 normal = LuaVector.Get_Vector(2); + float width = (float)lua.CheckNumber(3); + float height = (float)lua.CheckNumber(4); + Color color = LuaRender.GetColor(lua.GetObject(5)); + float rotation = 0; + if (lua.GetType(6) == LuaType.Number) + rotation = (float)lua.CheckNumber(6); + + MathLib.VectorVectors(normal, out Vector3 right, out Vector3 up); + + float widthAngle = MathLib.DEG2RAD(rotation); + float heightAngle = MathLib.DEG2RAD(rotation + 90.0f); + Vector3 halfWidth = (right * MathF.Cos(widthAngle) - up * MathF.Sin(widthAngle)) * width * 0.5f; + Vector3 halfHeight = (right * MathF.Cos(heightAngle) - up * MathF.Sin(heightAngle)) * height * 0.5f; + + QuadVertex(position + halfWidth - halfHeight, normal, 1, 1, color); + QuadVertex(position - halfWidth - halfHeight, normal, 0, 1, color); + QuadVertex(position - halfWidth + halfHeight, normal, 0, 0, color); + QuadVertex(position + halfWidth + halfHeight, normal, 1, 0, color); + return 0; + } + + [LuaFunction] + static int Specular(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.Specular if no mesh was started using mesh.Begin"); + return 0; + } + if (CanWriteVertex()) + Builder.Specular4ub((byte)(int)lua.CheckNumber(1), (byte)(int)lua.CheckNumber(2), (byte)(int)lua.CheckNumber(3), (byte)(int)lua.CheckNumber(4)); + return 0; + } + + [LuaFunction] + static int TangentS(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.TangentS if no mesh was started using mesh.Begin"); + return 0; + } + if (!CanWriteVertex()) + return 0; + if (lua.GetType(1) == LuaType.Number) + Builder.TangentS3f((float)lua.CheckNumber(1), (float)lua.CheckNumber(2), (float)lua.CheckNumber(3)); + else + Builder.TangentS3fv(LuaVector.Get_Vector(1)); + return 0; + } + + [LuaFunction] + static int TangentT(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.TangentT if no mesh was started using mesh.Begin"); + return 0; + } + if (!CanWriteVertex()) + return 0; + if (lua.GetType(1) == LuaType.Number) + Builder.TangentT3f((float)lua.CheckNumber(1), (float)lua.CheckNumber(2), (float)lua.CheckNumber(3)); + else + Builder.TangentT3fv(LuaVector.Get_Vector(1)); + return 0; + } + + [LuaFunction] + static int TexCoord(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.TexCoord if no mesh was started using mesh.Begin"); + return 0; + } + if (!CanWriteVertex()) + return 0; + + uint stage = (uint)lua.CheckNumber(1); + if (stage >= 8) + return 0; + + int args = lua.Top(); + if (args == 4) + Builder.TexCoord3f((int)stage, (float)lua.CheckNumber(2), (float)lua.CheckNumber(3), (float)lua.CheckNumber(4)); + else if (args == 3) + Builder.TexCoord2f((int)stage, (float)lua.CheckNumber(2), (float)lua.CheckNumber(3)); + else if (args < 3) + Builder.TexCoord1f((int)stage, (float)lua.CheckNumber(2)); + else + Builder.TexCoord4f((int)stage, (float)lua.CheckNumber(2), (float)lua.CheckNumber(3), (float)lua.CheckNumber(4), (float)lua.CheckNumber(5)); + return 0; + } + + [LuaFunction] + static int UserData(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.UserData if no mesh was started using mesh.Begin"); + return 0; + } + if (!CanWriteVertex()) + return 0; + Vector4 data = new((float)lua.CheckNumber(1), (float)lua.CheckNumber(2), (float)lua.CheckNumber(3), (float)lua.CheckNumber(4)); + if (CurrentMesh.GetVertexFormat().GetUserDataSize() > 3) + Builder.UserData(data); + return 0; + } + + [LuaFunction] + static int VertexCount(ILuaInterface lua) { + if (CurrentMesh == null) { + lua.Error("cannot call mesh.VertexCount if no mesh was started using mesh.Begin"); + return 0; + } + lua.PushNumber(Builder.VertexCount()); + return 1; + } +} diff --git a/Game.Client/GarrysMod/LuaParticleEmitter.cs b/Game.Client/GarrysMod/LuaParticleEmitter.cs new file mode 100644 index 000000000..7e43aea33 --- /dev/null +++ b/Game.Client/GarrysMod/LuaParticleEmitter.cs @@ -0,0 +1,12 @@ +using Source.Common.GarrysMod.Lua; + +namespace Game.Client.GarrysMod; + +public static partial class LuaParticleEmitter +{ + [LuaGlobal] + static int ParticleEmitter(ILuaInterface lua) { + // todo todO Todo TODO FIXME BUGBBUG + return 0; + } +} diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index cea079a63..cd49d92a7 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -647,6 +647,53 @@ static int DrawSprite(ILuaInterface lua) { BeamDraw.DrawSprite(pos, width, height, color); return 0; } + + internal static Color GetColor(ILuaObject? obj) { + if (obj == null || !obj.isTable()) + return new(255, 255, 255, 255); + return new((byte)(int)obj.GetMemberFloat("r", 255), (byte)(int)obj.GetMemberFloat("g", 255), (byte)(int)obj.GetMemberFloat("b", 255), (byte)(int)obj.GetMemberFloat("a", 255)); + } + + static void DrawQuad(in Vector3 p1, in Vector3 p2, in Vector3 p3, in Vector3 p4, in Color color, bool wireframe) { + using MatRenderContextPtr renderContext = new(materials); + IMesh mesh = renderContext.GetDynamicMesh(true); + MeshBuilder meshBuilder = new(); + meshBuilder.Begin(mesh, wireframe ? MaterialPrimitiveType.LineLoop : MaterialPrimitiveType.Quads, wireframe ? 4 : 1); + + meshBuilder.Position3fv(p1); + meshBuilder.TexCoord2f(0, 0, 0); + meshBuilder.Color4ub(color.R, color.G, color.B, color.A); + meshBuilder.AdvanceVertex(); + + meshBuilder.Position3fv(p2); + meshBuilder.TexCoord2f(0, 1, 0); + meshBuilder.Color4ub(color.R, color.G, color.B, color.A); + meshBuilder.AdvanceVertex(); + + meshBuilder.Position3fv(p3); + meshBuilder.TexCoord2f(0, 1, 1); + meshBuilder.Color4ub(color.R, color.G, color.B, color.A); + meshBuilder.AdvanceVertex(); + + meshBuilder.Position3fv(p4); + meshBuilder.TexCoord2f(0, 0, 1); + meshBuilder.Color4ub(color.R, color.G, color.B, color.A); + meshBuilder.AdvanceVertex(); + + meshBuilder.End(); + mesh.Draw(); + } + + [LuaFunction] + static int DrawQuad(ILuaInterface lua) { + Vector3 p1 = LuaVector.Get_Vector(1); + Vector3 p2 = LuaVector.Get_Vector(2); + Vector3 p3 = LuaVector.Get_Vector(3); + Vector3 p4 = LuaVector.Get_Vector(4); + Color color = GetColor(lua.GetObject(5)); + DrawQuad(p1, p2, p3, p4, color, false); + return 0; + } #endif [LuaFunction] diff --git a/Game.Client/GarrysMod/LuaUserMessages.cs b/Game.Client/GarrysMod/LuaUserMessages.cs new file mode 100644 index 000000000..e021e42f3 --- /dev/null +++ b/Game.Client/GarrysMod/LuaUserMessages.cs @@ -0,0 +1,52 @@ +using Game.Shared; + +using Source; +using Source.Common.Bitbuffers; +using Source.Common.GarrysMod.Lua; + +namespace Game.Client.GarrysMod; + +public static class LuaUserMessages +{ + public static void RegisterUserMessages(UserMessages messages) { + messages.Register("LuaUserMessage", -1); + messages.HookMessage("LuaUserMessage", MsgFunc_LuaUserMessage); + } + + static void MsgFunc_LuaUserMessage(bf_read msg) { + if (g_Lua == null || g_Lua.Global() == null) + return; + + Span name = stackalloc char[512]; + msg.ReadString(name, false, out _); + ReadOnlySpan nameStr = ((ReadOnlySpan)name).SliceNullTerminatedString(); + + LuaObject usermessage = new(); + g_Lua.Global().GetMember("usermessage", usermessage); + if (!usermessage.isTable()) { + Warning("Got Lua Message - but haven't got usermessage global table!"); + Warning($"Message was: '{nameStr}'\n"); + usermessage.UnReference(); + return; + } + + LuaObject incomingMessage = new(); + usermessage.GetMember("IncomingMessage", incomingMessage); + if (!incomingMessage.isFunction()) { + Warning("Got Lua Message - but haven't got usermessage.IncomingMessage function!"); + Warning($"Message was: '{nameStr}'\n"); + } + else { + LuaAchievements.UnsetIncrementFlag = true; + incomingMessage.Push(); + g_Lua.PushString(nameStr); + LuaBfRead.Push_bf_read(msg); + LuaDisposable disposable = new(g_Lua.Top(), LuaType.None); + g_Lua.CallInternalNoReturns(2); + LuaAchievements.UnsetIncrementFlag = false; + disposable.Dispose(); + } + incomingMessage.UnReference(); + usermessage.UnReference(); + } +} diff --git a/Game.Client/HL2/HudWeaponSelection.cs b/Game.Client/HL2/HudWeaponSelection.cs index 73b43c9c3..8058db268 100644 --- a/Game.Client/HL2/HudWeaponSelection.cs +++ b/Game.Client/HL2/HudWeaponSelection.cs @@ -91,7 +91,7 @@ public override void SetWeaponSelected() { } #endif - void OnWeaponPickup(BaseCombatWeapon weapon) { + public override void OnWeaponPickup(BaseCombatWeapon weapon) { HudHistoryResource? hr = gHUD.FindElement("CHudHistoryResource") as HudHistoryResource; hr?.AddToHistory(weapon); } diff --git a/Game.Client/HL2MP/C_HL2MP_Player.cs b/Game.Client/HL2MP/C_HL2MP_Player.cs index 2d673e48d..7f6a3ae6a 100644 --- a/Game.Client/HL2MP/C_HL2MP_Player.cs +++ b/Game.Client/HL2MP/C_HL2MP_Player.cs @@ -5,6 +5,7 @@ using Source; using Source.Common; using Source.Common.Commands; +using Source.Common.Formats.BSP; using Source.Common.Mathematics; using Source.Common.Physics; @@ -78,6 +79,38 @@ public override void PostDataUpdate(DataUpdateType updateType) { base.PostDataUpdate(updateType); } + public void Initialize() { + HeadYawPoseParam = LookupPoseParameter("head_yaw"); + GetPoseParameterRange(HeadYawPoseParam, out HeadYawMin, out HeadYawMax); + + HeadPitchPoseParam = LookupPoseParameter("head_pitch"); + GetPoseParameterRange(HeadPitchPoseParam, out HeadPitchMin, out HeadPitchMax); + + StudioHdr? hdr = GetModelPtr(); + if (hdr == null) + return; + for (int i = 0; i < hdr.GetNumPoseParameters(); i++) + SetPoseParameter(hdr, i, 0.0f); + } + + protected override StudioHdr? OnNewModel() { + StudioHdr? hdr = base.OnNewModel(); + + Initialize(); + Initialize(); //? sure garry, sure + + PlayerAnimState?.ClearAnimationState(); + + return hdr; + } + + public override void OnDataChanged(DataUpdateType updateType) { + base.OnDataChanged(updateType); + if (updateType == DataUpdateType.Created) + SetNextClientThink(CLIENT_THINK_ALWAYS); + UpdateVisibility(); + } + public override ref readonly QAngle EyeAngles() { if (IsLocalPlayer()) return ref base.EyeAngles(); @@ -106,6 +139,62 @@ public override void PostThink() { public void DoAnimationEvent(PlayerAnimEvent evt, int data, bool predicted) => PlayerAnimState.DoAnimationEvent(evt, data); #if GMOD_DLL + int IDEntIndex; + + public override void ClientThink() { + bool foundViewTarget = false; + + MathLib.AngleVectors(EyeAngles(), out Vector3 forward); + + for (int client = 1; client <= gpGlobals.MaxClients; ++client) { + C_BaseEntity? ent = Util.PlayerByIndex(client); + if (ent == null || !ent.IsPlayer()) + continue; + + if (ent.EntIndex() == EntIndex()) + continue; + + Vector3 dir = ent.GetAbsOrigin() - GetAbsOrigin(); + + if (dir.Length() > 128) + continue; + + MathLib.VectorNormalize(ref dir); + + if (Vector3.Dot(forward, dir) < 0.0f) + continue; + + LookAtTarget = ent.EyePosition(); + foundViewTarget = true; + break; + } + + if (!foundViewTarget) + LookAtTarget = GetAbsOrigin() + forward * 512; + + UpdateIDTarget(); + } + + public virtual void UpdateIDTarget() { + if (!IsLocalPlayer()) + return; + + IDEntIndex = 0; + + if (GetObserverMode() == Shared.ObserverMode.Chase || GetObserverMode() == Shared.ObserverMode.DeathCam) + return; + + Vector3 end = MainViewOrigin() + MainViewForward() * 1500; + Vector3 start = MainViewOrigin() + MainViewForward() * 10; + Util.TraceLine(start, end, Mask.Solid, this, Source.CollisionGroup.None, out Trace tr); + + if (!tr.StartSolid && tr.DidHitNonWorldEntity()) { + C_BaseEntity? entity = tr.Ent; + if (entity != null && entity != this) + IDEntIndex = entity.EntIndex(); + } + } + public override void UpdateClientSideAnimation() { QAngle eyeAngles = EyeAngles(); PlayerAnimState.Update(eyeAngles[YAW], eyeAngles[PITCH]); diff --git a/Game.Client/HLClient.cs b/Game.Client/HLClient.cs index 089660cce..49e0c9d13 100644 --- a/Game.Client/HLClient.cs +++ b/Game.Client/HLClient.cs @@ -128,6 +128,7 @@ public bool Init() { randomgaussian.AttachToStream(random); #if GMOD_DLL + get.Audio()!.Init(services); get.HTML()?.Init(get.GameDirParent(), HtmlResourceHandler.g_HtmlResourceHandler); get.IntroScreen()!.Start(); get.IntroScreen()!.Update("Start", true); @@ -207,6 +208,7 @@ public void Shutdown() { #if GMOD_DLL Game.Client.GarrysMod.GarrysMod.Lua.Kill(); get.MenuSystem()?.Shutdown(); + get.Audio()!.Shutdown(); get.HTML()?.Shutdown(); Game.Client.GarrysMod.MaterialProxyFactory.Shutdown(); #endif diff --git a/Game.Client/HUD/BaseHudChat.cs b/Game.Client/HUD/BaseHudChat.cs index 4983b3720..47207126f 100644 --- a/Game.Client/HUD/BaseHudChat.cs +++ b/Game.Client/HUD/BaseHudChat.cs @@ -429,6 +429,7 @@ public class BaseHudChat : EditableHudElement } protected BaseHudChatInputLine ChatInput; + public BaseHudChatInputLine GetChatInput() => ChatInput; protected BaseHudChatLine ChatLine; protected int FontHeight; protected HudChatHistory ChatHistory; diff --git a/Game.Client/IInput.cs b/Game.Client/IInput.cs index 2d9142f6a..a79dadaf5 100644 --- a/Game.Client/IInput.cs +++ b/Game.Client/IInput.cs @@ -32,6 +32,8 @@ public interface IInput void CAM_ToThirdPerson(); void CAM_ToFirstPerson(); bool CAM_IsThirdPerson(); + bool CAM_IsOrthographic(); + void CAM_OrthographicSize(out float w, out float h); void CAM_SetCameraThirdData(CameraThirdData? value, QAngle vec3_angle); void AccumulateMouse(); } diff --git a/Game.Client/InCamera.cs b/Game.Client/InCamera.cs index c07d3d51b..8da54cf4f 100644 --- a/Game.Client/InCamera.cs +++ b/Game.Client/InCamera.cs @@ -78,6 +78,13 @@ public void CAM_ToFirstPerson() { public bool CAM_IsThirdPerson() => CameraInThirdPerson; + public bool CAM_IsOrthographic() => CameraIsOrthographic; + + public void CAM_OrthographicSize(out float w, out float h) { + w = c_orthowidth.GetFloat(); + h = c_orthoheight.GetFloat(); + } + static KeyButtonState cam_pitchup, cam_pitchdown, cam_yawleft, cam_yawright; static KeyButtonState cam_in, cam_out; diff --git a/Game.Client/InMain.cs b/Game.Client/InMain.cs index eda25f57d..ff91d356d 100644 --- a/Game.Client/InMain.cs +++ b/Game.Client/InMain.cs @@ -271,7 +271,6 @@ public void CreateMove(int sequenceNumber, double inputSampleFrametime, bool act ComputeForwardMove(ref cmd); ScaleMovements(ref cmd); ControllerMove(inputSampleFrametime, ref cmd); - ApplyExtras(ref cmd); } cmd.Buttons = GetButtonBits(1); @@ -309,10 +308,6 @@ public void CreateMove(int sequenceNumber, double inputSampleFrametime, bool act #endif } - private void ApplyExtras(ref UserCmd cmd) { - cmd.IsTyping = clientMode!.IsTyping(); - } - public void ValidateUserCmd(ref UserCmd f, int from) { } diff --git a/Game.Client/PixelVisibility.cs b/Game.Client/PixelVisibility.cs new file mode 100644 index 000000000..90bd2d82c --- /dev/null +++ b/Game.Client/PixelVisibility.cs @@ -0,0 +1,422 @@ +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Commands; +using Source.Common.Engine; +using Source.Common.Formats.BSP; +using Source.Common.MaterialSystem; +using Source.Common.Mathematics; + +using System.Numerics; + +namespace Game.Client; + +public struct PixelVisQueryParams +{ + public const float PIXELVIS_DEFAULT_PROXY_SIZE = 2.0f; + public const float PIXELVIS_DEFAULT_FADE_TIME = 0.0625f; + + public Vector3 Position; + public float ProxySize; + public float ProxyAspect; + public float FadeTime; + public bool Setup; + public bool SizeInScreenspace; + + public PixelVisQueryParams() => Setup = false; + + public void Init(in Vector3 origin, float proxySizeIn = PIXELVIS_DEFAULT_PROXY_SIZE, float proxyAspectIn = 1.0f, float fadeTimeIn = PIXELVIS_DEFAULT_FADE_TIME) { + Position = origin; + ProxySize = proxySizeIn; + ProxyAspect = proxyAspectIn; + FadeTime = fadeTimeIn; + Setup = true; + SizeInScreenspace = false; + } +} + +public class PixelVisSet +{ + public float ProxySize; + public float ProxyAspect; + public float FadeTimeInv; + public ushort QueryList; + public ushort Serial; + public bool SizeIsScreenSpace; + int FrameIssued; + + public PixelVisSet() { + ProxySize = 0; + ProxyAspect = 0; + FadeTimeInv = 0; + FrameIssued = 0; + Serial = 0; + QueryList = 0xFFFF; + SizeIsScreenSpace = false; + } + + public void Init(in PixelVisQueryParams parms) { + Assert(parms.Setup); + ProxySize = parms.ProxySize; + ProxyAspect = parms.ProxyAspect; + if (parms.FadeTime > 0.0f) + FadeTimeInv = 1.0f / parms.FadeTime; + else + FadeTimeInv = 1.0f / 0.125f; + FrameIssued = 0; + SizeIsScreenSpace = parms.SizeInScreenspace; + } + + public void MarkActive() => FrameIssued = (int)gpGlobals.FrameCount; + + public bool IsActive() => throw new NotImplementedException(); +} + +public class PixelVisibilityQuery +{ + public Vector3 Origin; + public int FrameIssued; + float BrightnessTarget; + float ClipFraction; + nint QueryHandle; + nint QueryHandleCount; + bool WasQueriedThisFrame; + bool Failed; + bool HasValidQueryResults; + ushort ViewID; + + public PixelVisibilityQuery() { + using MatRenderContextPtr renderContext = new(materials); + SetView(0xFFFF); + QueryHandle = renderContext.CreateOcclusionQueryObject(); + QueryHandleCount = renderContext.CreateOcclusionQueryObject(); + } + + public void ResetOcclusionQueries() { + using MatRenderContextPtr renderContext = new(materials); + if (QueryHandle != MaterialSystemGlobals.INVALID_OCCLUSION_QUERY_OBJECT_HANDLE) + renderContext.ResetOcclusionQueryObject(QueryHandle); + if (QueryHandleCount != MaterialSystemGlobals.INVALID_OCCLUSION_QUERY_OBJECT_HANDLE) + renderContext.ResetOcclusionQueryObject(QueryHandleCount); + } + + public bool IsValid() => QueryHandle != MaterialSystemGlobals.INVALID_OCCLUSION_QUERY_OBJECT_HANDLE; + + public bool IsForView(int viewID) => ViewID == viewID; + + public bool IsActive() => throw new NotImplementedException(); + + public float GetFractionVisible(float fadeTimeInv) { + if (!IsValid()) + return 0.0f; + + if (!WasQueriedThisFrame) { + using MatRenderContextPtr renderContext = new(materials); + WasQueriedThisFrame = true; + int pixels = -1; + int pixelsPossible = -1; + if (PixelVisibility.r_pixelvisibility_partial.GetBool()) { + if (FrameIssued != -1) { + pixelsPossible = renderContext.OcclusionQuery_GetNumPixelsRendered(QueryHandleCount); + pixels = renderContext.OcclusionQuery_GetNumPixelsRendered(QueryHandle); + } + + if (PixelVisibility.r_pixelvisibility_spew.GetBool() && CurrentViewID() == 0) + DevMsg(1, $"Pixels visible: {pixels} (qh:{QueryHandle}) Pixels possible: {pixelsPossible} (qh:{QueryHandleCount}) (frame:{gpGlobals.FrameCount})\n"); + + if (pixels < 0 || pixelsPossible < 0) { + Failed = FrameIssued >= 0; + return BrightnessTarget * ClipFraction; + } + HasValidQueryResults = true; + + if (pixelsPossible > 0) { + float target = (float)pixels / (float)pixelsPossible; + target = (target >= 0.95f) ? 1.0f : (target < 0.0f) ? 0.0f : target; + float rate = (float)gpGlobals.FrameTime * fadeTimeInv; + BrightnessTarget = MathLib.Approach(target, BrightnessTarget, rate); + } + else + BrightnessTarget = 0.0f; + } + else { + if (FrameIssued != -1) + pixels = renderContext.OcclusionQuery_GetNumPixelsRendered(QueryHandle); + + if (PixelVisibility.r_pixelvisibility_spew.GetBool() && CurrentViewID() == 0) + DevMsg(1, $"Pixels visible: {pixels} (qh:{QueryHandle}) (frame:{gpGlobals.FrameCount})\n"); + + if (pixels < 0) { + Failed = FrameIssued >= 0; + return BrightnessTarget * ClipFraction; + } + HasValidQueryResults = true; + if (FrameIssued == gpGlobals.FrameCount - 1) { + float rate = (float)gpGlobals.FrameTime * fadeTimeInv; + float target = 0.0f; + if (pixels > 0) { + rate *= 0.5f; + target = 1.0f; + } + BrightnessTarget = MathLib.Approach(target, BrightnessTarget, rate); + } + else + BrightnessTarget = 0.0f; + } + } + + return BrightnessTarget * ClipFraction; + } + + public void IssueQuery(IMatRenderContext renderContext, float proxySize, float proxyAspect, IMaterial material, bool sizeIsScreenSpace) => throw new NotImplementedException(); + + public void IssueCountingQuery(IMatRenderContext renderContext, float proxySize, float proxyAspect, IMaterial material, bool sizeIsScreenSpace) => throw new NotImplementedException(); + + public void SetView(int viewID) { + ViewID = (ushort)viewID; + BrightnessTarget = 0.0f; + ClipFraction = 1.0f; + FrameIssued = -1; + Failed = false; + WasQueriedThisFrame = false; + HasValidQueryResults = false; + } +} + +public class PixelVisibilitySystem : AutoGameSystem +{ + readonly UtlMultiList SetList = new(); + readonly UtlMultiList QueryList = new(); + ushort FreeQueriesList; + ushort ActiveSetsList; + ushort FreeSetsList; + IMaterial? ProxyMaterial; + IMaterial? DrawMaterial; + bool HwCanTestGlows; + bool DrawQueries; + + public PixelVisibilitySystem() : base("CPixelVisibilitySystem") { + HwCanTestGlows = true; + DrawQueries = false; + } + + public override void LevelInitPreEntity() { + bool fastqueries = PixelVisibility.HasFastQueries(); + + HwCanTestGlows = PixelVisibility.r_dopixelvisibility.GetBool() && fastqueries && engine.GetDXSupportLevel() >= 80; + if (HwCanTestGlows) { + using MatRenderContextPtr renderContext = new(materials); + + nint query = renderContext.CreateOcclusionQueryObject(); + if (query != MaterialSystemGlobals.INVALID_OCCLUSION_QUERY_OBJECT_HANDLE) + renderContext.DestroyOcclusionQueryObject(query); + else + HwCanTestGlows = false; + } + + ProxyMaterial = materials.FindMaterial("engine/occlusionproxy", MaterialDefines.TEXTURE_GROUP_CLIENT_EFFECTS); + ProxyMaterial!.IncrementReferenceCount(); + DrawMaterial = materials.FindMaterial("engine/occlusionproxy_countdraw", MaterialDefines.TEXTURE_GROUP_CLIENT_EFFECTS); + DrawMaterial!.IncrementReferenceCount(); + FreeQueriesList = QueryList.CreateList(); + ActiveSetsList = SetList.CreateList(); + FreeSetsList = SetList.CreateList(); + } + + public override void LevelShutdownPostEntity() { + DrawMaterial!.DecrementReferenceCount(); + DrawMaterial = null; + ProxyMaterial!.DecrementReferenceCount(); + ProxyMaterial = null; + DeleteUnusedSets(true); + SetList.Purge(); + QueryList.Purge(); + FreeQueriesList = UtlMultiList.InvalidIndex(); + ActiveSetsList = UtlMultiList.InvalidIndex(); + FreeSetsList = UtlMultiList.InvalidIndex(); + } + + public float GetFractionVisible(in PixelVisQueryParams parms, ref int queryHandle) { + if (!HwCanTestGlows || PixelVisibility.building_cubemaps.GetBool()) + return PixelVisibility.GlowSightDistance(parms.Position, true) > 0 ? 1.0f : 0.0f; + if (CurrentViewID() < 0) + return 0.0f; + + PixelVisSet set = FindOrCreatePixelVisSet(parms, ref queryHandle); + ushort node = FindOrCreateQueryForView(set, (int)CurrentViewID()); + QueryList[node].Origin = parms.Position; + float fraction = QueryList[node].GetFractionVisible(set.FadeTimeInv); + set.MarkActive(); + return fraction; + } + + public void EndView() => throw new NotImplementedException(); + + public void EndScene() => throw new NotImplementedException(); + + public ushort FindQueryForView(PixelVisSet set, int viewID) { + ushort node = QueryList.Head(set.QueryList); + while (node != UtlMultiList.InvalidIndex()) { + if (QueryList[node].IsForView(viewID)) + return node; + node = QueryList.Next(node); + } + return UtlMultiList.InvalidIndex(); + } + + public ushort FindOrCreateQueryForView(PixelVisSet set, int viewID) { + ushort node = FindQueryForView(set, viewID); + if (node != UtlMultiList.InvalidIndex()) + return node; + + node = AllocQuery(); + QueryList.LinkToHead(set.QueryList, node); + QueryList[node].SetView(viewID); + return node; + } + + public void DeleteUnusedQueries(PixelVisSet set, bool deleteAll) { + ushort node = QueryList.Head(set.QueryList); + while (node != UtlMultiList.InvalidIndex()) { + ushort next = QueryList.Next(node); + if (deleteAll || !QueryList[node].IsActive()) { + QueryList.Unlink(set.QueryList, node); + QueryList.LinkToHead(FreeQueriesList, node); + } + node = next; + } + } + + public void DeleteUnusedSets(bool deleteAll) { + ushort node = SetList.Head(ActiveSetsList); + while (node != UtlMultiList.InvalidIndex()) { + ushort next = SetList.Next(node); + PixelVisSet set = SetList[node]; + if (deleteAll || !SetList[node].IsActive()) + DeleteUnusedQueries(set, true); + else + DeleteUnusedQueries(set, false); + if (QueryList.Head(set.QueryList) == UtlMultiList.InvalidIndex()) + FreeSet(node); + node = next; + } + } + + public void ShowQueries(bool show) => throw new NotImplementedException(); + + public ushort AllocQuery() { + ushort node = QueryList.Head(FreeQueriesList); + if (node != UtlMultiList.InvalidIndex()) { + QueryList.Unlink(FreeQueriesList, node); + QueryList[node].ResetOcclusionQueries(); + } + else + node = QueryList.Alloc(); + return node; + } + + public ushort AllocSet() { + ushort node = SetList.Head(FreeSetsList); + if (node != UtlMultiList.InvalidIndex()) + SetList.Unlink(FreeSetsList, node); + else { + node = SetList.Alloc(); + SetList[node].QueryList = QueryList.CreateList(); + } + SetList.LinkToHead(ActiveSetsList, node); + return node; + } + + public void FreeSet(ushort node) { + SetList.Unlink(ActiveSetsList, node); + SetList.LinkToHead(FreeSetsList, node); + SetList[node].Serial++; + } + + public PixelVisSet FindOrCreatePixelVisSet(in PixelVisQueryParams parms, ref int queryHandle) { + if (queryHandle != 0) { + ushort handle = (ushort)(queryHandle & 0xFFFF); + handle--; + ushort serial = (ushort)(queryHandle >> 16); + if (SetList.IsValidIndex(handle) && SetList[handle].Serial == serial) + return SetList[handle]; + } + + ushort node = AllocSet(); + SetList[node].Init(parms); + uint outHandle = SetList[node].Serial; + ushort nodeHandle = (ushort)(node + 1); + outHandle <<= 16; + outHandle |= nodeHandle; + queryHandle = (int)outHandle; + return SetList[node]; + } + + public bool SupportsOcclusion() => HwCanTestGlows; + + public void DebugInfo() => throw new NotImplementedException(); +} + +public struct TraceFilterGlow(IHandleEntity? passentity, CollisionGroup collisionGroup) : ITraceFilter +{ + public TraceFilterSimple Simple = new(passentity, collisionGroup); + + public bool ShouldHitEntity(IHandleEntity handleEntity, Contents contentsMask) { + IClientUnknown unk = (IClientUnknown)handleEntity; + ICollideable collide = unk.GetCollideable()!; + if (collide.GetSolid() != SolidType.VPhysics && collide.GetSolid() != SolidType.BSP) + return false; + return Simple.ShouldHitEntity(handleEntity, contentsMask); + } +} + +public static class PixelVisibility +{ + public static readonly ConVar r_pixelvisibility_partial = new("r_pixelvisibility_partial", "1"); + public static readonly ConVar r_dopixelvisibility = new("r_dopixelvisibility", "1"); + public static readonly ConVar r_drawpixelvisibility = new("r_drawpixelvisibility", "0", 0, "Show the occlusion proxies", callback: PixelvisDrawChanged); + public static readonly ConVar r_pixelvisibility_spew = new("r_pixelvisibility_spew", "0"); + public static readonly ConVarRef building_cubemaps = new("building_cubemaps"); + + const float MIN_PROXY_PIXELS = 5.0f; + + static readonly PixelVisibilitySystem g_PixelVisibilitySystem = new(); + + public static bool HasFastQueries() => true; + + public static float DrawProxy(IMatRenderContext renderContext, nint queryHandle, Vector3 origin, float scale, float proxyAspect, IMaterial material, bool screenspace) => throw new NotImplementedException(); + + static void PixelvisDrawChanged(IConVar var, in ConVarChangeContext ctx) => throw new NotImplementedException(); + + public static float GlowSightDistance(in Vector3 glowOrigin, bool shouldTrace) { + float dist = (glowOrigin - CurrentViewOrigin()).Length(); + C_BasePlayer? local = C_BasePlayer.GetLocalPlayer(); + if (local != null) + dist *= local.GetFOVDistanceAdjustFactor(); + + if (shouldTrace) { + Vector3 end = glowOrigin; + if (dist > 4) + end -= CurrentViewForward() * 4; + Mask traceFlags = Mask.Opaque | (Mask)Contents.Monster | (Mask)Contents.Debris; + + TraceFilterGlow filter = new(null, CollisionGroup.None); + Util.TraceLine(CurrentViewOrigin(), end, traceFlags, null, ref filter, out Trace tr); + if (tr.Fraction != 1.0f) + return -1; + } + + return dist; + } + + public static void EndCurrentView() => throw new NotImplementedException(); + + public static void EndScene() => throw new NotImplementedException(); + + public static float FractionVisible(in PixelVisQueryParams parms, ref int queryHandle) => g_PixelVisibilitySystem.GetFractionVisible(parms, ref queryHandle); + + public static bool IsAvailable() => throw new NotImplementedException(); + + public static void ShiftVisibilityViews(int sourceViewID, int destViewID) => throw new NotImplementedException(); +} diff --git a/Game.Client/ToolFrameworkClient.cs b/Game.Client/ToolFrameworkClient.cs index cf56cb136..23ca921bf 100644 --- a/Game.Client/ToolFrameworkClient.cs +++ b/Game.Client/ToolFrameworkClient.cs @@ -8,6 +8,8 @@ public class ToolFrameworkClient { public static bool ToolsEnabled() => false; + public static bool ToolFramework_IsThirdPersonCamera() => false; + public static void ToolFramework_RecordMaterialParams(IMaterial material) { // todo } diff --git a/Game.Client/View.cs b/Game.Client/View.cs index af65a498a..b07e5fdbf 100644 --- a/Game.Client/View.cs +++ b/Game.Client/View.cs @@ -221,9 +221,6 @@ private void SetUpViews() { viewEye.StereoEye = StereoEye.Mono; C_BasePlayer? player = C_BasePlayer.GetLocalPlayer(); - bool calcViewModelView = false; - Vector3 viewModelOrigin = default; - QAngle viewModelAngles = default; if (player != null) { player.CalcView(ref viewEye.Origin, ref viewEye.Angles, ref viewEye.ZNear, ref viewEye.ZFar, ref viewEye.FOV); @@ -237,10 +234,6 @@ private void SetUpViews() { viewEye.Angles = ve.GetAbsAngles(); } } - - calcViewModelView = true; - viewModelOrigin = viewEye.Origin; - viewModelAngles = viewEye.Angles; } clientMode.OverrideView(ref viewEye); @@ -250,11 +243,6 @@ private void SetUpViews() { viewEye.FOVViewmodel = MathF.Abs(clientMode.GetViewModelFOV() - flFOVOffset); - if (calcViewModelView) { - Assert(player != null); - player.CalcViewModelView(in viewModelOrigin, in viewModelAngles); - } - ViewRender.g_VecPrevRenderOrigin = ViewRender.g_VecRenderOrigin; ViewRender.g_VecPrevRenderAngles = ViewRender.g_VecRenderAngles; ViewRender.g_VecRenderOrigin = viewEye.Origin; diff --git a/Game.Client/WeaponSelection.cs b/Game.Client/WeaponSelection.cs index 582ea8f3c..ab95e622c 100644 --- a/Game.Client/WeaponSelection.cs +++ b/Game.Client/WeaponSelection.cs @@ -45,7 +45,7 @@ void Reset() { void UpdateSelectionTime() => SelectionTime = gpGlobals.CurTime; static BaseHudWeaponSelection GetInstance() => Instance!; - BaseHudWeaponSelection GetHudWeaponSelection() => GetInstance(); + public static BaseHudWeaponSelection GetHudWeaponSelection() => GetInstance(); public void VidInit() { gWR.LoadAllWeaponSprites(); @@ -128,7 +128,7 @@ public int KeyInput(int down, ButtonCode keynum, ReadOnlySpan currentBindi return 1; } - void OnWeaponPickup(BaseCombatWeapon weapon) { } + public virtual void OnWeaponPickup(BaseCombatWeapon weapon) { } static private void UserCmd_Slot(int slot) { int fastSwitchMode = hud_fastswitch.GetInt(); diff --git a/Game.Server/BaseAnimating.cs b/Game.Server/BaseAnimating.cs index 6f91bd945..b9493c0ca 100644 --- a/Game.Server/BaseAnimating.cs +++ b/Game.Server/BaseAnimating.cs @@ -206,10 +206,26 @@ public override void SetModel(ReadOnlySpan modelName) { SetSequence(0); PopulatePoseParameters(); + ResetPoseParameters(); } protected virtual void PopulatePoseParameters() { } + public void ResetPoseParameters() { + if (IsDynamicModelLoading()) + return; + + StudioHdr? studioHdr = GetModelPtr(); + if (studioHdr == null) + return; + + for (int i = 0; i < NUM_POSEPAREMETERS; i++) { + BoneSetup.Studio_SetPoseParameter(studioHdr, i, 0.0f, out float ctlValue); + if (ctlValue != PoseParameter[i]) + PoseParameterForModify()[i] = ctlValue; + } + } + public void ResetSequence(int sequence) { SetSequence(sequence); ResetSequenceInfo(); diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index 9f16e637c..fb78338fa 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -1961,6 +1961,11 @@ public bool IsFloating() { public partial ushort OverrideMaterial { get; set; } [NetworkVar("m_OverrideSubMaterials")] public partial ref readonly InlineArray32 OverrideSubMaterials { get; } + public ReadOnlySpan GetSubMaterialOverride(int index) { + if ((uint)index < 32 && NetworkString.Convert(OverrideSubMaterials[index]) is string name) + return name; + return ""; + } [NetworkVar("m_iHealth")] public partial int Health { get; set; } [NetworkVar("m_iMaxHealth")] @@ -3457,6 +3462,60 @@ public void TraceAttackToTriggers(in TakeDamageInfo info, in Vector3 start, in V public virtual void Think() => FnThink?.Invoke(this); +#if GMOD_DLL + public virtual void SetUseType(int type) { } + + InlineArray256 OverrideMaterialName; + + public virtual void SetMaterialOverride(ReadOnlySpan name) { + if (!name.IsEmpty && name[0] != '\0') { + int index = NetworkString.Add(name); + if (index != OverrideMaterial) + OverrideMaterial = (ushort)index; + strcpy(OverrideMaterialName, name); + return; + } + + strcpy(OverrideMaterialName, ""); + if (OverrideMaterial == 0) + return; + OverrideMaterial = 0; + } + + public virtual ReadOnlySpan GetMaterialOverride() => NetworkString.Convert(OverrideMaterial) ?? ""; + + InlineArray32 SubMaterialOverrideNames; + + public void SetSubMaterialOverride(int index, ReadOnlySpan name) { + if ((uint)index > 31) + return; + + if (!name.IsEmpty && name[0] != '\0') { + int stringIndex = NetworkString.Add(name); + if (stringIndex != OverrideSubMaterials[index]) + OverrideSubMaterialsForModify()[index] = (ushort)stringIndex; + string? converted = NetworkString.Convert(stringIndex); + if (converted != null && converted.Length == 0) + converted = null; + SubMaterialOverrideNames[index] = converted; + return; + } + + SubMaterialOverrideNames[index] = null; + if (OverrideSubMaterials[index] == 0) + return; + OverrideSubMaterialsForModify()[index] = 0; + } + + public void ClearSubMaterialOverrides() { + for (int i = 0; i < 32; i++) { + SubMaterialOverrideNames[i] = null; + if (OverrideSubMaterials[i] != 0) + OverrideSubMaterialsForModify()[i] = 0; + } + } +#endif + public virtual EntityCapabilities ObjectCaps() { Model? model = GetModel(); bool isBrush = (model != null && modelinfo.GetModelType(model) == ModelType.Brush); diff --git a/Game.Server/BoneManipulate.cs b/Game.Server/BoneManipulate.cs index ae12bee97..39fb34bd0 100644 --- a/Game.Server/BoneManipulate.cs +++ b/Game.Server/BoneManipulate.cs @@ -48,7 +48,7 @@ public void SetBoneAngles(byte index, in Vector3 ang, bool networkUpdate) { LocalBoneAng[index] = ang; } - public void SetBoneScale(byte index, Vector3 scale) { + public void SetBoneScale(byte index, Vector3 scale, bool networkUpdate) { if (scale.Length() > 512.0f) scale = Vector3.Normalize(scale) * 512.0f; diff --git a/Game.Server/GarrysMod/LuaNextBot.cs b/Game.Server/GarrysMod/LuaNextBot.cs index 60c8255b4..d7679afea 100644 --- a/Game.Server/GarrysMod/LuaNextBot.cs +++ b/Game.Server/GarrysMod/LuaNextBot.cs @@ -23,6 +23,12 @@ public LuaNextBot() { ScriptedEntity.Init(this, 1); } + int UseTypeCaps = (int)EntityCapabilities.ContinuousUse; + + public override void SetUseType(int type) => UseTypeCaps = type; + + public override EntityCapabilities ObjectCaps() => base.ObjectCaps() | (EntityCapabilities)UseTypeCaps; + public override ReadOnlySpan GetLuaScriptName() => ScriptedEntity.GetScriptName(); public override void InitializeScriptedEntity(ReadOnlySpan name) { diff --git a/Game.Server/GarrysMod/LuaUserMessages.cs b/Game.Server/GarrysMod/LuaUserMessages.cs new file mode 100644 index 000000000..a0a928bc8 --- /dev/null +++ b/Game.Server/GarrysMod/LuaUserMessages.cs @@ -0,0 +1,337 @@ +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Bitbuffers; +using Source.Common.Commands; +using Source.Common.Engine; +using Source.Common.GarrysMod.Lua; +using Source.Common.Mathematics; + +using System.Numerics; + +namespace Game.Server.GarrysMod; + +public class QueuedMessage +{ + public RecipientFilter? Filter; + public bf_write? Buffer; + public byte[] Data = new byte[512]; + public InlineArray16 Name; + public uint Player = 0xFFFFFFFF; + public bool SingleUser; +} + +public class UserMessageManager : AutoGameSystemPerFrame +{ + public static readonly UserMessageManager g_UserMessageManager = new(); + + static readonly ConVar sv_usermessage_maxsize = new("sv_usermessage_maxsize", "1024", 0, "The max number of bytes to output per tick"); + + static int NumPlayers; + + readonly List[] PlayerMessages = new List[Constants.ABSOLUTE_PLAYER_LIMIT]; + readonly List GlobalMessages = []; + int LuaUserMessage = -1; + + public UserMessageManager() : base(null) { + for (int i = 0; i < PlayerMessages.Length; i++) + PlayerMessages[i] = []; + } + + public override ReadOnlySpan Name() => "UserMessageManager"; + + public void AddToQueue(QueuedMessage msg) { + if (!msg.SingleUser) { + if (5000 < GlobalMessages.Count) + Warning($"Warning: {GlobalMessages.Count} global queued usermessages!\n"); + GlobalMessages.Add(msg); + return; + } + + int index; + BaseEntity? ent = msg.Player == 0xFFFFFFFF ? null : gEntList.GetBaseEntity(new BaseHandle(msg.Player)); + if (ent == null) + index = -100; + else { + Edict? edict = ent.Edict(); + if (edict == null) + index = -1; + else { + index = edict.EdictIndex - 1; + if ((uint)index < 129) { + if (5000 < PlayerMessages[index].Count) + Warning($"Warning: Player {index} has {PlayerMessages[index].Count} queued usermessages!\n"); + PlayerMessages[index].Add(msg); + return; + } + } + } + Warning($"Tried to send message to invalid or non existent player! ({index})\n"); + } + + void SendMessage(QueuedMessage msg) { + if (LuaUserMessage == -1) + LuaUserMessage = usermessages.LookupUserMessage("LuaUserMessage"); + + if (msg.Filter == null) + return; + if (msg.Filter.GetRecipientCount() <= 0) + return; + + bf_write buf = engine.UserMessageBegin(msg.Filter, LuaUserMessage); + int bits = msg.Buffer!.BitsWritten; + if (bits < buf.MaxBits) { + msg.Buffer.BaseArray.AsSpan(0, bits + 7 >> 3).CopyTo(buf.BaseArray); + buf.Seek(bits); + engine.MessageEnd(); + return; + } + engine.MessageEnd(); + Msg($"Error sending usermessage - too large ({((ReadOnlySpan)msg.Name).SliceNullTerminatedString()})"); + } + + static void Destroy(QueuedMessage? msg) { + if (msg == null) + return; + msg.Buffer = null; + msg.Filter = null; + } + + public override void LevelShutdownPreEntity() { + for (int i = 0; i < GlobalMessages.Count; i++) { + Destroy(GlobalMessages[i]); + GlobalMessages[i] = null; + } + GlobalMessages.Clear(); + + for (int p = 0; p < PlayerMessages.Length; p++) { + List queue = PlayerMessages[p]; + for (int i = 0; i < queue.Count; i++) { + Destroy(queue[i]); + queue[i] = null; + } + queue.Clear(); + } + } + + public override void PreClientUpdate() { + int players = 0; + int i = 0; + do { + i++; + BasePlayer? player = Util.PlayerByIndex(i); + if (player != null && player.Connected != PlayerConnectedState.Disconnected) + players++; + } while (i < 128); + + if (NumPlayers != players) + NumPlayers = players; + + for (int p = 1; p <= 128; p++) { + List queue = PlayerMessages[p - 1]; + BasePlayer? player = Util.PlayerByIndex(p); + if (player == null || player.Connected == PlayerConnectedState.Disconnected) { + queue.Clear(); + continue; + } + + int bytes = 0; + for (int j = 0; j < queue.Count; j++) { + QueuedMessage? msg = queue[j]; + if (msg == null) + continue; + + int size = msg.Buffer!.BitsWritten + 7 >> 3; + bytes += size; + if (300 < size) + Msg("Warning: Usermessage was larger than 256 bytes. This will cause problems.\n"); + SendMessage(msg); + Destroy(msg); + queue[j] = null; + if (sv_usermessage_maxsize.GetInt() < bytes) + break; + } + + if (bytes <= sv_usermessage_maxsize.GetInt()) + queue.Clear(); + } + + int globalBytes = 0; + for (int j = 0; j < GlobalMessages.Count; j++) { + QueuedMessage? msg = GlobalMessages[j]; + if (msg == null) + continue; + + int size = msg.Buffer!.BitsWritten + 7 >> 3; + globalBytes += size; + if (300 < size) + Msg("Warning: Usermessage was larger than 256 bytes. This will cause problems.\n"); + SendMessage(msg); + Destroy(msg); + GlobalMessages[j] = null; + if (sv_usermessage_maxsize.GetInt() < globalBytes) + return; + } + GlobalMessages.Clear(); + } +} + +public static partial class LuaUserMessages +{ + [LuaLibrary] + static readonly LuaLibrary LL_Factory_umsg = new("umsg"); + + static QueuedMessage? CurrentMessage; + + public static void RegisterUserMessages(UserMessages messages) => messages.Register("LuaUserMessage", -1); + + [LuaFunction] + static int Start(ILuaInterface lua) { + string name = g_Lua!.CheckString(1); + if (CurrentMessage != null) { + lua.ErrorFromLua("umsg.Start: Starting new message without ending the old one!\n"); + CurrentMessage.Buffer = null; + CurrentMessage.Filter = null; + CurrentMessage = null; + } + + CurrentMessage = new(); + CurrentMessage.Buffer = new bf_write(); + CurrentMessage.Buffer.StartWriting(CurrentMessage.Data, 512, 0, -1); + + if (g_Lua.isUserData(2)) { + if (g_Lua.GetType(2) == LuaType.Entity) { + BasePlayer? player = LuaPlayer.Get_Player(2, false); + CurrentMessage.Filter = new SingleUserRecipientFilter(player!); + CurrentMessage.Player = player != null ? player.GetRefEHandle().Index : 0xFFFFFFFF; + CurrentMessage.SingleUser = true; + } + else { + RecipientFilter? filter = LuaRecipientFilter.LC_RecipientFilter.Get(2) as RecipientFilter; + if (filter == null) { + CurrentMessage.Buffer = null; + CurrentMessage = null; + g_Lua.ErrorFromLua("umsg.Start: Error! Invalid Recipient Filter!\n"); + return 0; + } + CurrentMessage.Filter = new RecipientFilter(); + CurrentMessage.Filter.CopyFrom(filter); + } + + if (CurrentMessage.Filter == null) { + g_Lua.ErrorFromLua("umsg.Start: Recipient Filter Is NULL!? - making it BROADCAST\n"); + CurrentMessage.Filter = new BroadcastRecipientFilter(); + } + } + else + CurrentMessage.Filter = new BroadcastRecipientFilter(); + + CurrentMessage.Filter.MakeReliable(); + CurrentMessage.Filter.IgnorePredictionCull(); + strcpy(CurrentMessage.Name, name); + CurrentMessage.Buffer.WriteString(name); + return 0; + } + + [LuaFunction] + static int End(ILuaInterface lua) { + if (CurrentMessage == null) { + g_Lua!.ErrorFromLua("Calling umsg.End without a valid message!\n"); + return 0; + } + + if (CurrentMessage.Filter == null) { + g_Lua!.ErrorFromLua("Calling umsg.End without a valid RecipientFilter!?\n"); + CurrentMessage = null; + return 0; + } + + UserMessageManager.g_UserMessageManager.AddToQueue(CurrentMessage); + CurrentMessage = null; + return 0; + } + + [LuaFunction] + static int Angle(ILuaInterface lua) { + if (CurrentMessage != null) + CurrentMessage.Buffer!.WriteBitAngles(LuaAngle.Get_Angle(1)); + return 0; + } + + [LuaFunction] + static int Bool(ILuaInterface lua) { + if (CurrentMessage != null) + CurrentMessage.Buffer!.WriteOneBit(g_Lua!.GetBool(1) ? 1 : 0); + return 0; + } + + [LuaFunction] + static int Char(ILuaInterface lua) { + if (CurrentMessage != null) + CurrentMessage.Buffer!.WriteChar((int)g_Lua!.GetNumber(1)); + return 0; + } + + [LuaFunction] + static int Entity(ILuaInterface lua) { + if (CurrentMessage != null) { + BaseEntity? ent = LuaEntity.Get_Entity(1, true); + uint value = 0x7FFFFF; + if (ent != null) { + uint handle = ent.GetRefEHandle().Index; + value = (handle >> 14 & 0x3FF) << 13 | handle & 0x3FFF; + } + CurrentMessage.Buffer!.WriteLong((int)value); + } + return 0; + } + + [LuaFunction] + static int Float(ILuaInterface lua) { + if (CurrentMessage != null) + CurrentMessage.Buffer!.WriteFloat((float)g_Lua!.CheckNumber(1)); + return 0; + } + + [LuaFunction] + static int Long(ILuaInterface lua) { + if (CurrentMessage != null) + CurrentMessage.Buffer!.WriteLong((int)g_Lua!.GetNumber(1)); + return 0; + } + + [LuaFunction] + static int PoolString(ILuaInterface lua) { + NetworkString.Add(g_Lua!.CheckString(1)); + return 0; + } + + [LuaFunction] + static int Short(ILuaInterface lua) { + if (CurrentMessage != null) + CurrentMessage.Buffer!.WriteShort((int)g_Lua!.GetNumber(1)); + return 0; + } + + [LuaFunction] + static int String(ILuaInterface lua) { + if (CurrentMessage != null) + CurrentMessage.Buffer!.WriteString(g_Lua!.GetString(1)); + return 0; + } + + [LuaFunction] + static int Vector(ILuaInterface lua) { + if (CurrentMessage != null) + CurrentMessage.Buffer!.WriteBitVec3Coord(LuaVector.Get_Vector(1)); + return 0; + } + + [LuaFunction] + static int VectorNormal(ILuaInterface lua) { + if (CurrentMessage != null) + CurrentMessage.Buffer!.WriteBitVec3Normal(LuaVector.Get_Vector(1)); + return 0; + } +} diff --git a/Game.Server/Util.cs b/Game.Server/Util.cs index a1246f74a..071022955 100644 --- a/Game.Server/Util.cs +++ b/Game.Server/Util.cs @@ -267,10 +267,17 @@ public static void PointAtNamedEntity(BaseEntity dest, string? target) { public static int DropToFloor(BaseEntity entity, Mask mask) => DropToFloor(entity, mask, null); - public static int DropToFloor(BaseEntity entity, Mask mask, BaseEntity? ignore) { + public static int DropToFloor(BaseEntity entity, Mask mask, BaseEntity? ignore, float distance = 256.0f) { entity.SetGroundEntity(null); - TraceEntity(entity, entity.GetAbsOrigin(), entity.GetAbsOrigin() - new Vector3(0, 0, 256), mask, ignore, entity.GetCollisionGroup(), out Trace trace); + Trace trace; +#if GMOD_DLL + TraceEntity(entity, entity.GetAbsOrigin(), entity.GetAbsOrigin(), mask, ignore, entity.GetCollisionGroup(), out trace); + if (trace.Fraction == 0) + return -1; +#endif + + TraceEntity(entity, entity.GetAbsOrigin(), entity.GetAbsOrigin() - new Vector3(0, 0, distance), mask, ignore, entity.GetCollisionGroup(), out trace); if (trace.AllSolid) return -1; @@ -278,6 +285,12 @@ public static int DropToFloor(BaseEntity entity, Mask mask, BaseEntity? ignore) if (trace.Fraction == 1) return 0; +#if GMOD_DLL + float max = BaseEntity.k_flMaxEntityPosCoord * 8.0f; + if (!(-max < trace.EndPos.X && trace.EndPos.X < max && -max < trace.EndPos.Y && trace.EndPos.Y < max && -max < trace.EndPos.Z && trace.EndPos.Z < max)) + return 0; +#endif + entity.SetAbsOrigin(trace.EndPos); entity.SetGroundEntity(trace.Ent); #if GMOD_DLL diff --git a/Game.Shared/BasePlayerShared.cs b/Game.Shared/BasePlayerShared.cs index 0c8796fe1..5e8b0f879 100644 --- a/Game.Shared/BasePlayerShared.cs +++ b/Game.Shared/BasePlayerShared.cs @@ -777,7 +777,7 @@ private void SetStepSoundTime(StepSoundTimes stepSoundTime, bool walking) { } - Vector3 GetPlayerMins() { + public virtual Vector3 GetPlayerMins() { if (IsObserver()) return VEC_OBS_HULL_MIN_SCALED(this); else { @@ -788,7 +788,7 @@ Vector3 GetPlayerMins() { } } - Vector3 GetPlayerMaxs() { + public virtual Vector3 GetPlayerMaxs() { if (IsObserver()) return VEC_OBS_HULL_MAX_SCALED(this); else { diff --git a/Game.Shared/DebugOverlay.cs b/Game.Shared/DebugOverlay.cs index 0a0793a95..4558518ff 100644 --- a/Game.Shared/DebugOverlay.cs +++ b/Game.Shared/DebugOverlay.cs @@ -1,4 +1,5 @@ using Source.Common.Engine; +using Source.Common.Formats.BSP; using Source.Common.Mathematics; using System.Numerics; @@ -37,12 +38,11 @@ public static void BoxDirection(in Vector3 origin, in Vector3 mins, in Vector3 m public static void BoxAngles(in Vector3 origin, in Vector3 mins, in Vector3 maxs, QAngle angles, int r, int g, int b, int a, float duration) => debugoverlay.AddBoxOverlay(origin, mins, maxs, angles, r, g, b, a, duration); - public static void SweptBox(in Vector3 start, in Vector3 end, in Vector3 mins, in Vector3 maxs, QAngle angles, int r, int g, int b, int a, float duration) { - throw new NotImplementedException(); - } + public static void SweptBox(in Vector3 start, in Vector3 end, in Vector3 mins, in Vector3 maxs, QAngle angles, int r, int g, int b, int a, float duration) => debugoverlay.AddSweptBoxOverlay(start, end, mins, maxs, angles, r, g, b, a, duration); public static void EntityBounds(BaseEntity entity, int r, int g, int b, int a, float duration) { - throw new NotImplementedException(); + CollisionProperty collide = entity.CollisionProp(); + BoxAngles(collide.GetCollisionOrigin(), collide.OBBMins(), collide.OBBMaxs(), collide.GetCollisionAngles(), r, g, b, a, duration); } public static void DebugDrawLine(in Vector3 absStart, in Vector3 absEnd, int r, int g, int b, bool test, float duration) => Line(absStart + new Vector3(0, 0, 0.1f), absEnd + new Vector3(0, 0, 0.1f), r, g, b, test, duration); @@ -100,17 +100,11 @@ public static void Triangle(in Vector3 p1, in Vector3 p2, in Vector3 p3, int r, debugoverlay.AddTriangleOverlay(p1, p2, p3, r, g, b, a, noDepthTest, duration); } - public static void EntityText(int entityID, int text_offset, ReadOnlySpan text, float duration, int r, int g, int b, int a) { - throw new NotImplementedException(); - } + public static void EntityText(int entityID, int text_offset, ReadOnlySpan text, float duration, int r, int g, int b, int a) => debugoverlay.AddEntityTextOverlay(entityID, text_offset, duration, (int)Math.Clamp(r * 255.0f, 0.0f, 255.0f), (int)Math.Clamp(g * 255.0f, 0.0f, 255.0f), (int)Math.Clamp(b * 255.0f, 0.0f, 255.0f), (int)Math.Clamp(a * 255.0f, 0.0f, 255.0f), text); - public static void EntityTextAtPosition(in Vector3 origin, int text_offset, ReadOnlySpan text, float duration, int r, int g, int b, int a) { - throw new NotImplementedException(); - } + public static void EntityTextAtPosition(in Vector3 origin, int text_offset, ReadOnlySpan text, float duration, int r, int g, int b, int a) => debugoverlay.AddTextOverlayRGB(origin, text_offset, duration, r, g, b, a, text); - public static void Grid(in Vector3 position) { - throw new NotImplementedException(); - } + public static void Grid(in Vector3 position) => debugoverlay.AddGridOverlay(position); public static void Text(in Vector3 origin, ReadOnlySpan text, bool viewCheck, float duration) { BasePlayer? player = GetLocalPlayer(); @@ -132,8 +126,7 @@ public static void Text(in Vector3 origin, ReadOnlySpan text, bool viewChe // Clip text that is obscured if (viewCheck) { - Trace tr = default; - // Util.TraceLine(player.GetAbsOrigin(), origin, MASK_OPAQUE, NULL, COLLISION_GROUP_NONE, &tr); TODO TODO TODO + Util.TraceLine(player.GetAbsOrigin(), origin, Mask.Opaque, null, Source.CollisionGroup.None, out Trace tr); if ((tr.EndPos - origin).Length() > 10) return; @@ -145,7 +138,21 @@ public static void Text(in Vector3 origin, ReadOnlySpan text, bool viewChe public static void ScreenText(float flXpos, float flYpos, ReadOnlySpan text, int r, int g, int b, int a, float duration) => debugoverlay.AddScreenTextOverlay(flXpos, flYpos, duration, r, g, b, a, text); public static void Cross3D(in Vector3 position, in Vector3 mins, in Vector3 maxs, int r, int g, int b, bool noDepthTest, float duration) { - throw new NotImplementedException(); + Vector3 start = mins + position; + Vector3 end = maxs + position; + Line(start, end, r, g, b, noDepthTest, duration); + + start.X += maxs.X - mins.X; + end.X -= maxs.X - mins.X; + Line(start, end, r, g, b, noDepthTest, duration); + + start.Y += maxs.Y - mins.Y; + end.Y -= maxs.Y - mins.Y; + Line(start, end, r, g, b, noDepthTest, duration); + + start.X -= maxs.X - mins.X; + end.X += maxs.X - mins.X; + Line(start, end, r, g, b, noDepthTest, duration); } public static void Cross3D(in Vector3 position, float size, int r, int g, int b, bool noDepthTest, float duration) { @@ -155,19 +162,96 @@ public static void Cross3D(in Vector3 position, float size, int r, int g, int b, } public static void Cross3DOriented(in Vector3 position, QAngle angles, float size, int r, int g, int b, bool noDepthTest, float duration) { - throw new NotImplementedException(); + MathLib.AngleVectors(angles, out Vector3 forward, out Vector3 right, out Vector3 up); + + forward *= size; + right *= size; + up *= size; + + Line(position + right, position - right, r, g, b, noDepthTest, duration); + Line(position + forward, position - forward, r, g, b, noDepthTest, duration); + Line(position + up, position - up, r, g, b, noDepthTest, duration); } public static void Cross3DOriented(Matrix3x4 m, float size, int c, bool noDepthTest, float duration) { - throw new NotImplementedException(); + MathLib.MatrixGetColumn(m, 0, out Vector3 forward); + MathLib.MatrixGetColumn(m, 1, out Vector3 left); + MathLib.MatrixGetColumn(m, 2, out Vector3 up); + MathLib.MatrixGetColumn(m, 3, out Vector3 position); + + forward *= size; + left *= size; + up *= size; + + Line(position + left, position - left, 0, c, 0, noDepthTest, duration); + Line(position + forward, position - forward, c, 0, 0, noDepthTest, duration); + Line(position + up, position - up, 0, 0, c, noDepthTest, duration); } public static void DrawTickMarkedLine(in Vector3 startPos, in Vector3 endPos, float tickDist, int tickTextDist, int r, int g, int b, bool noDepthTest, float duration) { - throw new NotImplementedException(); + BasePlayer? player = GetDebugPlayer(); + if (player == null) + return; + + Vector3 lineDir = endPos - startPos; + float lineDist = MathLib.VectorNormalize(ref lineDir); + int numTicks = (int)(lineDist / tickDist); + Vector3 bodyDir; + +#if CLIENT_DLL + MathLib.AngleVectors(player.LocalEyeAngles(), out bodyDir); +#else + bodyDir = player.BodyDirection2D(); +#endif + + Vector3 upVec = 4 * bodyDir; + Vector3 tickPos = startPos; + int tickTextCnt = 0; + + MathLib.CrossProduct(lineDir, upVec, out Vector3 sideDir); + + Line(startPos, endPos, r, g, b, noDepthTest, duration); + + for (int i = 0; i < numTicks + 1; i++) { + Vector3 tickLeft = tickPos - sideDir; + Vector3 tickRight = tickPos + sideDir; + + if (tickTextCnt == tickTextDist) { + Vector3 textPos = tickLeft + new Vector3(0, 0, 8); + Line(tickLeft, tickRight, 255, 255, 255, noDepthTest, duration); + Text(textPos, i.ToString(), true, 0); + tickTextCnt = 0; + } + else + Line(tickLeft, tickRight, r, g, b, noDepthTest, duration); + + tickTextCnt++; + + tickPos += (tickDist * lineDir); + } } public static void DrawGroundCrossHairOverlay() { - throw new NotImplementedException(); + BasePlayer? player = GetDebugPlayer(); + if (player == null) + return; + + Vector3 source = player.EyePosition(); + player.EyeVectors(out Vector3 forward); + + Util.TraceLine(source, source + forward * 2048, Mask.Solid, player, Source.CollisionGroup.None, out Trace tr); + float dotPr = MathLib.DotProduct(new Vector3(0, 0, 1), tr.Plane.Normal); + if (tr.Fraction != 1.0 && dotPr > 0.5) { + tr.EndPos.Z += 1; + float scale = 6; + Vector3 startPos = tr.EndPos + new Vector3(-scale, 0, 0); + Vector3 endPos = tr.EndPos + new Vector3(scale, 0, 0); + Line(startPos, endPos, 255, 0, 0, false, 0); + + startPos = tr.EndPos + new Vector3(0, -scale, 0); + endPos = tr.EndPos + new Vector3(0, scale, 0); + Line(startPos, endPos, 255, 0, 0, false, 0); + } } public static void HorzArrow(in Vector3 startPos, in Vector3 endPos, float width, int r, int g, int b, int a, bool noDepthTest, float duration) { @@ -209,34 +293,146 @@ public static void HorzArrow(in Vector3 startPos, in Vector3 endPos, float width } public static void YawArrow(in Vector3 startPos, float yaw, float length, float width, int r, int g, int b, int a, bool noDepthTest, float duration) { - throw new NotImplementedException(); + Vector3 forward = Util.YawToVector(yaw); + HorzArrow(startPos, startPos + forward * length, width, r, g, b, a, noDepthTest, duration); } public static void VertArrow(in Vector3 startPos, in Vector3 endPos, float width, int r, int g, int b, int a, bool noDepthTest, float duration) { - throw new NotImplementedException(); + Vector3 lineDir = endPos - startPos; + MathLib.VectorNormalize(ref lineDir); + float radius = width / 2.0f; + + MathLib.VectorVectors(lineDir, out Vector3 sideDir, out Vector3 upVec); + + Vector3 p1 = startPos - upVec * radius; + Vector3 p2 = endPos - lineDir * width - upVec * radius; + Vector3 p3 = endPos - lineDir * width - upVec * width; + Vector3 p4 = endPos; + Vector3 p5 = endPos - lineDir * width + upVec * width; + Vector3 p6 = endPos - lineDir * width + upVec * radius; + Vector3 p7 = startPos + upVec * radius; + + Line(p1, p2, r, g, b, noDepthTest, duration); + Line(p2, p3, r, g, b, noDepthTest, duration); + Line(p3, p4, r, g, b, noDepthTest, duration); + Line(p4, p5, r, g, b, noDepthTest, duration); + Line(p5, p6, r, g, b, noDepthTest, duration); + Line(p6, p7, r, g, b, noDepthTest, duration); + + if (a > 0) { + Triangle(p5, p4, p3, r, g, b, a, noDepthTest, duration); + Triangle(p1, p7, p6, r, g, b, a, noDepthTest, duration); + Triangle(p6, p2, p1, r, g, b, a, noDepthTest, duration); + + Triangle(p3, p4, p5, r, g, b, a, noDepthTest, duration); + Triangle(p6, p7, p1, r, g, b, a, noDepthTest, duration); + Triangle(p1, p2, p6, r, g, b, a, noDepthTest, duration); + } } public static void Axis(in Vector3 position, QAngle angles, float size, bool noDepthTest, float duration) { - throw new NotImplementedException(); + MathLib.AngleVectors(angles, out Vector3 xvec, out Vector3 yvec, out Vector3 zvec); + + xvec = position + (size * xvec); + yvec = position - (size * yvec); + zvec = position + (size * zvec); + + Line(position, xvec, 255, 0, 0, noDepthTest, duration); + Line(position, yvec, 0, 255, 0, noDepthTest, duration); + Line(position, zvec, 0, 0, 255, noDepthTest, duration); } public static void Sphere(in Vector3 center, float radius, int r, int g, int b, bool noDepthTest, float duration) { - throw new NotImplementedException(); + Vector3 edge, lastEdge; + + float axisSize = radius; + Line(center + new Vector3(0, 0, -axisSize), center + new Vector3(0, 0, axisSize), r, g, b, noDepthTest, duration); + Line(center + new Vector3(0, -axisSize, 0), center + new Vector3(0, axisSize, 0), r, g, b, noDepthTest, duration); + Line(center + new Vector3(-axisSize, 0, 0), center + new Vector3(axisSize, 0, 0), r, g, b, noDepthTest, duration); + + lastEdge = new Vector3(radius + center.X, center.Y, center.Z); + float angle; + for (angle = 0.0f; angle <= 360.0f; angle += 22.5f) { + edge.X = radius * MathF.Cos(angle / 180.0f * MathF.PI) + center.X; + edge.Y = center.Y; + edge.Z = radius * MathF.Sin(angle / 180.0f * MathF.PI) + center.Z; + + Line(edge, lastEdge, r, g, b, noDepthTest, duration); + + lastEdge = edge; + } + + lastEdge = new Vector3(center.X, radius + center.Y, center.Z); + for (angle = 0.0f; angle <= 360.0f; angle += 22.5f) { + edge.X = center.X; + edge.Y = radius * MathF.Cos(angle / 180.0f * MathF.PI) + center.Y; + edge.Z = radius * MathF.Sin(angle / 180.0f * MathF.PI) + center.Z; + + Line(edge, lastEdge, r, g, b, noDepthTest, duration); + + lastEdge = edge; + } + + lastEdge = new Vector3(center.X, radius + center.Y, center.Z); + for (angle = 0.0f; angle <= 360.0f; angle += 22.5f) { + edge.X = radius * MathF.Cos(angle / 180.0f * MathF.PI) + center.X; + edge.Y = radius * MathF.Sin(angle / 180.0f * MathF.PI) + center.Y; + edge.Z = center.Z; + + Line(edge, lastEdge, r, g, b, noDepthTest, duration); + + lastEdge = edge; + } } public static void Circle(in Vector3 position, float radius, int r, int g, int b, int a, bool bNoDepthTest, float duration) { - throw new NotImplementedException(); + BasePlayer? player = GetLocalPlayer(); + if (player == null) + return; + + player.EyeVectors(out Vector3 clientForward); + + MathLib.VectorAngles(clientForward, out QAngle angles); + + Circle(position, angles, radius, r, g, b, a, bNoDepthTest, duration); } public static void Circle(in Vector3 position, QAngle angles, float radius, int r, int g, int b, int a, bool bNoDepthTest, float duration) { - throw new NotImplementedException(); + MathLib.AngleMatrix(angles, position, out Matrix3x4 xform); + MathLib.MatrixGetColumn(xform, 2, out Vector3 xAxis); + MathLib.MatrixGetColumn(xform, 1, out Vector3 yAxis); + Circle(position, xAxis, yAxis, radius, r, g, b, a, bNoDepthTest, duration); } public static void Circle(in Vector3 position, in Vector3 xAxis, in Vector3 yAxis, float radius, int r, int g, int b, int a, bool bNoDepthTest, float duration) { - throw new NotImplementedException(); + const uint segments = 16; + const float radStep = (MathF.PI * 2.0f) / segments; + + Vector3 lastPosition; + + Vector3 start = position + xAxis * radius; + Vector3 pos = start; + + for (uint i = 1; i <= segments; i++) { + lastPosition = pos; + + MathLib.SinCos(radStep * i, out float sin, out float cos); + pos = position + (xAxis * cos * radius) + (yAxis * sin * radius); + + Line(lastPosition, pos, r, g, b, bNoDepthTest, duration); + + if (a != 0 && i > 1) + debugoverlay.AddTriangleOverlay(start, lastPosition, pos, r, g, b, a, bNoDepthTest, duration); + } } public static void Sphere(in Vector3 position, QAngle angles, float radius, int r, int g, int b, int a, bool bNoDepthTest, float duration) { - throw new NotImplementedException(); + MathLib.AngleMatrix(angles, position, out Matrix3x4 xform); + MathLib.MatrixGetColumn(xform, 0, out Vector3 xAxis); + MathLib.MatrixGetColumn(xform, 1, out Vector3 yAxis); + MathLib.MatrixGetColumn(xform, 2, out Vector3 zAxis); + Circle(position, xAxis, yAxis, radius, r, g, b, a, bNoDepthTest, duration); + Circle(position, yAxis, zAxis, radius, r, g, b, a, bNoDepthTest, duration); + Circle(position, xAxis, zAxis, radius, r, g, b, a, bNoDepthTest, duration); } } \ No newline at end of file diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index 8d64a9c75..de73e8210 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -640,7 +640,7 @@ public bool RenderScene(in ViewSetup view) { } LuaCam.CheckMissingEnds(); - // todo: reset ShouldDrawLocalPlayer cache + LuaCam.ResetFrameStateChecked(); using (MatRenderContextPtr renderContext = new(materials)) { renderContext.GMOD_ForceFilterMode(true, 0); diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index 3609fe6b4..d0d1b4f0d 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -6,6 +6,7 @@ using Source.Common; using Source.Common.Audio; using Source.Common.Engine; +using Source.Common.Formats.BSP; using Source.Common.GarrysMod.Lua; using Source.Common.Mathematics; using Source.Common.Physics; @@ -1609,6 +1610,121 @@ static int Entity__GetPos(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Entity__AddEFlags(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (IsQueuedForRemoval(ent) || ent.IsMarkedForDeletion()) + return 0; + int flags = (int)lua.CheckNumber(2); + if ((flags & 1) == 0) + ent.AddEFlags((EFL)flags); + return 0; + } + + [LuaMethod] + static int Entity__RemoveEFlags(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (IsQueuedForRemoval(ent) || ent.IsMarkedForDeletion()) + return 0; + int flags = (int)lua.CheckNumber(2); + if ((flags & 1) == 0) + ent.RemoveEFlags((EFL)flags); + return 0; + } + + [LuaMethod] + static int Entity__SetMaterial(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ent.SetMaterialOverride(lua.GetType(2) == LuaType.Nil ? null : lua.CheckString(2)); + return 0; + } + + [LuaMethod] + static int Entity__GetMaterial(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + lua.PushString(ent.GetMaterialOverride()); + return 1; + } + + [LuaMethod] + static int Entity__GetRotatedAABB(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + Vector3 mins = LuaVector.Get_Vector(2); + Vector3 maxs = LuaVector.Get_Vector(3); + MathLib.RotateAABB(ent.EntityToWorldTransform(), mins, maxs, out Vector3 minsOut, out Vector3 maxsOut); + LuaVector.Push_Vector(minsOut); + LuaVector.Push_Vector(maxsOut); + return 2; + } + + [LuaMethod] + static int Entity__GetSubMaterial(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + lua.PushString(ent.GetSubMaterialOverride((int)lua.CheckNumber(2))); + return 1; + } + + [LuaMethod] + static int Entity__SetSubMaterial(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (lua.GetType(2) == LuaType.Nil) { + ent.ClearSubMaterialOverrides(); + return 0; + } + int index = (int)lua.GetNumber(2); + ReadOnlySpan name = lua.GetType(3) == LuaType.Nil ? null : lua.GetString(3); + ent.SetSubMaterialOverride(index, name); + return 0; + } + +#if GAME_DLL + [LuaMethod] + static int Entity__TakePhysicsDamage(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ent.VPhysicsTakeDamage(LuaTakeDamageInfo.Get_TakeDamageInfo(2)); + return 0; + } +#endif + + [LuaMethod] + static int Entity__NextThink(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ent.SetNextThink((float)lua.CheckNumber(2)); + return 0; + } + +#if GAME_DLL + [LuaMethod] + static int Entity__DropToFloor(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + int mask = (int)lua.CheckNumberOpt(2, (double)Mask.Solid); + BaseEntity? ignore = Get_Entity(3, true); + float distance = (float)lua.CheckNumberOpt(4, 256.0); + Util.DropToFloor(ent, (Mask)mask, ignore, distance); + return 0; + } + + [LuaMethod] + static int Entity__SetUseType(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + int type = (int)lua.CheckNumber(2); + if (type == 1) { + ent.SetUseType((int)EntityCapabilities.OnOffUse); + return 0; + } + if (type == 2) { + ent.SetUseType((int)EntityCapabilities.DirectionalUse); + return 0; + } + if (type == 3) { + ent.SetUseType((int)EntityCapabilities.ImpulseUse); + return 0; + } + ent.SetUseType((int)EntityCapabilities.ContinuousUse); + return 0; + } +#endif + [LuaMethod] static int Entity__LocalToWorld(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; @@ -2990,6 +3106,7 @@ static int Entity__GetManipulateBoneScale(ILuaInterface lua) { LuaVector.Push_Vector(manipulator.GetBoneScale((byte)(int)lua.CheckNumber(2))); return 1; } +#endif [LuaMethod] static int Entity__ManipulateBonePosition(ILuaInterface lua) { @@ -3022,10 +3139,12 @@ static int Entity__ManipulateBoneScale(ILuaInterface lua) { if (animating == null || ent.IsEFlagSet(EFL.KillMe) || animating.GetBoneManipulator(true) is not BoneManipulate manipulator) return 0; Vector3 scale = LuaVector.Get_Vector(3); - manipulator.SetBoneScale((byte)(int)lua.CheckNumber(2), scale); + manipulator.SetBoneScale((byte)(int)lua.CheckNumber(2), scale, true); return 0; } +#if GAME_DLL + [LuaMethod] static int Entity__GetName(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; @@ -3133,6 +3252,43 @@ static int Entity__InvalidateBoneCache(ILuaInterface lua) { ent.GetBaseAnimating()?.InvalidateBoneCache(); return 0; } + + [LuaMethod] + static int Entity__GetBoneMatrix(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || ent.IsEFlagSet(EFL.KillMe)) + return 0; + + int bone = (int)lua.CheckNumber(2); + if (bone < 0) + return 0; + + mdlcache.BeginLock(); + if (!animating.IsDynamicModelLoading()) { + StudioHdr? hdr = animating.GetModelPtr(); + if (hdr != null && bone < hdr.NumBones() && (animating.AccumulatedBoneMask & hdr.BoneFlags(bone)) != 0) { + Matrix4x4 matrix = default; + matrix.Init(animating.GetBone(bone)); + LuaVMatrix.Push_VMatrix(matrix); + mdlcache.EndLock(); + return 1; + } + } + mdlcache.EndLock(); + return 0; + } + + [LuaMethod] + static int Entity__SetupBones(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating != null) { + animating.InvalidateBoneCache(); + animating.SetupBones(null, -1, Studio.BONE_USED_BY_ANYTHING, gpGlobals.CurTime); + } + return 0; + } #endif [LuaMethod] diff --git a/Game.Shared/GarrysMod/LuaEnums.cs b/Game.Shared/GarrysMod/LuaEnums.cs index 1ef90896f..aff8baad8 100644 --- a/Game.Shared/GarrysMod/LuaEnums.cs +++ b/Game.Shared/GarrysMod/LuaEnums.cs @@ -2470,7 +2470,7 @@ public override void InitLibraries(ILuaInterface lua) { global.SetMemberEnumValue($"{RENDERGROUP}_OPAQUE_HUGE", RenderGroup.OpaqueEntityHuge); global.SetMemberEnumValue($"{RENDERGROUP}_TRANSLUCENT", RenderGroup.TranslucentEntity); global.SetMemberEnumValue($"{RENDERGROUP}_OPAQUE", RenderGroup.OpaqueEntity); - global.SetMemberEnumValue($"{RENDERGROUP}_BOTH", RenderGroup.OpaqueEntity | RenderGroup.OpaqueEntityHuge); + global.SetMemberEnumValue($"{RENDERGROUP}_BOTH", RenderGroup.TwoPass); global.SetMemberEnumValue($"{RENDERGROUP}_VIEWMODEL", RenderGroup.ViewModelOpaque); global.SetMemberEnumValue($"{RENDERGROUP}_VIEWMODEL_TRANSLUCENT", RenderGroup.ViewModelTranslucent); global.SetMemberEnumValue($"{RENDERGROUP}_OPAQUE_BRUSH", RenderGroup.OpaqueBrush); diff --git a/Game.Shared/GarrysMod/LuaGameSystem.cs b/Game.Shared/GarrysMod/LuaGameSystem.cs index a108b51e9..1d73224b5 100644 --- a/Game.Shared/GarrysMod/LuaGameSystem.cs +++ b/Game.Shared/GarrysMod/LuaGameSystem.cs @@ -50,6 +50,7 @@ static void RecacheMaterials() { materials.CacheUsedMaterials(); } public override void Update(double frametime) { + LuaMesh.FlushPendingDestroy(); // RemoveQueuedRenderTargets(); LuaEntity.RemoveQueuedEntities(); // RunMapCleanupIfNeeded(); @@ -99,7 +100,7 @@ public override void LevelInitPostEntity() { public override void LevelShutdownPreEntity() { #if CLIENT_DLL LuaProjectedTexture.RemoveAll(); - // todo: IMesh delete list + LuaMesh.FlushPendingDestroy(); #else // todo: server LevelShutdownPreEntity #endif diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs index 405ed4c57..379b6d102 100644 --- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs +++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs @@ -443,7 +443,6 @@ static int MsgN(ILuaInterface lua) { [LuaGlobal] static int ErrorNoHalt(ILuaInterface lua) => ErrorNoHalt("ErrorNoHalt tostring ERROR"); -#if CLIENT_DLL || MENU_DLL [LuaGlobal] static int Error(ILuaInterface lua) => ErrorNoHalt("Error() tostring ERROR"); @@ -468,6 +467,7 @@ static int ErrorNoHaltWithStack(ILuaInterface lua) { return 0; } +#if CLIENT_DLL || MENU_DLL [LuaGlobal] static int DebugInfo(ILuaInterface lua) { int pos = (int)lua.CheckNumber(1); diff --git a/Game.Shared/GarrysMod/LuaPlayer.cs b/Game.Shared/GarrysMod/LuaPlayer.cs index c4686f71f..6b35644d2 100644 --- a/Game.Shared/GarrysMod/LuaPlayer.cs +++ b/Game.Shared/GarrysMod/LuaPlayer.cs @@ -160,6 +160,13 @@ static int Player__KeyDown(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Player__KeyDownLast(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + lua.PushBool(((int)lua.CheckNumber(2) & (int)player.AfButtonLast) != 0); + return 1; + } + [LuaMethod] static int Player__Alive(ILuaInterface lua) { BasePlayer player = Get_Player(1, false)!; @@ -706,6 +713,29 @@ static int Player__GetViewEntity(ILuaInterface lua) { return 1; } +#if CLIENT_DLL + [LuaMethod] + static int Player__ShouldDrawLocalPlayer(ILuaInterface lua) { + BasePlayer? player = Get_Player(1, false); + if (player == null || !player.IsPlayer()) { + lua.ThrowError("Player entity is NULL or not a player (!?)"); + lua.PushBool(false); + return 1; + } + lua.PushBool(BasePlayer.ShouldDrawLocalPlayer()); + return 1; + } +#endif + +#if GAME_DLL + [LuaMethod] + static int Player__SetViewEntity(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + player.SetViewEntity(LuaEntity.Get_Entity(2, true)); + return 0; + } +#endif + [LuaMethod] static int Player____tostring(ILuaInterface lua) { BasePlayer? player = Get_Player(1, true); @@ -1109,6 +1139,13 @@ static int Player__GetCanZoom(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Player__IsDrivingEntity(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + lua.PushBool(player.Driving.Get() != null); + return 1; + } + [LuaMethod] static int Player__GetDrivingMode(ILuaInterface lua) { GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; @@ -1130,6 +1167,13 @@ static int Player__GetStepSize(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Player__GetViewOffset(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + LuaVector.Push_Vector(player.ViewOffset); + return 1; + } + [LuaMethod] static int Player__GetViewOffsetDucked(ILuaInterface lua) { GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; diff --git a/Game.Shared/GarrysMod/LuaSound.cs b/Game.Shared/GarrysMod/LuaSound.cs index 2d6df5bff..d3717e139 100644 --- a/Game.Shared/GarrysMod/LuaSound.cs +++ b/Game.Shared/GarrysMod/LuaSound.cs @@ -1,19 +1,139 @@ #if CLIENT_DLL || GAME_DLL using Source.Common.Audio; +using Source.Common.GarrysMod; using Source.Common.GarrysMod.Lua; +using Source.Common.Mathematics; using Source.Common.SoundEmitterSystem; +using System.Runtime.CompilerServices; + +using PitchInterval = Source.Common.SoundEmitterSystem.SoundInterval; +using VolumeInterval = Source.Common.SoundEmitterSystem.SoundInterval; + #if CLIENT_DLL namespace Game.Client.GarrysMod; #else namespace Game.Server.GarrysMod; #endif +#if CLIENT_DLL +public class PlaySoundThread : ILuaThreadedCall +{ + public IGModAudioChannel? Channel; + public string Path = ""; + public string Flags = ""; + public LuaObject Callback = new(); + public int Type; + public int ErrorCode; + Thread? WorkerThread; + volatile bool Running; + + public void Start() { + Running = true; + WorkerThread = new Thread(Run) { Name = "PlaySoundThread", IsBackground = true }; + WorkerThread.Start(); + } + + public void Run() { + Span error = stackalloc int[1]; + if (Type == 0) + Channel = get.Audio()!.PlayURL(Path, Flags, error); + else if (Type == 1) + Channel = get.Audio()!.PlayFile(Path, Flags, error); + ErrorCode = error[0]; + Running = false; + } + + public void OnThreadFinished() { } + + public bool IsFinished() => !Running; + + public void DoFinish(ILuaBase lua) { + if (Running) + Error("DoFinish called while still running!"); + + ILuaInterface luaInterface = (ILuaInterface)lua; + if (Callback.isFunction()) { + if (Channel == null) { + Callback.Push(); + lua.PushNil(); + lua.PushNumber(ErrorCode); + lua.PushString(get.Audio()!.GetErrorString(ErrorCode)); + luaInterface.CallFunctionProtected(3, 0, true); + return; + } + + Callback.Push(); + LuaAudioChannel.Push_IGModAudioChannel(Channel); + luaInterface.CallFunctionProtected(1, 0, true); + Channel = null; + return; + } + + Channel?.Destroy(); + Channel = null; + DestroyForced(); + } + + public void DestroyForced() { + WorkerThread?.Join(); + if (Channel != null) { + Channel.Stop(); + Channel.Destroy(); + Channel = null; + } + Callback.UnReference(); + } +} +#endif + public static partial class LuaSound { [LuaLibrary] static readonly LuaLibrary LL_Factory_sound = new("sound"); +#if CLIENT_DLL + [LuaFunction] + static int PlayURL(ILuaInterface lua) { + if (commandLine.CheckParm("-disablehttp")) { + lua.ErrorFromLua($"sound.PlayURL blocked by -disablehttp launch parameter. URL: {lua.CheckString(1)}\n"); + return 0; + } + + garrysmod.UpdateAudioVolume(); + + lua.CheckType(3, LuaType.Function); + PlaySoundThread thread = new(); + thread.Callback.SetFromStack(3); + thread.Flags = lua.CheckString(2).ToString(); + thread.Path = lua.CheckString(1).ToString(); + thread.Type = 0; + lua.AddThreadedCall(thread); + thread.Start(); + return 0; + } + + [LuaFunction] + static int PlayFile(ILuaInterface lua) { + garrysmod.UpdateAudioVolume(); + + string path = lua.CheckString(1).ToString().Replace("\\", "/"); + while (path.Contains("//")) + path = path.Replace("//", "/"); + path = path.Trim(' '); + + lua.CheckType(3, LuaType.Function); + PlaySoundThread thread = new(); + thread.Callback.SetFromStack(3); + thread.Flags = lua.CheckString(2).ToString(); + thread.Path = path; + thread.Type = 1; + lua.AddThreadedCall(thread); + thread.Start(); + return 0; + } +#endif + [LuaFunction] static int Add(ILuaInterface lua) { LuaObject data = new(); @@ -103,5 +223,63 @@ static int AddSoundOverrides(ILuaInterface lua) { soundemitterbase.AddSoundOverrides(lua.CheckString(1), false); return 0; } + + [LuaFunction] + static int GetProperties(ILuaInterface lua) { + int index = soundemitterbase.GetSoundIndex(lua.CheckString(1)); + if ((short)index == -1) + return 0; + + ref SoundParametersInternal parms = ref soundemitterbase.InternalGetParametersForSound(index); + if (Unsafe.IsNullRef(ref parms)) + return 0; + + int count = parms.NumSoundNames(); + if (count == 0) + return 0; + + LuaTable table = new(); + table.SetMember("channel", (float)(ushort)parms.GetChannel()); + table.SetMember("level", (float)parms.GetSoundLevel().Start); + + ref readonly VolumeInterval volume = ref parms.GetVolume(); + if (Float16.Convert16bitFloatTo32bits(volume.Range) != 0.0f) { + LuaTable volumes = new(); + float start = Float16.Convert16bitFloatTo32bits(volume.Start); + volumes.SetMemberDouble(1, start); + volumes.SetMemberDouble(2, Float16.Convert16bitFloatTo32bits(volume.Range) + start); + table.SetMember("volume", volumes); + volumes.UnReference(); + } + else + table.SetMember("volume", Float16.Convert16bitFloatTo32bits(volume.Start)); + + ref readonly PitchInterval pitch = ref parms.GetPitch(); + if (pitch.Range == 0) + table.SetMember("pitch", (float)pitch.Start); + else { + LuaTable pitches = new(); + pitches.SetMemberDouble(1, pitch.Start); + pitches.SetMemberDouble(2, pitch.Start + pitch.Range); + table.SetMember("pitch", pitches); + pitches.UnReference(); + } + + Span names = parms.GetSoundNames(); + if (count == 1) + table.SetMember("sound", soundemitterbase.GetWaveName(names[0].Symbol)); + else { + LuaTable sounds = new(null, (uint)count); + for (int i = 0; i < count; i++) + sounds.SetMember((float)(i + 1), soundemitterbase.GetWaveName(names[i].Symbol)); + table.SetMember("sound", sounds); + sounds.UnReference(); + } + + table.SetMember("name", soundemitterbase.GetSoundName(index)); + table.Push(); + table.UnReference(); + return 1; + } } #endif diff --git a/Game.Shared/GarrysMod/LuaUtil.cs b/Game.Shared/GarrysMod/LuaUtil.cs index 1cb9936f5..4d4e315f6 100644 --- a/Game.Shared/GarrysMod/LuaUtil.cs +++ b/Game.Shared/GarrysMod/LuaUtil.cs @@ -21,6 +21,9 @@ using System.Runtime.CompilerServices; using Source.Common.Hashing; +using SHA1Hash = System.Security.Cryptography.SHA1; +using SHA256Hash = System.Security.Cryptography.SHA256; + #if CLIENT_DLL namespace Game.Client.GarrysMod; #elif MENU_DLL @@ -34,6 +37,16 @@ public static partial class LuaUtil [LuaLibrary] static readonly LuaLibrary LL_Factory_util = new("util"); +#if CLIENT_DLL + public class PixelVisHandle + { + public int Handle; + } + + [LuaClass(typeof(PixelVisHandle), NullError = "Tried to use a NULL pixelvis_handle_t!")] + public static readonly LuaClass LC_pixelvis_handle_t = new("pixelvis_handle_t", LuaType.PixelVisHandle, null, null); +#endif + #if !MENU_DLL public static bool UTIL_IsValidModel(ReadOnlySpan name) { if (name.IsEmpty || name[0] <= ' ' || name.Length <= 3) @@ -104,6 +117,180 @@ public static bool UTIL_IsValidRagdollModel(ReadOnlySpan name) { #endif +#if CLIENT_DLL + static int DecodeBodygroups(StudioHeader studioHdr, ReadOnlySpan bodygroups) { + int body = 0; + for (int i = 0; i < bodygroups.Length; i++) { + char c = bodygroups[i]; + int value = -1; + if (c >= '0' && c <= '9') + value = c - '0'; + if (c >= 'a' && c <= 'z') + value = c - 'a' + 10; + if (c >= 'A' && c <= 'Z') + value = c - 'A' + 10; + + if (value < 0 || i >= studioHdr.NumBodyParts) + continue; + + MStudioBodyParts bodyPart = studioHdr.BodyPart(i); + if (value < bodyPart.NumModels) + body += (value - (body / bodyPart.Base % bodyPart.NumModels)) * bodyPart.Base; + } + return body; + } + + static void PushMeshVertex(ILuaInterface lua, in GetTrianglesVertex vert) { + lua.CreateTable(); + lua.PushNumber(vert.TexCoord.X); + lua.SetField(-2, "u"); + lua.PushNumber(vert.TexCoord.Y); + lua.SetField(-2, "v"); + LuaVector.Push_Vector(vert.Position); + lua.SetField(-2, "pos"); + LuaVector.Push_Vector(vert.Normal); + lua.SetField(-2, "normal"); + LuaVector.Push_Vector(new Vector3(vert.TangentS.X, vert.TangentS.Y, vert.TangentS.Z)); + lua.SetField(-2, "tangent"); + + lua.CreateTable(); + for (int i = 0; i < 4; i++) { + lua.PushNumber(i + 1); + lua.PushNumber(vert.TangentS[i]); + lua.SetTable(-3); + } + lua.SetField(-2, "userdata"); + + lua.CreateTable(); + for (int i = 0; i < vert.NumBones; i++) { + lua.PushNumber(i + 1); + lua.CreateTable(); + lua.PushNumber(vert.BoneIndex[i]); + lua.SetField(-2, "bone"); + lua.PushNumber(vert.BoneWeight[i]); + lua.SetField(-2, "weight"); + lua.SetTable(-3); + } + lua.SetField(-2, "weights"); + } + + [LuaFunction] + static int GetModelMeshes(ILuaInterface lua) { + string modelName = lua.CheckString(1); + int lod = (int)lua.CheckNumberOpt(2, 0); + string? bodygroups = null; + int body = 0; + if (lua.GetType(3) == LuaType.String) + bodygroups = lua.CheckString(3); + else if (lua.GetType(3) != LuaType.Nil) + body = (int)lua.CheckNumber(3); + int skin = (int)lua.CheckNumberOpt(4, 0); + + MDLHandle_t handle = mdlcache.FindMDL(modelName); + if (mdlcache.IsErrorModel(handle)) { + mdlcache.Release(handle); + return 0; + } + + mdlcache.PreloadModel(handle); + StudioHeader? studioHdr = mdlcache.GetStudioHdr(handle); + if (studioHdr == null || mdlcache.IsErrorModel(handle)) { + mdlcache.Release(handle); + return 0; + } + + if (bodygroups != null) + body = DecodeBodygroups(studioHdr, bodygroups); + + DrawModelInfo info = default; + info.StudioHdr = studioHdr; + info.HardwareData = mdlcache.GetHardwareData(handle)!; + info.Skin = skin; + info.Body = body; + info.Lod = lod; + + Span boneToWorld = stackalloc Matrix3x4[Studio.MAXSTUDIOBONES]; + GetTrianglesOutput output = new(); + studiorender.GetTriangles(ref info, boneToWorld, output); + + lua.CreateTable(); + for (int i = 0; i < studioHdr.NumBones; i++) { + MStudioBone bone = studioHdr.Bone(i); + Matrix4x4 matrix = default; + matrix.Init(bone.PoseToBone); + lua.PushNumber(i + 1); + lua.CreateTable(); + lua.PushNumber(bone.Parent); + lua.SetField(-2, "parent"); + LuaVMatrix.Push_VMatrix(matrix); + lua.SetField(-2, "matrix"); + lua.SetTable(-3); + } + + lua.CreateTable(); + for (int b = 0; b < output.MaterialBatches.Count; b++) { + GetTrianglesMaterialBatch batch = output.MaterialBatches[b]; + lua.PushNumber(b + 1); + lua.CreateTable(); + + lua.PushString(batch.Material != null ? batch.Material.GetName() : ""); + lua.SetField(-2, "material"); + + lua.CreateTable(); + for (int v = 0; v < batch.Verts.Count; v++) { + lua.PushNumber(v + 1); + PushMeshVertex(lua, batch.Verts[v]); + lua.SetTable(-3); + } + + lua.CreateTable(); + for (int t = 0; t < batch.TriListIndices.Count; t++) { + lua.PushNumber(t + 1); + lua.PushNumber(batch.TriListIndices[t] + 1); + lua.GetTable(-4); + lua.SetTable(-3); + } + lua.SetField(-3, "triangles"); + lua.SetField(-2, "verticies"); + + lua.SetTable(-3); + } + + mdlcache.Release(handle); + + lua.Push(-2); + lua.Remove(-3); + return 2; + } + + [LuaFunction] + static int GetPixelVisibleHandle(ILuaInterface lua) { + LC_pixelvis_handle_t.Push(new PixelVisHandle { Handle = 0 }); + return 1; + } + + [LuaFunction] + static int PixelVisible(ILuaInterface lua) { + PixelVisHandle? handle = (PixelVisHandle?)LC_pixelvis_handle_t.Get(3); + if (handle == null) { + lua.Error("Tried to use a NULL pixelvis_handle_t!"); + return 0; + } + float radius = (float)lua.GetNumber(2); + Vector3 pos = LuaVector.Get_Vector(1); + PixelVisQueryParams parms = new() { + Position = pos, + ProxySize = radius, + ProxyAspect = 1.0f, + FadeTime = 0.0625f, + Setup = true, + SizeInScreenspace = false + }; + lua.PushNumber(PixelVisibility.FractionVisible(parms, ref handle.Handle)); + return 1; + } +#endif + [LuaFunction] static int AimVector(ILuaInterface lua) { QAngle angles = LuaAngle.Get_Angle(1); @@ -124,6 +311,20 @@ static int AimVector(ILuaInterface lua) { } #if !MENU_DLL + [LuaFunction] + static int IntersectRayWithPlane(ILuaInterface lua) { + Vector3 rayOrigin = LuaVector.Get_Vector(1); + Vector3 rayDirection = LuaVector.Get_Vector(2); + Vector3 planePosition = LuaVector.Get_Vector(3); + Vector3 planeNormal = LuaVector.Get_Vector(4); + float t = CollisionUtils.IntersectRayWithPlane(rayOrigin, rayDirection, planeNormal, Vector3.Dot(planePosition, planeNormal)); + if (!(0.0f < t)) + return 0; + LuaVector.Push_Vector(rayDirection * t + rayOrigin); + lua.PushNumber(t); + return 2; + } + [LuaFunction] static int IntersectRayWithOBB(ILuaInterface lua) { Vector3 rayStart = LuaVector.Get_Vector(1); @@ -334,6 +535,24 @@ static int CRC(ILuaInterface lua) { return 1; } + [LuaFunction] + static int SHA256(ILuaInterface lua) { + if (!g_Lua!.IsType(1, LuaType.String)) + g_Lua.CheckString(1); + ReadOnlySpan data = g_Lua.GetStringBytes(1); + g_Lua.PushString(Convert.ToHexStringLower(SHA256Hash.HashData(data))); + return 1; + } + + [LuaFunction] + static int SHA1(ILuaInterface lua) { + if (!g_Lua!.IsType(1, LuaType.String)) + g_Lua.CheckString(1); + ReadOnlySpan data = g_Lua.GetStringBytes(1); + g_Lua.PushString(Convert.ToHexStringLower(SHA1Hash.HashData(data))); + return 1; + } + [LuaFunction] static int GetSurfacePropName(ILuaInterface lua) { int index = (int)g_Lua!.CheckNumber(1); diff --git a/Game.Shared/GarrysMod/SENT_AI.cs b/Game.Shared/GarrysMod/SENT_AI.cs index bcd0604c5..e7e69535b 100644 --- a/Game.Shared/GarrysMod/SENT_AI.cs +++ b/Game.Shared/GarrysMod/SENT_AI.cs @@ -44,6 +44,14 @@ public override void InitializeScriptedEntity(ReadOnlySpan name) { ScriptedEntity.StartLua(); } +#if GAME_DLL + int UseTypeCaps = (int)EntityCapabilities.ContinuousUse; + + public override void SetUseType(int type) => UseTypeCaps = type; + + public override EntityCapabilities ObjectCaps() => base.ObjectCaps() | (EntityCapabilities)UseTypeCaps; +#endif + #if CLIENT_DLL public override void OnDataChanged(DataUpdateType updateType) { base.OnDataChanged(updateType); diff --git a/Game.Shared/GarrysMod/SENT_Anim.cs b/Game.Shared/GarrysMod/SENT_Anim.cs index 28017ba10..3428b0f10 100644 --- a/Game.Shared/GarrysMod/SENT_Anim.cs +++ b/Game.Shared/GarrysMod/SENT_Anim.cs @@ -52,6 +52,12 @@ public override void InitializeScriptedEntity(ReadOnlySpan name) { } #if GAME_DLL + int UseTypeCaps = (int)EntityCapabilities.ContinuousUse; + + public override void SetUseType(int type) => UseTypeCaps = type; + + public override EntityCapabilities ObjectCaps() => base.ObjectCaps() | (EntityCapabilities)UseTypeCaps; + IPhysicsMotionController? MotionController; public override void StartMotionController() { @@ -218,7 +224,7 @@ public override void UpdateOnRemove() { StudioFlags DrawFlags; public override int DrawModel(StudioFlags flags) { - if (!ShouldDraw()) + if (!ShouldDrawInView()) return 0; if (InDraw) return base.DrawModel(flags | DrawFlags); @@ -249,8 +255,24 @@ public override bool GetShadowCastDirection(ref Vector3 direction, ShadowType sh } public override void ClientThink() { + ScriptedEntity.CallFunction((int)LUA_POOLEDSTRING.Think, false); + + float max = WorldSize.MAX_COORD_INTEGER * 8.0f; + ref Vector3 origin = ref GetNetworkOrigin(); + if (origin.X > -max && origin.X < max && origin.Y > -max && origin.Y < max && origin.Z > -max && origin.Z < max) { + IPhysicsObject? physics = VPhysicsGetObject(); + if (physics == null) + return; + if (physics.GetShadowController() != null) + physics.UpdateShadow(origin, GetNetworkAngles(), false, 0); + else + physics.SetPosition(origin, GetNetworkAngles(), true); + } + } + + public override void Think() { if (!IsMarkedForDeletion() && !ScriptedEntity.CallFunction((int)LUA_POOLEDSTRING.Think, true)) - SetNextClientThink(gpGlobals.CurTime + 0.2); + SetNextThink(gpGlobals.CurTime + 0.2); } #endif diff --git a/Game.Shared/GarrysMod/WeaponSWEP.cs b/Game.Shared/GarrysMod/WeaponSWEP.cs index a437d7af5..3b97487b1 100644 --- a/Game.Shared/GarrysMod/WeaponSWEP.cs +++ b/Game.Shared/GarrysMod/WeaponSWEP.cs @@ -296,6 +296,13 @@ public override bool Holster(BaseCombatWeapon? switchingTo) { return true; } +#if CLIENT_DLL + public virtual void CreateMoveThink() { + UpdateLuaData(true); + ScriptedEntity.CallFunction((int)LUA_POOLEDSTRING.Think, false); + } +#endif + public override void ItemPostFrame() { if (GetOwner() == null) return; diff --git a/Game.Shared/HL2/UserMessages.cs b/Game.Shared/HL2/UserMessages.cs index 9c76864a1..2a620bc4f 100644 --- a/Game.Shared/HL2/UserMessages.cs +++ b/Game.Shared/HL2/UserMessages.cs @@ -29,7 +29,11 @@ public void RegisterUsermessages() { Register("LogoTimeMsg", 4); Register("AchievementEvent", -1); Register("UpdateJalopyRadar", -1); - Register("LuaUserMessage", -1); +#if CLIENT_DLL + Game.Client.GarrysMod.LuaUserMessages.RegisterUserMessages(this); +#else + Game.Server.GarrysMod.LuaUserMessages.RegisterUserMessages(this); +#endif // Register("LuaCmd", -1); Register("SWEPCmd", -1); Register("AmmoPickup", -1); diff --git a/Game.Shared/HL2MP/HL2MPPlayerShared.cs b/Game.Shared/HL2MP/HL2MPPlayerShared.cs index c64ecf3eb..9fb416fcb 100644 --- a/Game.Shared/HL2MP/HL2MPPlayerShared.cs +++ b/Game.Shared/HL2MP/HL2MPPlayerShared.cs @@ -54,13 +54,20 @@ public partial class return VECTOR_CONE_15DEGREES; } - public void UpdateLookAt() { + public virtual void UpdateLookAt() { if (HeadYawPoseParam < 0 || HeadPitchPoseParam < 0) return; // orient eyes ViewTarget = LookAtTarget; +#if CLIENT_DLL + if (BlinkTimer.IsElapsed()) { + BlinkToggle = BlinkToggle == 0 ? 1 : 0; + BlinkTimer.Start(RandomFloat(1.5f, 4.0f)); + } +#endif + // Figure out where we want to look in world space. Vector3 to = LookAtTarget - EyePosition(); MathLib.VectorAngles(to, out QAngle desiredAngles); @@ -92,18 +99,20 @@ public void UpdateLookAt() { CurrentHeadPitch = MathLib.AngleNormalize(CurrentHeadPitch); SetPoseParameter(HeadPitchPoseParam, CurrentHeadPitch); } - Vector3 ViewTarget; - Vector3 LookAtTarget; - - int HeadYawPoseParam; - int HeadPitchPoseParam; - float LastBodyYaw; - float CurrentHeadYaw; - float CurrentHeadPitch; - float HeadYawMin; - float HeadYawMax; - float HeadPitchMin; - float HeadPitchMax; + protected Vector3 LookAtTarget; + + protected int HeadYawPoseParam; + protected int HeadPitchPoseParam; + protected float HeadYawMin; + protected float HeadYawMax; + protected float HeadPitchMin; + protected float HeadPitchMax; + protected float LastBodyYaw; + protected float CurrentHeadYaw; + protected float CurrentHeadPitch; +#if CLIENT_DLL + protected readonly CountdownTimer BlinkTimer = new(); +#endif internal QAngle GetAnimEyeAngles() => AngEyeAngles; } diff --git a/Game.Shared/SharedClassNames.cs b/Game.Shared/SharedClassNames.cs index 8b87034d0..95ddf4a2a 100644 --- a/Game.Shared/SharedClassNames.cs +++ b/Game.Shared/SharedClassNames.cs @@ -1,6 +1,7 @@ #if CLIENT_DLL global using BaseCombatCharacter = Game.Client.C_BaseCombatCharacter; global using BaseAnimating = Game.Client.C_BaseAnimating; +global using BoneManipulate = Game.Client.C_BoneManipulate; #endif #if GAME_DLL diff --git a/Source.AudioSystem/AudioSystem.cs b/Source.AudioSystem/AudioSystem.cs index e0df91efb..ba666e62e 100644 --- a/Source.AudioSystem/AudioSystem.cs +++ b/Source.AudioSystem/AudioSystem.cs @@ -8,6 +8,7 @@ using Source.Common.Commands; using Source.Common.Engine; using Source.Common.Filesystem; +using Source.Common.GarrysMod; namespace Source.AudioSystem; @@ -17,6 +18,9 @@ public static class AudioGlobals [Dependency] public static IFileSystem filesystem = null!; [Dependency] public static ISoundServices soundServices = null!; [Dependency] public static ICommandLine CommandLine = null!; +#if GMOD_DLL + [Dependency] public static IGet? get = null; +#endif } public class AudioSystem : IAudioSystem diff --git a/Source.AudioSystem/SndDma.Update.cs b/Source.AudioSystem/SndDma.Update.cs index f350e9b75..28bb51b0d 100644 --- a/Source.AudioSystem/SndDma.Update.cs +++ b/Source.AudioSystem/SndDma.Update.cs @@ -168,6 +168,11 @@ public static void S_Update(AudioState? pAudioState) { } } +#if GMOD_DLL + if (get != null && get.Audio() != null) + get.Audio()!.Update((uint)(long)((float)(Platform.Time - g_LastSoundFrame) * 1000.0f)); +#endif + if (s_bOnLoadScreen) return; diff --git a/Source.CodeAnalysis.Lua/LuaReferenceAnalyzer.cs b/Source.CodeAnalysis.Lua/LuaReferenceAnalyzer.cs index 630195bf4..5d74ef019 100644 --- a/Source.CodeAnalysis.Lua/LuaReferenceAnalyzer.cs +++ b/Source.CodeAnalysis.Lua/LuaReferenceAnalyzer.cs @@ -314,7 +314,7 @@ void Transfer(IOperation op, HashSet state, FlowResult result) { state.Clear(); break; } - if (invocation.TargetMethod.Name == "UnReference" && AsTracked(invocation.Instance) is ISymbol instance) + if ((invocation.TargetMethod.Name == "UnReference" || (invocation.TargetMethod.Name == "Dispose" && invocation.TargetMethod.ContainingType.Name == "LuaDisposable")) && AsTracked(invocation.Instance) is ISymbol instance) state.Remove(instance); ReleaseArguments(invocation.Arguments, state); break; diff --git a/Source.Common/GUI/IInputInternal.cs b/Source.Common/GUI/IInputInternal.cs index dd9287f17..79dcedd43 100644 --- a/Source.Common/GUI/IInputInternal.cs +++ b/Source.Common/GUI/IInputInternal.cs @@ -121,6 +121,7 @@ public unsafe struct SentenceModeItem bool ShouldModalSubTreeReceiveMessages(); IPanel? GetMouseCapture(); + IPanel? GetMouseFocus(); // InputInternal diff --git a/Source.Common/GarrysMod/IGmod_Audio.cs b/Source.Common/GarrysMod/IGmod_Audio.cs index efc53e666..7083c93ac 100644 --- a/Source.Common/GarrysMod/IGmod_Audio.cs +++ b/Source.Common/GarrysMod/IGmod_Audio.cs @@ -31,9 +31,7 @@ public interface IGModAudioChannel void GetPos(out Vector3 unk1, out Vector3 unk2, out Vector3 unk3); void SetTime(TimeUnit_t time, bool unk2); TimeUnit_t GetTime(); -#if WIN32 TimeUnit_t GetBufferedTime(); -#endif void Set3DFadeDistance(float unk1, float unk2); void Get3DFadeDistance(out float unk1, out float unk2); void Set3DCone(int unk1, int unk2, float unk3); @@ -51,10 +49,10 @@ public interface IGModAudioChannel int GetBitsPerSample(); float GetAverageBitRate(); void GetLevel(out float unk1, out float unk2); - void FFT(ref float unk1, GModChannelFFT unk2); + int FFT(float[] data, GModChannelFFT size); void SetChannelPan(float unk1); float GetChannelPan(); - ReadOnlySpan GetTags(int unk1); + nint GetTags(int type); void Set3DEnabled(bool unk1); bool Get3DEnabled(); void Restart(); @@ -62,17 +60,13 @@ public interface IGModAudioChannel public interface IBassAudioStream { - uint Decode(ReadOnlySpan data); + int Decode(Span buffer); int GetOutputBits(); int GetOutputRate(); int GetOutputChannels(); uint GetPosition(); void SetPosition(uint distance); - uint GetHandle(); // unsigned long -> DWORD -> HSTREAM - void MyFileCloseProc(object? unk1); - ulong MyFileLenProc(object? unk1); // unsigned long long -> QWORD - uint MyFileReadProc(object? unk1, uint unk2, object? unk3); // unsigned long -> DWORD - bool MyFileSeekProc(ulong unk1, object? unk2); + uint GetHandle(); } public interface IGMod_Audio diff --git a/Source.Common/IStudioRender.cs b/Source.Common/IStudioRender.cs index 0b3826b3f..b18203129 100644 --- a/Source.Common/IStudioRender.cs +++ b/Source.Common/IStudioRender.cs @@ -47,6 +47,27 @@ public struct DrawModelInfo { public InlineArray4 LocalLightDescs; } +public struct GetTrianglesVertex { + public Vector3 Position; + public Vector3 Normal; + public Vector4 TangentS; + public Vector2 TexCoord; + public Vector4 BoneWeight; + public InlineArray4 BoneIndex; + public int NumBones; +} + +public class GetTrianglesMaterialBatch { + public IMaterial? Material; + public List Verts = []; + public List TriListIndices = []; +} + +public class GetTrianglesOutput { + public List MaterialBatches = []; + public InlineArrayMaxStudioBones PoseToWorld; +} + public struct StudioRenderConfig { public float EyeShiftX; public float EyeShiftY; @@ -101,6 +122,7 @@ public interface IStudioRender { bool LoadModel(StudioHeader studioHDR, Memory vtxData, StudioHWData hardwareData); void UnloadModel(StudioHWData hardwareData); + void GetTriangles(ref DrawModelInfo info, Span boneToWorld, GetTrianglesOutput output); void GetMaterialList(StudioHeader studioHDR, ref SpanList materials); void GetMaterialListFromBodyAndSkin(MDLHandle_t studio, int skin, int body, ref SpanList outputMaterials); Span LockBoneMatrices(int boneCount); diff --git a/Source.Common/MaterialSystem/IMesh.cs b/Source.Common/MaterialSystem/IMesh.cs index 8d2651bdd..aebe89b08 100644 --- a/Source.Common/MaterialSystem/IMesh.cs +++ b/Source.Common/MaterialSystem/IMesh.cs @@ -646,11 +646,32 @@ internal unsafe void GenerateIndices(MaterialPrimitiveType primitiveType, int in } private unsafe static void GenerateLineStripIndexBuffer(ushort* indices, int indexCount, int indexOffset) { - throw new NotImplementedException(); + if (indices == null) + return; + + int numLines = indexCount / 2; + for (int i = 0; i < numLines; ++i) { + indices[0] = (ushort)(indexOffset + i); + indices[1] = (ushort)(indexOffset + i + 1); + indices += 2; + } } private unsafe static void GenerateLineLoopIndexBuffer(ushort* indices, int indexCount, int indexOffset) { - throw new NotImplementedException(); + if (indices == null) + return; + + int numLines = indexCount / 2; + + indices[0] = (ushort)(indexOffset + numLines - 1); + indices[1] = (ushort)indexOffset; + indices += 2; + + for (int i = 1; i < numLines; ++i) { + indices[0] = (ushort)(indexOffset + i - 1); + indices[1] = (ushort)(indexOffset + i); + indices += 2; + } } private unsafe static void GenerateSequentialIndexBuffer(ushort* indices, int indexCount, int indexOffset) { diff --git a/Source.Common/Mathematics/CompressedVector.cs b/Source.Common/Mathematics/CompressedVector.cs new file mode 100644 index 000000000..20298a1b3 --- /dev/null +++ b/Source.Common/Mathematics/CompressedVector.cs @@ -0,0 +1,29 @@ +namespace Source.Common.Mathematics; + +public static class Float16 +{ + public const float maxfloat16bits = 65504.0f; + + public static float Convert16bitFloatTo32bits(ushort input) { + int sign = input >> 15; + int mantissa = input & 1023; + int biased_exponent = (input >> 10) & 31; + + if (biased_exponent == 31 && mantissa == 0) + return sign != 0 ? -maxfloat16bits : maxfloat16bits; + + if (biased_exponent == 31 && mantissa != 0) + return 0.0f; + + if (biased_exponent == 0 && mantissa != 0) { + float m = mantissa / 1024.0f; + float s = sign != 0 ? -1.0f : 1.0f; + return s * m * (1.0f / (1 << 14)); + } + + int exponent = biased_exponent == 0 ? 0 : biased_exponent - 15 + 127; + return BitConverter.Int32BitsToSingle((sign << 31) | (exponent << 23) | (mantissa << 13)); + } + + public static float Convert16bitFloatTo32bits(Half input) => Convert16bitFloatTo32bits(BitConverter.HalfToUInt16Bits(input)); +} diff --git a/Source.Common/Mathematics/MathLib.cs b/Source.Common/Mathematics/MathLib.cs index 31438bfc8..061f32b53 100644 --- a/Source.Common/Mathematics/MathLib.cs +++ b/Source.Common/Mathematics/MathLib.cs @@ -2353,6 +2353,7 @@ public static void VectorVectors(in Vector3 forward, out Vector3 right, out Vect VectorNormalize(ref up); } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void SetScaleMatrix(float x, float y, float z, out Matrix3x4 dst) => dst = new(x, 0.0f, 0.0f, 0.0f, 0.0f, y, 0.0f, 0.0f, 0.0f, 0.0f, z, 0.0f); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void MatrixGetColumn(in Matrix3x4 inMatrix, int column, out Vector3 outVec) { outVec.X = inMatrix[0][column]; @@ -2413,6 +2414,21 @@ public static void TransformAABB(in Matrix3x4 transform, in Vector3 minsIn, in V maxsOut = worldCenter + worldExtents; } + public static void RotateAABB(in Matrix3x4 transform, in Vector3 minsIn, in Vector3 maxsIn, out Vector3 minsOut, out Vector3 maxsOut) { + Vector3 localCenter = (minsIn + maxsIn) * 0.5f; + Vector3 localExtents = maxsIn - localCenter; + + VectorRotate(localCenter, transform, out Vector3 newCenter); + + Vector3 newExtents; + newExtents.X = DotProductAbs(localExtents, transform[0]); + newExtents.Y = DotProductAbs(localExtents, transform[1]); + newExtents.Z = DotProductAbs(localExtents, transform[2]); + + minsOut = newCenter - newExtents; + maxsOut = newCenter + newExtents; + } + public static void IRotateAABB(in Matrix3x4 transform, in Vector3 minsIn, in Vector3 maxsIn, out Vector3 minsOut, out Vector3 maxsOut) { Vector3 oldCenter = (minsIn + maxsIn) * 0.5f; Vector3 oldExtents = maxsIn - oldCenter; diff --git a/Source.Common/ShaderAPI/IShaderUtil.cs b/Source.Common/ShaderAPI/IShaderUtil.cs index d97c8ad87..fc129260d 100644 --- a/Source.Common/ShaderAPI/IShaderUtil.cs +++ b/Source.Common/ShaderAPI/IShaderUtil.cs @@ -15,4 +15,5 @@ public interface IShaderUtil void SyncMatrix(MaterialMatrixMode mode); void RestoreShaderObjects(IServiceProvider services, int changeFlags = 0); void BindStandardTexture(Sampler sampler, StandardTextureId id); + bool IsRenderThreadSafe(); } diff --git a/Source.Common/UtlMultiList.cs b/Source.Common/UtlMultiList.cs new file mode 100644 index 000000000..a915ab782 --- /dev/null +++ b/Source.Common/UtlMultiList.cs @@ -0,0 +1,180 @@ +namespace Source.Common; + +public class UtlMultiList where T : class, new() +{ + struct ListElem + { + public T Element; + public ushort Previous; + public ushort Next; + } + + struct List + { + public ushort Head; + public ushort Tail; + public ushort Count; + } + + ListElem[] Memory = []; + readonly List Lists = []; + ushort FirstFree; + ushort TotalElements; + int MaxElementIndex; + + public UtlMultiList() => ConstructList(); + + void ConstructList() { + FirstFree = InvalidIndex(); + TotalElements = 0; + MaxElementIndex = 0; + } + + public T Element(ushort i) => Memory[i].Element; + public T this[ushort i] => Memory[i].Element; + + public void EnsureCapacity(int num) => throw new NotImplementedException(); + + public void Purge() { + RemoveAll(); + Lists.Clear(); + Memory = []; + FirstFree = InvalidIndex(); + TotalElements = 0; + MaxElementIndex = 0; + } + + public ushort CreateList() { + Lists.Add(new List { Head = InvalidIndex(), Tail = InvalidIndex(), Count = 0 }); + return (ushort)(Lists.Count - 1); + } + + public void DestroyList(ushort list) => throw new NotImplementedException(); + public bool IsValidList(ushort list) => list < Lists.Count; + + public ushort InsertBefore(ushort list, ushort before) => throw new NotImplementedException(); + public ushort InsertAfter(ushort list, ushort after) => throw new NotImplementedException(); + public ushort AddToHead(ushort list) => throw new NotImplementedException(); + public ushort AddToTail(ushort list) => throw new NotImplementedException(); + + public void Remove(ushort list, ushort elem) => throw new NotImplementedException(); + public void RemoveAll(ushort list) => throw new NotImplementedException(); + + public void RemoveAll() { + if (MaxElementIndex == 0) + return; + + for (int i = 0; i < MaxElementIndex; i++) + Memory[i].Element = null!; + + for (int i = 0; i < Lists.Count; i++) + Lists[i] = new List { Head = InvalidIndex(), Tail = InvalidIndex(), Count = 0 }; + + FirstFree = InvalidIndex(); + TotalElements = 0; + MaxElementIndex = 0; + } + + public ushort Alloc() { + ushort elem; + if (FirstFree == InvalidIndex()) { + if (!IndexInRange(MaxElementIndex)) + Error("CUtlMultiList overflow! (exhausted index range)\n"); + + if (MaxElementIndex == Memory.Length) + Array.Resize(ref Memory, Memory.Length == 0 ? 1 : Memory.Length * 2); + + elem = (ushort)MaxElementIndex; + ++MaxElementIndex; + } + else { + elem = FirstFree; + FirstFree = Memory[FirstFree].Next; + } + + Memory[elem].Next = Memory[elem].Previous = elem; + + ++TotalElements; + + Memory[elem].Element = new(); + + return elem; + } + + public void Free(ushort elem) => throw new NotImplementedException(); + + public void LinkBefore(ushort list, ushort before, ushort elem) => throw new NotImplementedException(); + + public void LinkAfter(ushort list, ushort after, ushort elem) { + Unlink(list, elem); + + ref ListElem newElem = ref Memory[elem]; + List l = Lists[list]; + + newElem.Previous = after; + if (after == InvalidIndex()) { + newElem.Next = l.Head; + l.Head = elem; + } + else { + ref ListElem afterElem = ref Memory[after]; + newElem.Next = afterElem.Next; + afterElem.Next = elem; + } + + if (newElem.Next == InvalidIndex()) + l.Tail = elem; + else + Memory[newElem.Next].Previous = elem; + + ++l.Count; + Lists[list] = l; + } + + public void Unlink(ushort list, ushort elem) { + if (IsInList(elem)) { + ref ListElem oldElem = ref Memory[elem]; + List l = Lists[list]; + + if (oldElem.Previous != InvalidIndex()) + Memory[oldElem.Previous].Next = oldElem.Next; + else + l.Head = oldElem.Next; + + if (oldElem.Next != InvalidIndex()) + Memory[oldElem.Next].Previous = oldElem.Previous; + else + l.Tail = oldElem.Previous; + + oldElem.Previous = oldElem.Next = elem; + + --l.Count; + Lists[list] = l; + } + } + + public void LinkToHead(ushort list, ushort elem) => LinkAfter(list, InvalidIndex(), elem); + public void LinkToTail(ushort list, ushort elem) => throw new NotImplementedException(); + + public static ushort InvalidIndex() => ushort.MaxValue; + public static bool IndexInRange(int index) => (ushort)index == index && (ushort)index != InvalidIndex(); + + public ushort Count(ushort list) => Lists[list].Count; + public ushort TotalCount() => TotalElements; + public int GetMaxElementIndex() => MaxElementIndex; + + public ushort Head(ushort list) => Lists[list].Head; + public ushort Tail(ushort list) => Lists[list].Tail; + public ushort Previous(ushort i) => Memory[i].Previous; + public ushort Next(ushort i) => Memory[i].Next; + + public bool IsValidIndex(ushort i) { + if (i < MaxElementIndex) { + ref ListElem value = ref Memory[i]; + return value.Previous != i || value.Next == i; + } + return false; + } + + public bool IsInList(ushort i) => i < MaxElementIndex && Previous(i) != i; +} diff --git a/Source.DataCache/MDLCache.cs b/Source.DataCache/MDLCache.cs index abd06c8bc..9424f63e3 100644 --- a/Source.DataCache/MDLCache.cs +++ b/Source.DataCache/MDLCache.cs @@ -881,7 +881,8 @@ public void MarkFrame() { } public bool PreloadModel(MDLHandle_t handle) { - throw new NotImplementedException(); + // TODO!! + return false; } public int Release(MDLHandle_t handle) { diff --git a/Source.Dedicated/Source.Dedicated.csproj b/Source.Dedicated/Source.Dedicated.csproj index dba724568..fa687ae81 100644 --- a/Source.Dedicated/Source.Dedicated.csproj +++ b/Source.Dedicated/Source.Dedicated.csproj @@ -33,5 +33,7 @@ + + diff --git a/Source.Engine/CdllEngineInterface.cs b/Source.Engine/CdllEngineInterface.cs index 1d22fe150..9865f6ecf 100644 --- a/Source.Engine/CdllEngineInterface.cs +++ b/Source.Engine/CdllEngineInterface.cs @@ -243,9 +243,7 @@ public bool IsStreaming(AudioSource? audioSource) { throw new NotImplementedException(); } - public ReadOnlySpan Key_BindingForKey(ButtonCode code) { - throw new NotImplementedException(); - } + public ReadOnlySpan Key_BindingForKey(ButtonCode code) => Key.BindingForKey(code); public void StartKeyTrapMode() => Key.StartTrapMode(); diff --git a/Source.Engine/DebugOverlay.cs b/Source.Engine/DebugOverlay.cs index c394aa05e..8ab5d6703 100644 --- a/Source.Engine/DebugOverlay.cs +++ b/Source.Engine/DebugOverlay.cs @@ -122,6 +122,53 @@ public override void Reset() { public bool NoDepthTest; } +public class OverlayBox2 : OverlayBase +{ + public override void Reset() { + base.Reset(); + Type = OverlayType.Box2; + } + public Vector3 Origin; + public Vector3 Mins; + public Vector3 Maxs; + public Vector3 Angles; + public Color EdgeColor; + public Color FaceColor; +} + +public class OverlaySphere : OverlayBase +{ + public override void Reset() { + base.Reset(); + Type = OverlayType.Sphere; + } + public Vector3 Origin; + public float Radius; + public int Theta; + public int Phi; + public int R; + public int G; + public int B; + public int A; +} + +public class OverlaySweptBox : OverlayBase +{ + public override void Reset() { + base.Reset(); + Type = OverlayType.SweptBox; + } + public Vector3 Start; + public Vector3 End; + public Vector3 Mins; + public Vector3 Maxs; + public QAngle Angles; + public int R; + public int G; + public int B; + public int A; +} + public class DebugOverlay : IVDebugOverlay { private InlineArray1024 Text; @@ -165,15 +212,96 @@ public void AddBoxOverlay(in Vector3 origin, in Vector3 mins, in Vector3 maxs, i } public void AddBoxOverlay2(in Vector3 origin, in Vector3 mins, in Vector3 max, in QAngle orientation, in Color faceColor, in Color edgeColor, float duration) { - throw new NotImplementedException(); + if (cl.IsPaused()) + return; + + lock (s_OverlayMutex) { + OverlayBox2 new_overlay = OverlayBase.New(); + + new_overlay.Origin = origin; + + new_overlay.Mins[0] = mins[0]; + new_overlay.Mins[1] = mins[1]; + new_overlay.Mins[2] = mins[2]; + + new_overlay.Maxs[0] = max[0]; + new_overlay.Maxs[1] = max[1]; + new_overlay.Maxs[2] = max[2]; + + new_overlay.Angles = orientation; + + new_overlay.FaceColor = faceColor; + new_overlay.EdgeColor = edgeColor; + + new_overlay.SetEndTime(duration); + + new_overlay.NextOverlay = s_pOverlays; + s_pOverlays = new_overlay; + } + } + + static bool GetEntityOriginClientOrServer(int ent_num, out Vector3 origin) { + lock (s_OverlayMutex) { + origin = default; + + if (sv.IsActive()) { + Edict? e = sv.Edicts![ent_num]; + if (e != null) { + IServerEntity? serverEntity = e.GetIServerEntity(); + if (serverEntity != null) + CM.WorldSpaceCenter(serverEntity.GetCollideable()!, out origin); + + return true; + } + } + else { + IClientEntity? clent = entitylist.GetClientEntity(ent_num); + if (clent != null) { + CM.WorldSpaceCenter(clent.GetCollideable()!, out origin); + return true; + } + } + + return false; + } } public void AddEntityTextOverlay(int ent_index, int line_offset, float duration, int r, int g, int b, int a, ReadOnlySpan text) { - throw new NotImplementedException(); + if (cl.IsPaused()) + return; + + lock (s_OverlayMutex) { + OverlayText new_overlay = new(); + + GetEntityOriginClientOrServer(ent_index, out Vector3 myPos); + + MathLib.VectorCopy(myPos, out new_overlay.Origin); + strcpy(new_overlay.Text, text); + new_overlay.UseOrigin = true; + new_overlay.LineOffset = line_offset; + new_overlay.SetEndTime(duration); + new_overlay.R = r; + new_overlay.G = g; + new_overlay.B = b; + new_overlay.A = a; + + new_overlay.NextOverlayText = s_pOverlayText; + s_pOverlayText = new_overlay; + } } + static Vector3 s_vGridPosition; + public void AddGridOverlay(in Vector3 origin) { - throw new NotImplementedException(); + if (cl.IsPaused()) + return; + + lock (s_OverlayMutex) { + s_vGridPosition[0] = origin[0]; + s_vGridPosition[1] = origin[1]; + s_vGridPosition[2] = origin[2]; + s_bDrawGrid = true; + } } public void AddLineOverlay(in Vector3 origin, in Vector3 dest, int r, int g, int b, bool noDepthTest, float duration) { @@ -201,15 +329,84 @@ public void AddLineOverlay(in Vector3 origin, in Vector3 dest, int r, int g, int } public void AddLineOverlayAlpha(in Vector3 origin, in Vector3 dest, int r, int g, int b, int a, bool noDepthTest, float duration) { - throw new NotImplementedException(); + if (cl.IsPaused()) + return; + + lock (s_OverlayMutex) { + OverlayLine new_overlay = OverlayBase.New(); + + new_overlay.Start = origin; + new_overlay.End = dest; + + new_overlay.R = r; + new_overlay.G = g; + new_overlay.B = b; + new_overlay.A = a; + + new_overlay.NoDepthTest = noDepthTest; + + new_overlay.SetEndTime(duration); + + new_overlay.NextOverlay = s_pOverlays; + s_pOverlays = new_overlay; + } } - public void AddScreenTextOverlay(float flXPos, float flYPos, float duration, int r, int g, int b, int a, ReadOnlySpan text) { - // throw new NotImplementedException(); + public void AddScreenTextOverlay(float flXPos, float flYPos, int line_offset, float duration, int r, int g, int b, int a, ReadOnlySpan text) { + if (cl.IsPaused()) + return; + + lock (s_OverlayMutex) { + OverlayText new_overlay = new(); + + strcpy(new_overlay.Text, text); + new_overlay.XPos = flXPos; + new_overlay.YPos = flYPos; + new_overlay.UseOrigin = false; + new_overlay.LineOffset = line_offset; + new_overlay.SetEndTime(duration); + new_overlay.R = r; + new_overlay.G = g; + new_overlay.B = b; + new_overlay.A = a; + + new_overlay.NextOverlayText = s_pOverlayText; + s_pOverlayText = new_overlay; + } } + public void AddScreenTextOverlay(float flXPos, float flYPos, float duration, int r, int g, int b, int a, ReadOnlySpan text) => AddScreenTextOverlay(flXPos, flYPos, 0, duration, r, g, b, a, text); + public void AddSweptBoxOverlay(in Vector3 start, in Vector3 end, in Vector3 mins, in Vector3 max, in QAngle angles, int r, int g, int b, int a, float flDuration) { - throw new NotImplementedException(); + if (cl.IsPaused()) + return; + + lock (s_OverlayMutex) { + OverlaySweptBox new_overlay = OverlayBase.New(); + + new_overlay.Start = start; + new_overlay.End = end; + + new_overlay.Mins[0] = mins[0]; + new_overlay.Mins[1] = mins[1]; + new_overlay.Mins[2] = mins[2]; + + new_overlay.Maxs[0] = max[0]; + new_overlay.Maxs[1] = max[1]; + new_overlay.Maxs[2] = max[2]; + + new_overlay.Angles = angles; + + new_overlay.R = r; + new_overlay.G = g; + new_overlay.B = b; + new_overlay.A = a; + + new_overlay.SetEndTime(flDuration); + + new_overlay.NextOverlay = s_pOverlays; + s_pOverlays = new_overlay; + } } public void AddTextOverlay(in Vector3 origin, float duration, ReadOnlySpan text) { @@ -256,18 +453,33 @@ public void AddTextOverlay(in Vector3 origin, int line_offset, float duration, R } } - public void AddTextOverlay(in Vector3 origin, int line_offset, float duration, int r, int g, int b, int a, ReadOnlySpan text) { - throw new NotImplementedException(); - } + public void AddTextOverlay(in Vector3 origin, int line_offset, float duration, int r, int g, int b, int a, ReadOnlySpan text) { } public void AddTextOverlayRGB(in Vector3 origin, int line_offset, float duration, float r, float g, float b, float alpha, ReadOnlySpan text) { - throw new NotImplementedException(); - } + if (cl.IsPaused()) + return; - public void AddTextOverlayRGB(in Vector3 origin, int line_offset, float duration, int r, int g, int b, int a, ReadOnlySpan text) { - throw new NotImplementedException(); + lock (s_OverlayMutex) { + OverlayText new_overlay = new(); + + MathLib.VectorCopy(origin, out new_overlay.Origin); + strcpy(new_overlay.Text, text); + new_overlay.UseOrigin = true; + new_overlay.LineOffset = line_offset; + new_overlay.SetEndTime(duration); + new_overlay.R = (int)Math.Clamp(r * 255.0f, 0.0f, 255.0f); + new_overlay.G = (int)Math.Clamp(g * 255.0f, 0.0f, 255.0f); + new_overlay.B = (int)Math.Clamp(b * 255.0f, 0.0f, 255.0f); + new_overlay.A = (int)Math.Clamp(alpha * 255.0f, 0.0f, 255.0f); + new_overlay.UseOrigin = true; + + new_overlay.NextOverlayText = s_pOverlayText; + s_pOverlayText = new_overlay; + } } + public void AddTextOverlayRGB(in Vector3 origin, int line_offset, float duration, int r, int g, int b, int a, ReadOnlySpan text) => AddTextOverlayRGB(origin, line_offset, duration, r * 1.0f / 255.0f, g * 1.0f / 255.0f, b * 1.0f / 255.0f, a * 1.0f / 255.0f, text); + public void AddTriangleOverlay(in Vector3 p1, in Vector3 p2, in Vector3 p3, int r, int g, int b, int a, bool noDepthTest, float duration) { if (cl.IsPaused()) return; @@ -373,8 +585,55 @@ public static void Draw3DOverlays() { DrawAllOverlays(); - // if (s_bDrawGrid) - // DrawGridOverlay(); + if (s_bDrawGrid) + DrawGridOverlay(); + } + } + + static int gridSpacing = 100; + static int numHorzSpaces = 16; + static int numVertSpaces = 3; + + static void DrawGridOverlay() { + lock (s_OverlayMutex) { + Vector3 startGrid; + startGrid.X = gridSpacing * ((int)s_vGridPosition[0] / gridSpacing); + startGrid.Y = gridSpacing * ((int)s_vGridPosition[1] / gridSpacing); + startGrid.Z = s_vGridPosition[2]; + + startGrid[0] -= (numHorzSpaces / 2) * gridSpacing; + startGrid[1] -= (numHorzSpaces / 2) * gridSpacing; + + Vector3 color = new(20, 180, 190); + for (int i = 1; i < numVertSpaces + 1; i++) { + MathLib.VectorCopy(startGrid, out Vector3 startLine); + for (int j = 0; j < numHorzSpaces + 1; j++) { + MathLib.VectorCopy(startLine, out Vector3 endLine); + endLine[0] += gridSpacing * numHorzSpaces; + renderUtils.RenderLine(startLine, endLine, new Color((int)color.X, (int)color.Y, (int)color.Z, 255), true); + + MathLib.VectorCopy(startLine, out Vector3 bottomStartLine); + for (int k = 0; k < numHorzSpaces + 1; k++) { + MathLib.VectorCopy(bottomStartLine, out Vector3 bottomEndLine); + bottomEndLine[2] -= gridSpacing; + renderUtils.RenderLine(bottomStartLine, bottomEndLine, new Color((int)color.X, (int)color.Y, (int)color.Z, 255), true); + bottomStartLine[0] += gridSpacing; + } + startLine[1] += gridSpacing; + } + + MathLib.VectorCopy(startGrid, out startLine); + for (int j = 0; j < numHorzSpaces + 1; j++) { + MathLib.VectorCopy(startLine, out Vector3 endLine); + + endLine[1] += gridSpacing * numHorzSpaces; + renderUtils.RenderLine(startLine, endLine, new Color((int)color.X, (int)color.Y, (int)color.Z, 255), true); + startLine[0] += gridSpacing; + } + color *= 0.7f; + startGrid[2] -= gridSpacing; + } + s_bDrawGrid = false; } } public static void DrawAllOverlays() { @@ -411,7 +670,7 @@ private static void DrawOverlay(OverlayBase overlay) { switch (overlay.Type) { case OverlayType.Line: OverlayLine line = (OverlayLine)overlay; - renderUtils.RenderLine(line.Start, line.End, new Color(line.R, line.G, line.B, line.A), line.NoDepthTest); + renderUtils.RenderLine(line.Start, line.End, new Color(line.R, line.G, line.B, line.A), !line.NoDepthTest); break; case OverlayType.Box: OverlayBox box = (OverlayBox)overlay; @@ -421,9 +680,28 @@ private static void DrawOverlay(OverlayBase overlay) { renderUtils.RenderWireframeBox(box.Origin, box.Angles, box.Mins, box.Maxs, new Color(box.R, box.G, box.B, 255), true); break; + case OverlayType.Box2: + OverlayBox2 box2 = (OverlayBox2)overlay; + + if (box2.FaceColor.A > 0) + renderUtils.RenderBox(box2.Origin, box2.Angles, box2.Mins, box2.Maxs, box2.FaceColor, false); + + if (box2.EdgeColor.A > 0) + renderUtils.RenderWireframeBox(box2.Origin, box2.Angles, box2.Mins, box2.Maxs, box2.EdgeColor, false); + break; +#if !SWDS + case OverlayType.Sphere: + OverlaySphere sphere = (OverlaySphere)overlay; + renderUtils.RenderSphere(sphere.Origin, sphere.Radius, sphere.Theta, sphere.Phi, new Color(sphere.R, sphere.G, sphere.B, sphere.A), MatSys.MaterialAmbientCube!); + break; +#endif + case OverlayType.SweptBox: + OverlaySweptBox sweptBox = (OverlaySweptBox)overlay; + renderUtils.RenderWireframeSweptBox(sweptBox.Start, sweptBox.End, sweptBox.Angles, sweptBox.Mins, sweptBox.Maxs, new Color(sweptBox.R, sweptBox.G, sweptBox.B, sweptBox.A), true); + break; case OverlayType.Triangle: OverlayTriangle tri = (OverlayTriangle)overlay; - renderUtils.RenderTriangle(tri.P1, tri.P2, tri.P3, new Color(tri.R, tri.G, tri.B, tri.A), tri.NoDepthTest); + renderUtils.RenderTriangle(tri.P1, tri.P2, tri.P3, new Color(tri.R, tri.G, tri.B, tri.A), !tri.NoDepthTest); break; } } @@ -439,8 +717,17 @@ private static void DestroyOverlay(OverlayBase overlay) { OverlayBase.Free(box); break; case OverlayType.Box2: + OverlayBox2 box2 = (OverlayBox2)overlay; + OverlayBase.Free(box2); + break; case OverlayType.Sphere: + OverlaySphere sphere = (OverlaySphere)overlay; + OverlayBase.Free(sphere); + break; case OverlayType.SweptBox: + OverlaySweptBox sweptBox = (OverlaySweptBox)overlay; + OverlayBase.Free(sweptBox); + break; case OverlayType.Triangle: OverlayTriangle tri = (OverlayTriangle)overlay; OverlayBase.Free(tri); diff --git a/Source.Engine/EngineTrace.cs b/Source.Engine/EngineTrace.cs index 4cb07e67e..a799ec356 100644 --- a/Source.Engine/EngineTrace.cs +++ b/Source.Engine/EngineTrace.cs @@ -526,7 +526,7 @@ public void TraceRay(in Ray ray, Mask mask, scoped ref Filter traceFilte trace.FractionLeftSolid *= flWorldFractionLeftSolidScale; } - public void HandleEntityToCollideable(IHandleEntity? handleEntity, out ICollideable? collide, out ReadOnlySpan debugName) { + public virtual void HandleEntityToCollideable(IHandleEntity? handleEntity, out ICollideable? collide, out ReadOnlySpan debugName) { collide = StaticPropMgr().GetStaticProp(handleEntity); if (collide != null) { debugName = "static prop"; @@ -635,6 +635,27 @@ public class EngineTraceClient : EngineTrace return unk!.GetCollideable(); } + public override void HandleEntityToCollideable(IHandleEntity? handleEntity, out ICollideable? collide, out ReadOnlySpan debugName) { + collide = StaticPropMgr().GetStaticProp(handleEntity); + if (collide != null) { + debugName = "static prop"; + return; + } + + IClientUnknown? unk = (IClientUnknown?)handleEntity; + if (unk == null) { + collide = null; + debugName = ""; + return; + } + + collide = unk.GetCollideable(); + debugName = "client entity"; + IClientNetworkable? network = unk.GetClientNetworkable(); + if (network != null && network.GetClientClass() != null) + debugName = network.GetClientClass()!.NetworkName; + } + public override void SetTraceEntity(ICollideable? collideable, ref Trace trace) { if (!trace.DidHit()) return; diff --git a/Source.Engine/GarrysMod/Get.cs b/Source.Engine/GarrysMod/Get.cs index bc043bf3d..2c1e4a308 100644 --- a/Source.Engine/GarrysMod/Get.cs +++ b/Source.Engine/GarrysMod/Get.cs @@ -139,7 +139,11 @@ public void Initialize(IFileSystem fileSystem) { introScreen = appSystemFactory.GetRequiredService(); materials = appSystemFactory.GetRequiredService(); resources = appSystemFactory.GetRequiredService(); - // todo: audio + audio = appSystemFactory.GetService(); + if (audio == null) { + Msg("Couldn't locate library [gmod_audio] or couldn't find module [IGModAudio001]\n"); + Error("Couldn't Load Library 'gmod_audio' (looking for interface IGModAudio001)"); + } serverAddons = appSystemFactory.GetRequiredService(); if (html == null) { diff --git a/Source.Engine/MatSysInterface.cs b/Source.Engine/MatSysInterface.cs index 811289ce4..25b279db3 100644 --- a/Source.Engine/MatSysInterface.cs +++ b/Source.Engine/MatSysInterface.cs @@ -297,6 +297,7 @@ private void InitDebugMaterials() { MaterialWorldWireframe = GL_LoadMaterial("debug/debugworldwireframe", MaterialDefines.TEXTURE_GROUP_OTHER); MaterialWorldWireframeZBuffer = GL_LoadMaterial("debug/debugworldwireframezbuffer", MaterialDefines.TEXTURE_GROUP_OTHER); MaterialShadowBuild = GL_LoadMaterial("engine/shadowbuild", MaterialDefines.TEXTURE_GROUP_OTHER); + MaterialAmbientCube = GL_LoadMaterial("debug/debugambientcube", MaterialDefines.TEXTURE_GROUP_OTHER); // TODO: the rest of these important materials #endif } @@ -997,6 +998,7 @@ public void WorldStaticMeshDestroy() { public IMaterial? MaterialWorldWireframe; public IMaterial? MaterialWorldWireframeZBuffer; public IMaterial? MaterialShadowBuild; + public IMaterial? MaterialAmbientCube; #endif public void GL_UnloadMaterial(IMaterial? material) => material?.DecrementReferenceCount(); diff --git a/Source.Engine/RenderUtils.cs b/Source.Engine/RenderUtils.cs index 7f1217352..5d6ac6724 100644 --- a/Source.Engine/RenderUtils.cs +++ b/Source.Engine/RenderUtils.cs @@ -378,4 +378,213 @@ internal void RenderWireframeBox(in Vector3 origin, in Vector3 angles, in Vector meshBuilder.End(); pMesh.Draw(); } + + internal void RenderSphere(in Vector3 center, float radius, int theta, int phi, in Color c, IMaterial material) { + InitializeStandardMaterials(); + + using MatRenderContextPtr renderContext = new(materials); + + byte chRed = c.R; + byte chGreen = c.G; + byte chBlue = c.B; + byte chAlpha = c.A; + + int triangles = 2 * theta * (phi - 1); + int indices = 2 * (theta + 1) * (phi - 1); + if (triangles == 0) + return; + + renderContext.Bind(material); + IMesh mesh = renderContext.GetDynamicMesh(); + MeshBuilder meshBuilder = new(); + + meshBuilder.Begin(mesh, MaterialPrimitiveType.TriangleStrip, triangles, indices); + + float OONPhi = 1.0f / (phi - 1); + float OONTheta = 1.0f / (theta - 1); + + int i, j; + for (i = 0; i < phi; ++i) { + for (j = 0; j < theta; ++j) { + float u = j / (float)(theta - 1); + float v = i / (float)(phi - 1); + float t = 2.0f * MathF.PI * u; + float p = MathF.PI * v; + + (float sinTheta, float cosTheta) = MathF.SinCos(t); + (float sinPhi, float cosPhi) = MathF.SinCos(p); + + Vector3 pos; + pos.X = radius * sinPhi * cosTheta; + pos.Y = radius * sinPhi * sinTheta; + pos.Z = radius * cosPhi; + + Vector3 normal = pos; + MathLib.VectorNormalize(ref normal); + + pos += center; + + meshBuilder.Position3f(pos.X, pos.Y, pos.Z); + meshBuilder.Normal3f(normal.X, normal.Y, normal.Z); + meshBuilder.Color4ub(chRed, chGreen, chBlue, chAlpha); + meshBuilder.TexCoord2f(0, j * OONTheta, i * OONPhi); + meshBuilder.AdvanceVertex(); + } + } + + int idx = 0; + for (i = 0; i < phi - 1; ++i) { + for (j = 0; j < theta; ++j) { + idx = theta * i + j; + + meshBuilder.Index((ushort)(idx + theta)); + meshBuilder.AdvanceIndex(); + + meshBuilder.Index((ushort)idx); + meshBuilder.AdvanceIndex(); + } + + if (i < phi - 2) { + meshBuilder.Index((ushort)idx); + meshBuilder.AdvanceIndex(); + + meshBuilder.Index((ushort)(idx + theta + 1)); + meshBuilder.AdvanceIndex(); + } + } + + meshBuilder.End(); + mesh.Draw(); + } + + internal void RenderSphere(in Vector3 center, float radius, int theta, int phi, in Color c, bool zBuffer) { + IMaterial material = zBuffer ? VertexColor : VertexColorIgnoreZ; + Color actual = new(c.R, c.G, c.B, c.A); + RenderSphere(center, radius, theta, phi, actual, material); + } + + static void DrawAxes(in Vector3 origin, Span pts, int idx, in Color c, ref MeshBuilder meshBuilder) { + MathLib.VectorAdd(pts[idx], origin, out Vector3 start); + meshBuilder.Position3fv(start); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + + int endidx = (idx & 0x1) != 0 ? idx - 1 : idx + 1; + MathLib.VectorAdd(pts[endidx], origin, out Vector3 temp); + meshBuilder.Position3fv(temp); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + + meshBuilder.Position3fv(start); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + + endidx = (idx & 0x2) != 0 ? idx - 2 : idx + 2; + MathLib.VectorAdd(pts[endidx], origin, out temp); + meshBuilder.Position3fv(temp); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + + meshBuilder.Position3fv(start); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + + endidx = (idx & 0x4) != 0 ? idx - 4 : idx + 4; + MathLib.VectorAdd(pts[endidx], origin, out temp); + meshBuilder.Position3fv(temp); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + } + + static void DrawExtrusionFace(in Vector3 start, in Vector3 end, Span pts, int idx1, int idx2, in Color c, ref MeshBuilder meshBuilder) { + MathLib.VectorAdd(pts[idx1], start, out Vector3 temp); + meshBuilder.Position3fv(temp); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + + MathLib.VectorAdd(pts[idx2], start, out temp); + meshBuilder.Position3fv(temp); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + + meshBuilder.Position3fv(temp); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + + MathLib.VectorAdd(pts[idx2], end, out temp); + meshBuilder.Position3fv(temp); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + + meshBuilder.Position3fv(temp); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + + MathLib.VectorAdd(pts[idx1], end, out temp); + meshBuilder.Position3fv(temp); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + + meshBuilder.Position3fv(temp); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + + MathLib.VectorAdd(pts[idx1], start, out temp); + meshBuilder.Position3fv(temp); + meshBuilder.Color4ub(c.R, c.G, c.B, c.A); + meshBuilder.AdvanceVertex(); + } + + internal void RenderWireframeSweptBox(in Vector3 start, in Vector3 end, in QAngle angles, in Vector3 mins, in Vector3 maxs, in Color c, bool zBuffer) { + InitializeStandardMaterials(); + + using MatRenderContextPtr renderContext = new(materials); + renderContext.Bind(zBuffer ? Wireframe : WireframeIgnoreZ); + + Color actual = new(c.R, c.G, c.B, c.A); + + MathLib.AngleMatrix(angles, out Matrix3x4 rotateMatrix); + + IMesh mesh = renderContext.GetDynamicMesh(); + MeshBuilder meshBuilder = new(); + meshBuilder.Begin(mesh, MaterialPrimitiveType.Lines, 30); + + MathLib.VectorSubtract(end, start, out Vector3 delta); + + Vector3 temp; + Span pts = stackalloc Vector3[8]; + Span dot = stackalloc float[8]; + int minidx = 0; + for (int i = 0; i < 8; ++i) { + temp.X = (i & 0x1) != 0 ? maxs[0] : mins[0]; + temp.Y = (i & 0x2) != 0 ? maxs[1] : mins[1]; + temp.Z = (i & 0x4) != 0 ? maxs[2] : mins[2]; + + MathLib.VectorRotate(temp, rotateMatrix, out pts[i]); + + dot[i] = MathLib.DotProduct(pts[i], delta); + if (dot[i] < dot[minidx]) + minidx = i; + } + + int maxidx = minidx ^ 0x7; + + DrawAxes(start, pts, minidx, actual, ref meshBuilder); + DrawAxes(end, pts, maxidx, actual, ref meshBuilder); + + for (int j = 0; j < 3; ++j) { + int dirflag1 = 1 << ((j + 1) % 3); + int dirflag2 = 1 << ((j + 2) % 3); + + int idx1, idx2, idx3; + idx1 = (minidx & dirflag1) != 0 ? minidx - dirflag1 : minidx + dirflag1; + idx2 = (minidx & dirflag2) != 0 ? minidx - dirflag2 : minidx + dirflag2; + idx3 = (minidx & dirflag2) != 0 ? idx1 - dirflag2 : idx1 + dirflag2; + + DrawExtrusionFace(start, end, pts, idx1, idx3, actual, ref meshBuilder); + DrawExtrusionFace(start, end, pts, idx2, idx3, actual, ref meshBuilder); + } + meshBuilder.End(); + mesh.Draw(); + } } diff --git a/Source.GUI.Controls/TextEntry.cs b/Source.GUI.Controls/TextEntry.cs index f75829bab..536e369f6 100644 --- a/Source.GUI.Controls/TextEntry.cs +++ b/Source.GUI.Controls/TextEntry.cs @@ -573,7 +573,12 @@ public override void OnCursorMoved(int x, int y) { public override void OnMousePressed(ButtonCode code) { #if GMOD_DLL - // todo: OnMousePressed hook + if (PushLuaHook(LUA_POOLEDSTRING.OnMousePressed)) { + PushLua(Lua!, LuaType.Panel); + Lua!.PushNumber((int)code); + if (Lua.CallInternalGetBool(2)) + return; + } #endif if (code == ButtonCode.MouseLeft) { bool keepChecking = SelectCheck(true); diff --git a/Source.GUI/VGuiInput.cs b/Source.GUI/VGuiInput.cs index 629e0a38a..adb04f349 100644 --- a/Source.GUI/VGuiInput.cs +++ b/Source.GUI/VGuiInput.cs @@ -308,6 +308,10 @@ public nint GetIMEWindow() { return context.MouseCapture; } + public IPanel? GetMouseFocus() { + return GetInputContext(Context).MouseFocus; + } + public IPanel? GetMouseOver() { return GetInputContext(Context).MouseOver; } diff --git a/Source.Launcher/Program.cs b/Source.Launcher/Program.cs index e06fadd00..2bdb5a1d4 100644 --- a/Source.Launcher/Program.cs +++ b/Source.Launcher/Program.cs @@ -1,3 +1,4 @@ +using Game.BASS; using Game.Client; using Game.Lua; using Game.MenuSystem; @@ -87,6 +88,7 @@ public void Boot() { #if GMOD_DLL .WithComponent() .WithComponent() + .WithComponent(GMod_Audio.g_GModAudio) .WithKeyedComponent("html_chromium", HTML.CEF.CefSystem.g_pHtmlSystem) .WithKeyedComponent("html_stub", HTML.Stub.StubSystem.g_pHtmlSystem) #endif diff --git a/Source.Launcher/Source.Launcher.csproj b/Source.Launcher/Source.Launcher.csproj index 300f20504..c7bf5fa99 100644 --- a/Source.Launcher/Source.Launcher.csproj +++ b/Source.Launcher/Source.Launcher.csproj @@ -21,6 +21,7 @@ + @@ -57,5 +58,7 @@ + + \ No newline at end of file diff --git a/Source.MaterialSystem/MatQueuedMesh.cs b/Source.MaterialSystem/MatQueuedMesh.cs index 266ca1d4d..4a19ba5a8 100644 --- a/Source.MaterialSystem/MatQueuedMesh.cs +++ b/Source.MaterialSystem/MatQueuedMesh.cs @@ -146,7 +146,7 @@ IMesh MST_SetupDynamicMesh(in MST_MeshInfo info) { if (verticesToLock != 0 && desc.Vertex.ActualVertexSize != 0) MST_CopyDynamicVB(in desc, info.VertexData, info.VertexCount * info.VertexSizeInBytes); - if (indicesToLock != 0 && info.IndexData != ScratchIndexBuffer && desc.Index.IndexSize != 0) + if (indicesToLock != 0 && info.IndexData != null && info.IndexData != ScratchIndexBuffer && desc.Index.IndexSize != 0) MST_CopyDynamicIB(in desc, info.IndexData, info.IndexCount); dynamicMesh.UnlockMesh(verticesToLock, indicesToLock, ref desc); @@ -311,7 +311,6 @@ public void QueueBuild() { IndexOverride = IndexOverride, PrimitiveType = Type }; - Assert(info.IndexData != null || Indices == 0); CallQueue.QueueCall(static s => s.Mesh.MST_BuildDynamicBuffers(in s.Info), (Mesh: this, Info: info)); CanSetAuxMeshes = true; diff --git a/Source.NET.slnx b/Source.NET.slnx index a3f97c6c4..eddedfe83 100644 --- a/Source.NET.slnx +++ b/Source.NET.slnx @@ -136,6 +136,9 @@ + + + @@ -161,8 +164,7 @@ - - + diff --git a/Source.ShaderAPI.Gl46/DynamicMeshGl46.cs b/Source.ShaderAPI.Gl46/DynamicMeshGl46.cs index 72b66591c..fe2c50374 100644 --- a/Source.ShaderAPI.Gl46/DynamicMeshGl46.cs +++ b/Source.ShaderAPI.Gl46/DynamicMeshGl46.cs @@ -69,9 +69,15 @@ public override void LockMesh(int vertexCount, int indexCount, ref MeshDesc desc if (IndexOverride || HasFlexMesh()) desc.Vertex.FirstVertex -= FirstVertex; - int firstIndex = Lock(false, -1, indexCount, ref desc.Index); - if (FirstIndex < 0) - FirstIndex = firstIndex; + if (Type != MaterialPrimitiveType.Points) { + int firstIndex = Lock(false, -1, indexCount, ref desc.Index); + if (FirstIndex < 0) + FirstIndex = firstIndex; + } + else { + desc.Index.Indices = ScratchIndexBuffer; + desc.Index.IndexSize = 0; + } base.Locked = true; } diff --git a/Source.ShaderAPI.Gl46/IndexBufferGl46.cs b/Source.ShaderAPI.Gl46/IndexBufferGl46.cs index 9caa82d96..4e602982a 100644 --- a/Source.ShaderAPI.Gl46/IndexBufferGl46.cs +++ b/Source.ShaderAPI.Gl46/IndexBufferGl46.cs @@ -1,4 +1,5 @@ using Source.Common.MaterialSystem; +using Source.Common.ShaderAPI; using System.Runtime.InteropServices; namespace Source.ShaderAPI.Gl46; @@ -18,6 +19,8 @@ public unsafe class IndexBufferGl46 : IDisposable internal bool ExternalMemory; internal bool SoftwareVertexProcessing; internal bool LateCreateShouldDiscard; + internal bool LateCreate; + internal IShaderUtil? ShaderUtil; int ibo = -1; int lastBufferSize = -1; @@ -36,8 +39,10 @@ public unsafe void RecomputeIBO() { return; } + bool renderThreadSafe = ShaderUtil == null || ShaderUtil.IsRenderThreadSafe(); + // Create the IBO if it doesn't exist - if (ibo == -1) + if (ibo == -1 && renderThreadSafe) ibo = (int)glCreateBuffer(); // Deallocate if Sysmembuffer != null and we cant fit in what we already allocated. @@ -48,8 +53,10 @@ public unsafe void RecomputeIBO() { } lastBufferSize = BufferSize; SysmemBuffer = NativeMemory.AllocZeroed((nuint)BufferSize); - glNamedBufferData((uint)ibo, BufferSize, null, Dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); - + if (renderThreadSafe) + glNamedBufferData((uint)ibo, BufferSize, null, Dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); + else + LateCreate = true; } if (SysmemBuffer == null) { @@ -65,6 +72,12 @@ public unsafe void RecomputeIBO() { public short* Lock(bool readOnly, int indexCount, out int startIndex, int firstIndex) { Assert(!Locked); + if (indexCount > IndexCount) { + startIndex = 0; + Error($"too many indices for index buffer. . tell a programmer ({indexCount}>{IndexCount})\n"); + return null; + } + bool discard = false; if (Dynamic) { if (Position == 0 || Flush || !HasEnoughRoom(indexCount)) { @@ -99,6 +112,9 @@ public unsafe void RecomputeIBO() { return (short*)ring!.Memory + position; } + if (position + indexCount > IndexCount) + return null; + if (SysmemBuffer == null) { RecomputeIBO(); } @@ -117,8 +133,10 @@ public void Unlock(int indexCount) { if (indexCount > 0) { if (Dynamic) Written = true; - else + else if (!LateCreate && (ShaderUtil == null || ShaderUtil.IsRenderThreadSafe())) glNamedBufferSubData((uint)ibo, LockedPosition * 2, indexCount * 2, (short*)SysmemBuffer + LockedPosition); + else + LateCreate = true; } Position += indexCount; Locked = false; @@ -150,8 +168,10 @@ public void ModifyUnlock(int firstIndex, int indexCount) { if (indexCount > 0) { if (Dynamic) Written = true; - else + else if (!LateCreate && (ShaderUtil == null || ShaderUtil.IsRenderThreadSafe())) glNamedBufferSubData((uint)ibo, firstIndex * 2, indexCount * 2, (short*)SysmemBuffer + firstIndex); + else + LateCreate = true; } Locked = false; } @@ -172,7 +192,8 @@ public void Dispose() { } } - public IndexBufferGl46(int count, bool dynamic = false) { + public IndexBufferGl46(int count, bool dynamic = false, IShaderUtil? shaderUtil = null) { + ShaderUtil = shaderUtil; Position = 0; Locked = false; Flush = true; @@ -189,7 +210,13 @@ public IndexBufferGl46(int count, bool dynamic = false) { } internal void HandleLateCreation() { + if (!LateCreate) + return; + if (ibo == -1) + ibo = (int)glCreateBuffer(); + glNamedBufferData((uint)ibo, BufferSize, SysmemBuffer, GL_STATIC_DRAW); + LateCreate = false; } internal uint IBO() => ring != null ? ring.Buffer : ibo > 0 ? (uint)ibo : throw new NullReferenceException("Index Buffer Object was null"); diff --git a/Source.ShaderAPI.Gl46/MeshGl46.cs b/Source.ShaderAPI.Gl46/MeshGl46.cs index 89578a931..6b26d4dca 100644 --- a/Source.ShaderAPI.Gl46/MeshGl46.cs +++ b/Source.ShaderAPI.Gl46/MeshGl46.cs @@ -180,7 +180,7 @@ public virtual VertexFormat GetVertexFormat() { } public virtual int IndexCount() { - throw new NotImplementedException(); + return IndexBuffer != null ? IndexBuffer.IndexCount : 0; } public virtual MaterialIndexFormat IndexFormat() { @@ -197,16 +197,32 @@ public void HandleLateCreation() { } public virtual bool Lock(int vertexCount, bool append, ref VertexDesc desc) { + Assert(!IsVBLocked); + + if (ShaderDevice.IsDeactivated() || vertexCount == 0) { + VertexBufferGl46.ComputeVertexDescription(null, 0, ref desc); + desc.FirstVertex = 0; + return false; + } + if (VertexBuffer == null) { int size = MeshMgr.VertexFormatSize(VertexFormat); - VertexBuffer = new VertexBufferGl46(VertexFormat, size, vertexCount, false); + VertexBuffer = new VertexBufferGl46(VertexFormat, size, vertexCount, false, ShaderUtil); } byte* vertexMemory = VertexBuffer.Lock(vertexCount, out desc.FirstVertex); - VertexBufferGl46.ComputeVertexDescription(vertexMemory, VertexFormat, ref desc); + if (vertexMemory == null) { + Assert(false); + Error($"failed to lock vertex buffer in MeshGl46.LockVertexBuffer: vertexCount={vertexCount}, firstVertex={desc.FirstVertex}\n"); + VertexBufferGl46.ComputeVertexDescription(null, 0, ref desc); + return false; + } + VertexBufferGl46.ComputeVertexDescription(vertexMemory, VertexFormat, ref desc); + IsVBLocked = true; return true; } + bool IsVBLocked; public virtual int Lock(bool readOnly, int firstIndex, int indexCount, ref IndexDesc desc) { if (ShaderDevice.IsDeactivated() || indexCount == 0) { @@ -215,10 +231,11 @@ public virtual int Lock(bool readOnly, int firstIndex, int indexCount, ref Index return 0; } - IndexBuffer ??= new IndexBufferGl46(indexCount, false); + IndexBuffer ??= new IndexBufferGl46(indexCount, false, ShaderUtil); desc.Indices = (ushort*)IndexBuffer.Lock(readOnly, indexCount, out int startIndex, firstIndex); if (desc.Indices == null) { + desc.Indices = ScratchIndexBuffer; desc.IndexSize = 0; Assert(false); Warning("Failed to lock index buffer...\n"); @@ -230,7 +247,7 @@ public virtual int Lock(bool readOnly, int firstIndex, int indexCount, ref Index return startIndex; } bool IsIBLocked; - static readonly ushort* ScratchIndexBuffer = (ushort*)NativeMemory.Alloc(6 * sizeof(ushort)); + protected static readonly ushort* ScratchIndexBuffer =(ushort*)NativeMemory.Alloc(6 * sizeof(ushort)); public virtual void LockMesh(int vertexCount, int indexCount, ref MeshDesc desc) { ShaderUtil.SyncMatrices(); @@ -258,7 +275,7 @@ public virtual void ModifyBegin(int firstVertex, int vertexCount, int firstIndex VertexBufferGl46.ComputeVertexDescription(vertexMemory, VertexFormat, ref desc.Vertex); if (indexCount > 0) { - IndexBuffer ??= new IndexBufferGl46(indexCount, false); + IndexBuffer ??= new IndexBufferGl46(indexCount, false, ShaderUtil); desc.Index.Indices = (ushort*)IndexBuffer.ModifyLock(firstIndex, indexCount, out int startIndex); desc.Index.IndexSize = 1; IsIBLocked = true; @@ -310,7 +327,10 @@ public virtual void SetPrimitiveType(MaterialPrimitiveType type) { } public virtual bool Unlock(int vertexCount, ref VertexDesc desc) { - VertexBuffer.Unlock(vertexCount); + if (!IsVBLocked) + return true; + VertexBuffer!.Unlock(vertexCount); + IsVBLocked = false; return true; } @@ -362,27 +382,28 @@ public virtual unsafe void RenderPass() { if (pPrim->NumIndices == 0) continue; - if (Type == MaterialPrimitiveType.Points || Type == MaterialPrimitiveType.InstancedQuads) { - throw new NotImplementedException(); + if (!bound) { + uint vao = ((ShaderAPIGl46)ShaderAPI).CurrentVertexDecl; + glVertexArrayVertexBuffer(vao, 0, VertexBuffer!.VBO(), 0, VertexBuffer.VertexSize); + if (colorMesh != null) + glVertexArrayVertexBuffer(vao, 1, colorMesh.VertexBuffer!.VBO(), ColorMeshVertOffsetInBytes, colorMesh.VertexBuffer.VertexSize); + + if (FlexVertexBuffer != null) + glVertexArrayVertexBuffer(vao, 2, FlexVertexBuffer.VBO(), FlexVertOffsetInBytes, FlexVertexBuffer.VertexSize); + else + glVertexArrayVertexBuffer(vao, 2, MeshMgr.GetZeroVertexBuffer(), 0, 4); + + if (IndexBuffer != null) + glVertexArrayElementBuffer(vao, IndexBuffer.IBO()); + bound = true; } + + if (Type == MaterialPrimitiveType.Points || Type == MaterialPrimitiveType.InstancedQuads) + glDrawArrays(Mode, (int)s_FirstVertex, pPrim->NumIndices); else { int numPrimitives = NumPrimitives(s_NumVertices, pPrim->NumIndices); CheckIndices(pPrim, numPrimitives); - if (!bound) { - uint vao = ((ShaderAPIGl46)ShaderAPI).CurrentVertexDecl; - glVertexArrayVertexBuffer(vao, 0, VertexBuffer!.VBO(), 0, VertexBuffer.VertexSize); - if (colorMesh != null) - glVertexArrayVertexBuffer(vao, 1, colorMesh.VertexBuffer!.VBO(), ColorMeshVertOffsetInBytes, colorMesh.VertexBuffer.VertexSize); - - if (FlexVertexBuffer != null) - glVertexArrayVertexBuffer(vao, 2, FlexVertexBuffer.VBO(), FlexVertOffsetInBytes, FlexVertexBuffer.VertexSize); - else - glVertexArrayVertexBuffer(vao, 2, MeshMgr.GetZeroVertexBuffer(), 0, 4); - - glVertexArrayElementBuffer(vao, IndexBuffer!.IBO()); - bound = true; - } glDrawElementsBaseVertex(Mode, pPrim->NumIndices, GL_UNSIGNED_SHORT, (void*)(pPrim->FirstIndex * 2), BaseVertexIndex); } } diff --git a/Source.ShaderAPI.Gl46/VertexBufferGl46.cs b/Source.ShaderAPI.Gl46/VertexBufferGl46.cs index 810940e0a..4d847f7b0 100644 --- a/Source.ShaderAPI.Gl46/VertexBufferGl46.cs +++ b/Source.ShaderAPI.Gl46/VertexBufferGl46.cs @@ -1,4 +1,5 @@ using Source.Common.MaterialSystem; +using Source.Common.ShaderAPI; using System.Runtime.InteropServices; @@ -22,6 +23,8 @@ public unsafe class VertexBufferGl46 : IDisposable internal bool SoftwareVertexProcessing; internal bool LateCreateShouldDiscard; internal bool Written; + internal bool LateCreate; + internal IShaderUtil? ShaderUtil; int vbo = -1; PersistentBufferRing? ring; @@ -32,7 +35,8 @@ public VertexBufferGl46(bool dynamic) { Dynamic = dynamic; } - public VertexBufferGl46(VertexFormat format, int vertexSize, int vertexCount, bool dynamic) { + public VertexBufferGl46(VertexFormat format, int vertexSize, int vertexCount, bool dynamic, IShaderUtil? shaderUtil = null) { + ShaderUtil = shaderUtil; VertexBufferFormat = format; VertexSize = vertexSize; VertexCount = vertexCount; @@ -146,8 +150,10 @@ public void RecomputeVBO() { return; } + bool renderThreadSafe = ShaderUtil == null || ShaderUtil.IsRenderThreadSafe(); + // Create the VBO if it doesn't exist - if (vbo == -1) + if (vbo == -1 && renderThreadSafe) vbo = (int)glCreateBuffer(); // Deallocate if Sysmembuffer != null and we cant fit in what we already allocated. if (BufferSize > lastBufferSize) { @@ -157,7 +163,10 @@ public void RecomputeVBO() { } lastBufferSize = BufferSize; SysmemBuffer = NativeMemory.AllocZeroed((nuint)BufferSize); - glNamedBufferData((uint)vbo, BufferSize, null, Dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); + if (renderThreadSafe) + glNamedBufferData((uint)vbo, BufferSize, null, Dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); + else + LateCreate = true; } } @@ -219,8 +228,10 @@ public void Unlock(int vertexCount) { if (bufferSize > 0) { if (Dynamic) Written = true; - else + else if (!LateCreate && (ShaderUtil == null || ShaderUtil.IsRenderThreadSafe())) glNamedBufferSubData((uint)vbo, lockOffset, bufferSize, (byte*)SysmemBuffer + lockOffset); + else + LateCreate = true; } Position = lockOffset + bufferSize; Locked = false; @@ -255,8 +266,10 @@ public void ModifyUnlock(int vertexCount) { if (vertexCount > 0) { if (Dynamic) Written = true; - else + else if (!LateCreate && (ShaderUtil == null || ShaderUtil.IsRenderThreadSafe())) glNamedBufferSubData((uint)vbo, modifyOffset, vertexCount * VertexSize, (byte*)SysmemBuffer + modifyOffset); + else + LateCreate = true; } Locked = false; } @@ -418,6 +431,12 @@ public void Dispose() { } internal void HandleLateCreation() { + if (!LateCreate) + return; + if (vbo == -1) + vbo = (int)glCreateBuffer(); + glNamedBufferData((uint)vbo, BufferSize, SysmemBuffer, GL_STATIC_DRAW); + LateCreate = false; } } diff --git a/Source.StudioRender/StudioRender.cs b/Source.StudioRender/StudioRender.cs index 291e5c162..2af761d4c 100644 --- a/Source.StudioRender/StudioRender.cs +++ b/Source.StudioRender/StudioRender.cs @@ -168,7 +168,7 @@ internal void DrawModelStaticProp(ref DrawModelInfo info, StudioRenderCtx RC, in } } - private void ComputePoseToWorld(Span poseToWorld, StudioHeader studioHdr, int boneMask, in Vector3 viewOrigin, Matrix3x4* pBoneToWorld) { + internal void ComputePoseToWorld(Span poseToWorld, StudioHeader studioHdr, int boneMask, in Vector3 viewOrigin, Matrix3x4* pBoneToWorld) { if ((studioHdr.Flags & StudioHdrFlags.StaticProp) != 0) { poseToWorld[0] = pBoneToWorld[0]; return; diff --git a/Source.StudioRender/StudioRenderContext.cs b/Source.StudioRender/StudioRenderContext.cs index 26bdcb7e2..e83c2f992 100644 --- a/Source.StudioRender/StudioRenderContext.cs +++ b/Source.StudioRender/StudioRenderContext.cs @@ -100,6 +100,107 @@ public void GetMaterialListFromBodyAndSkin(MDLHandle_t studio, int skin, int bod } } + public unsafe void GetTriangles(ref DrawModelInfo info, Span boneToWorld, GetTrianglesOutput output) { + output.MaterialBatches.Clear(); + + if (info.StudioHdr == null || info.HardwareData == null || info.HardwareData.NumLODs == 0 || info.HardwareData.LODs == null) + return; + + int lod = info.Lod; + int lastlod = info.HardwareData.NumLODs - 1; + + if (lod == Studio.USESHADOWLOD) + lod = lastlod; + else + lod = Math.Clamp(lod, 0, lastlod); + + if (lod < info.HardwareData.RootLOD) + lod = info.HardwareData.RootLOD; + + int skin = info.Skin; + if (skin >= info.StudioHdr.NumSkinFamilies) + skin = 0; + + Span skinRef = info.StudioHdr.SkinRef(0)[(skin * info.StudioHdr.NumSkinRef)..]; + + StudioMeshData[] studioMeshes = info.HardwareData.LODs[lod].MeshData!; + IMaterial[] materials = info.HardwareData.LODs[lod].Materials!; + + int boneMask = Studio.BONE_USED_BY_VERTEX_AT_LOD(lod); + fixed (Matrix3x4* pBoneToWorld = boneToWorld) + studioRenderImp.ComputePoseToWorld(output.PoseToWorld, info.StudioHdr, boneMask, RC.ViewOrigin, pBoneToWorld); + + for (int i = 0; i < info.StudioHdr.NumBodyParts; i++) { + studioRenderImp.R_StudioSetupModel(i, info.Body, out MStudioModel? model, info.StudioHdr); + + for (int k = 0; k < model!.NumMeshes; ++k) { + GetTrianglesMaterialBatch materialBatch = new(); + output.MaterialBatches.Add(materialBatch); + MStudioMesh mesh = model.Mesh(k); + + if (model.CacheVertexData(studioDataCache, info.StudioHdr) == null) + continue; + + MStudioMeshVertexData? vertData = mesh.GetVertexData(studioDataCache, info.StudioHdr); + Assert(vertData != null); + + for (int vertID = 0; vertID < mesh.NumVertices; vertID++) { + GetTrianglesVertex vert = default; + + vert.Position = vertData!.Position(vertID); + vert.Normal = vertData.Normal(vertID); + vert.TexCoord = vertData.TexCoord(vertID); + + if (vertData.HasTangentData()) + vert.TangentS = vertData.TangentS(vertID); + + ref MStudioBoneWeight vertexBoneWeight = ref vertData.BoneWeights(vertID); + vert.NumBones = vertexBoneWeight.NumBones; + for (int j = 0; j < vert.NumBones; j++) { + vert.BoneWeight = vert.BoneWeight.WithElement(j, vertexBoneWeight.Weight[j]); + vert.BoneIndex[j] = vertexBoneWeight.Bone[j]; + } + materialBatch.Verts.Add(vert); + } + + IMaterial material = materials[skinRef[mesh.Material]]; + Assert(material != null); + materialBatch.Material = material; + StudioMeshData meshData = studioMeshes[mesh.MeshID]; + if (meshData.NumGroup == 0) + continue; + + materialBatch.TriListIndices.Clear(); + + for (int stripGroupID = 0; stripGroupID < meshData.NumGroup; stripGroupID++) { + StudioMeshGroup meshGroup = meshData.MeshGroup![stripGroupID]; + + for (int stripID = 0; stripID < meshGroup.NumStrips; stripID++) { + OptimizedModel.StripHeader stripData = meshGroup.StripData![stripID]; + if ((stripData.Flags & OptimizedModel.StripHeaderFlags.IsTriList) != 0) { + for (int t = 0; t < stripData.NumIndices; t += 3) { + int idx = stripData.IndexOffset + t; + materialBatch.TriListIndices.Add(meshGroup.MeshIndex(idx)); + materialBatch.TriListIndices.Add(meshGroup.MeshIndex(idx + 1)); + materialBatch.TriListIndices.Add(meshGroup.MeshIndex(idx + 2)); + } + } + else { + Assert((stripData.Flags & OptimizedModel.StripHeaderFlags.IsTriStrip) != 0); + for (int t = 0; t < stripData.NumIndices - 2; ++t) { + int idx = stripData.IndexOffset + t; + int ccw = (t & 1) == 0 ? 1 : 0; + materialBatch.TriListIndices.Add(meshGroup.MeshIndex(idx)); + materialBatch.TriListIndices.Add(meshGroup.MeshIndex(idx + 1 + ccw)); + materialBatch.TriListIndices.Add(meshGroup.MeshIndex(idx + 2 - ccw)); + } + } + } + } + } + } + } + public void GetMaterialList(StudioHeader studioHDR, ref SpanList materials) { AssertMsg(studioHDR != null, "Don't ignore this assert! StudioRenderContext.GetMaterialList() has null studioHDR.");