diff --git a/.vscode/launch.json b/.vscode/launch.json index 932170ee1..5794ece59 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -8,6 +8,7 @@ "preLaunchTask": "build Source.Launcher", "program": "${workspaceFolder}/Build/Debug/Source.Launcher.dll", "cwd": "${workspaceFolder}/Build/Debug", + // "args": ["-noworkshop", "-noaddons"], "stopAtEntry": false }, { diff --git a/Game.Client/C_BaseAnimating.cs b/Game.Client/C_BaseAnimating.cs index aa7788d0e..f079bf282 100644 --- a/Game.Client/C_BaseAnimating.cs +++ b/Game.Client/C_BaseAnimating.cs @@ -1522,6 +1522,13 @@ private void UpdateBoneAttachments() { } + public virtual void RemoveFromPreviousBoneSetups() => PreviousBoneSetups.Remove(this); + + public int LookupBone(ReadOnlySpan name) { + Assert(GetModelPtr()); + return BoneSetup.Studio_BoneIndexByName(GetModelPtr(), name); + } + public int LookupAttachment(ReadOnlySpan attachmentName) { StudioHdr? hdr = GetModelPtr(); if (hdr == null) diff --git a/Game.Client/C_BaseEntity.cs b/Game.Client/C_BaseEntity.cs index c69bad800..f66ae2bf1 100644 --- a/Game.Client/C_BaseEntity.cs +++ b/Game.Client/C_BaseEntity.cs @@ -713,6 +713,14 @@ private static void RecvProxy_MoveType(ref readonly RecvProxyData data, object i DEFINE.FIELD(nameof(ProxyRandomValue), FieldType.Float ), ]); public virtual DataMap? GetPredDescMap() => PredMap; + public static readonly DataMap DataDesc = new(typeof(C_BaseEntity), [ + DEFINE.FIELD(nameof(ModelName), FieldType.String), + DEFINE.FIELD(nameof(AbsOrigin), FieldType.PositionVector), + DEFINE.FIELD(nameof(AbsRotation), FieldType.Vector), + // DEFINE.ARRAY(nameof(CoordinateFrame), FieldType.Float, 12), + DEFINE.FIELD(nameof(flags), FieldType.Integer), + ]); public virtual DataMap? GetDataDescMap() => DataDesc; + static readonly DynamicAccessor DA_Origin = FIELD.OF(nameof(Origin)); static readonly DynamicAccessor DA_Rotation = FIELD.OF(nameof(Rotation)); diff --git a/Game.Client/GarrysMod/C_GMOD_Player.cs b/Game.Client/GarrysMod/C_GMOD_Player.cs index 2948be022..78a235cab 100644 --- a/Game.Client/GarrysMod/C_GMOD_Player.cs +++ b/Game.Client/GarrysMod/C_GMOD_Player.cs @@ -97,6 +97,21 @@ public virtual void SetWeaponColor(in Vector3 color) { public override bool RestrictPlayerPitch() => (GModPlayerFlags & 16) == 0; public override bool CanAttack() => PressedWidget.Get() == null; + public C_BaseEntity? FindUseEntity() { + C_BaseEntity? ent = null; // todo: base.FindUseEntity() + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.FindUseEntity)) { + LuaEntity.Push_Entity(this); + LuaEntity.Push_Entity(ent); + if (gGM.CallReturns(2, 1)) { + ILuaObject ret = g_Lua!.GetReturn(0); + if (ret.GetType() == LuaType.Entity) + return (C_BaseEntity?)ret.GetEntity(); + return null; + } + } + return ent; + } + public override void UpdateClientSideAnimation() { if (Driving.Get() != null) { if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerDriveAnimate)) { diff --git a/Game.Client/GarrysMod/LuaPresets.cs b/Game.Client/GarrysMod/LuaPresets.cs index ef0a8b290..ee17e326d 100644 --- a/Game.Client/GarrysMod/LuaPresets.cs +++ b/Game.Client/GarrysMod/LuaPresets.cs @@ -1,3 +1,4 @@ +using Source; using Source.Common.Formats.Keyvalues; using Source.Common.GarrysMod.Lua; @@ -46,4 +47,114 @@ static int LoadPresets(ILuaInterface lua) { presets.UnReference(); return 1; } + + static void SavePreset(string group, string name, LuaObject preset, int index) { + Span fileName = stackalloc char[260]; + sprintf(fileName, "%d-%s").I(index).S(name); + strlower(fileName); + for (int i = 0; i < fileName.Length && fileName[i] != '\0'; i++) { + switch (fileName[i]) { + case '\t': + case '\n': + case '!': + case '"': + case '#': + case '%': + case '&': + case '\'': + case '*': + case '.': + case '/': + case ':': + case '<': + case '>': + case '?': + case '@': + case '\\': + case '`': + case '{': + case '}': + fileName[i] = '_'; + break; + } + } + + string path = $"settings/presets/{group}/{((ReadOnlySpan)fileName).SliceNullTerminatedString()}.txt"; + KeyValues kv = new(name); + + preset.Push(); + g_Lua!.PushNil(); + while (g_Lua.Next(-2)) { + if (g_Lua.GetType(-2) != LuaType.String) + g_Lua.ErrorNoHalt($"SavePresets: Preset keyvalue key is a {g_Lua.GetTypeName(g_Lua.GetType(-2))}, string expected"); + else if (g_Lua.GetType(-1) != LuaType.String) + g_Lua.ErrorNoHalt($"SavePresets: Preset keyvalue value is a {g_Lua.GetTypeName(g_Lua.GetType(-1))}, string expected"); + else + kv.SetString(g_Lua.GetString(-2), g_Lua.GetString(-1)); + g_Lua.Pop(1); + } + g_Lua.Pop(1); + + kv.WriteToFile(filesystem, path, null); + } + + static void SavePresetGroup(string group, LuaObject presets) { + if (group.Contains('\\') || group.Contains('/') || group.Contains('.') || group.Contains("..") || group.Contains("./") || group.IndexOfAny([':', '*', '?']) != -1) + return; + + ReadOnlySpan file = filesystem.FindFirstEx($"settings/presets/{group}/*.txt", null, out ulong handle); + while (!file.IsEmpty) { + filesystem.RemoveFile($"settings/presets/{group}/{file}", null); + file = filesystem.FindNext(handle); + } + filesystem.FindClose(handle); + filesystem.CreateDirHierarchy($"settings/presets/{group}/", null); + + int index = 1; + presets.Push(); + g_Lua!.PushNil(); + while (g_Lua.Next(-2)) { + LuaObject key = new(-2, LuaType.None); + LuaObject value = new(-1, LuaType.None); + if (!key.isString()) + g_Lua.ErrorNoHalt($"SavePresets: Preset Key is a {g_Lua.GetTypeName(key.GetType())}, string expected"); + else if (!value.isTable()) + g_Lua.ErrorNoHalt($"SavePresets: Preset value is a {g_Lua.GetTypeName(value.GetType())}, table expected"); + else + SavePreset(group, key.GetString()!, value, index++); + value.UnReference(); + key.UnReference(); + g_Lua.Pop(1); + } + g_Lua.Pop(1); + } + + [LuaGlobal] + static int SavePresets(ILuaInterface lua) { + LuaObject presets = new(1, LuaType.None); + if (!presets.isTable()) { + lua.TypeError("table", 1); + presets.UnReference(); + return 0; + } + + presets.Push(); + lua.PushNil(); + while (lua.Next(-2)) { + LuaObject key = new(-2, LuaType.None); + LuaObject value = new(-1, LuaType.None); + if (!key.isString()) + lua.ErrorNoHalt($"SavePresets: Group Key is a {lua.GetTypeName(key.GetType())}, string expected"); + else if (!value.isTable()) + lua.ErrorNoHalt($"SavePresets: Group Value is a {lua.GetTypeName(value.GetType())}, table expected"); + else + SavePresetGroup(key.GetString()!, value); + value.UnReference(); + key.UnReference(); + lua.Pop(1); + } + lua.Pop(1); + presets.UnReference(); + return 0; + } } diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index ba9217012..0c6ddec50 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -200,6 +200,17 @@ static int GetCurrentRenderTarget(ILuaInterface lua) { return 1; } + [LuaFunction] + static int CopyRenderTargetToTexture(ILuaInterface lua) { + ITexture? texture = (ITexture?)LuaTexture.LC_ITexture.Get(1); + using MatRenderContextPtr renderContext = new(materials); + ITexture? renderTarget = renderContext.GetRenderTarget(); + if (enginevgui.IsConsoleVisible() && !(renderTarget == null ? ViewRender.RenderingView : renderTarget.IsRenderTarget())) + return 0; + renderContext.CopyRenderTargetToTexture(texture); + return 0; + } + [LuaFunction] static int SetRenderTarget(ILuaInterface lua) { ITexture? texture = null; @@ -551,7 +562,6 @@ static int SetViewPort(ILuaInterface lua) { // todo: RenderView // todo: GetViewSetup // todo: RenderHUD - // todo: CopyRenderTargetToTexture static int CustomClipPlaneCount; [LuaFunction] diff --git a/Game.Client/HLClient.cs b/Game.Client/HLClient.cs index dc6ace73e..652ed102d 100644 --- a/Game.Client/HLClient.cs +++ b/Game.Client/HLClient.cs @@ -237,6 +237,24 @@ public bool CanShowSpeakerLabels() { public static bool g_bLevelInitialized; public static INetworkStringTable? g_pStringTableClientSideChoreoScenes; + public static INetworkStringTable? g_pStringTableMaterials; + + public static int GetMaterialIndex(ReadOnlySpan materialName) { + if (!materialName.IsEmpty) { + int index = g_pStringTableMaterials!.FindStringIndex(materialName); + Assert(index >= 0); + if (index >= 0) + return index; + } + return 0; + } + + public static ReadOnlySpan GetMaterialNameFromIndex(int index) { + if (index != (g_pStringTableMaterials!.GetMaxStrings() - 1)) + return g_pStringTableMaterials.GetString(index); + else + return null; + } public void EncodeUserCmdToBuffer(bf_write buf, int slot) { input.EncodeUserCmdToBuffer(buf, slot); @@ -272,7 +290,9 @@ public void View_Render(ViewRects rects) { public void InstallStringTableCallback(ReadOnlySpan tableName) { switch (tableName) { case "VguiScreen": Warning("FIXME: VguiScreen string table not being processed yet\n"); break; - case "Materials": Warning("FIXME: Materials string table not being processed yet\n"); break; + case "Materials": + g_pStringTableMaterials = networkstringtable.FindTable(tableName); + break; case "EffectDispatch": Warning("FIXME: EffectDispatch string table not being processed yet\n"); break; // I don't think InfoPanel is a thing? case "Scenes": diff --git a/Game.Client/View.cs b/Game.Client/View.cs index 22cb52b78..ba4541380 100644 --- a/Game.Client/View.cs +++ b/Game.Client/View.cs @@ -525,6 +525,8 @@ public void RenderView(in ViewSetup viewRender, ClearFlags clearFlags, RenderVie renderContext.Flush(); } } + + RenderingView = false; } private void ViewDrawScene(bool drew3dSkybox, SkyboxVisibility skyboxVisible, in ViewSetup viewRender, ClearFlags clearFlags, ViewID viewID, bool drawViewModel = false, DrawFlags baseDrawFlags = 0) { diff --git a/Game.Server/BaseAnimating.cs b/Game.Server/BaseAnimating.cs index e7a3e0e1e..3c418a604 100644 --- a/Game.Server/BaseAnimating.cs +++ b/Game.Server/BaseAnimating.cs @@ -622,6 +622,14 @@ public virtual void SetupBones(Span boneToWorld, int boneMask) { RemoveEFlags(EFL.SettingUpBones); } + public int LookupBone(ReadOnlySpan name) { + StudioHdr? studioHdr = GetModelPtr(); + Assert(studioHdr); + if (studioHdr == null) + return -1; + return BoneSetup.Studio_BoneIndexByName(studioHdr, name); + } + public int LookupAttachment(ReadOnlySpan name) { StudioHdr? studioHdr = GetModelPtr(); if (studioHdr == null) { diff --git a/Game.Server/BaseCombatWeapon.cs b/Game.Server/BaseCombatWeapon.cs index b4eeb88bf..0a983ae4a 100644 --- a/Game.Server/BaseCombatWeapon.cs +++ b/Game.Server/BaseCombatWeapon.cs @@ -102,7 +102,7 @@ public override void Use(BaseEntity? activator, BaseEntity? caller, UseType useT public override bool IsWeapon() => true; public override GarrysMod.LuaClass Lua_GetLuaClass() => GarrysMod.LuaEntity.LC_Weapon; - public static void W_Precache(){ + public static void W_Precache() { } @@ -268,4 +268,6 @@ public void CheckRespawn() { return; } } + + public override bool IsBaseCombatWeapon() => true; } diff --git a/Game.Server/GameInterface.cs b/Game.Server/GameInterface.cs index b79173fa6..0bea47e3d 100644 --- a/Game.Server/GameInterface.cs +++ b/Game.Server/GameInterface.cs @@ -22,8 +22,9 @@ namespace Game.Server; -public static class GameInterfaceGlobals { - public static readonly ConVar sv_unlockedchapters = new( "sv_unlockedchapters", "1", FCvar.Archive | FCvar.ArchiveXbox); +public static class GameInterfaceGlobals +{ + public static readonly ConVar sv_unlockedchapters = new("sv_unlockedchapters", "1", FCvar.Archive | FCvar.ArchiveXbox); } [EngineComponent] @@ -40,10 +41,25 @@ public static class GameInterface public static INetworkStringTable? g_pStringTableClientSideChoreoScenes; public static INetworkStringTable? g_pStringTableMaterials; - public static void PrecacheMaterial(ReadOnlySpan materialName){ + public static void PrecacheMaterial(ReadOnlySpan materialName) { g_pStringTableMaterials!.AddString(true, materialName); } + public static int GetMaterialIndex(ReadOnlySpan materialName) { + if (!materialName.IsEmpty) { + int index = g_pStringTableMaterials!.FindStringIndex(materialName); + if (index != INetworkStringTable.INVALID_STRING_INDEX) + return index; + else { + DevMsg($"Warning! GetMaterialIndex: couldn't find material {materialName}\n "); + return 0; + } + } + return 0; + } + + public static ReadOnlySpan GetMaterialNameFromIndex(int materialIndex) => g_pStringTableMaterials!.GetString(materialIndex); + public static bf_write? g_pMsgBuffer; public static void UserMessageBegin(in IRecipientFilter filter, ReadOnlySpan messagename) { Assert(g_pMsgBuffer == null); diff --git a/Game.Server/GarrysMod/GMOD_Player.cs b/Game.Server/GarrysMod/GMOD_Player.cs index 67af4151d..64b68548f 100644 --- a/Game.Server/GarrysMod/GMOD_Player.cs +++ b/Game.Server/GarrysMod/GMOD_Player.cs @@ -84,6 +84,21 @@ public override void Spawn() { public override bool RestrictPlayerPitch() => (GModPlayerFlags & 16) == 0; public override bool CanAttack() => PressedWidget.Get() == null; + public override BaseEntity? FindUseEntity() { + BaseEntity? ent = base.FindUseEntity(); + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.FindUseEntity)) { + LuaEntity.Push_Entity(this); + LuaEntity.Push_Entity(ent); + if (gGM.CallReturns(2, 1)) { + ILuaObject ret = g_Lua!.GetReturn(0); + if (ret.GetType() == LuaType.Entity) + return (BaseEntity?)ret.GetEntity(); + return null; + } + } + return ent; + } + public override BaseEntity EntSelectSpawnPoint() { BaseEntity? spot = null; while ((spot = gEntList.FindEntityByClassname(spot, "info_player_start")) != null) { diff --git a/Game.Shared/GarrysMod/BaseEntityLua.cs b/Game.Shared/GarrysMod/BaseEntityLua.cs index b16a57ebf..de92c9059 100644 --- a/Game.Shared/GarrysMod/BaseEntityLua.cs +++ b/Game.Shared/GarrysMod/BaseEntityLua.cs @@ -18,6 +18,30 @@ public partial class BaseEntity #endif { + public class LuaCallback + { + public int ID; + public readonly LuaObject Function = new(); + public bool Removed; + } + + public class LuaCallbackList + { + public readonly LinkedList Callbacks = []; + public int NextID; + public int Changes; + } + + public static readonly string[] LuaCallbackNames = ["OnAngleChange", "BuildBonePositions", "PhysicsCollide", "BuildFlexWeights"]; + public readonly LuaCallbackList[] LuaCallbacks = [new(), new(), new(), new()]; + + public static int LuaCallbackIndex(ReadOnlySpan name) { + for (int i = 0; i < LuaCallbackNames.Length; i++) + if (strcmp(name, LuaCallbackNames[i]) == 0) + return i; + return -1; + } + public LuaObject LuaCalcAbsolutePosition = new(); public LuaObject? LuaTableObject = new(); public LuaObject? LuaEntityObject = new(); diff --git a/Game.Shared/GarrysMod/LuaConVar.cs b/Game.Shared/GarrysMod/LuaConVar.cs index 42dc1e0b7..a522ed151 100644 --- a/Game.Shared/GarrysMod/LuaConVar.cs +++ b/Game.Shared/GarrysMod/LuaConVar.cs @@ -209,9 +209,8 @@ static int CreateConVar(ILuaInterface lua) { ConVar convar = g_Lua.CreateConVar(name, defaultValue, helpString, flags); convar.SetMin(hasMin, min); convar.SetMax(hasMax, max); - if ((flags & (int)FCvar.UserInfo) != 0) { - // todo: cvar.CallGlobalChangeCallbacks(convar, "", 0.0f); - } + if ((flags & (int)FCvar.UserInfo) != 0) + cvar.CallGlobalChangeCallbacks(convar, new ConVarChangeContext { Old = "" }); Push_ConVar(convar); return 1; diff --git a/Game.Shared/GarrysMod/LuaEngine.cs b/Game.Shared/GarrysMod/LuaEngine.cs index 5cfffeed0..64ba908b9 100644 --- a/Game.Shared/GarrysMod/LuaEngine.cs +++ b/Game.Shared/GarrysMod/LuaEngine.cs @@ -13,6 +13,12 @@ public static partial class LuaEngine [LuaLibrary] static readonly LuaLibrary LL_Factory_engine = new("engine"); + [LuaFunction] + static int TickInterval(ILuaInterface lua) { + g_Lua!.PushNumber(gpGlobals.IntervalPerTick); + return 1; + } + [LuaFunction] static int ActiveGamemode(ILuaInterface lua) { g_Lua!.PushString(filesystem.Gamemodes().Active().Name); diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index a3dfa3f96..4b9c61871 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -3,6 +3,7 @@ using Source; using Source.Common; +using Source.Common.Audio; using Source.Common.Engine; using Source.Common.GarrysMod.Lua; using Source.Common.Mathematics; @@ -1095,6 +1096,524 @@ static int Entity__GetColor4Part(ILuaInterface lua) { return 4; } + [LuaMethod] + static int Entity__AddCallback(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + string name = lua.CheckString(2); + if (!lua.IsType(3, LuaType.Function)) { + lua.TypeError("function", 3); + return 0; + } + + int index = BaseEntity.LuaCallbackIndex(name); + if (index == -1) + return 0; + +#if CLIENT_DLL + if (ent.GetBaseAnimating() != null && index == 1) + ent.GetBaseAnimating()!.RemoveFromPreviousBoneSetups(); +#endif + BaseEntity.LuaCallbackList list = ent.LuaCallbacks[index]; + list.Changes++; + BaseEntity.LuaCallback callback = new() { ID = list.NextID++ }; + callback.Function.SetFromStack(3); + callback.Removed = false; + list.Callbacks.AddLast(callback); + lua.PushNumber(callback.ID); + return 1; + } + + [LuaMethod] + static int Entity__EmitSound(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + string soundName = new(lua.CheckString(2)); + Bootil.String.Util.Trim(ref soundName); + if (soundName.Length == 0 || soundName[0] == ' ') + return 0; + + double level = lua.CheckNumberOpt(3, 75.0); + double pitch = lua.CheckNumberOpt(4, 100.0); + double volume = lua.CheckNumberOpt(5, 1.0); + + BaseEntity soundEnt = ent; + if (ent.IsWeapon()) + soundEnt = ((BaseCombatWeapon)ent).GetOwner() ?? ent; + +#if CLIENT_DLL + PASAttenuationFilter filter = new(soundEnt); + if (ent.IsPlayer() && prediction.InPrediction()) + filter.UsePredictionRules(); +#else + // if (lua.GetType(9) == LuaType.RecipientFilter) { filter = Get_CRecipientFilter(9) ... } // really important TODO + PASAttenuationFilter filter = new(soundEnt, ATTN_NORM); + if (ent.IsPlayer()) + filter.UsePredictionRules(); +#endif + + EmitSound_t ep = new() { + Channel = ent.IsWeapon() ? 1 : 0, + SoundName = soundName, + Volume = (float)volume, + SoundLevel = (SoundLevel)(int)level, + Pitch = (int)pitch + }; + if (lua.GetType(6) != LuaType.Nil) + ep.Channel = (int)lua.CheckNumber(6); + if (lua.GetType(7) != LuaType.Nil) + ep.Flags = (SoundFlags)(int)lua.CheckNumber(7); + if (lua.GetType(8) != LuaType.Nil) + ep.SpecialDSP = (int)lua.CheckNumber(8); + + if (!enginesound.IsSoundPrecached(soundName)) + BaseEntity.PrecacheScriptSound(soundName); + + BaseEntity.EmitSound(filter, soundEnt.EntIndex(), ep); + return 0; + } + + [LuaMethod] + static int Entity__ViewModelIndex(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (ent is not BaseViewModel viewModel) + return 0; + lua.PushNumber(viewModel.ViewModelIndex()); + return 1; + } + + [LuaMethod] + static int Entity__GetSequenceName(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating != null && !ent.IsMarkedForDeletion()) { + lua.PushString(animating.GetSequenceName((int)lua.GetNumber(2))); + return 1; + } + lua.PushString(""); + return 1; + } + + [LuaMethod] + static int Entity__SendViewModelMatchingSequence(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (ent is BaseViewModel viewModel) + viewModel.SendViewModelMatchingSequence((int)lua.CheckNumber(2)); + return 0; + } + + [LuaMethod] + static int Entity__SetSaveValue(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + foreach (EHANDLE handle in RemoveList) + if (handle.Get() == ent) + return 0; + if (ent.IsMarkedForDeletion()) + return 0; + + string name = lua.CheckString(2); + if (stricmp(name, "classname") == 0) { + lua.PushBool(false); + return 1; + } + + if (strnicmp(name, "m_ragdoll.", 10) == 0) { + if (stricmp(name, "m_ragdoll.allowStretch") != 0) { + if (name.Length < 17 || strcmp(name.AsSpan(name.Length - 17), "originParentSpace") != 0) { + lua.PushBool(false); + return 1; + } + } + } + else if (stricmp(name, "m_iEFlags") == 0) { + if (((int)lua.CheckNumber(3) & 1) != 0) { + lua.PushBool(false); + return 1; + } + } + else if (stricmp(name, "m_bActive") == 0) { + lua.PushBool(false); + return 1; + } + + TypeDescription? td = null; + for (DataMap? map = ent.GetDataDescMap(); map != null && td == null; map = map.BaseMap) { + foreach (TypeDescription field in map.DataDesc) { + if (field.Flags != FieldTypeDescFlags.Input && (field.Flags & FieldTypeDescFlags.Output) == 0 && ((field.ExternalName.Length != 0 && stricmp(name, field.ExternalName) == 0) || (field.FieldName.Length != 0 && stricmp(name, field.FieldName) == 0))) { + td = field; + break; + } + } + } +#if CLIENT_DLL + for (DataMap? map = ent.GetPredDescMap(); map != null && td == null; map = map.BaseMap) { + foreach (TypeDescription field in map.DataDesc) { + if (field.Flags != FieldTypeDescFlags.Input && (field.Flags & FieldTypeDescFlags.Output) == 0 && ((field.ExternalName.Length != 0 && stricmp(name, field.ExternalName) == 0) || (field.FieldName.Length != 0 && stricmp(name, field.FieldName) == 0))) { + td = field; + break; + } + } + } +#endif + if (td == null || (td.FieldSize > 1 && lua.GetType(3) != LuaType.Table)) { + lua.PushBool(false); + return 1; + } + + bool isArray = td.FieldSize > 1 && lua.GetType(3) == LuaType.Table; + Array? array = isArray ? (Array?)td.FieldInfo.GetValue(ent) : null; + + object? Convert1(LuaObject elem) { + return td.FieldType switch { + FieldType.EHandle => elem.GetType() == LuaType.Entity ? elem.GetEntity() : null, + FieldType.String or FieldType.ModelName or FieldType.SoundName => (object?)(elem.isString() ? elem.GetString() : null), + FieldType.Integer => elem.isNumber() ? (int)elem.GetFloat() : null, + FieldType.Float => elem.isNumber() ? elem.GetFloat() : null, + FieldType.Double => elem.isNumber() ? elem.GetDouble() : null, + FieldType.Character => elem.isNumber() ? (byte)elem.GetFloat() : null, + FieldType.Boolean => elem.isBool() ? elem.GetBool() : null, + FieldType.Time => elem.isNumber() ? elem.GetDouble() + gpGlobals.CurTime : null, + FieldType.Vector or FieldType.PositionVector => elem.isVector() ? elem.GetVector() : null, + _ => null, + }; + } + + if (isArray) { + switch (td.FieldType) { + case FieldType.EHandle: + case FieldType.String: + case FieldType.ModelName: + case FieldType.SoundName: + case FieldType.Integer: + case FieldType.Float: + case FieldType.Double: + case FieldType.Character: + case FieldType.Boolean: + case FieldType.Time: + case FieldType.Vector: + case FieldType.PositionVector: { + if (td.FieldType == FieldType.EHandle && !IsSettableHandle(name)) + break; + LuaObject table = new(); + table.SetFromStack(3); + bool set = false; + LuaObject elem = new(); + for (int i = 0; i < td.FieldSize; i++) { + table.GetMember(i + 1, elem); + object? v = Convert1(elem); + if (v != null) { + set = true; + if (td.FieldType == FieldType.EHandle) { + EHANDLE handle = (EHANDLE)array!.GetValue(i)!; + handle.Set((BaseEntity?)v); + array.SetValue(handle, i); + } + else + array!.SetValue(v, i); + } + } + elem.UnReference(); + table.UnReference(); + lua.PushBool(set); + return 1; + } + } + } + + switch (td.FieldType) { + case FieldType.EHandle: + if (!IsSettableHandle(name)) + break; + EHANDLE handle = (EHANDLE)td.FieldInfo.GetValue(ent)!; + handle.Set(Get_Entity(3, true)); + td.FieldInfo.SetValue(ent, handle); + lua.PushBool(true); + return 1; + case FieldType.String: + case FieldType.ModelName: + case FieldType.SoundName: + td.FieldInfo.SetValue(ent, new string(lua.CheckString(3))); + lua.PushBool(true); + return 1; + case FieldType.Integer: + td.FieldInfo.SetValue(ent, (int)lua.CheckNumber(3)); + lua.PushBool(true); + return 1; + case FieldType.Float: + td.FieldInfo.SetValue(ent, (float)lua.CheckNumber(3)); + lua.PushBool(true); + return 1; + case FieldType.Double: + td.FieldInfo.SetValue(ent, lua.CheckNumber(3)); + lua.PushBool(true); + return 1; + case FieldType.Short: + td.FieldInfo.SetValue(ent, (short)(int)lua.CheckNumber(3)); + lua.PushBool(true); + return 1; + case FieldType.Character: + td.FieldInfo.SetValue(ent, (byte)(int)lua.CheckNumber(3)); + lua.PushBool(true); + return 1; + case FieldType.Boolean: + td.FieldInfo.SetValue(ent, lua.GetBool(3)); + lua.PushBool(true); + return 1; + case FieldType.ModelIndex: +#if GAME_DLL + td.FieldInfo.SetValue(ent, BaseEntity.PrecacheModel(lua.CheckString(3), true)); +#endif + lua.PushBool(true); + return 1; + case FieldType.MaterialIndex: { + string material = lua.CheckString(3); +#if CLIENT_DLL + td.FieldInfo.SetValue(ent, HLClient.GetMaterialIndex(material)); +#else + td.FieldInfo.SetValue(ent, GameInterface.GetMaterialIndex(material)); + GameInterface.PrecacheMaterial(material); +#endif + lua.PushBool(true); + return 1; + } + case FieldType.Time: + td.FieldInfo.SetValue(ent, lua.CheckNumber(3) + gpGlobals.CurTime); + lua.PushBool(true); + return 1; + case FieldType.Tick: + td.FieldInfo.SetValue(ent, gpGlobals.TickCount + (int)lua.CheckNumber(3)); + lua.PushBool(true); + return 1; + case FieldType.Vector: + case FieldType.PositionVector: { + Vector3 vec; + if (lua.GetType(3) == LuaType.String) { + Span f = stackalloc float[3]; + UTIL_StringToVector(f, lua.CheckString(3)); + vec = new(f[0], f[1], f[2]); + } + else + vec = LuaVector.Get_Vector(3); + td.FieldInfo.SetValue(ent, vec); + lua.PushBool(true); + return 1; + } + default: + lua.PushBool(ent.KeyValue(lua.CheckString(2), lua.CheckString(3))); + return 1; + } + lua.PushBool(false); + return 1; + } + + static bool IsSettableHandle(ReadOnlySpan name) => + stricmp(name, "m_hThrower") == 0 || stricmp(name, "m_hOriginalThrower") == 0 || stricmp(name, "m_hFilter") == 0 + || stricmp(name, "m_hSpeechFilter") == 0 || stricmp(name, "m_hEnemyFilter") == 0 || stricmp(name, "m_hDamageFilter") == 0; + + [LuaMethod] + static int Entity__IsWorld(ILuaInterface lua) { + LuaType type = lua.GetType(1); + if (type != LuaType.Entity && type != LuaType.Nil) + lua.TypeError("Entity", 1); + BaseEntity? ent = UserGet(1); + if (ent == null) { + lua.PushBool(false); + return 1; + } +#if CLIENT_DLL + lua.PushBool(ent == cl_entitylist.GetBaseEntity(0)); +#else + Edict? edict = ent.Edict(); + lua.PushBool(edict == null || edict.EdictIndex == 0); +#endif + return 1; + } + + static void PushInternalValue(TypeDescription td, object? value) { + switch (td.FieldType) { + case FieldType.Float: + g_Lua!.PushNumber(Convert.ToSingle(value)); + break; + case FieldType.Double: + g_Lua!.PushNumber(Convert.ToDouble(value)); + break; + case FieldType.String: + case FieldType.ModelName: + case FieldType.SoundName: + g_Lua!.PushString(value?.ToString() ?? ""); + break; + case FieldType.Vector: + case FieldType.PositionVector: + g_Lua!.PushVector((Vector3)value!); + break; + case FieldType.Integer: + case FieldType.Short: + case FieldType.Character: + g_Lua!.PushNumber(Convert.ToInt32(value)); + break; + case FieldType.Boolean: + g_Lua!.PushBool(Convert.ToBoolean(value)); + break; + case FieldType.EHandle: + Push_Entity(((EHANDLE)value!).Get()); + break; + case FieldType.Time: + g_Lua!.PushNumber(Convert.ToDouble(value) - gpGlobals.CurTime); + break; + case FieldType.Tick: + g_Lua!.PushNumber(Convert.ToInt32(value) - gpGlobals.TickCount); + break; + default: + g_Lua!.PushNil(); + break; + } + } + + [LuaMethod] + static int Entity__GetInternalVariable(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + string name = lua.CheckString(2); + + TypeDescription? td = null; + for (DataMap? map = ent.GetDataDescMap(); map != null && td == null; map = map.BaseMap) { + foreach (TypeDescription field in map.DataDesc) { + if (field.Flags != FieldTypeDescFlags.Input && (field.Flags & FieldTypeDescFlags.Output) == 0 && ((field.ExternalName.Length != 0 && stricmp(name, field.ExternalName) == 0) || (field.FieldName.Length != 0 && stricmp(name, field.FieldName) == 0))) { + td = field; + break; + } + } + } +#if CLIENT_DLL + for (DataMap? map = ent.GetPredDescMap(); map != null && td == null; map = map.BaseMap) { + foreach (TypeDescription field in map.DataDesc) { + if (field.Flags != FieldTypeDescFlags.Input && (field.Flags & FieldTypeDescFlags.Output) == 0 && ((field.ExternalName.Length != 0 && stricmp(name, field.ExternalName) == 0) || (field.FieldName.Length != 0 && stricmp(name, field.FieldName) == 0))) { + td = field; + break; + } + } + } +#endif + if (td == null) + return 0; + + object? value = td.FieldInfo.GetValue(ent); + + switch (td.FieldType) { + case FieldType.Float: + case FieldType.Double: + case FieldType.String: + case FieldType.ModelName: + case FieldType.SoundName: + case FieldType.Vector: + case FieldType.PositionVector: + case FieldType.Integer: + case FieldType.Boolean: + case FieldType.Character: + case FieldType.EHandle: + case FieldType.Time: + if (td.FieldSize < 2 || value is not Array array) { + PushInternalValue(td, value); + return 1; + } + LuaTable table = new(null, td.FieldSize); + for (int i = 0; i < td.FieldSize; i++) { + PushInternalValue(td, array.GetValue(i)); + table.SetMember(i + 1); + } + table.Push(); + table.UnReference(); + return 1; + case FieldType.Short: + case FieldType.Tick: + PushInternalValue(td, value); + return 1; + case FieldType.Color32: { + Color color = (Color)value!; + lua.PushString($"{color.R} {color.G} {color.B} {color.A}"); + return 1; + } + case FieldType.ModelIndex: { + Model? model = modelinfo.GetModel(Convert.ToInt32(value)); + if (model == null) + return 0; + lua.PushString(modelinfo.GetModelName(model)); + return 1; + } + case FieldType.MaterialIndex: { +#if CLIENT_DLL + ReadOnlySpan material = HLClient.GetMaterialNameFromIndex(Convert.ToInt32(value)); +#else + ReadOnlySpan material = GameInterface.GetMaterialNameFromIndex(Convert.ToInt32(value)); +#endif + if (material.IsEmpty) + return 0; + lua.PushString(material); + return 1; + } + } + return 0; + } + + + [LuaMethod] + static int Entity__GetGroundEntity(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + Push_Entity(ent.GetGroundEntity()); + return 1; + } + + [LuaMethod] + static int Entity__GetPoseParameterRange(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || ent.IsMarkedForDeletion()) + return 0; + + int index; + if (lua.GetType(2) == LuaType.Number) + index = (int)lua.GetNumber(2); + else +#if CLIENT_DLL + index = animating.LookupPoseParameter(animating.GetModelPtr(), lua.CheckString(2)); +#else + index = animating.LookupPoseParameter(lua.CheckString(2)); +#endif + + if (!animating.GetPoseParameterRange(index, out float minValue, out float maxValue)) + return 0; + + lua.PushNumber(minValue); + lua.PushNumber(maxValue); + return 2; + } + + [LuaMethod] + static int Entity__LookupPoseParameter(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || ent.IsMarkedForDeletion()) + return 0; +#if CLIENT_DLL + lua.PushNumber(animating.LookupPoseParameter(animating.GetModelPtr(), lua.CheckString(2))); +#else + lua.PushNumber(animating.LookupPoseParameter(lua.CheckString(2))); +#endif + return 1; + } + + [LuaMethod] + static int Entity__LookupBone(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || ent.IsMarkedForDeletion() || animating.GetModelPtr() == null) + return 0; + + int bone = animating.LookupBone(lua.CheckString(2)); + if (bone == -1) + return 0; + + lua.PushNumber(bone); + return 1; + } + [LuaMethod] static int Entity__LookupSequence(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; diff --git a/Game.Shared/GarrysMod/LuaFileLibrary.cs b/Game.Shared/GarrysMod/LuaFileLibrary.cs index 29fa957df..53eeda120 100644 --- a/Game.Shared/GarrysMod/LuaFileLibrary.cs +++ b/Game.Shared/GarrysMod/LuaFileLibrary.cs @@ -86,7 +86,7 @@ static void ReplaceAllCharacters(ref string str, string find, string replace) { str = str[..pos] + replace + str[(pos + find.Length)..]; } - static bool IsFileAccessAllowed(string file, string path, bool write, bool anyExtension) { + public static bool IsFileAccessAllowed(string file, string path, bool write, bool anyExtension) { string str = file; Bootil.String.Util.Trim(ref str, " \t\n\r."); diff --git a/Game.Shared/GarrysMod/LuaGame.cs b/Game.Shared/GarrysMod/LuaGame.cs index 15ed1abca..daee405a2 100644 --- a/Game.Shared/GarrysMod/LuaGame.cs +++ b/Game.Shared/GarrysMod/LuaGame.cs @@ -16,6 +16,47 @@ public static partial class LuaGame [LuaLibrary] static readonly LuaLibrary LL_Factory_game = new("game"); + [LuaFunction] + static int AddParticles(ILuaInterface lua) { + string file = g_Lua!.CheckString(1); + if (LuaFileLibrary.IsFileAccessAllowed(file, "GAME", false, false)) { + // GMOD_LoadParticleConfigFile(file); // TODO! + } + return 0; + } + + [LuaFunction] + static int AddDecal(ILuaInterface lua) { + LuaObject materials = new(); + materials.SetFromStack(2); + if (!materials.isTable()) { + // decalsystem.AddDecal(lua.CheckString(1), lua.CheckString(2)); // TODO!!! + materials.UnReference(); + return 0; + } + + List list = []; + LuaObject entry = new(); + for (int i = 1; ; i++) { + materials.GetMember(i, entry); + if (!entry.isString()) + break; + list.Add(entry.GetString()!); + } + entry.UnReference(); + + // if (list.Count != 0) + // decalsystem.AddDecal(lua.CheckString(1), list); // TODO!!! + materials.UnReference(); + return 0; + } + + [LuaFunction] + static int MaxPlayers(ILuaInterface lua) { + g_Lua!.PushNumber(gpGlobals.MaxClients); + return 1; + } + [LuaFunction] static int GetMap(ILuaInterface lua) { #if CLIENT_DLL diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs index 9d66c8789..47f3d4bd7 100644 --- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs +++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs @@ -117,6 +117,48 @@ static int LocalToWorld(ILuaInterface lua) { return 2; } + [LuaGlobal] + static int WorldToLocal(ILuaInterface lua) { + Vector3 pos = LuaVector.Get_Vector(1); + QAngle ang = LuaAngle.Get_Angle(2); + Vector3 newSystemOrigin = LuaVector.Get_Vector(3); + QAngle newSystemAngles = LuaAngle.Get_Angle(4); + + MathLib.AngleMatrix(newSystemAngles, newSystemOrigin, out Matrix3x4 matrix); + MathLib.MatrixInvert(matrix, out Matrix3x4 inverse); + MathLib.VectorTransform(pos, inverse, out Vector3 localPos); + QAngle localAng = MathLib.TransformAnglesToWorldSpace(ang, inverse); + + LuaVector.Push_Vector(localPos); + LuaAngle.Push_Angle(localAng); + return 2; + } + + [LuaGlobal] + static int PrecacheParticleSystem(ILuaInterface lua) { + string name = lua.CheckString(1); + // PrecacheParticleSystem(name); // TODO! + return 0; + } + + [LuaGlobal] + static int CompileFile(ILuaInterface lua) { + bool showErrors = true; + if (lua.GetType(2) != LuaType.Nil) + showErrors = lua.GetBool(2); + return lua.FindAndRunScript(lua.CheckString(1), false, showErrors, "!UNKNOWN", true) ? 1 : 0; + } + + [LuaGlobal] + static int IsFirstTimePredicted(ILuaInterface lua) { +#if CLIENT_DLL + lua.PushBool(prediction.InPrediction() && prediction.IsFirstTimePredicted()); +#else + lua.PushBool(true); +#endif + return 1; + } + [LuaGlobal] static int HSVToColor(ILuaInterface lua) { float value = (float)lua.CheckNumber(3); @@ -261,6 +303,34 @@ static int Msg(ILuaInterface lua) { return 0; } +#if GAME_DLL + [LuaGlobal] + static int MsgAll(ILuaInterface lua) { + int top = g_Lua!.Top(); + LuaObject tostring = new(); + g_Lua.Global().GetMember("tostring", tostring); + if (tostring.isFunction()) { + StringBuilder buffer = new(); + for (int i = 1; i <= top; i++) { + LuaObject obj = new(i, LuaType.None); + tostring.Push(); + obj.Push(); + string str = g_Lua.CallInternalGetString(1) ?? "ERROR"; + buffer.Append(str.AsSpan(0, Math.Min(str.Length, Math.Max(0, 4096 - 1 - buffer.Length)))); + obj.UnReference(); + } + if (buffer.Length > 0) { + string message = buffer.ToString(); + Util.ClientPrintAll(Game.Shared.HudPrint.Console, "%s1", message); + if (engine.IsDedicatedServer()) + Dbg.Msg(message); + } + } + tostring.UnReference(); + return 0; + } +#endif + static Color GetColor(ILuaObject obj) => new( (byte)(int)obj.GetMemberFloat("r", 255.0f), (byte)(int)obj.GetMemberFloat("g", 255.0f), diff --git a/Game.Shared/GarrysMod/LuaHelper.cs b/Game.Shared/GarrysMod/LuaHelper.cs index dc4bf6881..209933cea 100644 --- a/Game.Shared/GarrysMod/LuaHelper.cs +++ b/Game.Shared/GarrysMod/LuaHelper.cs @@ -44,6 +44,56 @@ public static void KeyValuesToTable(KeyValues kv, ILuaObject table, bool preserv } } + public static void KeyValuesToTablePreserveOrder(KeyValues kv, ILuaObject? table, bool preserveKeyCase) { + int count = 0; + int arrayIndex = 1; + bool isArray = true; + KeyValues? sub = kv.GetFirstSubKey(); + if (sub != null) { + do { + count++; + if (sub.Name != "0") { + isArray = false; + break; + } + sub = sub.GetNextKey(); + } while (sub != null); + if (count == 1) + isArray = false; + } + + int entryIndex = 1; + for (sub = kv.GetFirstSubKey(); sub != null; sub = sub.GetNextKey()) { + string name = sub.Name.Length > 255 ? sub.Name[..255] : sub.Name; + if (!preserveKeyCase) + name = name.ToLowerInvariant(); + if (name == "0" && isArray) + name = (arrayIndex++).ToString(); + + LuaTable entry = new(null, 0); + entry.SetMember("Key", name); + table?.SetMember(entryIndex++, entry); + + switch (sub.Type) { + case KeyValues.Types.None: { + LuaTable subTable = new(null, 0); + entry.SetMember("Value", subTable); + KeyValuesToTablePreserveOrder(sub, subTable, preserveKeyCase); + subTable.UnReference(); + break; + } + case KeyValues.Types.Int: + case KeyValues.Types.Double: + entry.SetMember("Value", sub.GetFloat()); + break; + default: + entry.SetMember("Value", sub.GetString()); + break; + } + entry.UnReference(); + } + } + public static void CallOnLuaErrorHook(in LuaError error, string? addonTitle, ulong workshopID) { if (g_Lua == null || g_Lua.Global() == null) return; diff --git a/Game.Shared/GarrysMod/LuaObject.cs b/Game.Shared/GarrysMod/LuaObject.cs index fcad9e334..1898ba2e5 100644 --- a/Game.Shared/GarrysMod/LuaObject.cs +++ b/Game.Shared/GarrysMod/LuaObject.cs @@ -676,7 +676,12 @@ public void SetMemberMatrix(float key, in Matrix4x4 mat) { public IHandleEntity? GetMemberEntity(ReadOnlySpan name, IHandleEntity? def) => throw new NotImplementedException(); public IHandleEntity? GetMemberEntity(int key, IHandleEntity? def) => throw new NotImplementedException(); - public void SetMemberEntity(float key, IHandleEntity? ent) => throw new NotImplementedException(); + public void SetMemberEntity(float key, IHandleEntity? ent) { + if (!isTable()) + return; + LuaEntity.Push_Entity(EntityFromEntityHandle(ent)); + SetMember(key); + } public void SetMemberEntity(ReadOnlySpan name, IHandleEntity? ent) { if (!isTable()) return; diff --git a/Game.Shared/GarrysMod/LuaPlayer.cs b/Game.Shared/GarrysMod/LuaPlayer.cs index 78eead4fc..b39b178c0 100644 --- a/Game.Shared/GarrysMod/LuaPlayer.cs +++ b/Game.Shared/GarrysMod/LuaPlayer.cs @@ -389,6 +389,58 @@ static int Player__GetVehicle(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Player__GetWeapons(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + LuaTable table = new(null, MAX_WEAPONS); + int count = 0; + for (int i = 0; i < MAX_WEAPONS; i++) { + BaseCombatWeapon? weapon = player.MyWeapons[i].Get(); + if (weapon != null) + table.SetMemberEntity(++count, weapon); + } + table.Push(); + table.UnReference(); + return 1; + } + + [LuaMethod] + static int Player__GetUseEntity(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; +#if CLIENT_DLL + LuaEntity.Push_Entity(((GMOD_Player)player).FindUseEntity()); +#else + LuaEntity.Push_Entity(player.FindUseEntity()); +#endif + return 1; + } + + [LuaMethod] + static int Player__SetFOV(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + BaseEntity requester = player; + if (lua.GetType(4) != LuaType.Nil) + requester = LuaEntity.Get_Entity(4, false)!; + double zoomRate = lua.CheckNumberOpt(3, 0); + double fov = lua.GetNumber(2); + player.SetFOV(requester, (int)(float)fov, (float)zoomRate, 0); + return 0; + } + + [LuaMethod] + static int Player__GetFOV(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + lua.PushNumber(player.GetFOV()); + return 1; + } + + [LuaMethod] + static int Player__Nick(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + lua.PushString(player.GetPlayerName()); + return 1; + } + [LuaMethod] static int Player__GetShootPos(ILuaInterface lua) { BasePlayer player = Get_Player(1, false)!; diff --git a/Game.Shared/GarrysMod/LuaResource.cs b/Game.Shared/GarrysMod/LuaResource.cs new file mode 100644 index 000000000..157abc837 --- /dev/null +++ b/Game.Shared/GarrysMod/LuaResource.cs @@ -0,0 +1,54 @@ +#if CLIENT_DLL || GAME_DLL +using Source; +using Source.Common.GarrysMod.Lua; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +public static partial class LuaResource // TODO vvv +{ + [LuaLibrary] + static readonly LuaLibrary LL_Factory_resource = new("resource"); + + [LuaFunction] + static int AddFile(ILuaInterface lua) { +#if GAME_DLL + if (gpGlobals.MaxClients > 1) { + Span file = stackalloc char[260]; + strcpy(file, lua.CheckString(1)); + StrTools.FixSlashes(file, '/'); + // AddResource(file, true); + } +#endif + return 0; + } + + [LuaFunction] + static int AddSingleFile(ILuaInterface lua) { +#if GAME_DLL + if (gpGlobals.MaxClients > 1) { + Span file = stackalloc char[260]; + strcpy(file, lua.CheckString(1)); + StrTools.FixSlashes(file, '/'); + // AddResource(file, false); + } +#endif + return 0; + } + +#if GAME_DLL + [LuaFunction] + static int AddWorkshop(ILuaInterface lua) { + // if (gpGlobals.MaxClients > 1) { + // g_StringTablesDownloadables = networkstringtable.FindTable("downloadables"); + // if (g_StringTablesDownloadables != null) + // AddWorkshop(lua.CheckString(1)); + // } + return 0; + } +#endif +} +#endif diff --git a/Game.Shared/GarrysMod/LuaSound.cs b/Game.Shared/GarrysMod/LuaSound.cs new file mode 100644 index 000000000..60ac9acc9 --- /dev/null +++ b/Game.Shared/GarrysMod/LuaSound.cs @@ -0,0 +1,101 @@ +#if CLIENT_DLL || GAME_DLL +using Source.Common.Audio; +using Source.Common.GarrysMod.Lua; +using Source.Common.SoundEmitterSystem; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +public static partial class LuaSound +{ + [LuaLibrary] + static readonly LuaLibrary LL_Factory_sound = new("sound"); + + [LuaFunction] + static int Add(ILuaInterface lua) { + LuaObject data = new(); + data.SetFromStack(1); + if (!data.isTable()) { + g_Lua!.TypeError("table", 1); + data.UnReference(); + return 0; + } + + SoundParametersInternal parms = new(); + parms.SetChannel(data.GetMemberInt("channel", 0)); + parms.SetSoundLevel(data.GetMemberInt("level", (int)SoundLevel.LvlNorm)); + + LuaObject volume = new(); + data.GetMember("volume", volume); + float volumeStart; + float volumeEnd; + if (volume.isTable()) { + LuaObject entry = new(); + volume.GetMember(1, entry); + volumeStart = entry.isNumber() ? entry.GetFloat() : -1.0f; + volume.GetMember(2, entry); + volumeEnd = entry.isNumber() ? entry.GetFloat() : volumeStart; + entry.UnReference(); + } + else { + volumeStart = volume.isNumber() ? (float)volume.GetDouble() : 0.0f; + volumeEnd = volumeStart; + } + if (volumeStart > 0.0f && volumeEnd > 0.0f) + parms.SetVolume(volumeStart, volumeEnd - volumeStart); + + float pitchStart = data.GetMemberFloat("pitchstart", -1.0f); + float pitchEnd = data.GetMemberFloat("pitchend", -1.0f); + if (pitchStart <= 0.0f || pitchEnd <= 0.0f) { + LuaObject pitch = new(); + data.GetMember("pitch", pitch); + if (pitch.isTable()) { + LuaObject entry = new(); + pitch.GetMember(1, entry); + pitchStart = entry.isNumber() ? entry.GetFloat() : -1.0f; + pitch.GetMember(2, entry); + pitchEnd = entry.isNumber() ? entry.GetFloat() : pitchStart; + entry.UnReference(); + } + else { + pitchStart = pitch.isNumber() ? (float)pitch.GetDouble() : 0.0f; + pitchEnd = pitchStart; + } + pitch.UnReference(); + } + if (pitchStart > 0.0f && pitchEnd > 0.0f) + parms.SetPitch((int)pitchStart, (int)(pitchEnd - pitchStart)); + + LuaObject sound = new(); + data.GetMember("sound", sound); + if (sound.isString()) + soundemitterbase.ExpandSoundNameMacros(ref parms, sound.GetString()); + else if (sound.isTable()) { + string? wave; + for (int i = 1; (wave = sound.GetMemberStr(i, null)) != null; i++) + soundemitterbase.ExpandSoundNameMacros(ref parms, wave); + } + else { + lua.ErrorNoHalt("sound.Add called without anything in the 'sound' key! (or wrong type?)"); + sound.UnReference(); + volume.UnReference(); + data.UnReference(); + return 0; + } + + string? name = data.GetMemberStr("name", null); + if (name == null) + lua.ErrorNoHalt("sound.Add called without anything in the 'name' key! (or wrong type?)"); + else + soundemitterbase.AddSound(name, "scripts/sounds/lua.txt", parms); + + sound.UnReference(); + volume.UnReference(); + data.UnReference(); + return 0; + } +} +#endif diff --git a/Game.Shared/GarrysMod/LuaUtil.cs b/Game.Shared/GarrysMod/LuaUtil.cs index 0a3fdb98d..d562da728 100644 --- a/Game.Shared/GarrysMod/LuaUtil.cs +++ b/Game.Shared/GarrysMod/LuaUtil.cs @@ -17,6 +17,7 @@ using System.Numerics; using System.Runtime.CompilerServices; +using Source.Common.Hashing; #if CLIENT_DLL namespace Game.Client.GarrysMod; @@ -216,6 +217,51 @@ static int KeyValuesToTable(ILuaInterface lua) { return 1; } + [LuaFunction] + static int KeyValuesToTablePreserveOrder(ILuaInterface lua) { + LuaTable table = new(null, 0); + KeyValues kv = new("KeyValuesToTablePreserveOrder"); + kv.UsesEscapeSequences(g_Lua!.GetBool(2)); + kv.LoadFromBuffer("util.KeyValuesToTablePreserveOrder", g_Lua.CheckString(1)); + LuaHelper.KeyValuesToTablePreserveOrder(kv, table, g_Lua.GetBool(3)); + table.Push(); + table.UnReference(); + return 1; + } + + [LuaFunction] + static int SharedRandom(ILuaInterface lua) { + int seed = 0; + if (g_Lua!.GetType(4) == LuaType.Number) + seed = (int)g_Lua.CheckNumber(4); + g_Lua.PushNumber(SharedRandomFloat(g_Lua.CheckString(1), (float)g_Lua.CheckNumber(2), (float)g_Lua.CheckNumber(3), seed)); + return 1; + } + + [LuaFunction] + static int CRC(ILuaInterface lua) { + if (!g_Lua!.IsType(1, LuaType.String)) + g_Lua.CheckString(1); + ReadOnlySpan data = g_Lua.GetStringBytes(1); + CRC32_t crc = 0; + CRC32.Init(ref crc); + CRC32.ProcessBuffer(ref crc, data, data.Length); + CRC32.Final(ref crc); + g_Lua.PushString(((uint)crc).ToString()); + return 1; + } + + [LuaFunction] + static int GetSurfacePropName(ILuaInterface lua) { + int index = (int)g_Lua!.CheckNumber(1); + if (index >= 0 && index < physprops.SurfacePropCount()) { + g_Lua.PushString(physprops.GetPropName(index)); + return 1; + } + g_Lua.PushString(""); + return 1; + } + #if GAME_DLL [LuaFunction] static int AddNetworkString(string name) => NetworkString.Add(name); @@ -332,6 +378,68 @@ static int TraceLine(ILuaInterface lua) { Vector3 end = data.GetMemberVector("endpos", vec3_origin); Mask mask = (Mask)data.GetMemberUInt("mask", (uint)Mask.Solid); + TraceFilterLua filter = TraceFilterFromTable(data); + + Ray ray = default; + ray.Init(start, end); + + enginetrace.TraceRay(ray, mask | (Mask)Contents.HitBox, ref filter, out Trace tr); + + if (r_visualizetraces.GetBool()) + Game.Shared.DebugOverlay.DebugDrawLine(tr.StartPos, tr.EndPos, 255, 0, 0, true, -1.0f); + + if (!tr.StartSolid) + Util.ClipTraceToPlayers(start, end, mask | (Mask)Contents.HitBox, ref filter, ref tr); + + LuaObject output = new(); + data.GetMember("output", output); + PushTableFromTrace(ref tr, output); + output.UnReference(); + + filter.Function.UnReference(); + data.UnReference(); + return 1; + } + + [LuaFunction] + static int GetSurfaceIndex(ILuaInterface lua) { + g_Lua!.PushNumber(physprops.GetSurfaceIndex(g_Lua.CheckString(1))); + return 1; + } + + [LuaFunction] + static int TraceHull(ILuaInterface lua) { + if (g_PhysWorldObject == null) + return 0; + + LuaObject data = new(1, LuaType.None); + if (!data.isTable()) { + g_Lua!.TypeError("table", 1); + data.UnReference(); + return 0; + } + + Vector3 start = data.GetMemberVector("start", vec3_origin); + Vector3 end = data.GetMemberVector("endpos", vec3_origin); + Mask mask = (Mask)data.GetMemberUInt("mask", (uint)Mask.Solid); + Vector3 mins = data.GetMemberVector("mins", vec3_origin); + Vector3 maxs = data.GetMemberVector("maxs", vec3_origin); + + TraceFilterLua filter = TraceFilterFromTable(data); + + Util.TraceHull(start, end, mins, maxs, mask, ref filter, out Trace tr); + + LuaObject output = new(); + data.GetMember("output", output); + PushTableFromTrace(ref tr, output); + output.UnReference(); + + filter.Function.UnReference(); + data.UnReference(); + return 1; + } + + static TraceFilterLua TraceFilterFromTable(LuaObject data) { TraceFilterLua filter = new((CollisionGroup)data.GetMemberInt("collisiongroup", 0)); filter.SetIgnoreWorld(data.GetMemberBool("ignoreworld", false)); filter.SetIsWhitelist(data.GetMemberBool("whitelist", false)); @@ -359,26 +467,7 @@ static int TraceLine(ILuaInterface lua) { else if (filterObj.GetType() == LuaType.Entity) filter.AddEntityToIgnore(filterObj.GetEntity()); filterObj.UnReference(); - - Ray ray = default; - ray.Init(start, end); - - enginetrace.TraceRay(ray, mask | (Mask)Contents.HitBox, ref filter, out Trace tr); - - if (r_visualizetraces.GetBool()) - Game.Shared.DebugOverlay.DebugDrawLine(tr.StartPos, tr.EndPos, 255, 0, 0, true, -1.0f); - - if (!tr.StartSolid) - Util.ClipTraceToPlayers(start, end, mask | (Mask)Contents.HitBox, ref filter, ref tr); - - LuaObject output = new(); - data.GetMember("output", output); - PushTableFromTrace(ref tr, output); - output.UnReference(); - - filter.Function.UnReference(); - data.UnReference(); - return 1; + return filter; } } #endif diff --git a/Game.Shared/UtilShared.cs b/Game.Shared/UtilShared.cs index 335015bbe..d00f92921 100644 --- a/Game.Shared/UtilShared.cs +++ b/Game.Shared/UtilShared.cs @@ -43,7 +43,7 @@ public static int SeedFileLineHash(int seedvalue, ReadOnlySpan sharedname, return (int)(retval); } - public static float SharedRandomFloat(ReadOnlySpan sharedname, int minVal, int maxVal, int additionalSeed = 0) { + public static float SharedRandomFloat(ReadOnlySpan sharedname, float minVal, float maxVal, int additionalSeed = 0) { int seed = SeedFileLineHash(BaseEntity.GetPredictionRandomSeed(), sharedname, additionalSeed); RandomSeed(seed); return RandomFloat(minVal, maxVal); diff --git a/Source.Common/AssertDialog.cs b/Source.Common/AssertDialog.cs index 4ae4945e3..b44ab42a4 100644 --- a/Source.Common/AssertDialog.cs +++ b/Source.Common/AssertDialog.cs @@ -144,7 +144,7 @@ public static unsafe bool DoNewAssertDialog(ReadOnlySpan file, int line, R IgnoreAssertsInCurrentFile(result.AssertInfo.FileName); break; case AssertDialogResultType.Ignore: - if (result.UserInfo.LineRange > 0) { + if (result.UserInfo.IgnoreNumTimes > 1) { AssertDisable pDisable = IgnoreAssertsNearby(result.AssertInfo.FileName, result.AssertInfo.Line, 0); pDisable.IgnoreTimes = result.UserInfo.IgnoreNumTimes - 1; } @@ -153,10 +153,10 @@ public static unsafe bool DoNewAssertDialog(ReadOnlySpan file, int line, R IgnoreAssertsNearby(result.AssertInfo.FileName, result.AssertInfo.Line, 0); break; case AssertDialogResultType.IgnoreNearby: - if (result.UserInfo.IgnoreNumTimes < 1) + if (result.UserInfo.LineRange < 1) break; - IgnoreAssertsNearby(result.AssertInfo.FileName, result.AssertInfo.Line, result.UserInfo.IgnoreNumTimes); + IgnoreAssertsNearby(result.AssertInfo.FileName, result.AssertInfo.Line, result.UserInfo.LineRange); break; case AssertDialogResultType.IgnoreAll: AssertsEnabled = false; diff --git a/Source.Common/Commands/ConVar.cs b/Source.Common/Commands/ConVar.cs index 7cdf929a2..d983506c7 100644 --- a/Source.Common/Commands/ConVar.cs +++ b/Source.Common/Commands/ConVar.cs @@ -241,15 +241,18 @@ private void ChangeStringValue(ReadOnlySpan tempValue, double dbOldValue) value = new(tempValue); if (!Equals(oldValue, value)) { - Changed?.Invoke(this, new() { + ConVarChangeContext ctx = new() { Old = oldValue, New = value - }); + }; + Changed?.Invoke(this, in ctx); - // How do we link up global change callbacks? An interesting dilemma... + CVar.CallGlobalChangeCallbacks(this, in ctx); } } + static ICvar CVar => field ??= Singleton(); + public virtual void SetValue(ReadOnlySpan value) { parent!.InternalSetValue(value); } diff --git a/Source.Common/Commands/Cvar.cs b/Source.Common/Commands/Cvar.cs index bf84dfc80..389a9dba5 100644 --- a/Source.Common/Commands/Cvar.cs +++ b/Source.Common/Commands/Cvar.cs @@ -23,6 +23,7 @@ public Cvar(ICommandLine CommandLine, IServiceProvider services, ICvarQuery cvar this.cvarQuery = cvarQuery; } public event FnChangeCallback? Changed; + public void CallGlobalChangeCallbacks(ConVar var, in ConVarChangeContext ctx) => Changed?.Invoke(var, in ctx); List DisplayFuncs = []; Assembly? NextDLLIdentifier; diff --git a/Source.Common/Commands/ICvar.cs b/Source.Common/Commands/ICvar.cs index 887b50a1f..1f815fb51 100644 --- a/Source.Common/Commands/ICvar.cs +++ b/Source.Common/Commands/ICvar.cs @@ -42,6 +42,7 @@ public interface ICvar IEnumerable GetCommands(); event FnChangeCallback? Changed; + void CallGlobalChangeCallbacks(ConVar var, in ConVarChangeContext ctx); void InstallConsoleDisplayFunc(IConsoleDisplayFunc displayFunc); void RemoveConsoleDisplayFunc(IConsoleDisplayFunc displayFunc); diff --git a/Source.Common/MaterialSystem/PixelWriter.cs b/Source.Common/MaterialSystem/PixelWriter.cs index 87bb814bc..862e59c8d 100644 --- a/Source.Common/MaterialSystem/PixelWriter.cs +++ b/Source.Common/MaterialSystem/PixelWriter.cs @@ -219,7 +219,7 @@ internal void SetFormat(ImageFormat format, uint stride) { // FIXME: Add more color formats as need arises default: { if (!format_error_printed[(int)format]) { - Assert(false); + Assert(false, $"Unsupported image format {format}"); Msg($"PixelWriter.SetPixelMemory: Unsupported image format {format}\n"); format_error_printed[(int)format] = true; } diff --git a/Source.Engine/CvarUtilities.cs b/Source.Engine/CvarUtilities.cs index b3b95b3c1..0069d2cee 100644 --- a/Source.Engine/CvarUtilities.cs +++ b/Source.Engine/CvarUtilities.cs @@ -1,5 +1,6 @@ using Source.Common; using Source.Common.Commands; +using Source.Common.Networking; using Source.Engine.Client; using Source.Engine.Server; @@ -7,6 +8,38 @@ namespace Source.Engine; public class CvarUtilities(ICvar cvar, Host Host, Cmd cmd) { + public static void ConVarNetworkChangeCallback(IConVar conVar, in ConVarChangeContext ctx) { + ConVar var = (ConVar)conVar; + if (strcmp(var.GetString(), ctx.Old) == 0) + return; + + if (var.IsFlagSet(FCvar.UserInfo)) { + if (cl.IsConnected()) { + NET_SetConVar convar = new(); + convar.AddCVar(var.GetName(), var.GetString()); + cl.NetChannel!.SendNetMsg(convar); + } + } + + if (var.IsFlagSet(FCvar.Notify)) { + IGameEvent? ev = g_GameEventManager.CreateEvent("server_cvar"); + + if (ev != null) { + ev.SetString("cvarname", var.GetName()); + + if (var.IsFlagSet(FCvar.Protected)) + ev.SetString("cvarvalue", "***PROTECTED***"); + else + ev.SetString("cvarvalue", var.GetString()); + + g_GameEventManager.FireEvent(ev); + } + } + + // if (var.IsFlagSet(FCvar.Replicated) && sv.IsActive()) // TODO + // SV_ReplicateConVarChange((ConVar)conVar, var.GetString()); + } + public unsafe bool IsCommand(in TokenizedCommand args) { int c = args.ArgC(); if (c == 0) diff --git a/Source.Engine/Host.cs b/Source.Engine/Host.cs index 2c6d421fe..afd1568e3 100644 --- a/Source.Engine/Host.cs +++ b/Source.Engine/Host.cs @@ -524,6 +524,7 @@ public void Init(bool dedicated) { Cbuf = engineAPI.InitSubsystem()!; Cmd = engineAPI.InitSubsystem()!; Cvar = engineAPI.InitSubsystem()!; + Cvar.Changed += CvarUtilities.ConVarNetworkChangeCallback; // TODO CvarQuery soundServices = engineAPI.GetRequiredService(); #if !SWDS View = engineAPI.InitSubsystem()!; diff --git a/Source.SDLManager/SourceDllMain.cs b/Source.SDLManager/SourceDllMain.cs index ce472f079..aaf9e74bb 100644 --- a/Source.SDLManager/SourceDllMain.cs +++ b/Source.SDLManager/SourceDllMain.cs @@ -148,12 +148,16 @@ string lpszFace // Typeface name [DllImport("user32.dll")] static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); + [DllImport("user32.dll")] + static extern uint GetDlgItemInt(IntPtr hDlg, int nIDDlgItem, IntPtr lpTranslated, int bSigned); + [DllImport("user32.dll")] static extern int SetBkMode(IntPtr hdc, int mode); const nint HTCLIENT = 0x0001; const nint HTCAPTION = 0x0002; static AssertDialogOutgoing outgoing; + const int SS_PATHELLIPSIS = 32768; const nint IGNORE_TIMES_INPUT = 280; const nint IGNORE_NEARBY_INPUT = 281; const nint VIEW_STACK_TRACE = 282; @@ -200,6 +204,8 @@ static unsafe IntPtr WndProc(IntPtr hWnd, uint message, void* wParam, void* lPar break; writeHandledType: outgoing.Type = result; + outgoing.IgnoreNumTimes = (int)GetDlgItemInt(hWnd, (int)IGNORE_TIMES_INPUT, 0, 0); + outgoing.LineRange = (int)GetDlgItemInt(hWnd, (int)IGNORE_NEARBY_INPUT, 0, 0); handled = true; DestroyWindow(hWnd); return 1; @@ -240,7 +246,7 @@ private static unsafe void AssertDialog_OnMainThreadAssert(ref AssertDialog.Asse int curLine = 0; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// nint fileLabel = CreateWindowEx(0, "STATIC", $"File: {result.AssertInfo.FileName}", - WindowStyles.WS_VISIBLE | WindowStyles.WS_CHILD, + WindowStyles.WS_VISIBLE | WindowStyles.WS_CHILD | (WindowStyles)SS_PATHELLIPSIS, padding, padding + (curLine * (lineHeight + linePadding)), w - (padding * 2), lineHeight, hwnd, 0, 0, 0); curLine++; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////