From 2726b24360dfb8a6651ee31f0898c75e2b1ae113 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 4 Nov 2026 22:06:31 +0000 Subject: [PATCH] Constraints --- Game.Client/GarrysMod/LuaRender.cs | 29 + Game.Client/InMain.cs | 10 + Game.Server/BaseAnimating.cs | 22 +- Game.Server/BaseEntity.cs | 18 + Game.Server/EntityList.cs | 82 +- Game.Server/LogicEntities.cs | 75 +- Game.Server/PhysConstraint.cs | 1599 ++++++++++++++++- Game.Server/PhysController.cs | 851 +++++++++ Game.Server/PhysObj.cs | 251 +++ Game.Server/Player.cs | 3 + Game.Server/PlayerCommand.cs | 24 + Game.Server/RagdollProp.cs | 8 + Game.Server/Util.cs | 15 + Game.Shared/GarrysMod/LuaEntity.cs | 147 +- Game.Shared/GarrysMod/LuaGlobalFunctions.cs | 19 + Game.Shared/GarrysMod/LuaPhysObj.cs | 2 + Game.Shared/GarrysMod/SENT_Anim.cs | 67 +- Game.Shared/PhysicsShared.cs | 5 +- Game.Shared/UserCmd.cs | 4 +- .../NetworkVarGenerator.FieldAccessors.cs | 4 +- Source.Common/DataMap.cs | 12 +- 21 files changed, 3216 insertions(+), 31 deletions(-) create mode 100644 Game.Server/PhysController.cs diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index 2b9ee8e0d..cea079a63 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -620,6 +620,35 @@ static int Clear(ILuaInterface lua) { return 0; } + [LuaFunction] + static int SetMaterial(ILuaInterface lua) { + IMaterial? material = (IMaterial?)LuaMaterial.LC_IMaterial.Get(1); + if (material == null) + return 0; + using MatRenderContextPtr renderContext = new(materials); + CurrentMaterial.Init(material); + if (CurrentMaterial.IsNotNull) + renderContext.Bind(CurrentMaterial.Get()); + return 0; + } + + static readonly MaterialReference CurrentMaterial = new(); + +#if CLIENT_DLL + [LuaFunction] + static int DrawSprite(ILuaInterface lua) { + Vector3 pos = LuaVector.Get_Vector(1); + ILuaObject? colorObj = lua.GetObject(4); + Color color = new(255, 255, 255, 255); + if (colorObj != null && colorObj.isTable()) + color = new((byte)(int)colorObj.GetMemberFloat("r", 255), (byte)(int)colorObj.GetMemberFloat("g", 255), (byte)(int)colorObj.GetMemberFloat("b", 255), (byte)(int)colorObj.GetMemberFloat("a", 255)); + float height = (float)lua.GetNumber(3); + float width = (float)lua.GetNumber(2); + BeamDraw.DrawSprite(pos, width, height, color); + return 0; + } +#endif + [LuaFunction] static int ClearDepth(ILuaInterface lua) { bool stencil = lua.GetType(1) == (int)LuaType.Nil || lua.GetBool(1); diff --git a/Game.Client/InMain.cs b/Game.Client/InMain.cs index acb879325..eda25f57d 100644 --- a/Game.Client/InMain.cs +++ b/Game.Client/InMain.cs @@ -295,6 +295,16 @@ public void CreateMove(int sequenceNumber, double inputSampleFrametime, bool act cmd.RandomSeed = (int)(MD5Value.PseudoRandom((uint)sequenceNumber) & 0x7fffffff); #if GMOD_DLL + int buttonsPressed = 0; + for (ButtonCode code = ButtonCode.Key0; code < ButtonCode.Last; code++) { + bool isMouse = code >= ButtonCode.MouseFirst && code <= ButtonCode.MouseLast; + if (vguiInput.GetFocus() == null || isMouse) { + if (inputsystem.IsButtonDown(code) || (isMouse && vguiInput.IsMouseDown(code))) + cmd.ButtonsPressed[buttonsPressed++] = (byte)code; + if (buttonsPressed > 4) + break; + } + } MouseWheel = 0; #endif } diff --git a/Game.Server/BaseAnimating.cs b/Game.Server/BaseAnimating.cs index 9b1597fc6..6f91bd945 100644 --- a/Game.Server/BaseAnimating.cs +++ b/Game.Server/BaseAnimating.cs @@ -379,7 +379,7 @@ public Activity GetSequenceActivity(int sequence) { public bool IsModelScaled() => ModelScale > 1.0f + FLT_EPSILON || ModelScale < 1.0f - FLT_EPSILON; public float GetModelScale() => ModelScale; - StudioHdr? StudioHdr; + protected StudioHdr? StudioHdr; public Model? GetModel() => modelinfo.GetModel(GetModelIndex()); // todo... @@ -831,6 +831,26 @@ public bool GetAttachment(ReadOnlySpan attachmentName, out Vector3 absOrig } + public int GetAttachmentBone(int attachment) { + StudioHdr? studioHdr = GetModelPtr(); + if (studioHdr == null) + return 0; + + if (attachment < 1 || attachment > studioHdr.GetNumAttachments()) + return 0; + + return studioHdr.GetAttachmentBone(attachment - 1); + } + + public int GetPhysicsBone(int boneIndex) { + StudioHdr? studioHdr = GetModelPtr(); + if (studioHdr != null) { + if (boneIndex >= 0 && boneIndex < studioHdr.NumBones()) + return studioHdr.Bone(boneIndex).PhysicsBone; + } + return 0; + } + public bool GetAttachment(int attachment, out Vector3 absOrigin, out QAngle absAngles) { Matrix3x4 attachmentToWorld; diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index 68bbe12b9..e6c7dfc12 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -1770,6 +1770,9 @@ public virtual void VPhysicsFriction(IPhysicsObject obj, float energy, int surfa public virtual bool PhysicsSplash(in Vector3 centerPoint, in Vector3 normal, float rawSpeed, float scaledSpeed) => false; public IPhysicsObject? VPhysicsGetObject() => PhysicsObject; +#if GMOD_DLL + public virtual IPhysicsObject? VPhysicsGetElement(int index) => PhysicsObject; +#endif public void VPhysicsSetObject(IPhysicsObject? physics) { if (PhysicsObject != null && physics != null) @@ -3012,6 +3015,14 @@ public virtual void Precache() { } + public virtual void NotifySystemEvent(BaseEntity notify, NotifySystemEvent eventType, in NotifySystemEventParams parms) { } + +#if GMOD_DLL + public virtual void SetPhysObject(int index, IPhysicsObject? obj) { } + public virtual void SetEntity(ReadOnlySpan name, BaseEntity? entity) { } + public virtual void StartMotionController() { } +#endif + static bool _AllowPrecache; public static bool IsPrecacheAllowed() => _AllowPrecache; public static bool SetAllowPrecache(bool allow) => _AllowPrecache = allow; @@ -3551,6 +3562,8 @@ struct TeleportListEntry static void TeleportEntity(BaseEntity sourceEntity, ref TeleportListEntry entry, Vector3? newPosition, QAngle? newAngles, Vector3? newVelocity) { BaseEntity teleport = entry.Entity; + Vector3 prevOrigin = entry.PrevAbsOrigin; + QAngle prevAngles = entry.PrevAbsAngles; SolidFlags solidFlags = (SolidFlags)teleport.GetSolidFlags(); teleport.AddSolidFlags(SolidFlags.NotSolid); @@ -3580,6 +3593,7 @@ static void TeleportEntity(BaseEntity sourceEntity, ref TeleportListEntry entry, teleport.CalcAbsolutePosition(); } IPhysicsObject? phys = teleport.VPhysicsGetObject(); + bool rotatePhysics = false; // handle physics objects / shadows if (phys != null) { @@ -3591,10 +3605,14 @@ static void TeleportEntity(BaseEntity sourceEntity, ref TeleportListEntry entry, // don't rotate physics on players or bbox entities if (teleport.IsPlayer() || teleport.GetSolid() == SolidType.BBox) rotAngles = vec3_angle; + else + rotatePhysics = true; phys.SetPosition(teleport.GetAbsOrigin(), rotAngles, true); } + g_pNotify.ReportTeleportEvent(teleport, prevOrigin, prevAngles, rotatePhysics); + teleport.SetSolidFlags(solidFlags); } diff --git a/Game.Server/EntityList.cs b/Game.Server/EntityList.cs index 35d78d72b..8ba7e0dd0 100644 --- a/Game.Server/EntityList.cs +++ b/Game.Server/EntityList.cs @@ -14,6 +14,8 @@ namespace Game.Server; public static class EntityListGlobals { + public static readonly INotify g_pNotify = NotifyList.g_NotifyList; + [ConCommand("report_entities", "List all entities")] static void report_entities() { if (!Util.IsCommandIssuedByServerAdmin()) @@ -759,6 +761,80 @@ public void FrameUpdatePostEntityThink() { } } +public struct EntityNotify +{ + public BaseEntity Notify; + public BaseEntity Watched; +} + +public class NotifyList : INotify, IEntityListener +{ + public static readonly NotifyList g_NotifyList = new(); + + readonly List List = []; + + public void AddEntity(BaseEntity notify, BaseEntity watched) { + watched.AddEFlags(EFL.Notify); + List.Add(new() { Notify = notify, Watched = watched }); + } + + public void RemoveEntity(BaseEntity notify, BaseEntity watched) { + for (int i = List.Count; --i >= 0;) { + if (List[i].Notify == notify && List[i].Watched == watched) + FastRemove(i); + } + } + + public void ReportNamedEvent(BaseEntity entity, ReadOnlySpan inputName) { + Variant_t emptyVariant = default; + + if (!entity.IsEFlagSet(EFL.Notify)) + return; + + for (int i = 0; i < List.Count; i++) { + if (List[i].Watched == entity) + List[i].Notify.AcceptInput(inputName, entity, entity, emptyVariant, 0); + } + } + + public void LevelInitPreEntity() => gEntList.AddListenerEntity(this); + + public void LevelShutdownPreEntity() { + gEntList.RemoveListenerEntity(this); + List.Clear(); + } + + public void OnEntityCreated(BaseEntity entity) { } + + public void OnEntityDeleted(BaseEntity entity) { + ((INotify)this).ReportDestroyEvent(entity); + ClearEntity(entity); + } + + public void ClearEntity(BaseEntity notify) { + for (int i = List.Count; --i >= 0;) { + if (List[i].Notify == notify || List[i].Watched == notify) + FastRemove(i); + } + } + + public void ReportSystemEvent(BaseEntity entity, NotifySystemEvent eventType, in NotifySystemEventParams parms) { + if (!entity.IsEFlagSet(EFL.Notify)) + return; + + for (int i = 0; i < List.Count; i++) { + if (List[i].Watched == entity) + List[i].Notify.NotifySystemEvent(entity, eventType, parms); + } + } + + void FastRemove(int i) { + int last = List.Count - 1; + List[i] = List[last]; + List.RemoveAt(last); + } +} + public class EntityListSystem : AutoGameSystemPerFrame { public static EntityListSystem g_EntityListSystem = new(); @@ -766,8 +842,12 @@ public class EntityListSystem : AutoGameSystemPerFrame bool RespawnAllEntities; public override void LevelInitPreEntity() { - SimThinkManager.g_SimThinkManager.LevelInitPreEntity(); + NotifyList.g_NotifyList.LevelInitPreEntity(); EntityTouchManager.g_TouchManager.LevelInitPreEntity(); + SimThinkManager.g_SimThinkManager.LevelInitPreEntity(); + } + public override void LevelShutdownPreEntity() { + NotifyList.g_NotifyList.LevelShutdownPreEntity(); } public override void LevelShutdownPostEntity() { SimThinkManager.g_SimThinkManager.LevelShutdownPostEntity(); diff --git a/Game.Server/LogicEntities.cs b/Game.Server/LogicEntities.cs index b50118d30..e7235b46f 100644 --- a/Game.Server/LogicEntities.cs +++ b/Game.Server/LogicEntities.cs @@ -6,6 +6,10 @@ using Source.Common.Physics; using Source.Common.Server; +#if GMOD_DLL +using Game.Server.GarrysMod; +#endif + using System.Numerics; namespace Game.Server; @@ -1687,12 +1691,30 @@ public class LogicCollisionPair : LogicalEntity string? NameAttach2; bool Disabled; bool Succeeded; +#if GMOD_DLL + InlineArray2 PhysObjects; + InlineArray2 Entities; + InlineArray2 PhysIndices; + bool DisableOnRemove; + + public LogicCollisionPair() { + Entities[0] = new(); + Entities[1] = new(); + } +#endif public static readonly new DataMap DataDesc = new(typeof(LogicCollisionPair), LogicalEntity.DataDesc, [ DEFINE.KEYFIELD(nameof(NameAttach1), FieldType.String, "attach1"), DEFINE.KEYFIELD(nameof(NameAttach2), FieldType.String, "attach2"), DEFINE.KEYFIELD(nameof(Disabled), FieldType.Boolean, "startdisabled"), DEFINE.FIELD(nameof(Succeeded), FieldType.Boolean), +#if GMOD_DLL + DEFINE.KEYFIELD(nameof(DisableOnRemove), FieldType.Boolean, "disable_on_remove"), + DEFINE.FIELD("Entities[0]", FieldType.EHandle), + DEFINE.FIELD("Entities[1]", FieldType.EHandle), + DEFINE.FIELD("PhysIndices[0]", FieldType.Integer), + DEFINE.FIELD("PhysIndices[1]", FieldType.Integer), +#endif // Inputs DEFINE.INPUTFUNC(FieldType.Void, "DisableCollisions", nameof(InputDisableCollisions), (INPUTFUNCPTR)((self, data) => ((LogicCollisionPair)self).InputDisableCollisions(data))), @@ -1709,14 +1731,65 @@ public class LogicCollisionPair : LogicalEntity return g_PhysWorldObject; IPhysicsObject? physics = PhysicsHook.FindPhysicsObjectByName(name, errorEntity); - if (physics == null) + if (physics == null) { DevWarning($"{errorEntity.GetClassname()}: can't find {name}\n"); +#if GMOD_DLL + physics = g_PhysWorldObject; +#endif + } return physics; } +#if GMOD_DLL + public override void SetPhysObject(int index, IPhysicsObject? obj) { + PhysObjects[index] = obj; + BaseEntity? entity = (BaseEntity?)obj!.GetGameData(); + Entities[index].Set(entity); + PhysIndices[index] = 0; + entity = Entities[index].Get(); + if (entity != null) { + IPhysicsObject?[] list = new IPhysicsObject?[VPHYSICS_MAX_OBJECT_LIST_COUNT]; + int count = entity.VPhysicsGetObjectList(list); + if (count > 1) { + for (int i = 0; i < count; i++) { + if (list[i] == obj) + PhysIndices[index] = i; + } + } + } + } + + public override void OnRestore() { + BaseEntity? entity0 = Entities[0].Get(); + if (entity0 != null) + PhysObjects[0] = entity0.VPhysicsGetElement(PhysIndices[0]); + BaseEntity? entity1 = Entities[1].Get(); + if (entity1 != null) + PhysObjects[1] = entity1.VPhysicsGetElement(PhysIndices[1]); + Activate(); + } + + public override void UpdateOnRemove() { + if (DisableOnRemove && (!Succeeded || Disabled)) + EnableCollisions(true); + base.UpdateOnRemove(); + } +#endif + public void EnableCollisions(bool enable) { +#if GMOD_DLL + if (PhysObjects[0] != null || PhysObjects[1] != null) { + if (!LuaPhysObj.IsPhysicsObjectValid(PhysObjects[0])) + PhysObjects[0] = null; + if (!LuaPhysObj.IsPhysicsObjectValid(PhysObjects[1])) + PhysObjects[1] = null; + } + IPhysicsObject? physics0 = PhysObjects[0] ?? FindPhysicsObjectByNameOrWorld(NameAttach1, this); + IPhysicsObject? physics1 = PhysObjects[1] ?? FindPhysicsObjectByNameOrWorld(NameAttach2, this); +#else IPhysicsObject? physics0 = FindPhysicsObjectByNameOrWorld(NameAttach1, this); IPhysicsObject? physics1 = FindPhysicsObjectByNameOrWorld(NameAttach2, this); +#endif // need two different objects to do anything if (physics0 != null && physics1 != null && physics0 != physics1) { diff --git a/Game.Server/PhysConstraint.cs b/Game.Server/PhysConstraint.cs index 2e1d536f8..2a0f67c94 100644 --- a/Game.Server/PhysConstraint.cs +++ b/Game.Server/PhysConstraint.cs @@ -1,13 +1,1610 @@ global using static Game.Server.PhysConstraintEvents; +global using static Game.Server.PhysConstraintGlobals; + +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Audio; +using Source.Common.Commands; +using Source.Common.Mathematics; using Source.Common.Physics; +using Source.Common.SoundEmitterSystem; + +#if GMOD_DLL +using Game.Server.GarrysMod; +#endif + +using System.Numerics; namespace Game.Server; +public static class PhysConstraintGlobals +{ + public const int SF_CONSTRAINT_DISABLE_COLLISION = 1; + public const int SF_SLIDE_LIMIT_ENDS = 2; + public const int SF_PULLEY_RIGID = 2; + public const int SF_LENGTH_RIGID = 2; + public const int SF_RAGDOLL_FREEMOVEMENT = 2; + public const int SF_CONSTRAINT_START_INACTIVE = 4; + public const int SF_CONSTRAINT_ASSUME_WORLD_GEOMETRY = 8; + public const int SF_CONSTRAINT_NO_CONNECT_UNTIL_ACTIVATED = 16; + + public static readonly ConVar g_debug_constraint_sounds = new("g_debug_constraint_sounds", "0", FCvar.Cheat, "Enable debug printing about constraint sounds."); + + internal static readonly AnchorList g_AnchorList = new("CAnchorList"); + + public static void PhysTeleportConstrainedEntity(BaseEntity teleportSource, IPhysicsObject? object0, IPhysicsObject? object1, in Vector3 prevPosition, in QAngle prevAngles, bool physicsRotate) { + if (object0 == null || object1 == null) + return; + + BaseEntity? entity0 = (BaseEntity?)object0.GetGameData(); + BaseEntity? entity1 = (BaseEntity?)object1.GetGameData(); + if (entity0 == null || entity1 == null) + return; + + BaseEntity fixup = entity1; + if (teleportSource != entity0) { + if (teleportSource != entity1) { + Msg("Bogus teleport notification!!\n"); + return; + } + fixup = entity0; + } + + if (fixup.GetMoveType() != MoveType.VPhysics) + return; + + if (fixup.VPhysicsGetObject() == null || !fixup.VPhysicsGetObject()!.IsMoveable()) + return; + + QAngle oldAngles = prevAngles; + + if (!physicsRotate) + oldAngles = teleportSource.GetAbsAngles(); + + MathLib.AngleMatrix(oldAngles, prevPosition, out Matrix3x4 startCoord); + MathLib.MatrixInvert(startCoord, out Matrix3x4 startInv); + MathLib.ConcatTransforms(teleportSource.EntityToWorldTransform(), startInv, out Matrix3x4 xform); + + MathLib.ConcatTransforms(xform, fixup.EntityToWorldTransform(), out Matrix3x4 endCoord); + MathLib.MatrixAngles(endCoord, out QAngle fixupAngles, out Vector3 fixupPos); + fixup.Teleport(fixupPos, fixupAngles, null); + } + + static void DrawPhysicsBounds(IPhysicsObject obj, int r, int g, int b, int a) { + PhysCollide collide = obj.GetCollide(); + obj.GetPosition(out Vector3 pos, out QAngle angles); + physcollision.CollideGetAABB(out Vector3 mins, out Vector3 maxs, collide, vec3_origin, vec3_angle); + mins -= new Vector3(1, 1, 1); + maxs += new Vector3(1, 1, 1); + DebugOverlay.BoxAngles(pos, mins, maxs, angles, r, g, b, a, 0); + } + + internal static void DrawConstraintObjectsAxes(BaseEntity? constraintEntity, IPhysicsConstraint? constraint) { + if (constraint == null || constraintEntity == null) + return; + bool xform = constraint.GetConstraintTransform(out Matrix3x4 xformRef, out Matrix3x4 xformAtt); + IPhysicsObject? refObj = constraint.GetReferenceObject(); + + if (refObj != null && !refObj.IsStatic()) { + if (xform) { + MathLib.MatrixAngles(xformRef, out QAngle angles, out Vector3 pos); + refObj.LocalToWorld(out Vector3 posWorld, pos); + DebugOverlay.Axis(posWorld, vec3_angle, 12, false, 0); + } + DrawPhysicsBounds(refObj, 0, 255, 0, 12); + } + IPhysicsObject? attach = constraint.GetAttachedObject(); + if (attach != null && !attach.IsStatic()) { + if (xform) { + MathLib.MatrixAngles(xformAtt, out QAngle angles, out Vector3 pos); + attach.LocalToWorld(out Vector3 posWorld, pos); + DebugOverlay.Axis(posWorld, vec3_angle, 12, false, 0); + } + DrawPhysicsBounds(attach, 255, 0, 0, 12); + } + } + + public static bool GetConstraintAttachments(BaseEntity entity, Span attachOut, Span attachVPhysics) { + if (entity is PhysConstraint constraintEntity) { + IPhysicsConstraint? constraint = constraintEntity.GetPhysConstraint(); + if (constraint != null) { + IPhysicsObject? refObj = constraint.GetReferenceObject(); + attachVPhysics[0] = refObj; + attachOut[0] = refObj != null ? (BaseEntity?)refObj.GetGameData() : null; + IPhysicsObject? attach = constraint.GetAttachedObject(); + attachVPhysics[1] = attach; + attachOut[1] = attach != null ? (BaseEntity?)attach.GetGameData() : null; + return true; + } + } + return false; + } + + public static void DebugConstraint(BaseEntity entity) { + if (entity is PhysConstraint constraintEntity) { + IPhysicsConstraint? constraint = constraintEntity.GetPhysConstraint(); + constraint?.OutputDebugInfo(); + } + } + + internal static void FindPhysicsAnchor(string? name, ref HlConstraintInfo info, int index, BaseEntity errorEntity) { +#if GMOD_DLL + if (info.Objects[0] != null || info.Objects[1] != null) { + if (!LuaPhysObj.IsPhysicsObjectValid(info.Objects[0])) + info.Objects[0] = null; + if (!LuaPhysObj.IsPhysicsObjectValid(info.Objects[1])) + info.Objects[1] = null; + } +#endif + int anchorIndex = g_AnchorList.Find(name); + if (anchorIndex >= 0) { + ref ConstraintAnchorT anchor = ref g_AnchorList.Get(anchorIndex); + BaseEntity? entity = anchor.Entity.Get(); + if (entity != null) { + info.MassScale[index] = anchor.MassScale; + bool wroteAttachment = false; + if (anchor.ParentAttachment > 0) { + BaseAnimating? anim = entity.GetBaseAnimating(); + if (anim != null) { + IPhysicsObject?[] list = new IPhysicsObject?[VPHYSICS_MAX_OBJECT_LIST_COUNT]; + int listCount = entity.VPhysicsGetObjectList(list); + int physicsBone = anim.GetPhysicsBone(anim.GetAttachmentBone(anchor.ParentAttachment)); + if (physicsBone < listCount) { + info.Objects[index] = list[physicsBone]; + anim.GetAttachment(anchor.ParentAttachment, out Vector3 pos, out QAngle _); + list[physicsBone]!.WorldToLocal(out info.AnchorPosition[index], pos); + wroteAttachment = true; + } + } + } + if (!wroteAttachment) { + info.AnchorPosition[index] = anchor.LocalOrigin; + info.Objects[index] = entity.VPhysicsGetObject(); + } + } + else + anchorIndex = -1; + } + if (anchorIndex < 0) { + info.AnchorPosition[index] = vec3_origin; + info.Objects[index] = PhysicsHook.FindPhysicsObjectByName(name, errorEntity); + info.MassScale[index] = 1.0f; + } + } + + internal static IPhysicsConstraintGroup? GetRagdollConstraintGroup(IPhysicsObject? obj) { + if (obj != null) { + BaseEntity? entity = (BaseEntity?)obj.GetGameData(); + Ragdoll? ragdoll = RagdollProp.Ragdoll_GetRagdoll(entity!); + if (ragdoll != null) + return ragdoll.Group; + } + return null; + } + + public static IPhysicsConstraintGroup? GetConstraintGroup(string? systemName) { +#if GMOD_DLL + if (LuaGlobalFunctions.g_PhysConstrantSystem.Get() is PhysConstraintSystem globalGroup) + return globalGroup.GetVPhysicsGroup(); +#endif + BaseEntity? machine = gEntList.FindEntityByName(null, systemName); + + if (machine != null) { + if (machine is PhysConstraintSystem group) + return group.GetVPhysicsGroup(); + } + return null; + } + + internal static int GetUnitAxisIndex(in Vector3 axis) { + bool valid = false; + int index = -1; + + for (int i = 0; i < 3; i++) { + if (axis[i] != 0) { + if (MathF.Abs(axis[i]) == 1) { + if (index < 0) { + index = i; + valid = true; + continue; + } + } + valid = false; + } + } + return valid ? index : -1; + } +} + +public struct ConstraintAnchorT +{ + public Vector3 LocalOrigin; + public EHANDLE Entity; + public int ParentAttachment; + public string? Name; + public float MassScale; +} + +public class AnchorList(ReadOnlySpan name) : AutoGameSystem(name) +{ + readonly List List = []; + + public override void LevelShutdownPostEntity() => List.Clear(); + + public void AddToList(BaseEntity entity, float massScale) { + ConstraintAnchorT anchor = new(); + anchor.Entity = new(); + anchor.Entity.Set(entity.GetParent()); + anchor.ParentAttachment = entity.ParentAttachment; + anchor.Name = entity.GetEntityName(); + anchor.LocalOrigin = entity.GetLocalOrigin(); + anchor.MassScale = massScale; + List.Add(anchor); + } + + public int Find(string? name) { + for (int i = List.Count - 1; i >= 0; i--) { + if (FStrEq(List[i].Name ?? "", name ?? "")) + return i; + } + return -1; + } + + public ref ConstraintAnchorT Get(int index) => ref System.Runtime.InteropServices.CollectionsMarshal.AsSpan(List)[index]; +} + +[LinkEntityToClass("info_constraint_anchor")] +public class ConstraintAnchor : PointEntity +{ + public static readonly new DataMap DataDesc = new(typeof(ConstraintAnchor), BaseEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(MassScale), FieldType.Float, "massScale"), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + public float MassScale; + + public ConstraintAnchor() { + MassScale = 1.0f; + } + + public override void Spawn() { + if (GetParent() != null) { + g_AnchorList.AddToList(this, MassScale); + Util.Remove(this); + } + } +} + +[LinkEntityToClass("phys_constraintsystem")] +public class PhysConstraintSystem : LogicalEntity +{ + public static readonly new DataMap DataDesc = new(typeof(PhysConstraintSystem), BaseEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(AdditionalIterations), FieldType.Integer, "additionaliterations"), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + IPhysicsConstraintGroup? Machine; + int AdditionalIterations; + + public IPhysicsConstraintGroup? GetVPhysicsGroup() => Machine; + + public override void Spawn() { + if (Machine != null) + Error("CPhysConstraintSystem already has constraint group?\n"); + + ConstraintGroupParams group = default; + group.Defaults(); + group.AdditionalIterations = AdditionalIterations; + Machine = physenv.CreateConstraintGroup(group); + } +} + +public struct HlConstraintInfo +{ + public HlConstraintInfo() { + Objects[0] = Objects[1] = null; + Group = null; + AnchorPosition[0].Init(); + AnchorPosition[1].Init(); + Swapped = false; + MassScale[0] = MassScale[1] = 1.0f; + } + + public InlineArray2 AnchorPosition; + public InlineArray2 Objects; + public IPhysicsConstraintGroup? Group; + public InlineArray2 MassScale; + public bool Swapped; +} + +public abstract class PhysConstraint : LogicalEntity +{ + public static readonly new DataMap DataDesc = new(typeof(PhysConstraint), BaseEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(NameSystem), FieldType.String, "constraintsystem"), + DEFINE.KEYFIELD(nameof(NameAttach1), FieldType.String, "attach1"), + DEFINE.KEYFIELD(nameof(NameAttach2), FieldType.String, "attach2"), + DEFINE.KEYFIELD(nameof(BreakSound), FieldType.SoundName, "breaksound"), + DEFINE.KEYFIELD(nameof(ForceLimit), FieldType.Float, "forcelimit"), + DEFINE.KEYFIELD(nameof(TorqueLimit), FieldType.Float, "torquelimit"), + DEFINE.KEYFIELD(nameof(MinTeleportDistance), FieldType.Float, "teleportfollowdistance"), + + DEFINE.OUTPUT(nameof(OnBreakOutput), "OnBreak", eventFuncs), + + DEFINE.INPUTFUNC(FieldType.Void, "Break", nameof(InputBreak), (INPUTFUNCPTR)((self, data) => ((PhysConstraint)self).InputBreak(data))), + DEFINE.INPUTFUNC(FieldType.Void, "ConstraintBroken", nameof(InputOnBreak), (INPUTFUNCPTR)((self, data) => ((PhysConstraint)self).InputOnBreak(data))), + + DEFINE.INPUTFUNC(FieldType.Void, "TurnOn", nameof(InputTurnOn), (INPUTFUNCPTR)((self, data) => ((PhysConstraint)self).InputTurnOn(data))), + DEFINE.INPUTFUNC(FieldType.Void, "TurnOff", nameof(InputTurnOff), (INPUTFUNCPTR)((self, data) => ((PhysConstraint)self).InputTurnOff(data))), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + protected IPhysicsConstraint? Constraint; + + protected string? NameAttach1; + protected string? NameAttach2; + protected string? BreakSound; + protected string? NameSystem; + protected float ForceLimit; + protected float TorqueLimit; + protected uint TeleportTick; + protected float MinTeleportDistance; + + protected readonly OutputEvent OnBreakOutput = new(); + +#if GMOD_DLL + protected InlineArray2 PhysObjects; +#endif + + public PhysConstraint() { + Constraint = null; + NameAttach1 = null; + NameAttach2 = null; + BreakSound = null; + NameSystem = null; + ForceLimit = 0; + TorqueLimit = 0; + TeleportTick = uint.MaxValue; + MinTeleportDistance = 0.0f; +#if GMOD_DLL + PhysObjects[0] = null; + PhysObjects[1] = null; +#endif + } + + public override void Term() { + Deactivate(); + physenv.DestroyConstraint(Constraint!); + base.Term(); + } + + public override void Precache() { + if (BreakSound != null) + PrecacheScriptSound(BreakSound); + } + + public override void Spawn() { + base.Spawn(); + + Precache(); + } + + public void ClearStaticFlag(IPhysicsObject? obj) { + if (obj == null) + return; + PhysClearGameFlags(obj, PhysicsFlags.ConstraintStatic); + } + + public virtual void Deactivate() { + if (Constraint == null) + return; + Constraint.Deactivate(); + ClearStaticFlag(Constraint.GetReferenceObject()); + ClearStaticFlag(Constraint.GetAttachedObject()); + if ((SpawnFlags & SF_CONSTRAINT_DISABLE_COLLISION) != 0) { + IPhysicsObject? refObj = Constraint.GetReferenceObject(); + IPhysicsObject? att = Constraint.GetAttachedObject(); + if (refObj != null && att != null) + PhysEnableEntityCollisions(refObj, att); + } + } + + public void OnBreak() { + Deactivate(); + if (BreakSound != null) { + PASAttenuationFilter filter = new(this, ATTN_STATIC); + + Vector3 origin = GetAbsOrigin(); + Vector3 refPos = origin, attachPos = origin; + + IPhysicsObject? refObj = Constraint!.GetReferenceObject(); + if (refObj != null && refObj != g_PhysWorldObject) { + refObj.GetPosition(out refPos, out _); + attachPos = refPos; + } + IPhysicsObject? attach = Constraint.GetAttachedObject(); + if (attach != null && attach != g_PhysWorldObject) { + attach.GetPosition(out attachPos, out _); + if (refObj == null || refObj == g_PhysWorldObject) + refPos = attachPos; + } + + origin = refPos + attachPos; + origin *= 0.5f; + + scoped EmitSound_t ep = new(); + ep.Channel = (int)SoundEntityChannel.Static; + ep.SoundName = BreakSound; + ep.Volume = VOL_NORM; + ep.SoundLevel = ATTN_TO_SNDLVL(ATTN_STATIC); + ep.Origin = ref origin; + + HSOUNDSCRIPTHANDLE handle = ep.SoundScriptHandle; + EmitSound(filter, EntIndex(), ref ep, ref handle); + } + OnBreakOutput.FireOutput(this, this); + PhysCallbackRemove(NetworkProp()); + } + + public void InputBreak(in InputData inputdata) { + Constraint?.Deactivate(); + + OnBreak(); + } + + public void InputOnBreak(in InputData inputdata) { + OnBreak(); + } + + public void InputTurnOn(in InputData inputdata) { + if (HasSpawnFlags(SF_CONSTRAINT_NO_CONNECT_UNTIL_ACTIVATED)) + ActivateConstraint(); + + if (Constraint == null || Constraint.GetReferenceObject() == null || Constraint.GetAttachedObject() == null) + return; + + Constraint.Activate(); + Constraint.GetReferenceObject()!.Wake(); + Constraint.GetAttachedObject()!.Wake(); + } + + public void InputTurnOff(in InputData inputdata) { + Deactivate(); + } + + public override int DrawDebugTextOverlays() { + int pos = base.DrawDebugTextOverlays(); + if (Constraint != null && (DebugOverlays & DebugOverlayBits.Text) != 0) { + if (Constraint.GetConstraintParams(out ConstraintBreakableParams parms)) { + if ((parms.BodyMassScale[0] != 1.0f && parms.BodyMassScale[0] != 0.0f) || (parms.BodyMassScale[1] != 1.0f && parms.BodyMassScale[1] != 0.0f)) { + string str = $"mass ratio {parms.BodyMassScale[0]:F4}:{parms.BodyMassScale[1]:F4}\n"; + DebugOverlay.EntityTextAtPosition(GetAbsOrigin(), pos, str, 0, 255, 255, 0, 255); + } + } + else + DebugOverlay.EntityTextAtPosition(GetAbsOrigin(), pos, "", 0, 255, 255, 0, 255); + + pos++; + } + return pos; + } + + public override void DrawDebugGeometryOverlays() { + if ((DebugOverlays & (DebugOverlayBits.BBox | DebugOverlayBits.Pivot | DebugOverlayBits.AbsBox)) != 0) + DrawConstraintObjectsAxes(this, Constraint); + base.DrawDebugGeometryOverlays(); + } + + public void GetBreakParams(ref ConstraintBreakableParams parms, in HlConstraintInfo info) { + parms.Defaults(); + parms.ForceLimit = lbs2kg(ForceLimit); + parms.TorqueLimit = lbs2kg(TorqueLimit); + parms.IsActive = HasSpawnFlags(SF_CONSTRAINT_START_INACTIVE) ? false : true; + parms.BodyMassScale[0] = info.MassScale[0]; + parms.BodyMassScale[1] = info.MassScale[1]; + } + + public override void NotifySystemEvent(BaseEntity notify, NotifySystemEvent eventType, in NotifySystemEventParams parms) { + if (eventType != Game.Server.NotifySystemEvent.Teleport || (uint)gpGlobals.TickCount == TeleportTick) + return; + + float distance = (parms.Teleport.PrevOrigin - notify.GetAbsOrigin()).Length(); + + if (distance <= MinTeleportDistance) + return; + + TeleportTick = (uint)gpGlobals.TickCount; + + PhysTeleportConstrainedEntity(notify, Constraint!.GetReferenceObject()!, Constraint.GetAttachedObject()!, parms.Teleport.PrevOrigin, parms.Teleport.PrevAngles, parms.Teleport.PhysicsRotate); + } + + public virtual void OnConstraintSetup(ref HlConstraintInfo info) { +#if GMOD_DLL + if (info.Objects[0] != null || info.Objects[1] != null) { + if (!LuaPhysObj.IsPhysicsObjectValid(info.Objects[0])) + info.Objects[0] = null; + if (!LuaPhysObj.IsPhysicsObjectValid(info.Objects[1])) + info.Objects[1] = null; + } +#endif + if (info.Objects[0] != null && info.Objects[1] != null) + SetupTeleportationHandling(ref info); + if ((SpawnFlags & SF_CONSTRAINT_DISABLE_COLLISION) != 0) + PhysDisableEntityCollisions(info.Objects[0], info.Objects[1]); + } + + public IPhysicsConstraint? GetPhysConstraint() => Constraint; + + public string? GetNameAttach1() => NameAttach1; + public string? GetNameAttach2() => NameAttach2; + +#if GMOD_DLL + public override void SetPhysObject(int index, IPhysicsObject? obj) { + if (index < 2) { + PhysObjects[index] = obj; + return; + } + Msg($" SetPhysObject Error. {index} is too high! Should be either 0 or 1!\n"); + } +#endif + + protected void GetConstraintObjects(ref HlConstraintInfo info) { + FindPhysicsAnchor(NameAttach1, ref info, 0, this); + FindPhysicsAnchor(NameAttach2, ref info, 1, this); + +#if GMOD_DLL + if (info.Objects[0] != null || info.Objects[1] != null) { + if (!LuaPhysObj.IsPhysicsObjectValid(info.Objects[0])) + info.Objects[0] = null; + if (!LuaPhysObj.IsPhysicsObjectValid(info.Objects[1])) + info.Objects[1] = null; + } + + if (PhysObjects[0] != null || PhysObjects[1] != null) { + if (!LuaPhysObj.IsPhysicsObjectValid(PhysObjects[0])) + PhysObjects[0] = null; + if (!LuaPhysObj.IsPhysicsObjectValid(PhysObjects[1])) + PhysObjects[1] = null; + } + + if (info.Objects[0] == null) + info.Objects[0] = PhysObjects[0]; + if (info.Objects[1] == null) + info.Objects[1] = PhysObjects[1]; + + if (info.Objects[0] == null && info.Objects[1] != null) { + info.Objects[0] = g_PhysWorldObject; + info.MassScale[0] = info.MassScale[1] = 1.0f; + } + else if (info.Objects[0] != null && info.Objects[1] == null) { + info.Objects[1] = info.Objects[0]; + info.Objects[0] = g_PhysWorldObject; + info.MassScale[0] = info.MassScale[1] = 1.0f; + info.Swapped = true; + } +#else + if (info.Objects[0] == null && info.Objects[1] != null) { + if (!string.IsNullOrEmpty(NameAttach1)) { + Warning($"Bogus constraint {GetDebugName()} (attaches ENTITY NOT FOUND:{NameAttach1} to {NameAttach2})\n"); +#if HL2_EPISODIC + info.Objects[0] = info.Objects[1] = null; + return; +#endif + } + info.Objects[0] = g_PhysWorldObject; + info.MassScale[0] = info.MassScale[1] = 1.0f; + } + else if (info.Objects[0] != null && info.Objects[1] == null) { + if (!string.IsNullOrEmpty(NameAttach2)) { + Warning($"Bogus constraint {GetDebugName()} (attaches {NameAttach1} to ENTITY NOT FOUND:{NameAttach2})\n"); +#if HL2_EPISODIC + info.Objects[0] = info.Objects[1] = null; + return; +#endif + } + info.Objects[1] = info.Objects[0]; + info.Objects[0] = g_PhysWorldObject; + info.MassScale[0] = info.MassScale[1] = 1.0f; + info.Swapped = true; + } +#endif + + info.Group = GetRagdollConstraintGroup(info.Objects[0]); + if (info.Group == null) + info.Group = GetRagdollConstraintGroup(info.Objects[1]); + } + + protected void SetupTeleportationHandling(ref HlConstraintInfo info) { +#if GMOD_DLL + if (info.Objects[0] != null || info.Objects[1] != null) { + if (!LuaPhysObj.IsPhysicsObjectValid(info.Objects[0])) + info.Objects[0] = null; + if (!LuaPhysObj.IsPhysicsObjectValid(info.Objects[1])) + info.Objects[1] = null; + } +#endif + BaseEntity? entity0 = (BaseEntity?)info.Objects[0]!.GetGameData(); + if (entity0 != null) + g_pNotify.AddEntity(this, entity0); + + BaseEntity? entity1 = (BaseEntity?)info.Objects[1]!.GetGameData(); + if (entity1 != null) + g_pNotify.AddEntity(this, entity1); + } + + public override void Activate() { + base.Activate(); + + if (HasSpawnFlags(SF_CONSTRAINT_NO_CONNECT_UNTIL_ACTIVATED) == false) { + if (!ActivateConstraint()) + Util.Remove(this); + } + } + + protected bool ActivateConstraint() { +#if GMOD_DLL + if (LuaPhysObj.gPhysCallback) { + Warning($"Tried to activate constraint ({GetDebugName()}) in physics callback! This could cause crashes! Ignoring!\n"); + return false; + } +#endif + HlConstraintInfo info = new(); + if (Constraint != null) { + info.Objects[0] = Constraint.GetReferenceObject(); + info.Objects[1] = Constraint.GetAttachedObject(); + OnConstraintSetup(ref info); + return true; + } + + GetConstraintObjects(ref info); + if (info.Objects[0] == null || info.Objects[1] == null) + return false; + + if (info.Objects[0]!.IsStatic() && info.Objects[1]!.IsStatic()) { + Warning($"Constraint ({GetEntityName()}) attached to two static objects ({NameAttach1} and {(NameAttach2 == null ? "world" : NameAttach2)})!!!\n"); + return false; + } + + if (info.Objects[0] == info.Objects[1]) + return false; + + if (info.Objects[0]!.GetShadowController() != null && info.Objects[1]!.GetShadowController() != null) { + Warning($"Constraint ({GetEntityName()}) attached to two shadow objects ({NameAttach1} and {(NameAttach2 == null ? "world" : NameAttach2)})!!!\n"); + return false; + } + IPhysicsConstraintGroup? group = GetConstraintGroup(NameSystem); + if (group == null) + group = info.Group; + Constraint = CreateConstraint(group, info); + if (Constraint == null) + return false; + + Constraint.SetGameData(this); + + group?.Activate(); + + OnConstraintSetup(ref info); + + return true; + } + + protected abstract IPhysicsConstraint? CreateConstraint(IPhysicsConstraintGroup? group, in HlConstraintInfo info); +} + +[LinkEntityToClass("phys_hinge")] +public class PhysHinge : PhysConstraint, IVPhysicsWatcher +{ + public static readonly new DataMap DataDesc = new(typeof(PhysHinge), PhysConstraint.DataDesc, [ + DEFINE.KEYFIELD(nameof(HingeFriction), FieldType.Float, "hingefriction"), + DEFINE.FIELD("Hinge.WorldPosition", FieldType.PositionVector), + DEFINE.KEYFIELD("Hinge.WorldAxisDirection", FieldType.Vector, "hingeaxis"), + DEFINE.KEYFIELD(nameof(SystemLoadScale), FieldType.Float, "systemloadscale"), + DEFINE.INPUTFUNC(FieldType.Float, "SetAngularVelocity", nameof(InputSetVelocity), (INPUTFUNCPTR)((self, data) => ((PhysHinge)self).InputSetVelocity(data))), + DEFINE.INPUTFUNC(FieldType.Float, "SetHingeFriction", nameof(InputSetHingeFriction), (INPUTFUNCPTR)((self, data) => ((PhysHinge)self).InputSetHingeFriction(data))), +#if HL2_EPISODIC + DEFINE.KEYFIELD("SoundInfo.SoundProfile.KeyPoints[0]", FieldType.Float, "minSoundThreshold"), + DEFINE.KEYFIELD("SoundInfo.SoundProfile.KeyPoints[1]", FieldType.Float, "maxSoundThreshold"), + DEFINE.KEYFIELD("SoundInfo.TravelSoundFwd", FieldType.SoundName, "slidesoundfwd"), + DEFINE.KEYFIELD("SoundInfo.TravelSoundBack", FieldType.SoundName, "slidesoundback"), + + DEFINE.KEYFIELD("SoundInfo.ReversalSounds[0]", FieldType.SoundName, "reversalsoundSmall"), + DEFINE.KEYFIELD("SoundInfo.ReversalSounds[1]", FieldType.SoundName, "reversalsoundMedium"), + DEFINE.KEYFIELD("SoundInfo.ReversalSounds[2]", FieldType.SoundName, "reversalsoundLarge"), + + DEFINE.KEYFIELD("SoundInfo.SoundProfile.ReversalSoundThresholds[0]", FieldType.Float, "reversalsoundthresholdSmall"), + DEFINE.KEYFIELD("SoundInfo.SoundProfile.ReversalSoundThresholds[1]", FieldType.Float, "reversalsoundthresholdMedium"), + DEFINE.KEYFIELD("SoundInfo.SoundProfile.ReversalSoundThresholds[2]", FieldType.Float, "reversalsoundthresholdLarge"), + + DEFINE.THINKFUNC(nameof(SoundThink)), +#endif + ]); + public override DataMap? GetDataDescMap() => DataDesc; + +#if HL2_EPISODIC + protected readonly ConstraintSoundInfo SoundInfo = new(); + + public override void Term() { + SoundInfo.Dispose(); + base.Term(); + } +#endif + + ConstraintHingeParams Hinge; + float HingeFriction; + float SystemLoadScale; + + protected override IPhysicsConstraint? CreateConstraint(IPhysicsConstraintGroup? group, in HlConstraintInfo info) { + if (Hinge.WorldAxisDirection == vec3_origin) { + DevMsg("ERROR: Hinge with bad data!!!\n"); + return null; + } + GetBreakParams(ref Hinge.Constraint, info); + Hinge.Constraint.Strength = 1.0f; + Hinge.HingeAxis.SetAxisFriction(0, 0, HingeFriction * 1000); + + if (IsWorldHinge(info, out int hingeAxis)) + info.Objects[1]!.BecomeHinged(hingeAxis); + else + RemoveSpawnFlags(SF_CONSTRAINT_ASSUME_WORLD_GEOMETRY); + + return physenv.CreateHingeConstraint(info.Objects[0]!, info.Objects[1]!, group!, Hinge); + } + + public override void DrawDebugGeometryOverlays() { + if ((DebugOverlays & (DebugOverlayBits.BBox | DebugOverlayBits.Pivot | DebugOverlayBits.AbsBox)) != 0) + DebugOverlay.Line(Hinge.WorldPosition, Hinge.WorldPosition + 48 * Hinge.WorldAxisDirection, 0, 255, 0, false, 0); + base.DrawDebugGeometryOverlays(); + } + + void InputSetVelocity(in InputData inputdata) { + if (Constraint == null || Constraint.GetReferenceObject() == null || Constraint.GetAttachedObject() == null) + return; + + float speed = inputdata.Value.Float(); + float massLoad = 1; + int numMasses = 0; + if (Constraint.GetReferenceObject()!.IsMoveable()) { + massLoad = Constraint.GetReferenceObject()!.GetInertia().Length(); + numMasses++; + Constraint.GetReferenceObject()!.Wake(); + } + if (Constraint.GetAttachedObject()!.IsMoveable()) { + massLoad += Constraint.GetAttachedObject()!.GetInertia().Length(); + numMasses++; + Constraint.GetAttachedObject()!.Wake(); + } + if (numMasses > 0) + massLoad /= (float)numMasses; + + float loadscale = SystemLoadScale != 0 ? SystemLoadScale : 1; + Constraint.SetAngularMotor(speed, speed * loadscale * massLoad * loadscale * (1.0f / (float)TICK_INTERVAL)); + } + + void InputSetHingeFriction(in InputData inputdata) { + HingeFriction = inputdata.Value.Float(); + Msg($"Setting hinge friction to {HingeFriction:F6}\n"); + Hinge.HingeAxis.SetAxisFriction(0, 0, HingeFriction * 1000); + } + + public override void Deactivate() { + if (HasSpawnFlags(SF_CONSTRAINT_ASSUME_WORLD_GEOMETRY)) { + if (Constraint != null && Constraint.GetAttachedObject() != null) + Constraint.GetAttachedObject()!.RemoveHinged(); + } + + base.Deactivate(); + } + + public void NotifyVPhysicsStateChanged(IPhysicsObject physics, BaseEntity entity, bool awake) { +#if HL2_EPISODIC + Assert(Constraint != null); + if (Constraint == null) + return; + + if (awake) { + if (GetNextThink() == TICK_NEVER_THINK) { + SoundInfo.StartThinking(this, VelocitySampler.GetRelativeAngularVelocity(Constraint.GetAttachedObject()!, Constraint.GetReferenceObject()), Hinge.WorldAxisDirection); + + SetThink(SoundThink); + SetNextThink(gpGlobals.CurTime + SoundInfo.GetThinkRate()); + } + } + else { + if (GetNextThink() != TICK_NEVER_THINK && Constraint.GetAttachedObject()!.IsAsleep() && Constraint.GetReferenceObject()!.IsAsleep()) { + SoundInfo.StopThinking(this); + SetNextThink(TICK_NEVER_THINK); + } + } +#endif + } + +#if HL2_EPISODIC + public override void OnConstraintSetup(ref HlConstraintInfo info) { + BaseEntity? entity0 = info.Objects[0] != null ? (BaseEntity?)info.Objects[0]!.GetGameData() : null; + if (entity0 != null && !info.Objects[0]!.IsStatic()) + WatchVPhysicsStateChanges(this, entity0); + BaseEntity? entity1 = info.Objects[1] != null ? (BaseEntity?)info.Objects[1]!.GetGameData() : null; + if (entity1 != null && !info.Objects[1]!.IsStatic()) + WatchVPhysicsStateChanges(this, entity1); + base.OnConstraintSetup(ref info); + } +#endif + + public override void Spawn() { + Hinge.WorldPosition = GetLocalOrigin(); + Hinge.WorldAxisDirection -= GetLocalOrigin(); + MathLib.VectorNormalize(ref Hinge.WorldAxisDirection); +#if !GMOD_DLL + Util.SnapDirectionToAxis(ref Hinge.WorldAxisDirection); +#endif + + Hinge.HingeAxis.SetAxisFriction(0, 0, 0); + + if (HasSpawnFlags(SF_CONSTRAINT_ASSUME_WORLD_GEOMETRY)) { + MassCenterOverride parms = default; + if (NameAttach1 == null) { + parms.SnapToAxis(NameAttach2, Hinge.WorldPosition, Hinge.WorldAxisDirection); + PhysSetMassCenterOverride(parms); + } + else if (NameAttach2 == null) { + parms.SnapToAxis(NameAttach1, Hinge.WorldPosition, Hinge.WorldAxisDirection); + PhysSetMassCenterOverride(parms); + } + else + RemoveSpawnFlags(SF_CONSTRAINT_ASSUME_WORLD_GEOMETRY); + } + + Precache(); + } + +#if HL2_EPISODIC + public override void Activate() { + base.Activate(); + + SoundInfo.OnActivate(this); + if (Constraint != null) { + SoundInfo.StartThinking(this, VelocitySampler.GetRelativeAngularVelocity(Constraint.GetAttachedObject()!, Constraint.GetReferenceObject()), Hinge.WorldAxisDirection); + + SetThink(SoundThink); + SetNextThink(gpGlobals.CurTime + SoundInfo.GetThinkRate()); + } + } + + public override void Precache() { + base.Precache(); + SoundInfo.OnPrecache(this); + } + + void SoundThink() { + Assert(Constraint != null); + if (Constraint == null) + return; + + IPhysicsObject? attached = Constraint.GetAttachedObject(), reference = Constraint.GetReferenceObject(); + Assert(attached != null && reference != null); + if (attached != null && reference != null) { + Vector3 relativeVel = VelocitySampler.GetRelativeAngularVelocity(attached, reference); + if (g_debug_constraint_sounds.GetBool()) + DebugOverlay.Line(GetAbsOrigin(), GetAbsOrigin() + relativeVel, 255, 255, 0, true, 0.1f); + SoundInfo.OnThink(this, relativeVel); + + SetNextThink(gpGlobals.CurTime + SoundInfo.GetThinkRate()); + } + } +#endif + + bool IsWorldHinge(in HlConstraintInfo info, out int axisOut) { + axisOut = 0; + if (HasSpawnFlags(SF_CONSTRAINT_ASSUME_WORLD_GEOMETRY) && info.Objects[0] == g_PhysWorldObject) { + info.Objects[1]!.WorldToLocalVector(out Vector3 localHinge, Hinge.WorldAxisDirection); + Util.SnapDirectionToAxis(ref localHinge); + int hingeAxis = GetUnitAxisIndex(localHinge); + if (hingeAxis >= 0) { + axisOut = hingeAxis; + return true; + } + } + return false; + } +} + +[LinkEntityToClass("phys_ballsocket")] +public class PhysBallSocket : PhysConstraint +{ + protected override IPhysicsConstraint? CreateConstraint(IPhysicsConstraintGroup? group, in HlConstraintInfo info) { + ConstraintBallSocketParams ballsocket = default; + + ballsocket.Defaults(); + + for (int i = 0; i < 2; i++) { + info.Objects[i]!.WorldToLocal(out ballsocket.ConstraintPosition[i], GetAbsOrigin()); +#if GMOD_DLL + info.Objects[i]!.GetDamping(out float speed, out float rot); + if (speed < 0.2f) + speed = 0.2f; + if (rot < 0.2f) + rot = 0.2f; + info.Objects[i]!.SetDamping(ref speed, ref speed); +#endif + } + GetBreakParams(ref ballsocket.Constraint, info); + ballsocket.Constraint.TorqueLimit = 0; + + return physenv.CreateBallsocketConstraint(info.Objects[0]!, info.Objects[1]!, group!, ballsocket); + } +} + +[LinkEntityToClass("phys_slideconstraint")] +public class PhysSlideConstraint : PhysConstraint, IVPhysicsWatcher +{ + public static readonly new DataMap DataDesc = new(typeof(PhysSlideConstraint), PhysConstraint.DataDesc, [ + DEFINE.KEYFIELD(nameof(AxisEnd), FieldType.PositionVector, "slideaxis"), + DEFINE.KEYFIELD(nameof(SlideFriction), FieldType.Float, "slidefriction"), + DEFINE.KEYFIELD(nameof(SystemLoadScale), FieldType.Float, "systemloadscale"), + DEFINE.INPUTFUNC(FieldType.Float, "SetVelocity", nameof(InputSetVelocity), (INPUTFUNCPTR)((self, data) => ((PhysSlideConstraint)self).InputSetVelocity(data))), +#if HL2_EPISODIC + DEFINE.KEYFIELD("SoundInfo.SoundProfile.KeyPoints[0]", FieldType.Float, "minSoundThreshold"), + DEFINE.KEYFIELD("SoundInfo.SoundProfile.KeyPoints[1]", FieldType.Float, "maxSoundThreshold"), + DEFINE.KEYFIELD("SoundInfo.TravelSoundFwd", FieldType.SoundName, "slidesoundfwd"), + DEFINE.KEYFIELD("SoundInfo.TravelSoundBack", FieldType.SoundName, "slidesoundback"), + + DEFINE.KEYFIELD("SoundInfo.ReversalSounds[0]", FieldType.SoundName, "reversalsoundSmall"), + DEFINE.KEYFIELD("SoundInfo.ReversalSounds[1]", FieldType.SoundName, "reversalsoundMedium"), + DEFINE.KEYFIELD("SoundInfo.ReversalSounds[2]", FieldType.SoundName, "reversalsoundLarge"), + + DEFINE.KEYFIELD("SoundInfo.SoundProfile.ReversalSoundThresholds[0]", FieldType.Float, "reversalsoundthresholdSmall"), + DEFINE.KEYFIELD("SoundInfo.SoundProfile.ReversalSoundThresholds[1]", FieldType.Float, "reversalsoundthresholdMedium"), + DEFINE.KEYFIELD("SoundInfo.SoundProfile.ReversalSoundThresholds[2]", FieldType.Float, "reversalsoundthresholdLarge"), + + DEFINE.THINKFUNC(nameof(SoundThink)), +#endif + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + public Vector3 AxisEnd; + public float SlideFriction; + public float SystemLoadScale; + +#if HL2_EPISODIC + protected readonly ConstraintSoundInfo SoundInfo = new(); + + public override void Term() { + SoundInfo.Dispose(); + base.Term(); + } + +#endif + + void InputSetVelocity(in InputData inputdata) { + if (Constraint == null || Constraint.GetReferenceObject() == null || Constraint.GetAttachedObject() == null) + return; + + float speed = inputdata.Value.Float(); + float massLoad = 1; + int numMasses = 0; + if (Constraint.GetReferenceObject()!.IsMoveable()) { + massLoad = Constraint.GetReferenceObject()!.GetMass(); + numMasses++; + Constraint.GetReferenceObject()!.Wake(); + } + if (Constraint.GetAttachedObject()!.IsMoveable()) { + massLoad += Constraint.GetAttachedObject()!.GetMass(); + numMasses++; + Constraint.GetAttachedObject()!.Wake(); + } + if (numMasses > 0) + massLoad /= (float)numMasses; + float loadscale = SystemLoadScale != 0 ? SystemLoadScale : 1; + Constraint.SetLinearMotor(speed, speed * loadscale * massLoad * (1.0f / (float)TICK_INTERVAL)); + } + + public override void DrawDebugGeometryOverlays() { + if ((DebugOverlays & (DebugOverlayBits.BBox | DebugOverlayBits.Pivot | DebugOverlayBits.AbsBox)) != 0) { + DebugOverlay.Box(GetAbsOrigin(), -new Vector3(8, 8, 8), new Vector3(8, 8, 8), 0, 255, 0, 0, 0); + DebugOverlay.Box(AxisEnd, -new Vector3(4, 4, 4), new Vector3(4, 4, 4), 0, 0, 255, 0, 0); + DebugOverlay.Line(GetAbsOrigin(), AxisEnd, 255, 255, 0, false, 0); + } + base.DrawDebugGeometryOverlays(); + } + + public void NotifyVPhysicsStateChanged(IPhysicsObject physics, BaseEntity entity, bool awake) { +#if HL2_EPISODIC + Assert(Constraint != null); + if (Constraint == null) + return; + + if (awake) { + if (GetNextThink() == TICK_NEVER_THINK) { + Vector3 axisDirection = AxisEnd - GetAbsOrigin(); + MathLib.VectorNormalize(ref axisDirection); + Util.SnapDirectionToAxis(ref axisDirection); + + SoundInfo.StartThinking(this, VelocitySampler.GetRelativeVelocity(Constraint.GetAttachedObject(), Constraint.GetReferenceObject()), axisDirection); + SetThink(SoundThink); + SetNextThink(gpGlobals.CurTime + SoundInfo.GetThinkRate()); + } + } + else { + if (GetNextThink() != TICK_NEVER_THINK && Constraint.GetAttachedObject()!.IsAsleep() && Constraint.GetReferenceObject()!.IsAsleep()) { + SoundInfo.StopThinking(this); + SetNextThink(TICK_NEVER_THINK); + } + } +#endif + } + +#if HL2_EPISODIC + public override void OnConstraintSetup(ref HlConstraintInfo info) { + BaseEntity? entity0 = info.Objects[0] != null ? (BaseEntity?)info.Objects[0]!.GetGameData() : null; + if (entity0 != null && !info.Objects[0]!.IsStatic()) + WatchVPhysicsStateChanges(this, entity0); + BaseEntity? entity1 = info.Objects[1] != null ? (BaseEntity?)info.Objects[1]!.GetGameData() : null; + if (entity1 != null && !info.Objects[1]!.IsStatic()) + WatchVPhysicsStateChanges(this, entity1); + base.OnConstraintSetup(ref info); + } +#endif + + protected override IPhysicsConstraint? CreateConstraint(IPhysicsConstraintGroup? group, in HlConstraintInfo info) { + ConstraintSlidingParams sliding = default; + sliding.Defaults(); + GetBreakParams(ref sliding.Constraint, info); + sliding.Constraint.Strength = 1.0f; + + Vector3 axisDirection = AxisEnd - GetAbsOrigin(); +#if GMOD_DLL + if (axisDirection.Length() < 1.0f) { + axisDirection = new(0, 0, 1); + Msg("GMOD: Forcing sane values for slider constraint!\n"); + } + MathLib.VectorNormalize(ref axisDirection); +#else + MathLib.VectorNormalize(ref axisDirection); + Util.SnapDirectionToAxis(ref axisDirection); +#endif + + sliding.InitWithCurrentObjectState(info.Objects[0]!, info.Objects[1]!, axisDirection); + sliding.Friction = SlideFriction; + if ((SpawnFlags & SF_SLIDE_LIMIT_ENDS) != 0) { + info.Objects[1]!.GetPosition(out Vector3 position, out _); + + sliding.LimitMin = Vector3.Dot(axisDirection, GetAbsOrigin()); + sliding.LimitMax = Vector3.Dot(axisDirection, AxisEnd); + if (sliding.LimitMax < sliding.LimitMin) + (sliding.LimitMin, sliding.LimitMax) = (sliding.LimitMax, sliding.LimitMin); + + float limit = Vector3.Dot(position, axisDirection); + if (limit < sliding.LimitMin) + sliding.LimitMin = limit; + else if (limit > sliding.LimitMax) + sliding.LimitMax = limit; + sliding.LimitMin -= limit; + sliding.LimitMax -= limit; + } + + return physenv.CreateSlidingConstraint(info.Objects[0]!, info.Objects[1]!, group!, sliding); + } + +#if HL2_EPISODIC + void SoundThink() { + Assert(Constraint != null); + if (Constraint == null) + return; + + IPhysicsObject? attached = Constraint.GetAttachedObject(), reference = Constraint.GetReferenceObject(); + Assert(attached != null && reference != null); + if (attached != null && reference != null) { + Vector3 relativeVel = VelocitySampler.GetRelativeVelocity(attached, reference); + + Vector3 axisDirection = AxisEnd - GetAbsOrigin(); + relativeVel = AxisEnd * Vector3.Dot(relativeVel, AxisEnd) / Vector3.Dot(AxisEnd, AxisEnd); + + SoundInfo.OnThink(this, relativeVel); + + SetNextThink(gpGlobals.CurTime + SoundInfo.GetThinkRate()); + } + } + + public override void Activate() { + base.Activate(); + + if (Constraint == null) + return; + + SoundInfo.OnActivate(this); + + Vector3 axisDirection = AxisEnd - GetAbsOrigin(); + MathLib.VectorNormalize(ref axisDirection); + Util.SnapDirectionToAxis(ref axisDirection); + SoundInfo.StartThinking(this, VelocitySampler.GetRelativeVelocity(Constraint.GetAttachedObject(), Constraint.GetReferenceObject()), axisDirection); + + SetThink(SoundThink); + SetNextThink(gpGlobals.CurTime + SoundInfo.GetThinkRate()); + } + + public override void Precache() { + SoundInfo.OnPrecache(this); + } +#endif +} + +[LinkEntityToClass("phys_constraint")] +public class PhysFixed : PhysConstraint +{ + protected override IPhysicsConstraint? CreateConstraint(IPhysicsConstraintGroup? group, in HlConstraintInfo info) { + ConstraintFixedParams fixedParams = default; + fixedParams.Defaults(); + fixedParams.InitWithCurrentObjectState(info.Objects[0]!, info.Objects[1]!); + GetBreakParams(ref fixedParams.Constraint, info); + + if (info.Objects[0] == g_PhysWorldObject && info.Objects[1] != null) + PhysSetGameFlags(info.Objects[1]!, PhysicsFlags.ConstraintStatic); + + return physenv.CreateFixedConstraint(info.Objects[0]!, info.Objects[1]!, group!, fixedParams); + } + + public void MoveToRefPosition() { + if (Constraint != null) { + Constraint.GetConstraintTransform(out Matrix3x4 xformRef, out _); + IPhysicsObject? obj = Constraint.GetReferenceObject(); + if (obj != null && obj.IsMoveable()) { + MathLib.MatrixPosition(xformRef, out Vector3 pos); + obj.LocalToWorld(out Vector3 posWorld, pos); + SetAbsOrigin(posWorld); + } + } + } + + public override int DrawDebugTextOverlays() { + if ((DebugOverlays & DebugOverlayBits.Text) != 0) + MoveToRefPosition(); + return base.DrawDebugTextOverlays(); + } + + public override void DrawDebugGeometryOverlays() { + if ((DebugOverlays & (DebugOverlayBits.BBox | DebugOverlayBits.Pivot | DebugOverlayBits.AbsBox)) != 0) + MoveToRefPosition(); + base.DrawDebugGeometryOverlays(); + } +} + +[LinkEntityToClass("phys_pulleyconstraint")] +public class PhysPulley : PhysConstraint +{ + public static readonly new DataMap DataDesc = new(typeof(PhysPulley), PhysConstraint.DataDesc, [ + DEFINE.KEYFIELD(nameof(Position2), FieldType.PositionVector, "position2"), + DEFINE.AUTO_ARRAY(nameof(Offset), FieldType.Vector), + DEFINE.KEYFIELD(nameof(AddLength), FieldType.Float, "addlength"), + DEFINE.KEYFIELD(nameof(GearRatio), FieldType.Float, "gearratio"), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + Vector3 Position2; + InlineArray2 Offset; + float AddLength; + float GearRatio; + + public override void DrawDebugGeometryOverlays() { + if ((DebugOverlays & (DebugOverlayBits.BBox | DebugOverlayBits.Pivot | DebugOverlayBits.AbsBox)) != 0) { + Vector3 origin = GetAbsOrigin(); + Vector3 refPos = origin, attachPos = origin; + IPhysicsObject? refObj = Constraint!.GetReferenceObject(); + if (refObj != null) { + refObj.GetPositionMatrix(out Matrix3x4 matrix); + MathLib.VectorTransform(Offset[0], matrix, out refPos); + } + IPhysicsObject? attach = Constraint.GetAttachedObject(); + if (attach != null) { + attach.GetPositionMatrix(out Matrix3x4 matrix); + MathLib.VectorTransform(Offset[1], matrix, out attachPos); + } + DebugOverlay.Line(refPos, origin, 0, 255, 0, false, 0); + DebugOverlay.Line(origin, Position2, 128, 128, 128, false, 0); + DebugOverlay.Line(Position2, attachPos, 0, 255, 0, false, 0); + DebugOverlay.Box(origin, -new Vector3(8, 8, 8), new Vector3(8, 8, 8), 128, 255, 128, 32, 0); + DebugOverlay.Box(Position2, -new Vector3(8, 8, 8), new Vector3(8, 8, 8), 255, 128, 128, 32, 0); + } + base.DrawDebugGeometryOverlays(); + } + + protected override IPhysicsConstraint? CreateConstraint(IPhysicsConstraintGroup? group, in HlConstraintInfo info) { + ConstraintPulleyParams pulley = default; + pulley.Defaults(); + pulley.PulleyPosition[0] = GetAbsOrigin(); + pulley.PulleyPosition[1] = Position2; + + Matrix3x4 matrix; + InlineArray2 world = default; + + info.Objects[0]!.GetPositionMatrix(out matrix); + MathLib.VectorTransform(info.AnchorPosition[0], matrix, out world[0]); + info.Objects[1]!.GetPositionMatrix(out matrix); + MathLib.VectorTransform(info.AnchorPosition[1], matrix, out world[1]); + + for (int i = 0; i < 2; i++) { + pulley.ObjectPosition[i] = info.AnchorPosition[i]; + Offset[i] = info.AnchorPosition[i]; + } + + pulley.TotalLength = AddLength + (world[0] - pulley.PulleyPosition[0]).Length() + ((world[1] - pulley.PulleyPosition[1]).Length() * GearRatio); + + if (GearRatio != 0) + pulley.GearRatio = GearRatio; + GetBreakParams(ref pulley.Constraint, info); + if ((SpawnFlags & SF_PULLEY_RIGID) != 0) + pulley.IsRigid = true; + + return physenv.CreatePulleyConstraint(info.Objects[0]!, info.Objects[1]!, group!, pulley); + } +} + +[LinkEntityToClass("phys_lengthconstraint")] +public class PhysLength : PhysConstraint +{ + public static readonly new DataMap DataDesc = new(typeof(PhysLength), PhysConstraint.DataDesc, [ + DEFINE.AUTO_ARRAY(nameof(Offset), FieldType.Vector), + DEFINE.KEYFIELD(nameof(AddLength), FieldType.Float, "addlength"), + DEFINE.KEYFIELD(nameof(MinLength), FieldType.Float, "minlength"), + DEFINE.KEYFIELD(nameof(Attach), FieldType.PositionVector, "attachpoint"), +#if GMOD_DLL + DEFINE.KEYFIELD(nameof(Length), FieldType.Float, "length"), +#else + DEFINE.FIELD(nameof(TotalLength), FieldType.Float), +#endif + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + InlineArray2 Offset; + Vector3 Attach; + float AddLength; + float MinLength; + float TotalLength; +#if GMOD_DLL + float Length; +#endif + + public override void DrawDebugGeometryOverlays() { + if ((DebugOverlays & (DebugOverlayBits.BBox | DebugOverlayBits.Pivot | DebugOverlayBits.AbsBox)) != 0) { + Vector3 origin = GetAbsOrigin(); + Vector3 refPos = origin, attachPos = origin; + IPhysicsObject? refObj = Constraint!.GetReferenceObject(); + if (refObj != null) { + refObj.GetPositionMatrix(out Matrix3x4 matrix); + MathLib.VectorTransform(Offset[0], matrix, out refPos); + } + IPhysicsObject? attach = Constraint.GetAttachedObject(); + if (attach != null) { + attach.GetPositionMatrix(out Matrix3x4 matrix); + MathLib.VectorTransform(Offset[1], matrix, out attachPos); + } + Vector3 dir = attachPos - refPos; + + float len = MathLib.VectorNormalize(ref dir); + if (len > TotalLength) { + Vector3 mid = refPos + dir * TotalLength; + DebugOverlay.Line(refPos, mid, 0, 255, 0, false, 0); + DebugOverlay.Line(mid, attachPos, 255, 0, 0, false, 0); + } + else + DebugOverlay.Line(refPos, attachPos, 0, 255, 0, false, 0); + } + base.DrawDebugGeometryOverlays(); + } + + protected override IPhysicsConstraint? CreateConstraint(IPhysicsConstraintGroup? group, in HlConstraintInfo info) { + ConstraintLengthParams length = default; + length.Defaults(); + InlineArray2 position = default; + position[0] = GetAbsOrigin(); + position[1] = Attach; + int index = info.Swapped ? 1 : 0; + length.InitWorldspace(info.Objects[0]!, info.Objects[1]!, position[index], position[index == 0 ? 1 : 0]); +#if GMOD_DLL + if (Length <= 0) + length.TotalLength += AddLength; + else + length.TotalLength = Length; + if (length.TotalLength <= 0.1f) + length.TotalLength = 0.1f; +#else + length.TotalLength += AddLength; +#endif + length.MinLength = MinLength; + TotalLength = length.TotalLength; + if (HasSpawnFlags(SF_LENGTH_RIGID)) + length.MinLength = length.TotalLength; + + for (int i = 0; i < 2; i++) + Offset[i] = length.ObjectPosition[i]; + GetBreakParams(ref length.Constraint, info); + + return physenv.CreateLengthConstraint(info.Objects[0]!, info.Objects[1]!, group!, length); + } +} + +[LinkEntityToClass("phys_ragdollconstraint")] +public class RagdollConstraint : PhysConstraint +{ + public static readonly new DataMap DataDesc = new(typeof(RagdollConstraint), PhysConstraint.DataDesc, [ + DEFINE.KEYFIELD(nameof(XMin), FieldType.Float, "xmin"), + DEFINE.KEYFIELD(nameof(XMax), FieldType.Float, "xmax"), + DEFINE.KEYFIELD(nameof(YMin), FieldType.Float, "ymin"), + DEFINE.KEYFIELD(nameof(YMax), FieldType.Float, "ymax"), + DEFINE.KEYFIELD(nameof(ZMin), FieldType.Float, "zmin"), + DEFINE.KEYFIELD(nameof(ZMax), FieldType.Float, "zmax"), + DEFINE.KEYFIELD(nameof(XFriction), FieldType.Float, "xfriction"), + DEFINE.KEYFIELD(nameof(YFriction), FieldType.Float, "yfriction"), + DEFINE.KEYFIELD(nameof(ZFriction), FieldType.Float, "zfriction"), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + float XMin; + float XMax; + float YMin; + float YMax; + float ZMin; + float ZMax; + + float XFriction; + float YFriction; + float ZFriction; + + protected override IPhysicsConstraint? CreateConstraint(IPhysicsConstraintGroup? group, in HlConstraintInfo info) { + ConstraintRagdollParams ragdoll = default; + ragdoll.Defaults(); + + info.Objects[0]!.GetPositionMatrix(out Matrix3x4 entityToWorld); + MathLib.MatrixInvert(entityToWorld, out Matrix3x4 worldToEntity); + MathLib.ConcatTransforms(worldToEntity, EntityToWorldTransform(), out ragdoll.ConstraintToReference); + + info.Objects[1]!.GetPositionMatrix(out entityToWorld); + MathLib.MatrixInvert(entityToWorld, out worldToEntity); + MathLib.ConcatTransforms(worldToEntity, EntityToWorldTransform(), out ragdoll.ConstraintToAttached); + + ragdoll.OnlyAngularLimits = HasSpawnFlags(SF_RAGDOLL_FREEMOVEMENT) ? true : false; + + ragdoll.Axes[0].SetAxisFriction(XMin, XMax, XFriction); + ragdoll.Axes[1].SetAxisFriction(YMin, YMax, YFriction); + ragdoll.Axes[2].SetAxisFriction(ZMin, ZMax, ZFriction); + + if (HasSpawnFlags(SF_CONSTRAINT_START_INACTIVE)) + ragdoll.IsActive = false; + return physenv.CreateRagdollConstraint(info.Objects[0]!, info.Objects[1]!, group!, ragdoll); + } +} + public class PhysConstraintEvents : IPhysicsConstraintEvent { public static readonly PhysConstraintEvents constraintevents = new(); public static readonly IPhysicsConstraintEvent g_pConstraintEvents = constraintevents; + public void ConstraintBroken(IPhysicsConstraint constraint) { - throw new NotImplementedException(); + BaseEntity? entity = (BaseEntity?)constraint.GetGameData(); + if (entity != null) { + if (entity is IPhysicsConstraintEvent constraintEvent) + constraintEvent.ConstraintBroken(constraint); + else { + Variant_t emptyVariant = default; + entity.AcceptInput("ConstraintBroken", null, null, emptyVariant, 0); + } + } + } +} + +#if HL2_EPISODIC +public struct VelocitySampler +{ + public readonly float GetSampleRate() => IdealSampleRate; + + public void BeginSampling(in Vector3 relativeVelocity) => AddSample(relativeVelocity); + + public void AddSample(in Vector3 relativeVelocity) { + PrevSample = relativeVelocity; + PrevSampleTime = (float)gpGlobals.CurTime; + } + + public readonly int HasReversed(in Vector3 relativeVelocity, ReadOnlySpan thresholdAcceleration, ushort numThresholds) { + float vDot = Vector3.Dot(relativeVelocity, PrevSample); + if (vDot <= 0) { + Vector3 accel = relativeVelocity - PrevSample; + + float prevSampleLength = PrevSample.Length(); + float projection = 0; + if (prevSampleLength != 0) + projection = -(Vector3.Dot(accel, PrevSample) / prevSampleLength) / ((float)gpGlobals.CurTime - PrevSampleTime); + else + projection = accel.Length() / ((float)gpGlobals.CurTime - PrevSampleTime); + + if (g_debug_constraint_sounds.GetBool()) + Msg($"Reversal accel is {projection:F6}/{thresholdAcceleration[0]:F6}\n"); + + int retval; + for (retval = numThresholds - 1; retval >= 0; --retval) { + if (projection > thresholdAcceleration[retval]) + break; + } + + return retval; + } + else + return -1; + } + + public void Initialize(float samplerate) { + IdealSampleRate = samplerate; + } + + public static Vector3 GetRelativeVelocity(IPhysicsObject? obj, IPhysicsObject? referenceFrame) { + if (obj == null || referenceFrame == null) + return vec3_origin; + + obj.GetImplicitVelocity(out Vector3 childVelocity, out _); + referenceFrame!.GetImplicitVelocity(out Vector3 parentVelocity, out _); + + return childVelocity - parentVelocity; + } + + public static Vector3 GetRelativeAngularVelocity(IPhysicsObject obj, IPhysicsObject? referenceFrame) { + Assert(obj != null); + + if (referenceFrame != null) { + obj.GetImplicitVelocity(out _, out Vector3 childVelocityLocal); + obj.LocalToWorldVector(out Vector3 childVelocityWorld, childVelocityLocal); + referenceFrame.GetImplicitVelocity(out _, out Vector3 parentVelocityLocal); + obj.LocalToWorldVector(out Vector3 parentVelocityWorld, parentVelocityLocal); + + return childVelocityWorld - parentVelocityWorld; + } + else { + obj.GetImplicitVelocity(out _, out Vector3 childVelocityLocal); + obj.LocalToWorldVector(out Vector3 childVelocityWorld, childVelocityLocal); + + return childVelocityWorld; + } + } + + Vector3 PrevSample; + float PrevSampleTime; + + float IdealSampleRate; +} + +public struct SimpleConstraintSoundProfile +{ + public const int kMIN_THRESHOLD = 0; + public const int kMIN_FULL = 1; + public const int kHIGHWATER = 2; + + public InlineArray2 KeyPoints; + + public const int kREVERSAL_SOUND_ARRAY_SIZE = 3; + + public InlineArray3 ReversalSoundThresholds; + + public readonly float GetVolume(float inVel) { + if (inVel <= KeyPoints[kMIN_THRESHOLD]) + return 0; + else if (inVel >= KeyPoints[kMIN_FULL]) + return 1; + else + return (inVel - KeyPoints[kMIN_THRESHOLD]) / (KeyPoints[kMIN_FULL] - KeyPoints[kMIN_THRESHOLD]); + } +} + +public class ConstraintSoundInfo : IDisposable +{ + public void Dispose() => DeleteAllSounds(); + + public VelocitySampler Sampler; + public SimpleConstraintSoundProfile SoundProfile; + + public Vector3 ForwardAxis; + + public string? TravelSoundFwd, TravelSoundBack; + public SoundPatch? TravelSound; + public bool PlayTravelSound; + + public InlineArray3 ReversalSounds; + public bool PlayReversalSound; + + public float GetThinkRate() => 0.09f; + + static bool IsEmpty(string? str) => str == null || strlen(str) < 1; + + public void OnActivate(PhysConstraint outer) { + TravelSound = null; + Sampler.Initialize(GetThinkRate()); + + ValidateInternals(outer); + + PlayTravelSound = !IsEmpty(TravelSoundFwd) || !IsEmpty(TravelSoundBack); + PlayReversalSound = false; + for (int i = 0; i < SimpleConstraintSoundProfile.kREVERSAL_SOUND_ARRAY_SIZE; ++i) { + if (!IsEmpty(ReversalSounds[i])) { + PlayReversalSound = true; + break; + } + } + } + + protected void ValidateInternals(PhysConstraint outer) { + for (int i = 1; i < SimpleConstraintSoundProfile.kREVERSAL_SOUND_ARRAY_SIZE; ++i) { + if (SoundProfile.ReversalSoundThresholds[i] < SoundProfile.ReversalSoundThresholds[i - 1]) { + Warning($"Constraint reversal sounds for {outer.GetDebugName()} are out of order!"); + SoundProfile.ReversalSoundThresholds[i] = SoundProfile.ReversalSoundThresholds[i - 1]; + ReversalSounds[i] = ReversalSounds[i - 1]; + } + } + } + + public void OnPrecache(PhysConstraint outer) { + BaseEntity.PrecacheScriptSound(TravelSoundFwd); + BaseEntity.PrecacheScriptSound(TravelSoundBack); + for (int i = 0; i < SimpleConstraintSoundProfile.kREVERSAL_SOUND_ARRAY_SIZE; ++i) + BaseEntity.PrecacheScriptSound(ReversalSounds[i]); + } + + public void OnThink(PhysConstraint outer, in Vector3 relativeVelocity) { + int playReversal = Sampler.HasReversed(relativeVelocity, SoundProfile.ReversalSoundThresholds, SimpleConstraintSoundProfile.kREVERSAL_SOUND_ARRAY_SIZE); + float relativeVelMag = relativeVelocity.Length(); + + BaseEntity? childEntity = (BaseEntity?)outer.GetPhysConstraint()!.GetAttachedObject()!.GetGameData(); + if (childEntity == null) + return; + + float soundVol = SoundProfile.GetVolume(relativeVelMag); + + if (g_debug_constraint_sounds.GetBool()) { + childEntity.EntityText(0, $"Velocity: {relativeVelMag:F3}", Sampler.GetSampleRate()); + + childEntity.EntityText(1, $"Sound volume: {soundVol:F3}", Sampler.GetSampleRate()); + + if (playReversal >= 0) + childEntity.EntityText(2, $"Reversal [{playReversal}]", Sampler.GetSampleRate()); + } + + if (PlayTravelSound) { + if (soundVol > 0) { + if (TravelSound != null) + SoundEnvelopeController.GetController().SoundChangeVolume(TravelSound, soundVol, 0.1f); + else { + bool travellingForward = Vector3.Dot(relativeVelocity, ForwardAxis) > 0; + + SoundEnvelopeController controller = SoundEnvelopeController.GetController(); + PASAttenuationFilter filter = new(childEntity); + TravelSound = controller.SoundCreate(filter, childEntity.EntIndex(), travellingForward ? TravelSoundFwd : TravelSoundBack); + controller.Play(TravelSound, soundVol, 100); + } + } + else { + if (TravelSound != null) { + SoundEnvelopeController.GetController().SoundDestroy(TravelSound); + TravelSound = null; + } + } + } + + if (PlayReversalSound && (playReversal >= 0)) + childEntity.EmitSound(ReversalSounds[playReversal]); + + Sampler.AddSample(relativeVelocity); + } + + public void StartThinking(PhysConstraint outer, in Vector3 relativeVelocity, in Vector3 forwardVector) { + ForwardAxis = forwardVector; + Sampler.BeginSampling(relativeVelocity); + } + + public void StopThinking(PhysConstraint outer) { + DeleteAllSounds(); + } + + protected void DeleteAllSounds() { + if (TravelSound != null) { + SoundEnvelopeController.GetController().SoundDestroy(TravelSound); + TravelSound = null; + } } } +#endif diff --git a/Game.Server/PhysController.cs b/Game.Server/PhysController.cs new file mode 100644 index 000000000..27357ad46 --- /dev/null +++ b/Game.Server/PhysController.cs @@ -0,0 +1,851 @@ +global using static Game.Server.PhysControllerGlobals; + +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Mathematics; +using Source.Common.Physics; + +#if GMOD_DLL +using Game.Server.GarrysMod; +#endif + +using System.Numerics; + +namespace Game.Server; + +public static class PhysControllerGlobals +{ + public const int SF_THRUST_STARTACTIVE = 1; + public const int SF_THRUST_FORCE = 2; + public const int SF_THRUST_TORQUE = 4; + public const int SF_THRUST_LOCAL_ORIENTATION = 8; + public const int SF_THRUST_MASS_INDEPENDENT = 16; + public const int SF_THRUST_IGNORE_POS = 32; + + public const int SF_MOTOR_START_ON = 1; + public const int SF_MOTOR_NOCOLLIDE = 2; + public const int SF_MOTOR_HINGE = 4; + public const int SF_MOTOR_LOCAL = 8; + + public const int SF_KEEPUPRIGHT_START_INACTIVE = 1; + + public static void CalculateVelocityOffsetLocal(IPhysicsObject phys, in Vector3 forceLocal, in Vector3 positionLocal, out Vector3 outVelLocal, out Vector3 outAngular) { + phys.LocalToWorld(out Vector3 posWorld, positionLocal); + phys.LocalToWorldVector(out Vector3 forceWorld, forceLocal); + phys.CalculateVelocityOffset(forceWorld, posWorld, out Vector3 velWorld, out outAngular); + phys.WorldToLocalVector(out outVelLocal, velWorld); + } + + public static BaseEntity? CreateKeepUpright(in Vector3 vecOrigin, in QAngle vecAngles, BaseEntity? owner, float angularLimit, bool active) { + KeepUpright? keepUpright = (KeepUpright?)BaseEntity.Create("phys_keepupright", vecOrigin, vecAngles, owner); + if (keepUpright != null) { + keepUpright.AttachedObject.Set(owner); + keepUpright.AngularLimit = angularLimit; + if (!active) + keepUpright.AddSpawnFlags(SF_KEEPUPRIGHT_START_INACTIVE); + keepUpright.Spawn(); + keepUpright.Activate(); + } + + return keepUpright; + } + + public static Vector3 ComputeRotSpeedToAlignAxes(in Vector3 testAxis, in Vector3 alignAxis, in Vector3 currentSpeed, float damping, float scale, float maxSpeed) { + Vector3 rotationAxis = Vector3.Cross(testAxis, alignAxis); + + float cosine = Vector3.Dot(testAxis, alignAxis); + float sine = MathLib.VectorNormalize(ref rotationAxis); + float angle = MathF.Atan2(sine, cosine); + + angle = MathLib.RAD2DEG(angle); + Vector3 angular = rotationAxis * scale * angle; + angular -= rotationAxis * damping * Vector3.Dot(currentSpeed, rotationAxis); + + float len = MathLib.VectorNormalize(ref angular); + + if (len > maxSpeed) + len = maxSpeed; + + return angular * len; + } +} + +public class ConstantForceController : IMotionEvent +{ + public static readonly DataMap DataDesc = new(typeof(ConstantForceController), null, [ + DEFINE.FIELD(nameof(ControlType), FieldType.Integer), + DEFINE.FIELD(nameof(Linear), FieldType.Vector), + DEFINE.FIELD(nameof(Angular), FieldType.Vector), + DEFINE.FIELD(nameof(LinearSave), FieldType.Vector), + DEFINE.FIELD(nameof(AngularSave), FieldType.Vector), + ]); + + public SimResult ControlType; + public Vector3 Linear; + public Vector3 Angular; + public Vector3 LinearSave; + public Vector3 AngularSave; + + public void Init(SimResult controlType) { + ControlType = controlType; + } + + public void SetConstantForce(in Vector3 linear, in Vector3 angular) { + Linear = linear; + Angular = angular; + LinearSave = linear; + AngularSave = angular; + } + + public void ScaleConstantForce(float scale) { + Linear = LinearSave * scale; + Angular = AngularSave * scale; + } + + public SimResult Simulate(IPhysicsMotionController? controller, IPhysicsObject? obj, TimeUnit_t deltaTime, out Vector3 linear, out Vector3 angular) { +#if GMOD_DLL + for (int i = 0; i < 3; i++) { + if (!float.IsFinite(Linear[i])) + Linear[i] = 10000.0f; + } + for (int i = 0; i < 3; i++) { + if (!float.IsFinite(Angular[i])) + Angular[i] = 10000.0f; + } +#endif + linear = Linear; + angular = Angular; + + return ControlType; + } +} + +public abstract class PhysForce : PointEntity +{ + public static readonly new DataMap DataDesc = new(typeof(PhysForce), BaseEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(NameAttach), FieldType.String, "attach1"), + DEFINE.KEYFIELD(nameof(Force), FieldType.Float, "force"), + DEFINE.KEYFIELD(nameof(ForceTime), FieldType.Float, "forcetime"), + + DEFINE.FIELD(nameof(AttachedObject), FieldType.EHandle), + DEFINE.EMBEDDED(nameof(Integrator)), + + DEFINE.INPUTFUNC(FieldType.Void, "Activate", nameof(InputActivate), (INPUTFUNCPTR)((self, data) => ((PhysForce)self).InputActivate(data))), + DEFINE.INPUTFUNC(FieldType.Void, "Deactivate", nameof(InputDeactivate), (INPUTFUNCPTR)((self, data) => ((PhysForce)self).InputDeactivate(data))), + DEFINE.INPUTFUNC(FieldType.Float, "scale", nameof(InputForceScale), (INPUTFUNCPTR)((self, data) => ((PhysForce)self).InputForceScale(data))), + + DEFINE.THINKFUNC(nameof(ForceOff)), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + protected IPhysicsMotionController? Controller; + + protected string? NameAttach; + protected float Force; + protected float ForceTime; + protected EHANDLE AttachedObject = new(); + protected bool WasRestored; +#if GMOD_DLL + protected IPhysicsObject? PhysObject; +#endif + + protected readonly ConstantForceController Integrator = new(); + + public PhysForce() { + Controller = null; + WasRestored = false; + } + + public override void Term() { + if (Controller != null) + physenv.DestroyMotionController(Controller); + base.Term(); + } + + public override void Spawn() { + if ((SpawnFlags & SF_THRUST_LOCAL_ORIENTATION) != 0) + Integrator.Init(SimResult.LocalAcceleration); + else + Integrator.Init(SimResult.GlobalAcceleration); + } + + public override void OnRestore() { + base.OnRestore(); + + Controller?.SetEventHandler(Integrator); + WasRestored = true; + } + + public override void Activate() { + base.Activate(); + + Controller?.WakeObjects(); + if (WasRestored) + return; + +#if GMOD_DLL + if (PhysObject == null && AttachedObject.Get() == null) +#else + if (AttachedObject.Get() == null) +#endif + AttachedObject.Set(gEntList.FindEntityByName(null, NameAttach)); + + OnActivate(); + + if ((SpawnFlags & SF_THRUST_STARTACTIVE) != 0) + ForceOn(); + } + +#if GMOD_DLL + public override void SetPhysObject(int index, IPhysicsObject? obj) { + if (index == 0) + PhysObject = obj; + else + obj = PhysObject; + if (obj != null) { + BaseEntity? entity = (BaseEntity?)obj.GetGameData(); + AttachedObject.Set(entity); + } + } +#endif + + void InputActivate(in InputData inputdata) { + ForceOn(); + } + + void InputDeactivate(in InputData inputdata) { + ForceOff(); + } + + void InputForceScale(in InputData inputdata) { + ScaleForce(inputdata.Value.Float()); + } + + public void ForceOn() { + if (Controller != null) + return; + + ActivateForce(); + if (ForceTime != 0) { + SetNextThink(gpGlobals.CurTime + ForceTime); + SetThink(ForceOff); + } + } + + public void ActivateForce() { +#if GMOD_DLL + if (Controller != null) + return; + + if (PhysObject != null && !LuaPhysObj.IsPhysicsObjectValid(PhysObject)) + PhysObject = null; + + BaseEntity? attached = AttachedObject.Get(); + if (attached == null) + return; + IPhysicsObject? phys = PhysObject ?? attached.VPhysicsGetObject(); + if (phys == null || !LuaPhysObj.IsPhysicsObjectValid(phys)) + return; +#else + IPhysicsObject? phys = null; + BaseEntity? attached = AttachedObject.Get(); + if (attached != null) + phys = attached.VPhysicsGetObject(); + + if (phys == null) + return; +#endif + + SetupForces(phys, out Vector3 linear, out Vector3 angular); + + Integrator.SetConstantForce(linear, angular); + Controller = physenv.CreateMotionController(Integrator); + Controller.AttachObject(phys, true); + phys.Wake(); + } + + public void ForceOff() { + if (Controller == null) + return; + + physenv.DestroyMotionController(Controller); + Controller = null; + SetThink(null); + SetNextThink(TICK_NEVER_THINK); + BaseEntity? attached = AttachedObject.Get(); + if (attached != null) { +#if GMOD_DLL + if (PhysObject != null && !LuaPhysObj.IsPhysicsObjectValid(PhysObject)) + PhysObject = null; + IPhysicsObject? phys = PhysObject ?? attached.VPhysicsGetObject(); + if (phys != null && LuaPhysObj.IsPhysicsObjectValid(phys)) + phys.Wake(); +#else + IPhysicsObject? phys = attached.VPhysicsGetObject(); + phys?.Wake(); +#endif + } + } + + public void ScaleForce(float scale) { +#if GMOD_DLL + if (Controller == null) { + ForceOn(); + if (Controller == null) + return; + } + + if (scale == 0.0f) + scale = 0.001f; +#else + if (Controller == null) + ForceOn(); +#endif + + Integrator.ScaleConstantForce(scale); + Controller!.WakeObjects(); + } + + public abstract void SetupForces(IPhysicsObject phys, out Vector3 linear, out Vector3 angular); + + public virtual void OnActivate() { } +} + +[LinkEntityToClass("phys_thruster")] +public class PhysThruster : PhysForce +{ + public static readonly new DataMap DataDesc = new(typeof(PhysThruster), PhysForce.DataDesc, [ + DEFINE.FIELD(nameof(LocalOrigin), FieldType.Vector), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + Vector3 LocalOrigin; + + public override void OnActivate() { + BaseEntity? attached = AttachedObject.Get(); +#if GMOD_DLL + if (attached == null && PhysObject == null) + return; + { +#else + if (attached != null) { +#endif + MathLib.MatrixInvert(attached!.EntityToWorldTransform(), out Matrix3x4 worldToAttached); + MathLib.ConcatTransforms(worldToAttached, EntityToWorldTransform(), out Matrix3x4 thrusterToAttached); + MathLib.MatrixGetColumn(thrusterToAttached, 3, out LocalOrigin); + + if (HasSpawnFlags(SF_THRUST_LOCAL_ORIENTATION)) { + MathLib.MatrixAngles(thrusterToAttached, out QAngle angles); + SetLocalAngles(angles); + } + if (HasSpawnFlags(SF_THRUST_IGNORE_POS)) + LocalOrigin.Init(); + } + } + + public override void SetupForces(IPhysicsObject phys, out Vector3 linear, out Vector3 angular) { + MathLib.AngleVectors(GetLocalAngles(), out Vector3 thrustVector); + thrustVector *= Force; + + if ((SpawnFlags & SF_THRUST_MASS_INDEPENDENT) != 0) + thrustVector *= phys.GetMass(); + if ((SpawnFlags & SF_THRUST_LOCAL_ORIENTATION) != 0) + CalculateVelocityOffsetLocal(phys, thrustVector, LocalOrigin, out linear, out angular); + else { + MathLib.VectorTransform(LocalOrigin, AttachedObject.Get()!.EntityToWorldTransform(), out Vector3 position); + phys.CalculateVelocityOffset(thrustVector, position, out linear, out angular); + } + + if ((SpawnFlags & SF_THRUST_FORCE) == 0) + linear.Init(); + + if ((SpawnFlags & SF_THRUST_TORQUE) == 0) + angular.Init(); + } +} + +[LinkEntityToClass("phys_torque")] +public class PhysTorque : PhysForce +{ + public static readonly new DataMap DataDesc = new(typeof(PhysTorque), PhysForce.DataDesc, [ + DEFINE.KEYFIELD(nameof(Axis), FieldType.Vector, "axis"), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + Vector3 Axis; + + public override void Spawn() { + SpawnFlags |= SF_THRUST_TORQUE | SF_THRUST_MASS_INDEPENDENT; + SpawnFlags &= ~SF_THRUST_FORCE; + + Axis -= GetAbsOrigin(); + MathLib.VectorNormalize(ref Axis); +#if !GMOD_DLL + Util.SnapDirectionToAxis(ref Axis); +#endif + base.Spawn(); + } + + public override void SetupForces(IPhysicsObject phys, out Vector3 linear, out Vector3 angular) { + linear = default; + linear.Init(); + +#if GMOD_DLL + if (Force == 0.0f || Force > 500000.0f || Force < -500000.0f) { + angular = default; + return; + } +#endif + + phys.GetPositionMatrix(out Matrix3x4 matrix); + + MathLib.VectorIRotate(Axis, matrix, out Vector3 axis_ls); + + angular = axis_ls * Force; + } +} + +public class MotorController : IMotionEvent +{ + public static readonly DataMap DataDesc = new(typeof(MotorController), null, [ + DEFINE.FIELD(nameof(Speed), FieldType.Float), + DEFINE.FIELD(nameof(MaxTorque), FieldType.Float), + DEFINE.KEYFIELD(nameof(Axis), FieldType.Vector, "axis"), + DEFINE.KEYFIELD(nameof(InertiaFactor), FieldType.Float, "inertiafactor"), + DEFINE.FIELD(nameof(LastSpeed), FieldType.Float), + DEFINE.FIELD(nameof(LastAcceleration), FieldType.Float), + DEFINE.FIELD(nameof(LastForce), FieldType.Float), + DEFINE.FIELD(nameof(RestistanceDamping), FieldType.Float), + ]); + + public float Speed; + public float MaxTorque; + public Vector3 Axis; + public float InertiaFactor; + + public float LastSpeed; + public float LastAcceleration; + public float LastForce; + public float RestistanceDamping; + + public SimResult Simulate(IPhysicsMotionController? controller, IPhysicsObject? obj, TimeUnit_t deltaTime, out Vector3 linear, out Vector3 angular) { + linear = vec3_origin; + angular = vec3_origin; + + if (Speed == 0) + return SimResult.Nothing; + + obj!.GetPositionMatrix(out Matrix3x4 matrix); + + obj.GetVelocity(out _, out Vector3 currentRotAxis); + MathLib.VectorIRotate(Axis, matrix, out Vector3 motorAxis_ls); + float currentSpeed = Vector3.Dot(currentRotAxis, motorAxis_ls); + + float inertia = MathLib.DotProductAbs(obj.GetInertia(), motorAxis_ls); + + float accel = Speed - currentSpeed; + float rotForce = accel * inertia * InertiaFactor; + + if (MathF.Abs(LastAcceleration) > 0) { + float deltaSpeed = currentSpeed - LastSpeed; + if (deltaSpeed * accel > 0) { + float factor = deltaSpeed / LastAcceleration; + factor = 1 - Math.Clamp(factor, 0.0f, 1.0f); + rotForce += LastForce * factor * RestistanceDamping; + } + else { + if (currentSpeed != 0) { + float increase = deltaSpeed / LastAcceleration; + if (MathF.Abs(increase) < 0.05) + rotForce += LastForce * RestistanceDamping; + } + } + } + + if (MaxTorque != 0) { + if (rotForce > MaxTorque) + rotForce = MaxTorque; + else if (rotForce < -MaxTorque) + rotForce = -MaxTorque; + } + + LastForce = rotForce; + LastAcceleration = (rotForce / inertia); + LastSpeed = currentSpeed; + + angular = motorAxis_ls * rotForce; + + return SimResult.LocalForce; + } +} + +[LinkEntityToClass("phys_motor")] +public class PhysMotor : LogicalEntity +{ + public static readonly new DataMap DataDesc = new(typeof(PhysMotor), BaseEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(NameAttach), FieldType.String, "attach1"), + DEFINE.FIELD(nameof(AttachedObject), FieldType.EHandle), + DEFINE.KEYFIELD(nameof(SpinUp), FieldType.Float, "spinup"), + DEFINE.KEYFIELD(nameof(AdditionalAcceleration), FieldType.Float, "addangaccel"), + DEFINE.FIELD(nameof(AngularAcceleration), FieldType.Float), + DEFINE.FIELD(nameof(LastTime), FieldType.Time), + + DEFINE.INPUTFUNC(FieldType.Float, "SetSpeed", nameof(InputSetTargetSpeed), (INPUTFUNCPTR)((self, data) => ((PhysMotor)self).InputSetTargetSpeed(data))), + DEFINE.INPUTFUNC(FieldType.Void, "TurnOn", nameof(InputTurnOn), (INPUTFUNCPTR)((self, data) => ((PhysMotor)self).InputTurnOn(data))), + DEFINE.INPUTFUNC(FieldType.Void, "TurnOff", nameof(InputTurnOff), (INPUTFUNCPTR)((self, data) => ((PhysMotor)self).InputTurnOff(data))), + + DEFINE.EMBEDDED(nameof(Motor)), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + string? NameAttach; + EHANDLE AttachedObject = new(); + float SpinUp; + float AdditionalAcceleration; + float AngularAcceleration; + float LastTime; +#if GMOD_DLL + IPhysicsObject? PhysObject; +#endif + + IPhysicsConstraint? Hinge; + IPhysicsMotionController? Controller; + readonly MotorController Motor = new(); + + void CalculateAcceleration() { + if (SpinUp != 0) + AngularAcceleration = MathF.Abs(Speed / SpinUp); + else + AngularAcceleration = MathF.Abs(Speed); + } + + void InputSetTargetSpeed(in InputData inputdata) { + if (Speed == inputdata.Value.Float()) + return; + + Speed = inputdata.Value.Float(); + TargetSpeedChanged(); + CalculateAcceleration(); + } + + void TargetSpeedChanged() { + SetNextThink(gpGlobals.CurTime); + LastTime = (float)gpGlobals.CurTime; + Controller!.WakeObjects(); + } + + void InputTurnOn(in InputData inputdata) { + TurnOn(); + } + + void InputTurnOff(in InputData inputdata) { + Motor.Speed = 0; + SetNextThink(TICK_NEVER_THINK); + } + + public override void Term() { + BaseEntity? attached = AttachedObject.Get(); + if (attached != null && Hinge != null) { + IPhysicsObject? phys = attached.VPhysicsGetObject(); + if (phys != null) + PhysClearGameFlags(phys, PhysicsFlags.NoPlayerPickup); + } + + physenv.DestroyConstraint(Hinge!); + physenv.DestroyMotionController(Controller!); + base.Term(); + } + + public override void Spawn() { + Motor.Axis -= GetLocalOrigin(); + float axisLength = MathLib.VectorNormalize(ref Motor.Axis); + if (axisLength > 1.0f) + Util.SnapDirectionToAxis(ref Motor.Axis); + else { + Warning($"phys_motor {GetDebugName()} does not have a valid axis helper, and self-destructed!\n"); + + Motor.Speed = 0; + SetNextThink(TICK_NEVER_THINK); + + Util.Remove(this); + } + } + +#if GMOD_DLL + public override void SetPhysObject(int index, IPhysicsObject? obj) { + if (index == 0) + PhysObject = obj; + else + obj = PhysObject; + if (obj != null) { + BaseEntity? entity = (BaseEntity?)obj.GetGameData(); + AttachedObject.Set(entity); + } + } +#endif + + void TurnOn() { + BaseEntity? attached = AttachedObject.Get(); + if (attached == null) + return; + + IPhysicsObject? phys = attached.VPhysicsGetObject(); + if (phys != null) { +#if GMOD_DLL + Controller?.WakeObjects(); +#else + Controller!.WakeObjects(); +#endif + LastTime = (float)(gpGlobals.CurTime - TICK_INTERVAL); + Think(); + } + } + + public override void Activate() { + base.Activate(); + + if (PhysObject == null && AttachedObject.Get() == null) { + BaseEntity? attach = gEntList.FindEntityByName(null, NameAttach); + if (attach != null && attach.GetMoveType() == Source.MoveType.VPhysics) { + AttachedObject.Set(attach); + IPhysicsObject phys = attach.VPhysicsGetObject()!; + CalculateAcceleration(); + phys.GetPositionMatrix(out Matrix3x4 matrix); + MathLib.VectorIRotate(Motor.Axis, matrix, out Vector3 motorAxis_ls); + float inertia = MathLib.DotProductAbs(phys.GetInertia(), motorAxis_ls); + Motor.MaxTorque = inertia * Motor.InertiaFactor * (AngularAcceleration + AdditionalAcceleration); + Motor.RestistanceDamping = 1.0f; + } + } + +#if GMOD_DLL + if (PhysObject != null && !LuaPhysObj.IsPhysicsObjectValid(PhysObject)) + PhysObject = null; + + IPhysicsObject? attachedPhys = PhysObject; + BaseEntity? attachedEntity = AttachedObject.Get(); + if (attachedEntity != null) { + attachedPhys ??= attachedEntity.VPhysicsGetObject(); + if (attachedPhys == null) { + Warning("Phys Motor Error: No physics object found. Deleting.\n"); + Util.Remove(this); + return; + } + } + else if (attachedPhys == null) + return; + { + IPhysicsObject? pPhys = attachedPhys; +#else + BaseEntity? attachedEntity = AttachedObject.Get(); + if (attachedEntity != null) { + IPhysicsObject? pPhys = attachedEntity.VPhysicsGetObject(); +#endif + + if ((SpawnFlags & SF_MOTOR_HINGE) != 0) { + if (Hinge == null) { + ConstraintHingeParams hingeParams = default; + hingeParams.Defaults(); + hingeParams.WorldAxisDirection = Motor.Axis; + hingeParams.WorldPosition = GetLocalOrigin(); + + Hinge = physenv.CreateHingeConstraint(g_PhysWorldObject!, pPhys!, null!, hingeParams); + Hinge.SetGameData(this); + PhysSetGameFlags(pPhys!, PhysicsFlags.NoPlayerPickup); + } + + if ((SpawnFlags & SF_MOTOR_NOCOLLIDE) != 0) + PhysDisableEntityCollisions(g_PhysWorldObject, pPhys); + } + else + Hinge = null; + + if (Controller == null) { + Controller = physenv.CreateMotionController(Motor); +#if GMOD_DLL + Controller.AttachObject(pPhys!, false); +#else + Controller.AttachObject(attachedEntity.VPhysicsGetObject()!, false); +#endif + + if ((SpawnFlags & SF_MOTOR_START_ON) != 0) + TurnOn(); + } + } + } + + public override void OnRestore() { + base.OnRestore(); + Controller?.SetEventHandler(Motor); + } + + public override void Think() { + Assert(AngularAcceleration >= 0); + + Motor.Speed = MathLib.Approach(Speed, Motor.Speed, AngularAcceleration * (float)(gpGlobals.CurTime - LastTime)); + LastTime = (float)gpGlobals.CurTime; + if (Motor.Speed != Speed) + SetNextThink(gpGlobals.CurTime); + } +} + +[LinkEntityToClass("phys_keepupright")] +public class KeepUpright : PointEntity, IMotionEvent +{ + public static readonly new DataMap DataDesc = new(typeof(KeepUpright), BaseEntity.DataDesc, [ + DEFINE.FIELD(nameof(WorldGoalAxis), FieldType.Vector), + DEFINE.FIELD(nameof(LocalTestAxis), FieldType.Vector), + DEFINE.KEYFIELD(nameof(NameAttach), FieldType.String, "attach1"), + DEFINE.FIELD(nameof(AttachedObject), FieldType.EHandle), + DEFINE.KEYFIELD(nameof(AngularLimit), FieldType.Float, "angularlimit"), + DEFINE.FIELD(nameof(Active), FieldType.Boolean), + DEFINE.FIELD(nameof(DampAllRotation), FieldType.Boolean), + + DEFINE.INPUTFUNC(FieldType.Void, "TurnOn", nameof(InputTurnOn), (INPUTFUNCPTR)((self, data) => ((KeepUpright)self).InputTurnOn(data))), + DEFINE.INPUTFUNC(FieldType.Void, "TurnOff", nameof(InputTurnOff), (INPUTFUNCPTR)((self, data) => ((KeepUpright)self).InputTurnOff(data))), + DEFINE.INPUTFUNC(FieldType.Float, "SetAngularLimit", nameof(InputSetAngularLimit), (INPUTFUNCPTR)((self, data) => ((KeepUpright)self).InputSetAngularLimit(data))), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + Vector3 WorldGoalAxis; + Vector3 LocalTestAxis; + IPhysicsMotionController? Controller; + string? NameAttach; + internal EHANDLE AttachedObject = new(); + internal float AngularLimit; + bool Active; + bool DampAllRotation; +#if GMOD_DLL + IPhysicsObject? PhysObject; +#endif + + public KeepUpright() { + AngularLimit = 15; + AttachedObject.Set(null); + DampAllRotation = false; + } + + public override void Term() { + if (Controller != null) { + physenv.DestroyMotionController(Controller); + Controller = null; + } + base.Term(); + } + + void InputTurnOn(in InputData inputdata) { + Active = true; + } + + void InputTurnOff(in InputData inputdata) { + Active = false; + } + + void InputSetAngularLimit(in InputData inputdata) { + AngularLimit = inputdata.Value.Float(); + } + +#if GMOD_DLL + public override void SetPhysObject(int index, IPhysicsObject? obj) { + if (index == 0) + PhysObject = obj; + else + obj = PhysObject; + if (obj != null) { + BaseEntity? entity = (BaseEntity?)obj.GetGameData(); + AttachedObject.Set(entity); + } + } +#endif + + public override void Spawn() { + LocalTestAxis.Init(0, 0, 1); + GetVectors(out _, out _, out WorldGoalAxis); + + SetMoveType(Source.MoveType.None); + + if ((SpawnFlags & SF_KEEPUPRIGHT_START_INACTIVE) != 0) + Active = false; + else + Active = true; + } + + public override void Activate() { + base.Activate(); + +#if GMOD_DLL + if (PhysObject != null && !LuaPhysObj.IsPhysicsObjectValid(PhysObject)) + PhysObject = null; +#endif + + if (Controller == null) { + IPhysicsObject? phys; + BaseEntity? attached = AttachedObject.Get(); +#if GMOD_DLL + if (attached != null) + phys = PhysObject ?? attached.VPhysicsGetObject(); + else { + IPhysicsObject? found = PhysicsHook.FindPhysicsObjectByName(NameAttach, this); + phys = PhysObject ?? found; + if (phys != null && Controller != null) { + physenv.DestroyMotionController(Controller); + Controller = null; + } + } +#else + if (attached != null) + phys = attached.VPhysicsGetObject(); + else + phys = PhysicsHook.FindPhysicsObjectByName(NameAttach, this); +#endif + + if (phys == null) { + Util.Remove(this); + return; + } +#if HL2_DLL && !GMOD_DLL + if (AngularLimit == 150.0f) { + BaseEntity? entity = (BaseEntity?)phys.GetGameData(); + if (entity != null && entity.GetServerVehicle() != null && !stristr(gpGlobals.MapName, "d2_coast_01").IsEmpty) + DampAllRotation = true; + } +#endif + + Controller = physenv.CreateMotionController(this); + Controller.AttachObject(phys, false); + } + else + Controller.SetEventHandler(this); + } + + public SimResult Simulate(IPhysicsMotionController? controller, IPhysicsObject? obj, TimeUnit_t deltaTime, out Vector3 linear, out Vector3 angular) { + linear = default; + angular = default; + if (!Active) + return SimResult.Nothing; + + linear.Init(); + + obj!.GetVelocity(out _, out Vector3 angVel); + + obj.GetPositionMatrix(out Matrix3x4 matrix); + + MathLib.VectorIRotate(WorldGoalAxis, matrix, out Vector3 currentLocalTargetAxis); + + float invDeltaTime = (float)(1 / deltaTime); + + if (DampAllRotation) { + angular = ComputeRotSpeedToAlignAxes(LocalTestAxis, currentLocalTargetAxis, angVel, 0, invDeltaTime, AngularLimit); + angular -= angVel; + angular *= invDeltaTime; + return SimResult.LocalAcceleration; + } + + angular = ComputeRotSpeedToAlignAxes(LocalTestAxis, currentLocalTargetAxis, angVel, 1.0f, invDeltaTime, AngularLimit); + angular *= invDeltaTime; + + return SimResult.LocalAcceleration; + } +} diff --git a/Game.Server/PhysObj.cs b/Game.Server/PhysObj.cs index 22d0df016..c719a66e3 100644 --- a/Game.Server/PhysObj.cs +++ b/Game.Server/PhysObj.cs @@ -9,6 +9,10 @@ using System.Numerics; +#if GMOD_DLL +using Game.Server.GarrysMod; +#endif + using DEFINE = Source.DEFINE; namespace Game.Server; @@ -29,6 +33,253 @@ public enum SF } +[LinkEntityToClass("phys_spring")] +public class PhysicsSpring : BaseEntity +{ + public const int SF_SPRING_ONLYSTRETCH = 1; + + public static readonly new DataMap DataDesc = new(typeof(PhysicsSpring), BaseEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(TempConstant), FieldType.Float, "constant"), + DEFINE.KEYFIELD(nameof(TempLength), FieldType.Float, "length"), + DEFINE.KEYFIELD(nameof(TempDamping), FieldType.Float, "damping"), + DEFINE.KEYFIELD(nameof(TempRelativeDamping), FieldType.Float, "relativedamping"), + + DEFINE.KEYFIELD(nameof(NameAttachStart), FieldType.String, "attach1"), + DEFINE.KEYFIELD(nameof(NameAttachEnd), FieldType.String, "attach2"), + + DEFINE.FIELD(nameof(Start), FieldType.PositionVector), + DEFINE.KEYFIELD(nameof(End), FieldType.PositionVector, "springaxis"), + DEFINE.FIELD(nameof(IsLocal), FieldType.Boolean), + + DEFINE.INPUTFUNC(FieldType.Float, "SetSpringConstant", nameof(InputSetSpringConstant), (INPUTFUNCPTR)((self, data) => ((PhysicsSpring)self).InputSetSpringConstant(data))), + DEFINE.INPUTFUNC(FieldType.Float, "SetSpringLength", nameof(InputSetSpringLength), (INPUTFUNCPTR)((self, data) => ((PhysicsSpring)self).InputSetSpringLength(data))), + DEFINE.INPUTFUNC(FieldType.Float, "SetSpringDamping", nameof(InputSetSpringDamping), (INPUTFUNCPTR)((self, data) => ((PhysicsSpring)self).InputSetSpringDamping(data))), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + IPhysicsSpring? Spring; + bool IsLocal; + + float TempConstant; + float TempLength; + float TempDamping; + float TempRelativeDamping; + + string? NameAttachStart; + string? NameAttachEnd; + Vector3 Start; + Vector3 End; + uint TeleportTick; +#if GMOD_DLL + InlineArray2 PhysObjects; +#endif + + public PhysicsSpring() { + Spring = null; + TempConstant = 150; + TempLength = 0; + TempDamping = 2.0f; + TempRelativeDamping = 0.01f; + IsLocal = false; + TeleportTick = uint.MaxValue; +#if GMOD_DLL + PhysObjects[0] = null; + PhysObjects[1] = null; +#endif + } + + public override void Term() { + if (Spring != null) + physenv.DestroySpring(Spring); + base.Term(); + } + + public IPhysicsObject? GetStartObject() => Spring?.GetStartObject(); + public IPhysicsObject? GetEndObject() => Spring?.GetEndObject(); + +#if GMOD_DLL + public override void SetPhysObject(int index, IPhysicsObject? obj) => PhysObjects[index] = obj; +#endif + + public static bool GetSpringAttachments(BaseEntity entity, Span attachOut, Span attachVPhysics) { + if (entity is PhysicsSpring springEntity) { + IPhysicsObject? refObj = springEntity.GetStartObject(); + attachOut[0] = refObj != null ? (BaseEntity?)refObj.GetGameData() : null; + attachVPhysics[0] = refObj; + IPhysicsObject? attach = springEntity.GetEndObject(); + attachOut[1] = attach != null ? (BaseEntity?)attach.GetGameData() : null; + attachVPhysics[1] = attach; + return true; + } + return false; + } + + void InputSetSpringConstant(in InputData inputdata) { +#if GMOD_DLL + TempConstant = Math.Clamp(inputdata.Value.Float(), 0.0f, 50000.0f); + Spring?.SetSpringConstant(TempConstant); +#else + TempConstant = inputdata.Value.Float(); + Spring!.SetSpringConstant(inputdata.Value.Float()); +#endif + } + + void InputSetSpringDamping(in InputData inputdata) { +#if GMOD_DLL + TempDamping = Math.Clamp(inputdata.Value.Float(), 0.0f, 10000.0f); + Spring?.SetSpringDamping(TempDamping); +#else + TempDamping = inputdata.Value.Float(); + Spring!.SetSpringDamping(inputdata.Value.Float()); +#endif + } + + void InputSetSpringLength(in InputData inputdata) { +#if GMOD_DLL + TempLength = Math.Clamp(inputdata.Value.Float(), 0.0f, 4096.0f); + Spring?.SetSpringLength(TempLength); +#else + TempLength = inputdata.Value.Float(); + Spring!.SetSpringLength(inputdata.Value.Float()); +#endif + } + + public override int DrawDebugTextOverlays() { + int text_offset = base.DrawDebugTextOverlays(); + + if ((DebugOverlays & DebugOverlayBits.Text) != 0) { + EntityText(text_offset, $"Constant: {TempConstant:F2}", 0); + text_offset++; + + EntityText(text_offset, $"Length: {TempLength:F2}", 0); + text_offset++; + + EntityText(text_offset, $"Damping: {TempDamping:F2}", 0); + text_offset++; + } + return text_offset; + } + + public override void DrawDebugGeometryOverlays() { + if (Spring == null) + return; + + if ((DebugOverlays & DebugOverlayBits.BBox) != 0) { + Spring.GetEndpoints(out Vector3 startPos, out Vector3 endPos); + + Vector3 springDir = endPos - startPos; + MathLib.VectorNormalize(ref springDir); + + Vector3 length = startPos + (springDir * TempLength); + + DebugOverlay.Line(startPos, length, 0, 0, 255, false, 0); + DebugOverlay.Line(length, endPos, 255, 0, 0, false, 0); + } + base.DrawDebugGeometryOverlays(); + } + + public static bool PointIsNearer(IPhysicsObject object1, in Vector3 point1, in Vector3 point2) { + object1.GetPosition(out Vector3 center, out _); + + float dist1 = (center - point1).LengthSquared(); + float dist2 = (center - point2).LengthSquared(); + + if (dist1 < dist2) + return true; + + return false; + } + + void GetSpringObjectConnections(string? nameStart, string? nameEnd, out IPhysicsObject? start, out IPhysicsObject? end) { + IPhysicsObject? startObject = PhysicsHook.FindPhysicsObjectByName(nameStart, this); + IPhysicsObject? endObject = PhysicsHook.FindPhysicsObjectByName(nameEnd, this); + +#if GMOD_DLL + if (PhysObjects[0] != null || PhysObjects[1] != null) { + if (!LuaPhysObj.IsPhysicsObjectValid(PhysObjects[0])) + PhysObjects[0] = null; + if (!LuaPhysObj.IsPhysicsObjectValid(PhysObjects[1])) + PhysObjects[1] = null; + } + if (startObject == null) + startObject = PhysObjects[0]; + if (endObject == null) + endObject = PhysObjects[1]; +#endif + + if (startObject == null) + startObject = g_PhysWorldObject; + else if (endObject == null) { + endObject = startObject; + startObject = g_PhysWorldObject; + } + else { + BaseEntity? entity0 = (BaseEntity?)startObject.GetGameData(); + if (entity0 != null) + g_pNotify.AddEntity(this, entity0); + + BaseEntity? entity1 = (BaseEntity?)endObject.GetGameData(); + if (entity1 != null) + g_pNotify.AddEntity(this, entity1); + } + + start = startObject; + end = endObject; + } + + public override void Activate() { + base.Activate(); + + if (Spring == null) { + GetSpringObjectConnections(NameAttachStart, NameAttachEnd, out IPhysicsObject? start, out IPhysicsObject? end); + + if ((start == null || end == null) || (start == end)) { + DevMsg($"ERROR: Can't init spring {GetDebugName()} from \"{NameAttachStart}\" to \"{NameAttachEnd}\"\n"); + Util.Remove(this); + return; + } + +#if !GMOD_DLL + if (!PointIsNearer(end, End, Start)) + (Start, End) = (End, Start); +#endif + + SpringParams spring = default; +#if GMOD_DLL + spring.Constant = Math.Clamp(TempConstant, 0.0f, 50000.0f); + spring.Damping = Math.Clamp(TempDamping, 0.0f, 10000.0f); + spring.NaturalLength = TempLength; + spring.RelativeDamping = Math.Clamp(TempRelativeDamping, 0.0f, 1000.0f); +#else + spring.Constant = TempConstant; + spring.Damping = TempDamping; + spring.NaturalLength = TempLength; + spring.RelativeDamping = TempRelativeDamping; +#endif + spring.StartPosition = Start; + spring.EndPosition = End; + spring.UseLocalPositions = false; + spring.OnlyStretch = HasSpawnFlags(SF_SPRING_ONLYSTRETCH); + Spring = physenv.CreateSpring(start, end, ref spring); + } + } + + public override void Spawn() { + SetSolid(SolidType.None); + Start = GetAbsOrigin(); + if (TempLength <= 0) + TempLength = (End - Start).Length(); + } + + public override void NotifySystemEvent(BaseEntity notify, NotifySystemEvent eventType, in NotifySystemEventParams parms) { + if (eventType != Server.NotifySystemEvent.Teleport || (uint)gpGlobals.TickCount == TeleportTick) + return; + + TeleportTick = (uint)gpGlobals.TickCount; + PhysTeleportConstrainedEntity(notify, Spring!.GetStartObject(), Spring.GetEndObject(), parms.Teleport.PrevOrigin, parms.Teleport.PrevAngles, parms.Teleport.PhysicsRotate); + } +} + [LinkEntityToClass("env_physimpact")] public class PhysImpact : PointEntity { diff --git a/Game.Server/Player.cs b/Game.Server/Player.cs index 53203e2de..ab490e26e 100644 --- a/Game.Server/Player.cs +++ b/Game.Server/Player.cs @@ -678,6 +678,9 @@ public virtual void StopObserverMode() { public InButtons AfButtonLast; public InButtons AfButtonDisabled; public InButtons AfButtonForced; +#if GMOD_DLL + public Source.InlineArray5 ButtonsPressed; +#endif //----------------------------------------------------------------------------- // Purpose: Strips off IN_xxx flags from the player's input diff --git a/Game.Server/PlayerCommand.cs b/Game.Server/PlayerCommand.cs index 87179559a..58957d782 100644 --- a/Game.Server/PlayerCommand.cs +++ b/Game.Server/PlayerCommand.cs @@ -1,5 +1,9 @@ using Game.Server; using Game.Shared; +#if GMOD_DLL +using Game.Server.GarrysMod; +using Source.Common.GarrysMod.Lua; +#endif using Source.Common.Commands; using Source.Common.GUI; @@ -158,6 +162,20 @@ void RunThink(BasePlayer player, double frametime) { void RunPostThink(BasePlayer player) => player.PostThink(); +#if GMOD_DLL + static void CallButtonHooks(BasePlayer player, ReadOnlySpan buttons, ReadOnlySpan others, LUA_POOLEDSTRING hook) { + foreach (byte button in buttons) { + if (button == 0) + break; + if (others.Contains(button) || gGM == null || !gGM.CallWithArgs((int)hook)) + continue; + LuaEntity.Push_Entity(player); + g_Lua!.PushNumber(button); + gGM.CallNoReturns(2); + } + } +#endif + static double lastWarningTime; public void RunCommand(BasePlayer player, AnonymousSafeFieldPointer ucmd, IMoveHelper moveHelper) { ref UserCmd cmd = ref ucmd.Get(); @@ -196,6 +214,12 @@ public void RunCommand(BasePlayer player, AnonymousSafeFieldPointer ucm g_pGameMovement.StartTrackPredictionErrors(player); +#if GMOD_DLL + CallButtonHooks(player, cmd.ButtonsPressed, player.ButtonsPressed, LUA_POOLEDSTRING.PlayerButtonDown); + CallButtonHooks(player, player.ButtonsPressed, cmd.ButtonsPressed, LUA_POOLEDSTRING.PlayerButtonUp); + player.ButtonsPressed = cmd.ButtonsPressed; +#endif + // CommentarySystem_PePlayerRunCommand( player, ucmd ); if (cmd.WeaponSelect != 0) { diff --git a/Game.Server/RagdollProp.cs b/Game.Server/RagdollProp.cs index abff3f13d..4bf9948d2 100644 --- a/Game.Server/RagdollProp.cs +++ b/Game.Server/RagdollProp.cs @@ -41,6 +41,14 @@ public RagdollProp() { readonly Ragdoll ragdoll = new(); public Ragdoll GetRagdoll() => ragdoll; +#if GMOD_DLL + public override IPhysicsObject? VPhysicsGetElement(int index) { + if (index < 0 || ragdoll.ListCount <= index || ragdoll.List[index].Object == null) + return VPhysicsGetObject(); + return ragdoll.List[index].Object; + } +#endif + public static bool Ragdoll_IsPropRagdoll(BaseEntity entity) => entity is RagdollProp; public static Ragdoll? Ragdoll_GetRagdoll(BaseEntity entity) => (entity as RagdollProp)?.GetRagdoll(); diff --git a/Game.Server/Util.cs b/Game.Server/Util.cs index 3fb277ee8..936d2c2e5 100644 --- a/Game.Server/Util.cs +++ b/Game.Server/Util.cs @@ -201,6 +201,21 @@ public static partial class Util { public static float AngleMod(float a) => MathLib.AngleMod(a); + public static void SnapDirectionToAxis(ref Vector3 direction, float epsilon = 0.002f) { + float proj = 1 - epsilon; + for (int i = 0; i < 3; i++) { + if (MathF.Abs(direction[i]) > proj) { + if (direction[i] < 0) + direction[i] = -1.0f; + else + direction[i] = 1.0f; + direction[(i + 1) % 3] = 0; + direction[(i + 2) % 3] = 0; + return; + } + } + } + public static float AngleDiff(float destAngle, float srcAngle) { float delta; diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index d6b1df1c5..3609fe6b4 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -346,13 +346,115 @@ static int Entity__SetBodyGroups(ILuaInterface lua) { return 0; } + [LuaMethod] + static int Entity__AlignAngles(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + QAngle from = LuaAngle.Get_Angle(2); + QAngle to = LuaAngle.Get_Angle(3); + + QAngle entAngles = ent.GetAbsAngles(); + + MathLib.AngleMatrix(from, out Matrix3x4 fromMatrix); + MathLib.AngleMatrix(entAngles, out Matrix3x4 entMatrix); + MathLib.MatrixInvert(entMatrix, out Matrix3x4 entInverse); + + Matrix4x4 a = entInverse; + Matrix4x4 b = fromMatrix; + MathLib.MatrixMultiply(a, b, out Matrix4x4 local); + MathLib.MatrixToAngles(local, out QAngle localAngles); + + MathLib.AngleMatrix(to, out Matrix3x4 toMatrix); + MathLib.AngleMatrix(localAngles, out Matrix3x4 localMatrix); + MathLib.MatrixInvert(localMatrix, out Matrix3x4 localInverse); + + Matrix4x4 c = toMatrix; + Matrix4x4 d = localInverse; + MathLib.MatrixMultiply(c, d, out Matrix4x4 result); + MathLib.MatrixToAngles(result, out QAngle resultAngles); + + LuaAngle.Push_Angle(resultAngles); + return 1; + } + #if GAME_DLL + [LuaMethod] + static int Entity__Fire(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (IsQueuedForRemoval(ent)) + return 0; + + Variant_t value = new(); + if (lua.GetType(3) == LuaType.Number) + value.SetFloat((float)lua.GetNumber(3)); + else if (lua.GetType(3) == LuaType.Bool) + value.SetBool(lua.GetBool(3)); + else + value.SetString(lua.GetType(3) == LuaType.String ? lua.GetString(3) : ""); + + float delay = (float)lua.CheckNumberOpt(4, 0); + BaseEntity? caller = Get_Entity(6, true); + BaseEntity? activator = Get_Entity(5, true); + g_EventQueue.AddEvent(ent, lua.GetString(2), value, delay, activator, caller, 0); + return 0; + } + + [LuaMethod] + static int Entity__StartMotionController(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (PhysIsInCallback()) { + lua.ErrorFromLua("Cannot call StartMotionController in a physics callback!"); + return 0; + } + ent.StartMotionController(); + return 0; + } + + [LuaMethod] + static int Entity__SetEntity(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseEntity? other = Get_Entity(3, true); + ent.SetEntity(lua.CheckString(2), other); + return 0; + } + [LuaMethod] static int Entity__DeleteOnRemove(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; ent.DeleteOnRemove(Get_Entity(2, false)); return 0; } + + [LuaMethod] + static int Entity__Input(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (IsQueuedForRemoval(ent)) + return 0; + + Variant_t value = new(); + if (lua.GetType(5) == LuaType.Number) + value.SetFloat((float)lua.GetNumber(5)); + else if (lua.GetType(5) == LuaType.Bool) + value.SetBool(lua.GetBool(5)); + else + value.SetString(lua.GetType(5) == LuaType.String ? lua.GetString(5) : ""); + + BaseEntity? caller = Get_Entity(4, true); + BaseEntity? activator = Get_Entity(3, true); + lua.PushBool(ent.AcceptInput(lua.GetString(2), activator, caller, value, 0)); + return 1; + } + + [LuaMethod] + static int Entity__SetPhysConstraintObjects(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (!IsQueuedForRemoval(ent)) { + IPhysicsObject? obj0 = LuaPhysObj.Get_IPhysicsObject(2, false); + IPhysicsObject? obj1 = LuaPhysObj.Get_IPhysicsObject(3, false); + ent.SetPhysObject(0, obj0); + ent.SetPhysObject(1, obj1); + } + return 0; + } #endif [LuaMethod] @@ -624,8 +726,8 @@ static int Entity__SetColor4Part(ILuaInterface lua) { #if GAME_DLL [LuaMethod] static int Entity__IsConstraint(ILuaInterface lua) { - // todo: once physconstraint is ported - lua.PushBool(false); + BaseEntity? ent = Get_Entity(1, false); + lua.PushBool(ent is PhysConstraint); return 1; } #endif @@ -1956,7 +2058,7 @@ static int Entity__SetSaveValue(ILuaInterface lua) { } bool isArray = td.FieldSize > 1 && lua.GetType(3) == LuaType.Table; - Array? array = isArray ? (Array?)td.FieldInfo.GetValue(ent) : null; + Array? array = isArray ? td.Accessor.GetValue(ent) : null; object? Convert1(LuaObject elem) { return td.FieldType switch { @@ -2019,64 +2121,64 @@ static int Entity__SetSaveValue(ILuaInterface lua) { case FieldType.EHandle: if (!IsSettableHandle(name)) break; - EHANDLE handle = (EHANDLE)td.FieldInfo.GetValue(ent)!; + EHANDLE handle = td.Accessor.GetValue(ent); handle.Set(Get_Entity(3, true)); - td.FieldInfo.SetValue(ent, handle); + td.Accessor.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))); + td.Accessor.SetValue(ent, new string(lua.CheckString(3))); lua.PushBool(true); return 1; case FieldType.Integer: - td.FieldInfo.SetValue(ent, (int)lua.CheckNumber(3)); + td.Accessor.SetValue(ent, (int)lua.CheckNumber(3)); lua.PushBool(true); return 1; case FieldType.Float: - td.FieldInfo.SetValue(ent, (float)lua.CheckNumber(3)); + td.Accessor.SetValue(ent, (float)lua.CheckNumber(3)); lua.PushBool(true); return 1; case FieldType.Double: - td.FieldInfo.SetValue(ent, lua.CheckNumber(3)); + td.Accessor.SetValue(ent, lua.CheckNumber(3)); lua.PushBool(true); return 1; case FieldType.Short: - td.FieldInfo.SetValue(ent, (short)(int)lua.CheckNumber(3)); + td.Accessor.SetValue(ent, (short)(int)lua.CheckNumber(3)); lua.PushBool(true); return 1; case FieldType.Character: - td.FieldInfo.SetValue(ent, (byte)(int)lua.CheckNumber(3)); + td.Accessor.SetValue(ent, (byte)(int)lua.CheckNumber(3)); lua.PushBool(true); return 1; case FieldType.Boolean: - td.FieldInfo.SetValue(ent, lua.GetBool(3)); + td.Accessor.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)); + td.Accessor.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)); + td.Accessor.SetValue(ent, HLClient.GetMaterialIndex(material)); #else - td.FieldInfo.SetValue(ent, GameInterface.GetMaterialIndex(material)); + td.Accessor.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); + td.Accessor.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)); + td.Accessor.SetValue(ent, gpGlobals.TickCount + (int)lua.CheckNumber(3)); lua.PushBool(true); return 1; case FieldType.Vector: @@ -2089,7 +2191,7 @@ static int Entity__SetSaveValue(ILuaInterface lua) { } else vec = LuaVector.Get_Vector(3); - td.FieldInfo.SetValue(ent, vec); + td.Accessor.SetValue(ent, vec); lua.PushBool(true); return 1; } @@ -2191,7 +2293,7 @@ static int Entity__GetInternalVariable(ILuaInterface lua) { if (td == null) return 0; - object? value = td.FieldInfo.GetValue(ent); + object? value = td.Accessor.GetValue(ent); switch (td.FieldType) { case FieldType.Float: @@ -2930,6 +3032,13 @@ static int Entity__GetName(ILuaInterface lua) { lua.PushString(ent.GetEntityName() ?? ""); return 1; } + + [LuaMethod] + static int Entity__SetName(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ent.SetName(lua.CheckString(2)); + return 0; + } #endif [LuaMethod] diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs index 2a624aa9f..c6a5c05f0 100644 --- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs +++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs @@ -1,4 +1,8 @@ #if CLIENT_DLL || GAME_DLL || MENU_DLL +#if CLIENT_DLL || GAME_DLL +using Game.Shared; +#endif + using Source; using Source.Common.Commands; using Source.Common.Mathematics; @@ -103,6 +107,21 @@ public static void RGBtoHSV(int r, int g, int b, out float h, out float s, out f v = maxInt / 255.0f; } +#if CLIENT_DLL || GAME_DLL + public static EHANDLE g_PhysConstrantSystem = new(); + +#if GAME_DLL + public static BaseEntity? GetGlobalConstraintSystem() => g_PhysConstrantSystem.Get(); +#endif + + [LuaGlobal] + static int SetPhysConstraintSystem(ILuaInterface lua) { + BaseEntity? ent = LuaEntity.Get_Entity(1, true); + g_PhysConstrantSystem.Set(ent); + return 0; + } +#endif + #if !MENU_DLL [LuaGlobal] static int LocalToWorld(ILuaInterface lua) { diff --git a/Game.Shared/GarrysMod/LuaPhysObj.cs b/Game.Shared/GarrysMod/LuaPhysObj.cs index 261ece4ea..6346b607d 100644 --- a/Game.Shared/GarrysMod/LuaPhysObj.cs +++ b/Game.Shared/GarrysMod/LuaPhysObj.cs @@ -16,6 +16,8 @@ public static partial class LuaPhysObj { const int MAX_OBJECT_LIST = 0x400; + public static bool gPhysCallback; + [LuaClass(typeof(IPhysicsObject), NullError = "Tried to use a NULL physics object!")] public static readonly LuaClass LC_PhysObj = new("PhysObj", LuaType.PhysObj, null, null); diff --git a/Game.Shared/GarrysMod/SENT_Anim.cs b/Game.Shared/GarrysMod/SENT_Anim.cs index ace1489a3..28017ba10 100644 --- a/Game.Shared/GarrysMod/SENT_Anim.cs +++ b/Game.Shared/GarrysMod/SENT_Anim.cs @@ -24,7 +24,7 @@ public partial class #if CLIENT_DLL C_SENT_Anim : C_BaseAnimatingOverlay #elif GAME_DLL - SENT_Anim : BaseAnimatingOverlay + SENT_Anim : BaseAnimatingOverlay, IMotionEvent #endif { [NetworkTable] @@ -52,6 +52,71 @@ public override void InitializeScriptedEntity(ReadOnlySpan name) { } #if GAME_DLL + IPhysicsMotionController? MotionController; + + public override void StartMotionController() { + if (MotionController != null) { + physenv.DestroyMotionController(MotionController); + MotionController = null; + } + MotionController = physenv.CreateMotionController(this); + IPhysicsObject? phys = VPhysicsGetObject(); + if (phys != null) + MotionController.AttachObject(phys, true); + } + + public SimResult Simulate(IPhysicsMotionController? controller, IPhysicsObject? obj, TimeUnit_t deltaTime, out Vector3 linear, out Vector3 angular) { + linear = vec3_origin; + angular = vec3_origin; + if (ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.PhysicsSimulate)) { + LuaPhysObj.Push_PhysObj(obj); + g_Lua!.PushNumber(deltaTime); + if (ScriptedEntity.Call(2, 3) && g_Lua.GetReturn(0).isNumber()) { + int result = g_Lua.GetReturn(0).GetInt(); + if (result > 0) { + ILuaObject linearObj = g_Lua.GetReturn(1); + ILuaObject angularObj = g_Lua.GetReturn(2); + if (linearObj.isVector() && angularObj.isVector()) { + linear = linearObj.GetVector(); + angular = angularObj.GetVector(); + } + } + return (SimResult)result; + } + } + return SimResult.Nothing; + } + + public override void Term() { + if (MotionController != null) { + physenv.DestroyMotionController(MotionController); + MotionController = null; + } + base.Term(); + } + + public override void Spawn() { + string model = new(GetModelName()); + PrecacheModel(model, true); + SetModel(model); + if (DynamicModelPending || StudioHdr == null) { + if (!DynamicModelPending && GetModel() != null) + LockStudioHdr(); + if (DynamicModelPending || StudioHdr == null) + SetModel("models/error.mdl"); + } + + base.Spawn(); + SetThink(Think); + SetNextThink(gpGlobals.CurTime + 0.1); + m_takedamage = (byte)Damage.Yes; + + bool allowPrecache = IsPrecacheAllowed(); + SetAllowPrecache(true); + ScriptedEntity.CallFunction("Initialize", false); + SetAllowPrecache(allowPrecache); + } + public override void Use(BaseEntity? activator, BaseEntity? caller, UseType useType, float value) { if (IsMarkedForDeletion() || !ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.Use)) return; diff --git a/Game.Shared/PhysicsShared.cs b/Game.Shared/PhysicsShared.cs index 404bff1f6..660ce6d1d 100644 --- a/Game.Shared/PhysicsShared.cs +++ b/Game.Shared/PhysicsShared.cs @@ -26,14 +26,15 @@ public struct Friction public TimeUnit_t LastEffectTime; } -public struct GameVCollisionEvent { +public struct GameVCollisionEvent +{ public VCollisionEvent VCollisionEvent; public InlineArray2 PreVelocity; public InlineArray2 PostVelocity; public InlineArray2 PreAngularVelocity; public InlineArray2 Entities; - public void Init(ref VCollisionEvent ev){ + public void Init(ref VCollisionEvent ev) { this.VCollisionEvent = ev; Entities[0] = null; Entities[1] = null; diff --git a/Game.Shared/UserCmd.cs b/Game.Shared/UserCmd.cs index 61c750732..9e8c596bd 100644 --- a/Game.Shared/UserCmd.cs +++ b/Game.Shared/UserCmd.cs @@ -218,6 +218,8 @@ public static void ReadUsercmd(bf_read buf, ref UserCmd move, ref UserCmd from) move.MouseDeltaY = buf.ReadShort(); if (buf.ReadOneBit() != 0) { + for (int i = 0; i < MAX_BUTTONS_PRESSED; i++) + move.ButtonsPressed[i] = 0; for (int i = 0; i < MAX_BUTTONS_PRESSED; i++) { move.ButtonsPressed[i] = (byte)buf.ReadUBitLong(8); if (move.ButtonsPressed[i] == 0) @@ -379,9 +381,9 @@ public static void WriteUsercmd(bf_write buf, in UserCmd to, in UserCmd from) { if (HasChanged(to.ButtonsPressed, from.ButtonsPressed)) { buf.WriteOneBit(1); for (int i = 0; i < 5; i++) { + buf.WriteUBitLong(to.ButtonsPressed[i], 8); if (to.ButtonsPressed[i] == 0) break; - buf.WriteUBitLong(to.ButtonsPressed[i], 8); } } else { diff --git a/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.FieldAccessors.cs b/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.FieldAccessors.cs index 1edb83abe..d9833ccb0 100644 --- a/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.FieldAccessors.cs +++ b/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.FieldAccessors.cs @@ -106,7 +106,9 @@ private static bool IsInvocationNamed(SyntaxNode node, HashSet names) { if (container.Name == "DEFINE") { if (method.Parameters.Length == 0 || method.Parameters[0].Name != "name") return null; - INamedTypeSymbol? declaring = FindDataMapField(owner, expression)?.ContainingType ?? FindNetworkVarProperty(owner, expression)?.ContainingType; + int rootEnd = expression.IndexOfAny(new[] { '.', '[' }); + string root = rootEnd >= 0 ? expression.Substring(0, rootEnd) : expression; + INamedTypeSymbol? declaring = FindDataMapField(owner, root)?.ContainingType ?? FindNetworkVarProperty(owner, root)?.ContainingType; model = declaring == null ? null : BuildScalar(compilation, declaring, expression, null, failure); } else { diff --git a/Source.Common/DataMap.cs b/Source.Common/DataMap.cs index 458e783fb..f26db2fc0 100644 --- a/Source.Common/DataMap.cs +++ b/Source.Common/DataMap.cs @@ -76,7 +76,8 @@ public class TypeDescription public readonly string FieldName = ""; public readonly FieldInfo FieldInfo; DynamicAccessor? accessor; - public DynamicAccessor Accessor => accessor ??= FieldAccessorRegistry.TryCreate(FieldInfo.DeclaringType!, FieldInfo.Name, null) + public DynamicAccessor Accessor => accessor ??= (FieldName.AsSpan().IndexOfAny('.', '[') >= 0 ? FieldAccessorRegistry.Create(FieldInfo.DeclaringType!, FieldName, null) : null) + ?? FieldAccessorRegistry.TryCreate(FieldInfo.DeclaringType!, FieldInfo.Name, null) ?? FieldAccessorRegistry.Create(FieldInfo.DeclaringType!, FieldInfo.Name.StartsWith("__nv_", StringComparison.Ordinal) ? FieldInfo.Name[5..] : FieldInfo.Name, null); public nuint PackedOffset = nuint.MaxValue; public readonly ushort FieldSize; @@ -781,11 +782,16 @@ public static FieldInfo GetField_R(Type t, string name){ throw new Exception($"can't find field {name}"); } + static ReadOnlySpan RootName(ReadOnlySpan name) { + int end = name.IndexOfAny('.', '['); + return end >= 0 ? name[..end] : name; + } + static TypeDescription _FIELD(ReadOnlySpan name, FieldType fieldType, int count, FieldTypeDescFlags flags, ReadOnlySpan mapname, float tolerance) { - return new(fieldType, name, GetField_R(typeof(T), new(name)), (ushort)count, flags, mapname, null, null, tolerance); + return new(fieldType, name, GetField_R(typeof(T), new(RootName(name))), (ushort)count, flags, mapname, null, null, tolerance); } static TypeDescription _FIELD_ARRAY(ReadOnlySpan name, FieldType fieldType, int count, FieldTypeDescFlags flags, ReadOnlySpan mapname, float tolerance) { - return new(fieldType, name, GetField_R(typeof(T), new(name)), (ushort)count, flags, mapname, null, null, tolerance); + return new(fieldType, name, GetField_R(typeof(T), new(RootName(name))), (ushort)count, flags, mapname, null, null, tolerance); } public static TypeDescription FIELD(ReadOnlySpan name, FieldType fieldType) {