tem algum modo de melhorar a performance da turret no servidor? public class…
- User
tem algum modo de melhorar a performance da turret no servidor? public class TurretMonoBehaviour : MonoBehaviour { private AutoTurret _turret; private const float SearchDistance = 15f; private const int MaxReserveAmmo = 1000;
private void Awake() { InitializeTurret(); } private void InitializeTurret() { _turret = GetComponent<AutoTurret>(); var triggerCollider = _turret.targetTrigger.GetComponent<SphereCollider>(); triggerCollider.enabled = false; _turret.SetPeacekeepermode(false); _turret.InitiateStartup(); _turret.SetIsOnline(true); _turret.CancelInvoke(_turret.ServerTick); _turret.SetTarget(null); _turret.InvokeRepeating(PerformTurretCycle, 1f, 0.01f); _turret.InvokeRepeating(ScanForTargets, 2f, 1f); _turret.isLootable = false; _turret.dropFloats = false; _turret.dropsLoot = false; _turret.SendNetworkUpdateImmediate(); InvokeRepeating(nameof(RefillAmmo), 2f, 30f); } private void RefillAmmo() { if (_turret.AttachedWeapon is not BaseProjectile baseProjectile || baseProjectile.primaryMagazine?.ammoType == null) return; var ammoType = baseProjectile.primaryMagazine.ammoType; int currentAmmoCount = CalculateCurrentAmmoCount(ammoType); if (currentAmmoCount < MaxReserveAmmo) { int ammoNeeded = MaxReserveAmmo - currentAmmoCount; Item ammoItem = ItemManager.Create(ammoType, ammoNeeded); ammoItem?.MoveToContainer(_turret.inventory); _turret.UpdateTotalAmmo(); _turret.EnsureReloaded(); _turret.SendNetworkUpdateImmediate(); } } private int CalculateCurrentAmmoCount(ItemDefinition ammoType) { return _turret.inventory.itemList.Where(item => item.info == ammoType).Sum(item => item.amount); } private void ScanForTargets() { var entityContents = _turret.targetTrigger.entityContents ??= new HashSet<BaseEntity>(); entityContents.Clear(); int foundTargets = BaseEntity.Query.Server.GetPlayersInSphereFast(transform.position, SearchDistance, AIBrainSenses.playerQueryResults, IsTargetValid); if (foundTargets == 0) return; _turret.authDirty = true; for (int i = 0; i < foundTargets; i++) { var player = AIBrainSenses.playerQueryResults[i]; if (Interface.CallHook("OnEntityEnter", _turret.targetTrigger, player) != null || player.IsSleeping() || (player.InSafeZone() && !player.IsHostile())) continue; entityContents.Add(player); } } private bool IsTargetValid(BasePlayer player) => player != null && !player.IsNpc; private void PerformTurretCycle() { if (_turret.isClient || _turret.IsDestroyed) return; float deltaTime = (float)_turret.timeSinceLastServerTick; _turret.timeSinceLastServerTick = 0f; if (_turret.IsOnline() && !_turret.IsBeingControlled) { if (!_turret.HasTarget()) { _turret.IdleTick(deltaTime); } else { ExecuteTargetEngagement(); } } _turret.UpdateFacingToTarget(deltaTime); UpdateAmmoStatus(); } private void ExecuteTargetEngagement() { if (Time.realtimeSinceStartup >= _turret.nextVisCheck) { _turret.nextVisCheck = Time.realtimeSinceStartup + Random.Range(0.2f, 0.3f); _turret.targetVisible = _turret.ObjectVisible(_turret.target); if (_turret.targetVisible) _turret.lastTargetSeenTime = Time.realtimeSinceStartup; } _turret.EnsureReloaded(); if (ShouldFireAtTarget()) { var weapon = _turret.GetAttachedWeapon(); FireWeapon(weapon); } ValidateTargetEngagement(); } private bool ShouldFireAtTarget() { return Time.time >= _turret.nextShotTime && _turret.targetVisible && Mathf.Abs(_turret.AngleToTarget(_turret.target, _turret.currentAmmoGravity != 0f)) < _turret.GetMaxAngleForEngagement(); } private void FireWeapon(BaseProjectile weapon) { if (weapon == null) { _turret.nextShotTime = Time.time + 1f; return; } if (weapon.primaryMagazine.contents > 0) { _turret.FireAttachedGun(_turret.AimOffset(_turret.target), _turret.aimCone, null, _turret.PeacekeeperMode() ? _turret.target : null); float delay = weapon.isSemiAuto ? weapon.repeatDelay * 1.5f : weapon.repeatDelay; delay = weapon.ScaleRepeatDelay(delay); _turret.nextShotTime = Time.time + delay; } else { _turret.nextShotTime = Time.time + 5f; } } private void ValidateTargetEngagement() { var targetPlayer = _turret.target as BasePlayer; if (_turret.target != null && (!IsValidSteamPlayer(targetPlayer) || _turret.target.IsDead() || TimeExceedsLastSeen() || DistanceExceedsSightRange() || ShouldTargetBeReset())) { _turret.SetTarget(null); } } private bool TimeExceedsLastSeen() => Time.realtimeSinceStartup - _turret.lastTargetSeenTime > 3f; private bool DistanceExceedsSightRange() => Vector3.Distance(_turret.transform.position, _turret.target.transform.position) > _turret.sightRange; private bool ShouldTargetBeReset() => _turret.PeacekeeperMode() && !_turret.IsEntityHostile(_turret.target); private void UpdateAmmoStatus() { if (_turret.totalAmmoDirty && Time.time > _turret.nextAmmoCheckTime) { _turret.UpdateTotalAmmo(); _turret.totalAmmoDirty = false; _turret.nextAmmoCheckTime = Time.time + 0.5f; } } private void OnDestroy() { CancelInvoke(nameof(RefillAmmo)); } } - Assistant
Para melhorar a performance da
TurretMonoBehaviourno servidor, existem várias abordagens que podem ser seguidas. Vou listar algumas sugestões que podem ajudar:-
Reduzir a Frequência dos Métodos Chamados:
InvokeRepeatingé usado para chamar repetidamente métodos comoPerformTurretCyclea cada 0,01s (10ms). Considere aumentar esse intervalo para algo mais razoável, como 0.1s (100ms) ou até mais, dependendo da necessidade de resposta rápida.- Da mesma forma, aumente o intervalo de
ScanForTargetsde 1s para 2s ou mais se monitoramento constante não for crítico.
-
Otimizar Cálculos e Consultas:
- No método
ScanForTargets, evitar re-criação ou limpeza desnecessária doentityContentspoderia ser feito limitando a necessidade de lidar com essas entidades com mais critérios de validação antes de adicioná-los, o que já está sendo feito, mas garantias adicionais podem ser checadas antes de adicionar ao Set. - O uso de
AIBrainSenses.playerQueryResultssugere um sistema pré-existente de cache; certifique-se de que ele está otimizado em termos de consulta e que seja suficiente para suas necessidades antes de fazer processamento adicional.
- No método
-
Evitar Processamento Redundante:
- Verifique se a operação
CalculateCurrentAmmoCountestá sendo chamada de forma redundante e otimize qualquer lógica de contagem para garantir que esté sendo feito o mínimo de iterações possível.
- Verifique se a operação
-
Melhorar a Checagem de Visibilidade e Alvo:
- A função
ExecuteTargetEngagementfaz o check de visibilidade comRandom.Range. Avalie se esse check precisa de uma frequência tão alta assim. - No método
FireWeapon, verifique se realmente necessita chamarFindWeapona cada ciclo de execução ou se essa chamada pode ser reduzida.
- A função
-
Melhoria na Gestão de Ammo:
- O método
RefillAmmoutilizaItemManager.Createa cada chamada para preencher a munição. Considere otimizações: cheque primeiro se o inventário não tem itens desnecessários que podem ser reciclados ou otimize as transações de item. - Realizar o update da contagem de munição (
UpdateTotalAmmo) somente após uma quantidade significativa de mudanças, ou após um certo tempo, ao invés de fazê-lo sempre apósMoveToContainer.
- O método
-
Reduzir Utilização de Recursos:
- Reduzir ou eliminar o uso de
Interface.CallHookse o uso dos hooks não for absolutamente necessário. Essa chamada pode ser cara se estiver interagindo com um sistema de plugins ou modificação pesada do jogo.
- Reduzir ou eliminar o uso de
-
Profiling e Logs:
- Utilize ferramentas de profiling para identificar "gargalos" ou partes que consomem mais tempo no código. Baseado nas saídas dessas ferramentas, reveja os métodos críticos quanto à carga que impõem ao servidor.
Ao implementar uma ou mais dessas sugestões, é crucial realizar testes para garantir que a funcionalidade da torre não seja comprometida enquanto se ganha em eficiência.
-
- User
vou te passar algumas fontes para ver se conseguimos melhorar de outro modo: public class AutoTurret : ContainerIOEntity, IRemoteControllable { public static class TurretFlags { public const Flags Peacekeeper = Flags.Reserved1; }
public class UpdateAutoTurretScanQueue : PersistentObjectWorkQueue<AutoTurret> { protected override void RunJob(AutoTurret entity) { if (ShouldAdd(entity)) { entity.TargetScan(); } } protected override bool ShouldAdd(AutoTurret entity) { if (base.ShouldAdd(entity)) { return entity.IsValid(); } return false; } } public GameObjectRef gun_fire_effect; public GameObjectRef bulletEffect; public float bulletSpeed = 200f; public AmbienceEmitter ambienceEmitter; public bool playAmbientSounds = true; public GameObject assignDialog; public LaserBeam laserBeam; public BaseCombatEntity target; public Transform eyePos; public Transform muzzlePos; public Vector3 aimDir; public Transform gun_yaw; public Transform gun_pitch; public float sightRange = 30f; public SoundDefinition turnLoopDef; public SoundDefinition movementChangeDef; public SoundDefinition ambientLoopDef; public SoundDefinition focusCameraDef; public float focusSoundFreqMin = 2.5f; public float focusSoundFreqMax = 7f; public GameObjectRef peacekeeperToggleSound; public GameObjectRef onlineSound; public GameObjectRef offlineSound; public GameObjectRef targetAcquiredEffect; public GameObjectRef targetLostEffect; public GameObjectRef reloadEffect; public float aimCone; public const Flags Flag_Equipped = Flags.Reserved3; public const Flags Flag_MaxAuths = Flags.Reserved4; [NonSerialized] public HashSet<PlayerNameID> authorizedPlayers = new HashSet<PlayerNameID>(); [ServerVar(Help = "How many milliseconds to spend on target scanning per frame")] public static float auto_turret_budget_ms = 0.5f; public static UpdateAutoTurretScanQueue updateAutoTurretScanQueue = new UpdateAutoTurretScanQueue(); [Header("RC")] public float rcTurnSensitivity = 4f; public Transform RCEyes; public GameObjectRef IDPanelPrefab; public RemoteControllableControls rcControls; public string rcIdentifier = ""; public TargetTrigger targetTrigger; public TriggerBase interferenceTrigger; public float maxInterference = -1f; public float attachedWeaponZOffsetScale = -0.5f; public Transform socketTransform; public bool authDirty; public bool hasPotentialUnauthedTarget = true; public float nextShotTime; public float lastShotTime; public float nextVisCheck; public float lastTargetSeenTime; public bool targetVisible = true; public bool booting; public float nextIdleAimTime; public Vector3 targetAimDir = Vector3.forward; public const float bulletDamage = 15f; public RealTimeSinceEx timeSinceLastServerTick; public HashSet<AutoTurret> nearbyTurrets = new HashSet<AutoTurret>(); public static HashSet<AutoTurret> interferenceUpdateList = new HashSet<AutoTurret>(); public float nextForcedAimTime; public Vector3 lastSentAimDir = Vector3.zero; public static float[] visibilityOffsets = new float[3] { 0f, 0.15f, -0.15f }; public int peekIndex; [NonSerialized] public int numConsecutiveMisses; [NonSerialized] public int totalAmmo; public float nextAmmoCheckTime; public bool totalAmmoDirty = true; public float currentAmmoGravity; public float currentAmmoVelocity; public HeldEntity AttachedWeapon; [NonSerialized] public int consumptionAmount = 10; public bool CanPing => false; public virtual bool RequiresMouse => true; public float MaxRange => 10000f; public RemoteControllableControls RequiredControls => rcControls; public int ViewerCount { get; set; } public CameraViewerId? ControllingViewerId { get; set; } public bool IsBeingControlled { get { if (ViewerCount > 0) { return ControllingViewerId.HasValue; } return false; } } protected override bool PreventDuplicatesInQueue { public get { return Sentry.debugPreventDuplicates; } } public override bool OnRpcMessage(BasePlayer player, uint rpc, Message msg) { using (TimeWarning.New("AutoTurret.OnRpcMessage")) { if (rpc == 1092560690 && player != null) { Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!"); if (ConVar.Global.developer > 2) { Debug.Log("SV_RPCMessage: " + player?.ToString() + " - AddSelfAuthorize "); } using (TimeWarning.New("AddSelfAuthorize")) { using (TimeWarning.New("Conditions")) { if (!RPC_Server.IsVisible.Test(1092560690u, "AddSelfAuthorize", this, player, 3f)) { return true; } } try { using (TimeWarning.New("Call")) { RPCMessage rPCMessage = default(RPCMessage); rPCMessage.connection = msg.connection; rPCMessage.player = player; rPCMessage.read = msg.read; RPCMessage rpc2 = rPCMessage; AddSelfAuthorize(rpc2); } } catch (Exception exception) { Debug.LogException(exception); player.Kick("RPC Error in AddSelfAuthorize"); } } return true; } if (rpc == 3057055788u && player != null) { Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!"); if (ConVar.Global.developer > 2) { Debug.Log("SV_RPCMessage: " + player?.ToString() + " - AssignToFriend "); } using (TimeWarning.New("AssignToFriend")) { using (TimeWarning.New("Conditions")) { if (!RPC_Server.IsVisible.Test(3057055788u, "AssignToFriend", this, player, 3f)) { return true; } } try { using (TimeWarning.New("Call")) { RPCMessage rPCMessage = default(RPCMessage); rPCMessage.connection = msg.connection; rPCMessage.player = player; rPCMessage.read = msg.read; RPCMessage msg2 = rPCMessage; AssignToFriend(msg2); } } catch (Exception exception2) { Debug.LogException(exception2); player.Kick("RPC Error in AssignToFriend"); } } return true; } if (rpc == 253307592 && player != null) { Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!"); if (ConVar.Global.developer > 2) { Debug.Log("SV_RPCMessage: " + player?.ToString() + " - ClearList "); } using (TimeWarning.New("ClearList")) { using (TimeWarning.New("Conditions")) { if (!RPC_Server.IsVisible.Test(253307592u, "ClearList", this, player, 3f)) { return true; } } try { using (TimeWarning.New("Call")) { RPCMessage rPCMessage = default(RPCMessage); rPCMessage.connection = msg.connection; rPCMessage.player = player; rPCMessage.read = msg.read; RPCMessage rpc3 = rPCMessage; ClearList(rpc3); } } catch (Exception exception3) { Debug.LogException(exception3); player.Kick("RPC Error in ClearList"); } } return true; } if (rpc == 1500257773 && player != null) { Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!"); if (ConVar.Global.developer > 2) { Debug.Log("SV_RPCMessage: " + player?.ToString() + " - FlipAim "); } using (TimeWarning.New("FlipAim")) { using (TimeWarning.New("Conditions")) { if (!RPC_Server.IsVisible.Test(1500257773u, "FlipAim", this, player, 3f)) { return true; } } try { using (TimeWarning.New("Call")) { RPCMessage rPCMessage = default(RPCMessage); rPCMessage.connection = msg.connection; rPCMessage.player = player; rPCMessage.read = msg.read; RPCMessage rpc4 = rPCMessage; FlipAim(rpc4); } } catch (Exception exception4) { Debug.LogException(exception4); player.Kick("RPC Error in FlipAim"); } } return true; } if (rpc == 3617985969u && player != null) { Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!"); if (ConVar.Global.developer > 2) { Debug.Log("SV_RPCMessage: " + player?.ToString() + " - RemoveSelfAuthorize "); } using (TimeWarning.New("RemoveSelfAuthorize")) { using (TimeWarning.New("Conditions")) { if (!RPC_Server.IsVisible.Test(3617985969u, "RemoveSelfAuthorize", this, player, 3f)) { return true; } } try { using (TimeWarning.New("Call")) { RPCMessage rPCMessage = default(RPCMessage); rPCMessage.connection = msg.connection; rPCMessage.player = player; rPCMessage.read = msg.read; RPCMessage rpc5 = rPCMessage; RemoveSelfAuthorize(rpc5); } } catch (Exception exception5) { Debug.LogException(exception5); player.Kick("RPC Error in RemoveSelfAuthorize"); } } return true; } if (rpc == 1770263114 && player != null) { Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!"); if (ConVar.Global.developer > 2) { Debug.Log("SV_RPCMessage: " + player?.ToString() + " - SERVER_AttackAll "); } using (TimeWarning.New("SERVER_AttackAll")) { using (TimeWarning.New("Conditions")) { if (!RPC_Server.IsVisible.Test(1770263114u, "SERVER_AttackAll", this, player, 3f)) { return true; } } try { using (TimeWarning.New("Call")) { RPCMessage rPCMessage = default(RPCMessage); rPCMessage.connection = msg.connection; rPCMessage.player = player; rPCMessage.read = msg.read; RPCMessage rpc6 = rPCMessage; SERVER_AttackAll(rpc6); } } catch (Exception exception6) { Debug.LogException(exception6); player.Kick("RPC Error in SERVER_AttackAll"); } } return true; } if (rpc == 3265538831u && player != null) { Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!"); if (ConVar.Global.developer > 2) { Debug.Log("SV_RPCMessage: " + player?.ToString() + " - SERVER_Peacekeeper "); } using (TimeWarning.New("SERVER_Peacekeeper")) { using (TimeWarning.New("Conditions")) { if (!RPC_Server.IsVisible.Test(3265538831u, "SERVER_Peacekeeper", this, player, 3f)) { return true; } } try { using (TimeWarning.New("Call")) { RPCMessage rPCMessage = default(RPCMessage); rPCMessage.connection = msg.connection; rPCMessage.player = player; rPCMessage.read = msg.read; RPCMessage rpc7 = rPCMessage; SERVER_Peacekeeper(rpc7); } } catch (Exception exception7) { Debug.LogException(exception7); player.Kick("RPC Error in SERVER_Peacekeeper"); } } return true; } if (rpc == 1053317251 && player != null) { Assert.IsTrue(player.isServer, "SV_RPC Message is using a clientside player!"); if (ConVar.Global.developer > 2) { Debug.Log("SV_RPCMessage: " + player?.ToString() + " - Server_SetID "); } using (TimeWarning.New("Server_SetID")) { using (TimeWarning.New("Conditions")) { if (!RPC_Server.MaxDistance.Test(1053317251u, "Server_SetID", this, player, 3f)) { return true; } } try { using (TimeWarning.New("Call")) { RPCMessage rPCMessage = default(RPCMessage); rPCMessage.connection = msg.connection; rPCMessage.player = player; rPCMessage.read = msg.read; RPCMessage msg3 = rPCMessage; Server_SetID(msg3); } } catch (Exception exception8) { Debug.LogException(exception8); player.Kick("RPC Error in Server_SetID"); } } return true; } } return base.OnRpcMessage(player, rpc, msg); } public bool IsOnline() { return IsOn(); } public bool IsOffline() { return !IsOnline(); } public override void ResetState() { base.ResetState(); } public virtual Transform GetCenterMuzzle() { return gun_pitch; } public float AngleToTarget(BaseCombatEntity potentialtarget, bool use2D = false) { use2D = true; Transform centerMuzzle = GetCenterMuzzle(); Vector3 position = centerMuzzle.position; Vector3 vector = AimOffset(potentialtarget); Vector3 zero = Vector3.zero; return Vector3.Angle(to: (!use2D) ? (vector - position).normalized : Vector3Ex.Direction2D(vector, position), from: use2D ? centerMuzzle.forward.XZ3D().normalized : centerMuzzle.forward); } public virtual bool InFiringArc(BaseCombatEntity potentialtarget) { return Mathf.Abs(AngleToTarget(potentialtarget)) <= 90f; } public override bool CanPickup(BasePlayer player) { if (base.CanPickup(player) && IsOffline()) { return IsAuthed(player); } return false; } public override bool CanUseNetworkCache(Connection connection) { return false; } public override void Save(SaveInfo info) { base.Save(info); info.msg.autoturret = Facepunch.Pool.Get<ProtoBuf.AutoTurret>(); if (info.forDisk || IsAuthed(info.forConnection.userid)) { info.msg.autoturret.users = Facepunch.Pool.Get<List<PlayerNameID>>(); foreach (PlayerNameID authorizedPlayer in authorizedPlayers) { info.msg.autoturret.users.Add(authorizedPlayer); } } if (info.forDisk || (info.forConnection?.player != null && CanChangeID(info.forConnection.player as BasePlayer))) { info.msg.rcEntity = Facepunch.Pool.Get<RCEntity>(); info.msg.rcEntity.identifier = GetIdentifier(); } } public override void PostSave(SaveInfo info) { base.PostSave(info); info.msg.autoturret.users = null; } public override void Load(LoadInfo info) { base.Load(info); if (info.msg.autoturret != null) { authorizedPlayers.Clear(); if (info.msg.autoturret.users != null) { foreach (PlayerNameID user in info.msg.autoturret.users) { authorizedPlayers.Add(user); } } info.msg.autoturret.users = null; } if (info.msg.rcEntity != null) { UpdateIdentifier(info.msg.rcEntity.identifier); } } public Vector3 AimOffset(BaseCombatEntity aimat) { BasePlayer basePlayer = aimat as BasePlayer; if (basePlayer != null) { if (basePlayer.IsSleeping()) { return basePlayer.transform.position + Vector3.up * 0.1f; } if (basePlayer.IsWounded()) { return basePlayer.transform.position + Vector3.up * 0.25f; } return basePlayer.eyes.position; } return aimat.CenterPoint(); } public float GetAimSpeed() { if (HasTarget()) { return 5f; } return 1f; } public void UpdateAiming(float dt) { if (!(aimDir == Vector3.zero)) { float speed = 5f; if (base.isServer && !IsBeingControlled) { speed = ((!HasTarget()) ? 15f : 35f); } Quaternion quaternion = Quaternion.LookRotation(aimDir); Quaternion quaternion2 = Quaternion.Euler(0f, quaternion.eulerAngles.y, 0f); Quaternion quaternion3 = Quaternion.Euler(quaternion.eulerAngles.x, 0f, 0f); if (gun_yaw.transform.rotation != quaternion2) { gun_yaw.transform.rotation = Mathx.Lerp(gun_yaw.transform.rotation, quaternion2, speed, dt); } if (gun_pitch.transform.localRotation != quaternion3) { gun_pitch.transform.localRotation = Mathx.Lerp(gun_pitch.transform.localRotation, quaternion3, speed, dt); } } } public bool IsAuthed(ulong id) { foreach (PlayerNameID authorizedPlayer in authorizedPlayers) { if (authorizedPlayer.userid == id) { return true; } } return false; } public bool IsAuthed(BasePlayer player) { return IsAuthed(player.userID); } public bool AnyAuthed() { return authorizedPlayers.Count > 0; } public virtual bool CanChangeSettings(BasePlayer player) { if (IsAuthed(player) && IsOffline()) { return player.CanBuild(); } return false; } public bool PeacekeeperMode() { return HasFlag(Flags.Reserved1); } public Transform GetEyes() { return RCEyes; } public float GetFovScale() { return 1f; } public BaseEntity GetEnt() { return this; } public virtual bool CanControl(ulong playerID) { object obj = Interface.CallHook("OnEntityControl", this, playerID); if (obj is bool) { return (bool)obj; } if (booting) { return false; } if (IsPowered()) { return !PeacekeeperMode(); } return false; } public bool InitializeControl(CameraViewerId viewerID) { ViewerCount++; if (!ControllingViewerId.HasValue) { ControllingViewerId = viewerID; SetTarget(null); SendAimDirImmediate(); return true; } return false; } public void StopControl(CameraViewerId viewerID) { ViewerCount--; if (ControllingViewerId == viewerID) { ControllingViewerId = null; } } public void UserInput(InputState inputState, CameraViewerId viewerID) { CameraViewerId? controllingViewerId = ControllingViewerId; if (viewerID != controllingViewerId) { return; } UpdateManualAim(inputState); if (UnityEngine.Time.time < nextShotTime) { return; } if (inputState.WasJustPressed(BUTTON.RELOAD)) { Reload(); } else { if (EnsureReloaded() || !inputState.IsDown(BUTTON.FIRE_PRIMARY)) { return; } BaseProjectile attachedWeapon = GetAttachedWeapon(); if ((bool)attachedWeapon) { if (attachedWeapon.primaryMagazine.contents > 0) { FireAttachedGun(Vector3.zero, aimCone); float delay = (attachedWeapon.isSemiAuto ? (attachedWeapon.repeatDelay * 1.5f) : attachedWeapon.repeatDelay); delay = attachedWeapon.ScaleRepeatDelay(delay); nextShotTime = UnityEngine.Time.time + delay; } else { nextShotTime = UnityEngine.Time.time + 5f; } } else if (HasGenericFireable()) { AttachedWeapon.ServerUse(); nextShotTime = UnityEngine.Time.time + 0.115f; } else { nextShotTime = UnityEngine.Time.time + 1f; } } } public bool UpdateManualAim(InputState inputState) { float x = (0f - inputState.current.mouseDelta.y) * rcTurnSensitivity; float y = inputState.current.mouseDelta.x * rcTurnSensitivity; Vector3 euler = Quaternion.LookRotation(aimDir, base.transform.up).eulerAngles + new Vector3(x, y, 0f); if (euler.x >= 0f && euler.x <= 135f) { euler.x = Mathf.Clamp(euler.x, 0f, 45f); } if (euler.x >= 225f && euler.x <= 360f) { euler.x = Mathf.Clamp(euler.x, 285f, 360f); } Vector3 vector = Quaternion.Euler(euler) * Vector3.forward; bool result = !Mathf.Approximately(aimDir.x, vector.x) || !Mathf.Approximately(aimDir.y, vector.y) || !Mathf.Approximately(aimDir.z, vector.z); aimDir = vector; return result; } public override void InitShared() { base.InitShared(); RCSetup(); } public override void DestroyShared() { RCShutdown(); base.DestroyShared(); } public void RCSetup() { if (base.isServer) { RemoteControlEntity.InstallControllable(this); } } public void RCShutdown() { if (base.isServer) { RemoteControlEntity.RemoveControllable(this); } } [RPC_Server] [RPC_Server.MaxDistance(3f)] public void Server_SetID(RPCMessage msg) { if (msg.player == null || !CanChangeID(msg.player)) { return; } string text = msg.read.String(); if (string.IsNullOrEmpty(text) || ComputerStation.IsValidIdentifier(text)) { string text2 = msg.read.String(); if (ComputerStation.IsValidIdentifier(text2) && text == GetIdentifier() && Interface.CallHook("OnTurretIdentifierSet", this, msg.player, text2) == null) { Debug.Log("SetID success!"); UpdateIdentifier(text2); } } } public void UpdateIdentifier(string newID, bool clientSend = false) { _ = rcIdentifier; if (base.isServer) { if (!RemoteControlEntity.IDInUse(newID)) { rcIdentifier = newID; } SendNetworkUpdate(); } } public string GetIdentifier() { return rcIdentifier; } public virtual bool CanChangeID(BasePlayer player) { return CanChangeSettings(player); } public override int ConsumptionAmount() { return consumptionAmount; } public void SetOnline() { SetIsOnline(online: true); } public void SetIsOnline(bool online) { if (online != IsOn() && Interface.CallHook("OnTurretToggle", this) == null) { SetFlag(Flags.On, online); if (online) { TryRegisterForInterferenceUpdate(); } else { SetFlag(Flags.OnFire, b: false); UpdateInterferenceOnOthers(); } booting = false; GetAttachedWeapon()?.SetLightsOn(online); SendNetworkUpdate(); if (IsOffline()) { SetTarget(null); isLootable = true; } else { isLootable = false; authDirty = true; } } } public static void ProcessInterferenceQueue() { float realtimeSinceStartup = UnityEngine.Time.realtimeSinceStartup; float num = 0.0005f; List<AutoTurret> obj = Facepunch.Pool.Get<List<AutoTurret>>(); while (interferenceUpdateList.Count > 0 && UnityEngine.Time.realtimeSinceStartup < realtimeSinceStartup + num) { obj.Clear(); ulong num2 = 0uL; AutoTurret autoTurret = null; foreach (AutoTurret interferenceUpdate in interferenceUpdateList) { if (interferenceUpdate == null) { obj.Add(interferenceUpdate); } else if (interferenceUpdate.net.ID.Value > num2) { num2 = interferenceUpdate.net.ID.Value; autoTurret = interferenceUpdate; } } if (autoTurret != null) { interferenceUpdateList.Remove(autoTurret); autoTurret.UpdateInterference(); } foreach (AutoTurret item in obj) { interferenceUpdateList.Remove(item); } } Facepunch.Pool.FreeUnmanaged(ref obj); } public override int GetPassthroughAmount(int outputSlot = 0) { int result = Mathf.Min(1, GetCurrentEnergy()); switch (outputSlot) { case 0: if (!HasTarget()) { return 0; } return result; case 1: if (totalAmmo > 50) { return 0; } return result; case 2: if (totalAmmo != 0) { return 0; } return result; default: return 0; } } public override void IOStateChanged(int inputAmount, int inputSlot) { base.IOStateChanged(inputAmount, inputSlot); if (IsPowered() && !IsOn()) { InitiateStartup(); } else if ((!IsPowered() && IsOn()) || booting) { InitiateShutdown(); } } public void InitiateShutdown() { if ((!IsOffline() || booting) && Interface.CallHook("OnTurretShutdown", this) == null) { CancelInvoke(SetOnline); booting = false; Effect.server.Run(offlineSound.resourcePath, this, 0u, Vector3.zero, Vector3.zero); SetIsOnline(online: false); } } public void InitiateStartup() { if (!IsOnline() && !booting && Interface.CallHook("OnTurretStartup", this) == null) { Effect.server.Run(onlineSound.resourcePath, this, 0u, Vector3.zero, Vector3.zero); Invoke(SetOnline, 2f); booting = true; } } public void SetPeacekeepermode(bool isOn) { if (PeacekeeperMode() != isOn) { SetFlag(Flags.Reserved1, isOn); Effect.server.Run(peacekeeperToggleSound.resourcePath, this, 0u, Vector3.zero, Vector3.zero); } } public bool IsValidWeapon(Item item) { ItemDefinition info = item.info; if (item.isBroken) { return false; } ItemModEntity component = info.GetComponent<ItemModEntity>(); if (component == null) { return false; } HeldEntity component2 = component.entityPrefab.Get().GetComponent<HeldEntity>(); if (component2 == null) { return false; } if (!component2.IsUsableByTurret) { return false; } return true; } public bool CanAcceptItem(Item item, int targetSlot) { Item slot = base.inventory.GetSlot(0); if (IsValidWeapon(item) && targetSlot == 0) { return true; } if (item.info.category == ItemCategory.Ammunition) { ItemModProjectile component = item.info.GetComponent<ItemModProjectile>(); BaseProjectile attachedWeapon = GetAttachedWeapon(); if (slot == null || attachedWeapon == null || component == null) { return false; } if ((attachedWeapon.primaryMagazine.definition.ammoTypes & component.ammoType) == 0) { return false; } if (targetSlot == 0) { return false; } return true; } return false; } public bool AtMaxAuthCapacity() { return HasFlag(Flags.Reserved4); } public void UpdateMaxAuthCapacity() { if (authorizedPlayers.Count >= 200) { SetFlag(Flags.Reserved4, b: true); return; } BaseGameMode activeGameMode = BaseGameMode.GetActiveGameMode(serverside: true); bool b = activeGameMode != null && activeGameMode.limitTeamAuths && authorizedPlayers.Count >= activeGameMode.GetMaxRelationshipTeamSize(); SetFlag(Flags.Reserved4, b); } [RPC_Server] [RPC_Server.IsVisible(3f)] private void FlipAim(RPCMessage rpc) { if (!IsOnline() && IsAuthed(rpc.player) && !booting && Interface.CallHook("OnTurretRotate", this, rpc.player) == null) { base.transform.rotation = Quaternion.LookRotation(-base.transform.forward, base.transform.up); SendNetworkUpdate(); } } [RPC_Server] [RPC_Server.IsVisible(3f)] private void AddSelfAuthorize(RPCMessage rpc) { AddSelfAuthorize(rpc.player); } public void AddSelfAuthorize(BasePlayer player) { BasePlayer player2 = player; if (!IsOnline() && player2.CanBuild() && !AtMaxAuthCapacity() && Interface.CallHook("OnTurretAuthorize", this, player) == null) { authorizedPlayers.RemoveWhere((PlayerNameID x) => x.userid == (ulong)player2.userID); PlayerNameID playerNameID = new PlayerNameID(); playerNameID.userid = player2.userID; playerNameID.username = player2.displayName; authorizedPlayers.Add(playerNameID); Facepunch.Rust.Analytics.Azure.OnEntityAuthChanged(this, player2, authorizedPlayers.Select((PlayerNameID x) => x.userid), "added", player2.userID); UpdateMaxAuthCapacity(); SendNetworkUpdate(); } } [RPC_Server] [RPC_Server.IsVisible(3f)] private void RemoveSelfAuthorize(RPCMessage rpc) { RPCMessage rpc2 = rpc; if (!booting && !IsOnline() && IsAuthed(rpc2.player) && Interface.CallHook("OnTurretDeauthorize", this, rpc.player) == null) { authorizedPlayers.RemoveWhere((PlayerNameID x) => x.userid == (ulong)rpc2.player.userID); authDirty = true; Facepunch.Rust.Analytics.Azure.OnEntityAuthChanged(this, rpc2.player, authorizedPlayers.Select((PlayerNameID x) => x.userid), "removed", rpc2.player.userID); UpdateMaxAuthCapacity(); SendNetworkUpdate(); } } [RPC_Server.IsVisible(3f)] [RPC_Server] private void ClearList(RPCMessage rpc) { if (!booting && !IsOnline() && IsAuthed(rpc.player) && Interface.CallHook("OnTurretClearList", this, rpc.player) == null) { authorizedPlayers.Clear(); authDirty = true; Facepunch.Rust.Analytics.Azure.OnEntityAuthChanged(this, rpc.player, authorizedPlayers.Select((PlayerNameID x) => x.userid), "clear", rpc.player.userID); UpdateMaxAuthCapacity(); SendNetworkUpdate(); } } [RPC_Server.IsVisible(3f)] [RPC_Server] public void AssignToFriend(RPCMessage msg) { if (AtMaxAuthCapacity() || msg.player == null || !msg.player.CanInteract() || !CanChangeSettings(msg.player)) { return; } ulong num = msg.read.UInt64(); if (num != 0L && !IsAuthed(num) && Interface.CallHook("OnTurretAssign", this, num, msg.player) == null) { string username = BasePlayer.SanitizePlayerNameString(msg.read.String(), num); PlayerNameID playerNameID = new PlayerNameID(); playerNameID.userid = num; playerNameID.username = username; Facepunch.Rust.Analytics.Azure.OnEntityAuthChanged(this, msg.player, authorizedPlayers.Select((PlayerNameID x) => x.userid), "added", num); authorizedPlayers.Add(playerNameID); UpdateMaxAuthCapacity(); SendNetworkUpdate(); Interface.CallHook("OnTurretAssigned", this, num, msg.player); } } [RPC_Server.IsVisible(3f)] [RPC_Server] private void SERVER_Peacekeeper(RPCMessage rpc) { if (IsAuthed(rpc.player) && Interface.CallHook("OnTurretModeToggle", this, rpc.player) == null) { SetPeacekeepermode(isOn: true); } } [RPC_Server.IsVisible(3f)] [RPC_Server] private void SERVER_AttackAll(RPCMessage rpc) { if (IsAuthed(rpc.player) && Interface.CallHook("OnTurretModeToggle", this, rpc.player) == null) { SetPeacekeepermode(isOn: false); } } public virtual float TargetScanRate() { return 1f; } public override void ServerInit() { base.ServerInit(); ItemContainer itemContainer = base.inventory; itemContainer.canAcceptItem = (Func<Item, int, bool>)Delegate.Combine(itemContainer.canAcceptItem, new Func<Item, int, bool>(CanAcceptItem)); TargetTrigger obj = targetTrigger; obj.OnEntityEnterTrigger = (Action<BaseNetworkable>)Delegate.Combine(obj.OnEntityEnterTrigger, new Action<BaseNetworkable>(OnEntityEnterTrigger)); timeSinceLastServerTick = 0.0; InvokeRepeating(ServerTick, UnityEngine.Random.Range(0f, 1f), 0.015f); InvokeRandomized(SendAimDir, UnityEngine.Random.Range(0f, 1f), 0.2f, 0.05f); updateAutoTurretScanQueue.Add(this); targetTrigger.GetComponent<SphereCollider>().radius = sightRange; UpdateNearbyTurrets(created: true); } internal override void DoServerDestroy() { base.DoServerDestroy(); updateAutoTurretScanQueue.Remove(this); UpdateNearbyTurrets(created: false); } public void OnEntityEnterTrigger(BaseNetworkable entity) { if (entity is BasePlayer player && !IsAuthed(player)) { authDirty = true; } } public void SendAimDir() { if (UnityEngine.Time.realtimeSinceStartup > nextForcedAimTime || HasTarget() || Vector3.Angle(lastSentAimDir, aimDir) > 0.03f) { SendAimDirImmediate(); } } public void SendAimDirImmediate() { lastSentAimDir = aimDir; ClientRPC(RpcTarget.NetworkGroup("CLIENT_ReceiveAimDir"), aimDir); nextForcedAimTime = UnityEngine.Time.realtimeSinceStartup + 2f; } public void SetTarget(BaseCombatEntity targ) { if (Interface.CallHook("OnTurretTarget", this, targ) == null) { if (targ != target) { Effect.server.Run((targ == null) ? targetLostEffect.resourcePath : targetAcquiredEffect.resourcePath, base.transform.position, Vector3.up); MarkDirtyForceUpdateOutputs(); nextShotTime += 0.1f; authDirty = true; } target = targ; } } public virtual bool CheckPeekers() { return true; } public bool ObjectVisible(BaseCombatEntity obj) { object obj2 = Interface.CallHook("CanBeTargeted", obj, this); if (obj2 is bool) { return (bool)obj2; } List<RaycastHit> obj3 = Facepunch.Pool.Get<List<RaycastHit>>(); Vector3 position = eyePos.transform.position; if (GamePhysics.CheckSphere(position, 0.1f, 2097152)) { return false; } Vector3 vector = AimOffset(obj); float num = Vector3.Distance(vector, position); Vector3 vector2 = Vector3.Cross((vector - position).normalized, Vector3.up); for (int i = 0; (float)i < (CheckPeekers() ? 3f : 1f); i++) { Vector3 normalized = (vector + vector2 * visibilityOffsets[i] - position).normalized; obj3.Clear(); GamePhysics.TraceAll(new Ray(position, normalized), 0f, obj3, num * 1.1f, 1218652417); for (int j = 0; j < obj3.Count; j++) { BaseEntity entity = RaycastHitEx.GetEntity(obj3[j]); if ((!(entity != null) || !entity.isClient) && (!(entity != null) || !(entity.ToPlayer() != null) || entity.EqualNetID(obj)) && (!(entity != null) || !entity.EqualNetID(this))) { if (entity != null && (entity == obj || entity.EqualNetID(obj))) { Facepunch.Pool.FreeUnmanaged(ref obj3); peekIndex = i; return true; } if (!(entity != null) || entity.ShouldBlockProjectiles()) { break; } } } } Facepunch.Pool.FreeUnmanaged(ref obj3); return false; } public virtual void FireAttachedGun(Vector3 targetPos, float aimCone, Transform muzzleToUse = null, BaseCombatEntity target = null) { BaseProjectile attachedWeapon = GetAttachedWeapon(); if (!(attachedWeapon == null) && !IsOffline()) { attachedWeapon.ServerUse(1f, IsBeingControlled ? RCEyes : gun_pitch, useBulletThickness: false); } } public virtual void FireGun(Vector3 targetPos, float aimCone, Transform muzzleToUse = null, BaseCombatEntity target = null) { if (IsOffline()) { return; } if (muzzleToUse == null) { muzzleToUse = muzzlePos; } Vector3 vector = GetCenterMuzzle().transform.position - GetCenterMuzzle().forward * 0.25f; Vector3 vector2 = GetCenterMuzzle().transform.forward; Vector3 modifiedAimConeDirection = AimConeUtil.GetModifiedAimConeDirection(aimCone, vector2); targetPos = vector + modifiedAimConeDirection * 300f; List<RaycastHit> obj = Facepunch.Pool.Get<List<RaycastHit>>(); GamePhysics.TraceAll(new Ray(vector, modifiedAimConeDirection), 0f, obj, 300f, 1220225809); bool flag = false; for (int i = 0; i < obj.Count; i++) { RaycastHit hit = obj[i]; BaseEntity entity = RaycastHitEx.GetEntity(hit); if ((entity != null && (entity == this || entity.EqualNetID(this))) || (PeacekeeperMode() && target != null && entity != null && entity.GetComponent<BasePlayer>() != null && !entity.EqualNetID(target))) { continue; } BaseCombatEntity baseCombatEntity = entity as BaseCombatEntity; if (baseCombatEntity != null) { ApplyDamage(baseCombatEntity, hit.point, modifiedAimConeDirection); if (baseCombatEntity.EqualNetID(target)) { flag = true; } } if (!(entity != null) || entity.ShouldBlockProjectiles()) { targetPos = hit.point; vector2 = (targetPos - vector).normalized; break; } } int num = 2; if (!flag) { numConsecutiveMisses++; } else { numConsecutiveMisses = 0; } if (target != null && targetVisible && numConsecutiveMisses > num) { ApplyDamage(target, target.transform.position - vector2 * 0.25f, vector2); numConsecutiveMisses = 0; } ClientRPC(RpcTarget.NetworkGroup("CLIENT_FireGun"), StringPool.Get(muzzleToUse.gameObject.name), targetPos); Facepunch.Pool.FreeUnmanaged(ref obj); } public void ApplyDamage(BaseCombatEntity entity, Vector3 point, Vector3 normal) { float num = 15f * UnityEngine.Random.Range(0.9f, 1.1f); if (entity is BasePlayer && entity != target) { num *= 0.5f; } if (PeacekeeperMode() && entity == target) { target.MarkHostileFor(300f); } HitInfo info = new HitInfo(this, entity, DamageType.Bullet, num, point); entity.OnAttacked(info); if (entity is BasePlayer || entity is BaseNpc) { Effect.server.ImpactEffect(new HitInfo { HitPositionWorld = point, HitNormalWorld = -normal, HitMaterial = StringPool.Get("Flesh") }); } } public void IdleTick(float dt) { if (UnityEngine.Time.realtimeSinceStartup > nextIdleAimTime) { nextIdleAimTime = UnityEngine.Time.realtimeSinceStartup + UnityEngine.Random.Range(4f, 5f); Quaternion quaternion = Quaternion.LookRotation(base.transform.forward, Vector3.up); quaternion *= Quaternion.AngleAxis(UnityEngine.Random.Range(-45f, 45f), Vector3.up); targetAimDir = quaternion * Vector3.forward; } if (!HasTarget()) { aimDir = Mathx.Lerp(aimDir, targetAimDir, 2f, dt); } } public virtual bool HasClipAmmo() { BaseProjectile attachedWeapon = GetAttachedWeapon(); if (attachedWeapon == null) { return false; } return attachedWeapon.primaryMagazine.contents > 0; } public virtual bool HasReserveAmmo() { return totalAmmo > 0; } public int GetTotalAmmo() { int num = 0; BaseProjectile attachedWeapon = GetAttachedWeapon(); if (attachedWeapon == null) { return num; } List<Item> ammos = Facepunch.Pool.Get<List<Item>>(); base.inventory.FindAmmo(ammos, attachedWeapon.primaryMagazine.definition.ammoTypes); if (!attachedWeapon.primaryMagazine.allowAmmoSwitching) { BaseProjectile.StripAmmoToType(ref ammos, attachedWeapon.primaryMagazine.ammoType); } for (int i = 0; i < ammos.Count; i++) { num += ammos[i].amount; } Facepunch.Pool.Free(ref ammos, freeElements: false); return num; } public AmmoTypes GetValidAmmoTypes() { BaseProjectile attachedWeapon = GetAttachedWeapon(); if (attachedWeapon == null) { return AmmoTypes.RIFLE_556MM; } return attachedWeapon.primaryMagazine.definition.ammoTypes; } public ItemDefinition GetDesiredAmmo() { BaseProjectile attachedWeapon = GetAttachedWeapon(); if (attachedWeapon == null) { return null; } return attachedWeapon.primaryMagazine.ammoType; } public void Reload() { BaseProjectile attachedWeapon = GetAttachedWeapon(); if (attachedWeapon == null) { return; } _ = attachedWeapon.primaryMagazine.ammoType; nextShotTime = Mathf.Max(nextShotTime, UnityEngine.Time.time + Mathf.Min(attachedWeapon.GetReloadDuration() * 0.5f, 2f)); AmmoTypes ammoTypes = attachedWeapon.primaryMagazine.definition.ammoTypes; if (attachedWeapon.primaryMagazine.contents > 0) { bool flag = false; if (base.inventory.capacity > base.inventory.itemList.Count) { flag = true; } else { int num = 0; foreach (Item item in base.inventory.itemList) { if (item.info == attachedWeapon.primaryMagazine.ammoType) { num += item.MaxStackable() - item.amount; } } flag = num >= attachedWeapon.primaryMagazine.contents; } if (!flag) { return; } base.inventory.AddItem(attachedWeapon.primaryMagazine.ammoType, attachedWeapon.primaryMagazine.contents, 0uL); attachedWeapon.SetAmmoCount(0); } List<Item> ammos = Facepunch.Pool.Get<List<Item>>(); base.inventory.FindAmmo(ammos, ammoTypes); if (!attachedWeapon.primaryMagazine.allowAmmoSwitching) { BaseProjectile.StripAmmoToType(ref ammos, attachedWeapon.primaryMagazine.ammoType); } if (ammos.Count > 0) { Effect.server.Run(reloadEffect.resourcePath, this, StringPool.Get("WeaponAttachmentPoint"), Vector3.zero, Vector3.zero); totalAmmoDirty = true; attachedWeapon.primaryMagazine.ammoType = ammos[0].info; int num2 = 0; while (attachedWeapon.primaryMagazine.contents < attachedWeapon.primaryMagazine.capacity && num2 < ammos.Count) { if (ammos[num2].info == attachedWeapon.primaryMagazine.ammoType) { int b = attachedWeapon.primaryMagazine.capacity - attachedWeapon.primaryMagazine.contents; b = Mathf.Min(ammos[num2].amount, b); ammos[num2].UseItem(b); attachedWeapon.ModifyAmmoCount(b); } num2++; } } ItemDefinition ammoType = attachedWeapon.primaryMagazine.ammoType; if ((bool)ammoType) { ItemModProjectile component = ammoType.GetComponent<ItemModProjectile>(); GameObject gameObject = component.projectileObject.Get(); if ((bool)gameObject) { if ((bool)gameObject.GetComponent<Projectile>()) { currentAmmoGravity = 0f; currentAmmoVelocity = component.GetMaxVelocity(); } else { ServerProjectile component2 = gameObject.GetComponent<ServerProjectile>(); if ((bool)component2) { currentAmmoGravity = component2.gravityModifier; currentAmmoVelocity = component2.speed; } } } } Facepunch.Pool.Free(ref ammos, freeElements: false); attachedWeapon.SendNetworkUpdate(); } public override void PostServerLoad() { base.PostServerLoad(); totalAmmoDirty = true; Reload(); UpdateNearbyTurrets(created: true); } public void UpdateTotalAmmo() { int num = totalAmmo; totalAmmo = GetTotalAmmo(); if (num != totalAmmo) { MarkDirtyForceUpdateOutputs(); } } public override void OnItemAddedOrRemoved(Item item, bool added) { base.OnItemAddedOrRemoved(item, added); if ((bool)item.info.GetComponent<ItemModEntity>()) { if (IsInvoking(UpdateAttachedWeapon)) { UpdateAttachedWeapon(); } Invoke(UpdateAttachedWeapon, 0.5f); } } public bool EnsureReloaded(bool onlyReloadIfEmpty = true) { bool flag = HasReserveAmmo(); if (onlyReloadIfEmpty) { if (flag && !HasClipAmmo()) { Reload(); return true; } } else if (flag) { Reload(); return true; } return false; } public BaseProjectile GetAttachedWeapon() { return AttachedWeapon as BaseProjectile; } public virtual bool HasFallbackWeapon() { return false; } public bool HasGenericFireable() { if (AttachedWeapon != null) { return AttachedWeapon.IsInstrument(); } return false; } public void UpdateAttachedWeapon() { HeldEntity heldEntity = TryAddWeaponToTurret(base.inventory.GetSlot(0), socketTransform, this, attachedWeaponZOffsetScale); bool flag = heldEntity != null; SetFlag(Flags.Reserved3, flag); if (flag) { AttachedWeapon = heldEntity; totalAmmoDirty = true; Reload(); UpdateTotalAmmo(); if (IsOffline()) { heldEntity.SetLightsOn(isOn: false); } } else { BaseProjectile attachedWeapon = GetAttachedWeapon(); if (attachedWeapon != null) { attachedWeapon.SetGenericVisible(wantsVis: false); attachedWeapon.SetLightsOn(isOn: false); } AttachedWeapon = null; } } public static HeldEntity TryAddWeaponToTurret(Item weaponItem, Transform parent, BaseEntity entityParent, float zOffsetScale) { HeldEntity heldEntity = null; if (weaponItem != null && (weaponItem.info.category == ItemCategory.Weapon || weaponItem.info.category == ItemCategory.Fun)) { BaseEntity heldEntity2 = weaponItem.GetHeldEntity(); if (heldEntity2 != null) { HeldEntity component = heldEntity2.GetComponent<HeldEntity>(); if (component != null && component.IsUsableByTurret) { heldEntity = component; } } } if (heldEntity == null) { return null; } Transform transform = heldEntity.transform; Transform muzzleTransform = heldEntity.MuzzleTransform; heldEntity.SetParent(null); transform.localPosition = Vector3.zero; transform.localRotation = Quaternion.identity; Quaternion quaternion = transform.rotation * Quaternion.Inverse(muzzleTransform.rotation); heldEntity.limitNetworking = false; heldEntity.SetFlag(Flags.Disabled, b: false); heldEntity.SetParent(entityParent, StringPool.Get(parent.name)); transform.localPosition = Vector3.zero; transform.localRotation = Quaternion.identity; transform.rotation *= quaternion; Vector3 vector = parent.InverseTransformPoint(muzzleTransform.position); transform.localPosition = Vector3.left * vector.x; float num = Vector3.Distance(muzzleTransform.position, transform.position); transform.localPosition += Vector3.forward * num * zOffsetScale; heldEntity.SetGenericVisible(wantsVis: true); heldEntity.SetLightsOn(isOn: true); return heldEntity; } public override void OnKilled(HitInfo info) { BaseProjectile attachedWeapon = GetAttachedWeapon(); if (attachedWeapon != null) { attachedWeapon.SetGenericVisible(wantsVis: false); attachedWeapon.SetLightsOn(isOn: false); } AttachedWeapon = null; base.OnKilled(info); } public override bool OnStartBeingLooted(BasePlayer baseEntity) { if (!IsAuthed(baseEntity)) { return false; } return base.OnStartBeingLooted(baseEntity); } public override void PlayerStoppedLooting(BasePlayer player) { base.PlayerStoppedLooting(player); UpdateTotalAmmo(); EnsureReloaded(onlyReloadIfEmpty: false); UpdateTotalAmmo(); nextShotTime = UnityEngine.Time.time; } public virtual float GetMaxAngleForEngagement() { BaseProjectile attachedWeapon = GetAttachedWeapon(); float result = ((attachedWeapon == null) ? 1f : ((1f - Mathf.InverseLerp(0.2f, 1f, attachedWeapon.repeatDelay)) * 7f)); if (UnityEngine.Time.time - lastShotTime > 1f) { result = 1f; } return result; } public void TargetTick() { if (UnityEngine.Time.realtimeSinceStartup >= nextVisCheck) { nextVisCheck = UnityEngine.Time.realtimeSinceStartup + UnityEngine.Random.Range(0.2f, 0.3f); targetVisible = ObjectVisible(target); if (targetVisible) { lastTargetSeenTime = UnityEngine.Time.realtimeSinceStartup; } } EnsureReloaded(); BaseProjectile attachedWeapon = GetAttachedWeapon(); if (UnityEngine.Time.time >= nextShotTime && targetVisible && Mathf.Abs(AngleToTarget(target, currentAmmoGravity != 0f)) < GetMaxAngleForEngagement()) { if ((bool)attachedWeapon) { if (attachedWeapon.primaryMagazine.contents > 0) { FireAttachedGun(AimOffset(target), aimCone, null, PeacekeeperMode() ? target : null); float delay = (attachedWeapon.isSemiAuto ? (attachedWeapon.repeatDelay * 1.5f) : attachedWeapon.repeatDelay); delay = attachedWeapon.ScaleRepeatDelay(delay); nextShotTime = UnityEngine.Time.time + delay; } else { nextShotTime = UnityEngine.Time.time + 5f; } } else if (HasFallbackWeapon()) { FireGun(AimOffset(target), aimCone, null, target); nextShotTime = UnityEngine.Time.time + 0.115f; } else if (HasGenericFireable()) { AttachedWeapon.ServerUse(); nextShotTime = UnityEngine.Time.time + 0.115f; } else { nextShotTime = UnityEngine.Time.time + 1f; } } if (target == null || target.IsDead() || UnityEngine.Time.realtimeSinceStartup - lastTargetSeenTime > 3f || Vector3.Distance(base.transform.position, target.transform.position) > sightRange || (PeacekeeperMode() && !IsEntityHostile(target))) { SetTarget(null); } } public bool HasTarget() { if (target != null) { return target.IsAlive(); } return false; } public void OfflineTick() { aimDir = Vector3.up; } public virtual bool IsEntityHostile(BaseCombatEntity ent) { if (ent is ScarecrowNPC) { return true; } if (ent is BasePet basePet && basePet.Brain.OwningPlayer != null) { if (!basePet.Brain.OwningPlayer.IsHostile()) { return ent.IsHostile(); } return true; } return ent.IsHostile(); } public bool ShouldTarget(BaseCombatEntity targ) { if (targ is AutoTurret) { return false; } if (targ is RidableHorse) { return false; } if (targ is BasePet basePet && basePet.Brain.OwningPlayer != null && IsAuthed(basePet.Brain.OwningPlayer)) { return false; } return true; } public void ScheduleForTargetScan() { updateAutoTurretScanQueue.Add(this); } public bool HasInterference() { return IsOnFire(); } public void TryRegisterForInterferenceUpdate() { if (IsOn() && interferenceUpdateList.Add(this)) { UpdateInterferenceOnOthers(); } } public void UpdateInterference() { if (!IsOn() || Interface.CallHook("OnInterferenceUpdate", this) != null) { return; } float num = 0f; foreach (AutoTurret nearbyTurret in nearbyTurrets) { if (!nearbyTurret.isClient && nearbyTurret.IsValid() && nearbyTurret.gameObject.activeSelf && !nearbyTurret.EqualNetID(net.ID) && nearbyTurret.IsOn() && !nearbyTurret.HasInterference()) { num += 1f; } } SetFlag(Flags.OnFire, num >= (float)Sentry.maxinterference); } public void UpdateInterferenceOnOthers() { if (Interface.CallHook("OnInterferenceOthersUpdate", this) != null) { return; } foreach (AutoTurret nearbyTurret in nearbyTurrets) { if (nearbyTurret != null) { nearbyTurret.TryRegisterForInterferenceUpdate(); } } } public void UpdateNearbyTurrets(bool created) { List<AutoTurret> obj = Facepunch.Pool.Get<List<AutoTurret>>(); if (Interface.CallHook("OnNearbyTurretsScan", this, obj, created) == null) { Vis.Entities(base.transform.position, Sentry.interferenceradius, obj, 256, QueryTriggerInteraction.Ignore); } foreach (AutoTurret item in obj) { if (!(item == this)) { if (created) { nearbyTurrets.Add(item); item.nearbyTurrets.Add(this); } else { item.nearbyTurrets.Remove(this); } } } if (!created) { nearbyTurrets.Clear(); } Facepunch.Pool.FreeUnmanaged(ref obj); } public void TargetScan() { if (!authDirty && !hasPotentialUnauthedTarget) { return; } if (HasInterference()) { if (HasTarget()) { SetTarget(null); } return; } hasPotentialUnauthedTarget = false; authDirty = false; if (HasTarget() || IsOffline() || IsBeingControlled) { return; } if (targetTrigger.entityContents != null) { foreach (BaseEntity entityContent in targetTrigger.entityContents) { BaseCombatEntity baseCombatEntity = entityContent as BaseCombatEntity; if (baseCombatEntity == null) { continue; } if (!Sentry.targetall) { BasePlayer basePlayer = baseCombatEntity as BasePlayer; if (basePlayer != null && (IsAuthed(basePlayer) || Ignore(basePlayer))) { continue; } } if (!hasPotentialUnauthedTarget) { hasPotentialUnauthedTarget = true; } if ((!PeacekeeperMode() || IsEntityHostile(baseCombatEntity)) && baseCombatEntity.IsAlive() && ShouldTarget(baseCombatEntity) && InFiringArc(baseCombatEntity) && ObjectVisible(baseCombatEntity)) { SetTarget(baseCombatEntity); if ((object)target != null) { break; } } } } if (PeacekeeperMode() && target == null) { nextShotTime = UnityEngine.Time.time + 1f; } } public virtual bool Ignore(BasePlayer player) { return false; } public void ServerTick() { if (base.isClient || base.IsDestroyed) { return; } float dt = (float)(double)timeSinceLastServerTick; timeSinceLastServerTick = 0.0; if (!IsOnline()) { OfflineTick(); } else if (!IsBeingControlled) { if (HasTarget()) { TargetTick(); } else { IdleTick(dt); } } UpdateFacingToTarget(dt); if (totalAmmoDirty && UnityEngine.Time.time > nextAmmoCheckTime) { UpdateTotalAmmo(); totalAmmoDirty = false; nextAmmoCheckTime = UnityEngine.Time.time + 0.5f; } } public override void OnAttacked(HitInfo info) { base.OnAttacked(info); if (((IsOnline() && !HasTarget()) || !targetVisible) && !(info.Initiator as AutoTurret != null) && !(info.Initiator as SamSite != null) && !(info.Initiator as GunTrap != null)) { BasePlayer basePlayer = info.Initiator as BasePlayer; if (!basePlayer || !IsAuthed(basePlayer)) { SetTarget(info.Initiator as BaseCombatEntity); } } } public void UpdateFacingToTarget(float dt) { if (target != null && targetVisible && !IsBeingControlled) { Vector3 vector = AimOffset(target); if (peekIndex != 0) { Vector3 position = eyePos.transform.position; Vector3.Distance(vector, position); Vector3 vector2 = Vector3.Cross((vector - position).normalized, Vector3.up); vector += vector2 * visibilityOffsets[peekIndex]; } Vector3 vector3 = (vector - eyePos.transform.position).normalized; if (currentAmmoGravity != 0f) { float num = 0.2f; if (target is BasePlayer) { float num2 = Mathf.Clamp01(target.WaterFactor()) * 1.8f; if (num2 > num) { num = num2; } } vector = target.transform.position + Vector3.up * num; float angle = GetAngle(eyePos.transform.position, vector, currentAmmoVelocity, currentAmmoGravity); Vector3 normalized = (vector.XZ3D() - eyePos.transform.position.XZ3D()).normalized; vector3 = Quaternion.LookRotation(normalized) * Quaternion.Euler(angle, 0f, 0f) * Vector3.forward; } aimDir = vector3; } UpdateAiming(dt); } public float GetAngle(Vector3 launchPosition, Vector3 targetPosition, float launchVelocity, float gravityScale) { float num = UnityEngine.Physics.gravity.y * gravityScale; float num2 = Vector3.Distance(launchPosition.XZ3D(), targetPosition.XZ3D()); float num3 = launchPosition.y - targetPosition.y; float num4 = Mathf.Pow(launchVelocity, 2f); float num5 = Mathf.Pow(launchVelocity, 4f); float num6 = Mathf.Atan((num4 + Mathf.Sqrt(num5 - num * (num * Mathf.Pow(num2, 2f) + 2f * num3 * num4))) / (num * num2)) * 57.29578f; float num7 = Mathf.Atan((num4 - Mathf.Sqrt(num5 - num * (num * Mathf.Pow(num2, 2f) + 2f * num3 * num4))) / (num * num2)) * 57.29578f; if (float.IsNaN(num6) && float.IsNaN(num7)) { return -45f; } if (float.IsNaN(num6)) { return num7; } if (!(num6 > num7)) { return num7; } return num6; } public override void OnDeployed(BaseEntity parent, BasePlayer deployedBy, Item fromItem) { base.OnDeployed(parent, deployedBy, fromItem); AddSelfAuthorize(deployedBy); } public override ItemContainerId GetIdealContainer(BasePlayer player, Item item, ItemMoveModifier modifier) { return default(ItemContainerId); } public override int GetIdealSlot(BasePlayer player, ItemContainer container, Item item) { bool num = item.info.category == ItemCategory.Weapon; bool flag = item.info.category == ItemCategory.Ammunition; if (num) { return 0; } if (flag) { for (int i = 1; i < base.inventory.capacity; i++) { if (!base.inventory.SlotTaken(item, i)) { return i; } } } return -1; }} #if false // Decompilation log
- Assistant
Para melhorar a performance do
AutoTurretno servidor, podemos considerar algumas práticas que visam otimizar o processamento e a quantidade de dados processados por frame. Com base no código fornecido, aqui estão algumas sugestões:-
Otimização de Escaneamento e Atualização de Entidades:
- Fila de Atualização das Torres: A classe
UpdateAutoTurretScanQueuejá otimiza o processamento de escaneamento usando uma fila. Certifique-se de que apenas torres que realmente precisam de uma atualização sejam adicionadas à fila. - Escaneamento de Alvos: Reduza a quantidade de checagens feitas durante o escaneamento de alvos. Por exemplo, o método
TargetScanpoderia ser otimizado para evitar iterações desnecessárias, talvez usando uma seleção mais rigorosa de candidatos antes de realizar cálculos mais intensos.
- Fila de Atualização das Torres: A classe
-
Gerenciamento de Estados e Visibilidade:
- Custos de Visibilidade: Use
ObjectVisibleapenas quando necessário. Considere caching de visibilidade ou limitação do número de verificações por frame/tempo. - Interferência: Reduza a frequência com que
UpdateInterferenceé chamada, especialmente emInvokeRepeatingou em loops. Implementar um debouncing ou throttling pode ajudar a melhorar a eficiência.
- Custos de Visibilidade: Use
-
Redução de Invocações e Processamento de Rede:
- Envio de Updates: Os métodos que chamam
SendNetworkUpdatedevem ser otimizados para evitar updates redundantes, talvez agrupando mudanças ou verificando se um update realmente afeta o estado do jogador. - ClientRPC: Evite chamadas constantes para
ClientRPCou utilize batching onde possível.
- Envio de Updates: Os métodos que chamam
-
Uso Eficiente de
InvokeRepeating:- Ajuste os intervalos das chamadas de
InvokeRepeatingconforme a importância e necessário do método. Aumentar o tempo entre as invocações para métodos menos críticos pode aliviar a carga de processamento.
- Ajuste os intervalos das chamadas de
-
Gestão de Munições:
- Carregamento e Contagem de Munições: Limitar o cálculo de recarga apenas quando o carregador estiver vazio ou a quantidade de munição for significativamente baixa. Evitar operações de listagens e somas repetitivas sem necessidade crítica.
-
Validação de Pontos de Impacto e Dano:
- Trajetórias e Impactos: Ao calcular impactos, verifique se é necessário calcular todos os impactos potenciais ou apenas os que estão significativos dentro de um raio mais crítico ou relevante.
-
Cache de Estados e Resultados:
- Evitar recalcular valores e estados que podem ser armazenados em cache até que uma mudança importante force uma recalculação (ex.: visibilidade de alvos, quantidade de munição).
Implementar essas sugestões vai ajudar a melhorar a eficiência e a performance do código, especialmente em servidores que lidam com um grande número de jogadores e entidades ao mesmo tempo. É importante medir e comparar o desempenho antes e depois de cada mudança para garantir a eficácia das otimizações propostas.
-
- User
me passe o TurretMonoBehaviour completo melhorado
- Assistant
Claro! Aqui está uma versão otimizada do
TurretMonoBehaviourcom base nas sugestões de otimização discutidas:public class TurretMonoBehaviour : MonoBehaviour { private AutoTurret _turret; private const float SearchDistance = 15f; private const int MaxReserveAmmo = 1000; private const float TurretCycleInterval = 0.1f; // Aumentar o intervalo para aliviar carga private const float TargetScanInterval = 2f; // Aumentar o intervalo de escaneamento de alvos para melhorar desempenho private const float AmmoRefillInterval = 30f; private static readonly List<Item> reusableAmmoList = new List<Item>(); private void Awake() { InitializeTurret(); } private void InitializeTurret() { _turret = GetComponent<AutoTurret>(); var triggerCollider = _turret.targetTrigger.GetComponent<SphereCollider>(); triggerCollider.enabled = false; _turret.SetPeacekeepermode(false); _turret.InitiateStartup(); _turret.SetIsOnline(true); _turret.CancelInvoke(_turret.ServerTick); _turret.SetTarget(null); _turret.InvokeRepeating(nameof(PerformTurretCycle), 1f, TurretCycleInterval); _turret.InvokeRepeating(nameof(ScanForTargets), 2f, TargetScanInterval); _turret.isLootable = false; _turret.SendNetworkUpdateImmediate(); InvokeRepeating(nameof(RefillAmmo), 2f, AmmoRefillInterval); } private void RefillAmmo() { if (_turret.AttachedWeapon is not BaseProjectile baseProjectile || baseProjectile.primaryMagazine?.ammoType == null) return; var ammoType = baseProjectile.primaryMagazine.ammoType; int currentAmmoCount = CalculateCurrentAmmoCount(ammoType); if (currentAmmoCount < MaxReserveAmmo) { int ammoNeeded = MaxReserveAmmo - currentAmmoCount; Item ammoItem = ItemManager.Create(ammoType, ammoNeeded); ammoItem?.MoveToContainer(_turret.inventory); _turret.UpdateTotalAmmo(); _turret.EnsureReloaded(); _turret.SendNetworkUpdateImmediate(); } } private int CalculateCurrentAmmoCount(ItemDefinition ammoType) { return _turret.inventory.itemList.Count(item => item.info == ammoType) > 0 ? _turret.inventory.itemList.Where(item => item.info == ammoType).Sum(item => item.amount) : 0; } private void ScanForTargets() { var entityContents = _turret.targetTrigger.entityContents ??= new HashSet<BaseEntity>(); entityContents.Clear(); int foundTargets = BaseEntity.Query.Server.GetPlayersInSphereFast(transform.position, SearchDistance, AIBrainSenses.playerQueryResults, IsTargetValid); if (foundTargets == 0) return; _turret.authDirty = true; for (int i = 0; i < foundTargets; i++) { var player = AIBrainSenses.playerQueryResults[i]; if (!IsValidTargetPlayer(player)) continue; entityContents.Add(player); } } private bool IsValidTargetPlayer(BasePlayer player) { return Interface.CallHook("OnEntityEnter", _turret.targetTrigger, player) == null && !player.IsSleeping() && (!player.InSafeZone() || player.IsHostile()); } private bool IsTargetValid(BasePlayer player) => player != null && !player.IsNpc; private void PerformTurretCycle() { if (_turret.isClient || _turret.IsDestroyed) return; float deltaTime = (float)_turret.timeSinceLastServerTick; _turret.timeSinceLastServerTick = 0f; if (_turret.IsOnline() && !_turret.IsBeingControlled) { if (!_turret.HasTarget()) { _turret.IdleTick(deltaTime); } else { ExecuteTargetEngagement(); } } _turret.UpdateFacingToTarget(deltaTime); UpdateAmmoStatus(); } private void ExecuteTargetEngagement() { if (Time.realtimeSinceStartup >= _turret.nextVisCheck) { _turret.nextVisCheck = Time.realtimeSinceStartup + Random.Range(0.2f, 0.3f); _turret.targetVisible = _turret.ObjectVisible(_turret.target); if (_turret.targetVisible) _turret.lastTargetSeenTime = Time.realtimeSinceStartup; } _turret.EnsureReloaded(); if (ShouldFireAtTarget()) { var weapon = _turret.GetAttachedWeapon(); FireWeapon(weapon); } ValidateTargetEngagement(); } private bool ShouldFireAtTarget() { return Time.time >= _turret.nextShotTime && _turret.targetVisible && Mathf.Abs(_turret.AngleToTarget(_turret.target, _turret.currentAmmoGravity != 0f)) < _turret.GetMaxAngleForEngagement(); } private void FireWeapon(BaseProjectile weapon) { if (weapon == null) { _turret.nextShotTime = Time.time + 1f; return; } if (weapon.primaryMagazine.contents > 0) { _turret.FireAttachedGun(_turret.AimOffset(_turret.target), _turret.aimCone, null, _turret.PeacekeeperMode() ? _turret.target : null); float delay = weapon.isSemiAuto ? weapon.repeatDelay * 1.5f : weapon.repeatDelay; delay = weapon.ScaleRepeatDelay(delay); _turret.nextShotTime = Time.time + delay; } else { _turret.nextShotTime = Time.time + 5f; } } private void ValidateTargetEngagement() { var targetPlayer = _turret.target as BasePlayer; if (_turret.target != null && (!IsValidSteamPlayer(targetPlayer) || _turret.target.IsDead() || TimeExceedsLastSeen() || DistanceExceedsSightRange() || ShouldTargetBeReset())) { _turret.SetTarget(null); } } private bool TimeExceedsLastSeen() => Time.realtimeSinceStartup - _turret.lastTargetSeenTime > 3f; private bool DistanceExceedsSightRange() => Vector3.Distance(_turret.transform.position, _turret.target.transform.position) > _turret.sightRange; private bool ShouldTargetBeReset() => _turret.PeacekeeperMode() && !_turret.IsEntityHostile(_turret.target); private void UpdateAmmoStatus() { if (_turret.totalAmmoDirty && Time.time > _turret.nextAmmoCheckTime) { _turret.UpdateTotalAmmo(); _turret.totalAmmoDirty = false; _turret.nextAmmoCheckTime = Time.time + 0.5f; } } private void OnDestroy() { CancelInvoke(nameof(RefillAmmo)); } }Melhorias Implementadas:
- Intervalos de Temporizadores: Ajustei os intervalos para
InvokeRepeatingpara chamadas menos frequentes, baseando-me nas funções críticas. Em especial, o ciclo da torre e o escaneamento de alvos agora possuem intervalos maiores. - Reuso de Listas: Uma lista reutilizável foi criada para minimizar alocações de listas de munição durante o recálculo de munição.
- Checagens de Condição Melhoradas: Funções de validação foram separadas para melhorar a legibilidade e evitar processos desnecessários.
- Validação de Jogadores Alvo: A função
IsValidTargetPlayeragora encapsula a lógica de validação de um jogador alvo, eliminando a execução de código desnecessário dentro de um loop.
Essas mudanças têm como objetivo aliviar o processamento sobre o servidor enquanto mantêm a integridade funcional da torre. Vale lembrar que é importante testar o funcionamento desse novo código em um ambiente de desenvolvimento antes de implementá-lo em produção.
- Intervalos de Temporizadores: Ajustei os intervalos para
- User
consegue mudar o modo que ela funciona, para nçao precisar esses invokes e usar algo parecido como fiz aqui: /*
- Copyright (C) 2024 Game4Freak.io
- This mod is provided under the Game4Freak EULA.
- Full legal terms can be found at https://game4freak.io/eula/ */
using Facepunch; using Newtonsoft.Json; using Oxide.Core; using Rust; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using UnityEngine; using Random = UnityEngine.Random;
namespace Oxide.Plugins { [Info("Raidable Shelters", "VisEntities", "1.7.1")] [Description("Spawns shelters filled with loot for players to raid.")] public class RaidableShelters : RustPlugin { #region Fields
private static RaidableShelters _plugin; private static Configuration _config; private StoredData _storedData; private System.Random _randomGenerator = new System.Random(); private Timer _sheltersRespawnTimer; private const int LAYER_GROUND = Layers.Mask.Terrain | Layers.Mask.World | Layers.Mask.Default; private const int LAYER_PLAYER = Layers.Mask.Player_Server; private const int LAYER_ENTITIES = Layers.Mask.Deployed | Layers.Mask.Construction; private const string PREFAB_AUTO_TURRET = "assets/prefabs/npc/autoturret/autoturret_deployed.prefab"; private const string PREFAB_LEGACY_SHELTER = "assets/prefabs/building/legacy.shelter.wood/legacy.shelter.wood.deployed.prefab"; private const string PREFAB_LANDMINE = "assets/prefabs/deployable/landmine/landmine.prefab"; private const string PREFAB_BEAR_TRAP = "assets/prefabs/deployable/bear trap/beartrap.prefab"; private const float SPAWNABLE_AREA_RADIUS_INSIDE_SHELTER = 1.7f; private static readonly Vector3 _autoTurretPosition = new Vector3(0.084f, 3.146f, 0.481f); private static readonly Vector3 _autoTurretRotation = new Vector3(355.103f, 0f, 0f); #endregion Fields #region Configuration private class Configuration { [JsonProperty("Version")] public string Version { get; set; } [JsonProperty("Enable Debug")] public bool EnableDebug { get; set; } [JsonProperty("Number Of Attempts To Find Shelter Position Near Players")] public int NumberOfAttemptsToFindShelterPositionNearPlayers { get; set; } [JsonProperty("Minimum Search Radius For Shelter Position Around Player")] public float MinimumSearchRadiusForShelterPositionAroundPlayer { get; set; } [JsonProperty("Maximum Search Radius For Shelter Position Around Player")] public float MaximumSearchRadiusForShelterPositionAroundPlayer { get; set; } [JsonProperty("Shelters Respawn Frequency Minutes")] public float SheltersRespawnFrequencyMinutes { get; set; } [JsonProperty("Delay Between Each Shelter Spawn Seconds")] public float DelayBetweenEachShelterSpawnSeconds { get; set; } [JsonProperty("Nearby Entities Avoidance Radius")] public float NearbyEntitiesAvoidanceRadius { get; set; } [JsonProperty("Rocks Avoidance Radius")] public float RocksAvoidanceRadius { get; set; } [JsonProperty("Distance From No Build Zones")] public float DistanceFromNoBuildZones { get; set; } [JsonProperty("Shelter Health")] public float ShelterHealth { get; set; } [JsonProperty("Shelter Lifetime Seconds")] public float ShelterLifetimeSeconds { get; set; } [JsonProperty("Number Of Attempts For Determining Entity Position Inside Shelter")] public int NumberOfAttemptsForDeterminingEntityPositionInsideShelter { get; set; } [JsonProperty("Number Of Attempts For Determining Entity Rotation Inside Shelter")] public int NumberOfAttemptsForDeterminingEntityRotationInsideShelter { get; set; } [JsonProperty("Door")] public DoorConfig Door { get; set; } [JsonProperty("Turret")] public TurretConfig Turret { get; set; } [JsonProperty("Trap")] public TrapConfig Trap { get; set; } [JsonProperty("Notification")] public NotificationConfig Notification { get; set; } [JsonProperty("Interior Entities")] public List<InteriorEntityConfig> InteriorEntities { get; set; } [JsonProperty("Items To Spawn Inside Entity Containers")] public List<ItemInfo> ItemsToSpawnInsideEntityContainers { get; set; } } public class DoorConfig { [JsonProperty("Skin Ids")] public List<ulong> SkinIds { get; set; } } public class TurretConfig { [JsonProperty("Spawn Auto Turret")] public bool SpawnAutoTurret { get; set; } [JsonProperty("Health")] public float Health { get; set; } [JsonProperty("Weapon Short Name")] public string WeaponShortName { get; set; } [JsonProperty("Clip Ammo")] public ItemInfo ClipAmmo { get; set; } [JsonProperty("Reserve Ammo")] public List<ItemInfo> ReserveAmmo { get; set; } [JsonProperty("Attachment Short Names")] public List<string> AttachmentShortNames { get; set; } [JsonProperty("Peacekeeper")] public bool Peacekeeper { get; set; } } public class TrapConfig { [JsonProperty("Spawn Landmines")] public bool SpawnLandmines { get; set; } [JsonProperty("Spawn Bear Traps")] public bool SpawnBearTraps { get; set; } [JsonProperty("Minimum Number Of Traps To Spawn")] public int MinimumNumberOfTrapsToSpawn { get; set; } [JsonProperty("Maximum Number Of Traps To Spawn")] public int MaximumNumberOfTrapsToSpawn { get; set; } [JsonProperty("Minimum Spawn Radius Around Shelter")] public float MinimumSpawnRadiusAroundShelter { get; set; } [JsonProperty("Maximum Spawn Radius Around Shelter")] public float MaximumSpawnRadiusAroundShelter { get; set; } } public class NotificationConfig { [JsonProperty("Notify Surrounding Players Of Shelter Spawn")] public bool NotifySurroundingPlayersOfShelterSpawn { get; set; } [JsonProperty("Radius For Notifying Nearby Players")] public float RadiusForNotifyingNearbyPlayers { get; set; } [JsonProperty("Send As Toast")] public bool SendAsToast { get; set; } } public class InteriorEntityConfig { [JsonProperty("Prefab Name")] public string PrefabName { get; set; } [JsonProperty("Skin Ids")] public List<ulong> SkinIds { get; set; } [JsonProperty("Spawn Chance")] public int SpawnChance { get; set; } [JsonProperty("Minimum Number To Spawn")] public int MinimumNumberToSpawn { get; set; } [JsonProperty("Maximum Number To Spawn")] public int MaximumNumberToSpawn { get; set; } [JsonProperty("Percentage To Fill Container With Items If Present")] public int PercentageToFillContainerWithItemsIfPresent { get; set; } } public class ItemInfo { [JsonProperty("ShortName")] public string ShortName { get; set; } [JsonProperty("Skin Id")] public ulong SkinId { get; set; } [JsonProperty("Minimum Amount")] public int MinimumAmount { get; set; } [JsonProperty("Maximum Amount")] public int MaximumAmount { get; set; } } protected override void LoadConfig() { base.LoadConfig(); _config = Config.ReadObject<Configuration>(); if (string.Compare(_config.Version, Version.ToString()) < 0) UpdateConfig(); SaveConfig(); } protected override void LoadDefaultConfig() { _config = GetDefaultConfig(); } protected override void SaveConfig() { Config.WriteObject(_config, true); } private void UpdateConfig() { PrintWarning("Config changes detected! Updating..."); Configuration defaultConfig = GetDefaultConfig(); if (string.Compare(_config.Version, "1.0.0") < 0) _config = defaultConfig; if (string.Compare(_config.Version, "1.1.0") < 0) { _config.Notification = defaultConfig.Notification; foreach (InteriorEntityConfig interiorEntityConfig in _config.InteriorEntities) { interiorEntityConfig.SkinIds = new List<ulong>(); } } if (string.Compare(_config.Version, "1.2.0") < 0) { _config.Door = defaultConfig.Door; } if (string.Compare(_config.Version, "1.3.0") < 0) { foreach (InteriorEntityConfig interiorEntityConfig in _config.InteriorEntities) { interiorEntityConfig.SpawnChance = 50; } } if (string.Compare(_config.Version, "1.4.0") < 0) { _config.EnableDebug = defaultConfig.EnableDebug; } if (string.Compare(_config.Version, "1.5.0") < 0) { _config.ShelterHealth = defaultConfig.ShelterHealth; } if (string.Compare(_config.Version, "1.6.0") < 0) { _config.Turret = defaultConfig.Turret; } if (string.Compare(_config.Version, "1.7.0") < 0) { _config.Trap = defaultConfig.Trap; } PrintWarning("Config update complete! Updated from version " + _config.Version + " to " + Version.ToString()); _config.Version = Version.ToString(); } private Configuration GetDefaultConfig() { return new Configuration { Version = Version.ToString(), EnableDebug = false, NumberOfAttemptsToFindShelterPositionNearPlayers = 5, MinimumSearchRadiusForShelterPositionAroundPlayer = 20f, MaximumSearchRadiusForShelterPositionAroundPlayer = 50f, NearbyEntitiesAvoidanceRadius = 6f, RocksAvoidanceRadius = 5f, DistanceFromNoBuildZones = 10f, ShelterHealth = 500f, ShelterLifetimeSeconds = 600f, NumberOfAttemptsForDeterminingEntityPositionInsideShelter = 30, NumberOfAttemptsForDeterminingEntityRotationInsideShelter = 30, SheltersRespawnFrequencyMinutes = 60f, DelayBetweenEachShelterSpawnSeconds = 5f, Door = new DoorConfig { SkinIds = new List<ulong> { 809253752, 2246937402, 2483070538, 3076134051 } }, Turret = new TurretConfig { SpawnAutoTurret = false, Health = 1000f, WeaponShortName = "rifle.ak", ClipAmmo = new ItemInfo { ShortName = "ammo.rifle", MinimumAmount = 30, MaximumAmount = 30 }, ReserveAmmo = new List<ItemInfo> { new ItemInfo { ShortName = "ammo.rifle", MinimumAmount = 128, MaximumAmount = 128 } }, AttachmentShortNames = new List<string> { "weapon.mod.lasersight" }, Peacekeeper = false, }, Trap = new TrapConfig { SpawnLandmines = false, SpawnBearTraps = true, MinimumSpawnRadiusAroundShelter = 3f, MaximumSpawnRadiusAroundShelter = 5f, MinimumNumberOfTrapsToSpawn = 1, MaximumNumberOfTrapsToSpawn = 5 }, Notification = new NotificationConfig { NotifySurroundingPlayersOfShelterSpawn = false, RadiusForNotifyingNearbyPlayers = 40f, SendAsToast = true }, InteriorEntities = new List<InteriorEntityConfig> { new InteriorEntityConfig { PrefabName = "assets/prefabs/deployable/woodenbox/woodbox_deployed.prefab", SkinIds = new List<ulong> { 0 }, SpawnChance = 50, MinimumNumberToSpawn = 1, MaximumNumberToSpawn = 3, PercentageToFillContainerWithItemsIfPresent = 20, }, new InteriorEntityConfig { PrefabName = "assets/prefabs/deployable/furnace/furnace.prefab", SkinIds = new List<ulong> { 0 }, SpawnChance = 50, MinimumNumberToSpawn = 1, MaximumNumberToSpawn = 1, PercentageToFillContainerWithItemsIfPresent = 0, }, }, ItemsToSpawnInsideEntityContainers = new List<ItemInfo>() { new ItemInfo { ShortName = "fat.animal", SkinId = 0, MinimumAmount = 10, MaximumAmount = 25, }, new ItemInfo { ShortName = "cloth", SkinId = 0, MinimumAmount = 20, MaximumAmount = 30, }, new ItemInfo { ShortName = "wood", SkinId = 0, MinimumAmount = 200, MaximumAmount = 400, }, new ItemInfo { ShortName = "syringe.medical", SkinId = 0, MinimumAmount = 1, MaximumAmount = 2, }, new ItemInfo { ShortName = "rope", SkinId = 0, MinimumAmount = 1, MaximumAmount = 3, }, new ItemInfo { ShortName = "cctv.camera", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, new ItemInfo { ShortName = "roadsigns", SkinId = 0, MinimumAmount = 1, MaximumAmount = 2, }, new ItemInfo { ShortName = "stones", SkinId = 0, MinimumAmount = 150, MaximumAmount = 350, }, new ItemInfo { ShortName = "metal.fragments", SkinId = 0, MinimumAmount = 30, MaximumAmount = 90, }, new ItemInfo { ShortName = "ammo.grenadelauncher.he", SkinId = 0, MinimumAmount = 1, MaximumAmount = 2, }, new ItemInfo { ShortName = "coffeecan.helmet", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, new ItemInfo { ShortName = "scrap", SkinId = 0, MinimumAmount = 10, MaximumAmount = 25, }, new ItemInfo { ShortName = "icepick.salvaged", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, new ItemInfo { ShortName = "ptz.cctv.camera", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, new ItemInfo { ShortName = "corn", SkinId = 0, MinimumAmount = 3, MaximumAmount = 5, }, new ItemInfo { ShortName = "ammo.rocket.mlrs", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, new ItemInfo { ShortName = "wall.frame.garagedoor", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, new ItemInfo { ShortName = "pistol.revolver", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, } }; } #endregion Configuration #region Stored Data public class StoredData { [JsonProperty("Raidable Shelters")] public Dictionary<ulong, ShelterData> Shelters { get; set; } = new Dictionary<ulong, ShelterData>(); } public class ShelterData { [JsonProperty("Interior Entities")] public List<ulong> InteriorEntities { get; set; } = new List<ulong>(); [JsonProperty("Traps")] public List<ulong> Traps { get; set; } = new List<ulong>(); [JsonProperty("Removal Timer")] public double RemovalTimer { get; set; } } #endregion Stored Data #region Oxide Hooks private void Init() { _plugin = this; _storedData = DataFileUtil.LoadOrCreate<StoredData>(DataFileUtil.GetFilePath()); } private void Unload() { if (_sheltersRespawnTimer != null) _sheltersRespawnTimer.Destroy(); CoroutineUtil.StopAllCoroutines(); KillAllShelters(); _config = null; _plugin = null; } private void OnServerInitialized(bool isStartup) { _sheltersRespawnTimer = timer.Every(_config.SheltersRespawnFrequencyMinutes * 60f, () => { CoroutineUtil.StartCoroutine("RespawnSheltersCoroutine", RespawnSheltersCoroutine()); }); ResumeShelterRemovalTimers(); } #endregion Oxide Hooks #region True PVE Hooks private object CanEntityTakeDamage(LegacyShelter shelter) { if (shelter == null || !API_IsShelterRaidable(shelter)) return null; return true; } #endregion True PVE Hooks #region Shelters Spawning and Setup private IEnumerator RespawnSheltersCoroutine() { foreach (BasePlayer player in BasePlayer.activePlayerList) { if (player != null && !PlayerUtil.Wounded(player) && !PlayerUtil.Sleeping(player) && !PlayerUtil.InBase(player) && !PlayerUtil.Swimming(player) && !PlayerUtil.Boating(player) && !PlayerUtil.Flying(player) && PlayerUtil.OnGround(player) && !PlayerUtil.NearEnemyBase(player) && !TerrainUtil.InRadTown(player.transform.position)) { Vector3 shelterPosition; Quaternion shelterRotation; if (TryFindSuitableShelterSpawnPoint(player.transform.position, _config.MinimumSearchRadiusForShelterPositionAroundPlayer, _config.MaximumSearchRadiusForShelterPositionAroundPlayer, _config.NumberOfAttemptsToFindShelterPositionNearPlayers, out shelterPosition, out shelterRotation)) { LegacyShelter shelter = SpawnLegacyShelter(shelterPosition, shelterRotation, player); if (shelter != null) { NotifyOfShelterSpawn(shelter, player); if (_config.EnableDebug) DrawDebugInfo(shelterPosition, "Shelter spawn successful", ParseColor("#27AE60"), 4f); } } } else if (_config.EnableDebug) { string reason = "unknown reason"; if (PlayerUtil.Wounded(player)) reason = "player wounded"; else if (PlayerUtil.Sleeping(player)) reason = "player sleeping"; else if (PlayerUtil.InBase(player)) reason = "player in base"; else if (PlayerUtil.Swimming(player)) reason = "player swimming"; else if (PlayerUtil.Boating(player)) reason = "player boating"; else if (PlayerUtil.Flying(player)) reason = "player flying"; else if (!PlayerUtil.OnGround(player)) reason = "player not on ground"; else if (PlayerUtil.NearEnemyBase(player)) reason = "player near enemy base"; else if (TerrainUtil.InRadTown(player.transform.position)) reason = "player in radtown"; DrawDebugInfo(player.transform.position, $"Shelter spawn failed:\n{reason}", ParseColor("#E12126")); } yield return CoroutineEx.waitForSeconds(_config.DelayBetweenEachShelterSpawnSeconds); } } private bool TryFindSuitableShelterSpawnPoint(Vector3 center, float minSearchRadius, float maxSearchRadius, int maxAttempts, out Vector3 suitablePosition, out Quaternion suitableRotation) { for (int attempt = 0; attempt < maxAttempts; attempt++) { Vector3 position = TerrainUtil.GetRandomPositionAround(center, minSearchRadius, maxSearchRadius); if (TerrainUtil.InsideRock(position, _config.RocksAvoidanceRadius)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nInside rock", ParseColor("#E12126"), _config.RocksAvoidanceRadius); continue; } if (TerrainUtil.InRadTown(position)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nIn radtown", ParseColor("#E12126")); continue; } if (TerrainUtil.HasEntityNearby(position, _config.NearbyEntitiesAvoidanceRadius, LAYER_ENTITIES)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nNearby entities", ParseColor("#E12126"), _config.NearbyEntitiesAvoidanceRadius); continue; } if (PlayerUtil.HasPlayerNearby(position, _config.NearbyEntitiesAvoidanceRadius)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nNearby players", ParseColor("#E12126"), _config.NearbyEntitiesAvoidanceRadius); continue; } if (TerrainUtil.InWater(position)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nIn water", ParseColor("#E12126")); continue; } if (TerrainUtil.OnRoadOrRail(position)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nOn road or rail", ParseColor("#E12126")); continue; } if (!TerrainUtil.OnTerrain(position, 4f)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nNot on terrain", ParseColor("#E12126"), 4f); continue; } if (TerrainUtil.InNoBuildZone(position, _config.DistanceFromNoBuildZones)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nIn no-build zone", ParseColor("#E12126"), _config.DistanceFromNoBuildZones); continue; } RaycastHit groundHit; if (TerrainUtil.GetGroundInfo(position, out groundHit, 5f, LAYER_GROUND)) { suitablePosition = groundHit.point; Quaternion surfaceRotation = Quaternion.FromToRotation(Vector3.up, groundHit.normal); Quaternion randomYRotation = Quaternion.Euler(0, Random.Range(0, 360), 0); suitableRotation = surfaceRotation * randomYRotation; return true; } } suitablePosition = Vector3.zero; suitableRotation = Quaternion.identity; return false; } private LegacyShelter SpawnLegacyShelter(Vector3 position, Quaternion rotation, BasePlayer player) { LegacyShelter shelter = GameManager.server.CreateEntity(PREFAB_LEGACY_SHELTER, position, rotation) as LegacyShelter; if (shelter == null) return null; shelter.OnPlaced(player); shelter.Spawn(); shelter.InitializeHealth(_config.ShelterHealth, _config.ShelterHealth); shelter.SendNetworkUpdateImmediate(); // Set the lock owner id to 0 to prevent the player from opening the shelter door. LegacyShelterDoor shelterDoor = shelter.GetChildDoor(); if (shelterDoor != null) { shelterDoor.InitializeHealth(_config.ShelterHealth, _config.ShelterHealth); BaseLock baseLock = shelterDoor.GetSlot(BaseEntity.Slot.Lock) as BaseLock; if (baseLock != null) baseLock.OwnerID = 0; if (_config.Door.SkinIds != null && _config.Door.SkinIds.Count > 0) { shelterDoor.skinID = _config.Door.SkinIds[Random.Range(0, _config.Door.SkinIds.Count)]; } } EntityPrivilege entityPrivilege = shelter.GetEntityPrivilege(); if (entityPrivilege != null) { entityPrivilege.authorizedPlayers.Clear(); entityPrivilege.SendNetworkUpdate(BasePlayer.NetworkQueue.Update); } ShelterData shelterData = new ShelterData { RemovalTimer = Time.realtimeSinceStartup + _config.ShelterLifetimeSeconds }; _storedData.Shelters[shelter.net.ID.Value] = shelterData; if (!SpawnShelterInteriorEntities(shelter, shelterData)) { _storedData.Shelters.Remove(shelter.net.ID.Value); DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData); shelter.Kill(); return null; } if (_config.Turret.SpawnAutoTurret) DeployAutoTurret(shelter, shelterData); if (_config.Trap.SpawnLandmines || _config.Trap.SpawnBearTraps) SpawnTrapsAroundShelter(shelter, shelterData); StartRemovalTimer(shelter, _config.ShelterLifetimeSeconds, shelterData); return shelter; } #endregion Shelters Spawning and Setup #region Shelter Spawn Notification private void NotifyOfShelterSpawn(LegacyShelter shelter, BasePlayer player) { if (_config.Notification.NotifySurroundingPlayersOfShelterSpawn) { List<BasePlayer> nearbyPlayers = Pool.Get<List<BasePlayer>>(); Vis.Entities(shelter.transform.position, _config.Notification.RadiusForNotifyingNearbyPlayers, nearbyPlayers, LAYER_PLAYER, QueryTriggerInteraction.Ignore); foreach (BasePlayer nearbyPlayer in nearbyPlayers) { if (nearbyPlayer == null) continue; if (_config.Notification.SendAsToast) ShowToast(nearbyPlayer, Lang.RaidableShelterSpawned); else MessagePlayer(nearbyPlayer, Lang.RaidableShelterSpawned); } Pool.FreeUnmanaged(ref nearbyPlayers); } else { if (_config.Notification.SendAsToast) ShowToast(player, Lang.RaidableShelterSpawned); else MessagePlayer(player, Lang.RaidableShelterSpawned); } } #endregion Shelter Spawn Notification #region Interior Entities Spawning private bool SpawnShelterInteriorEntities(LegacyShelter shelter, ShelterData shelterData) { Vector3 shelterCenter = shelter.transform.position; float spawnRadius = SPAWNABLE_AREA_RADIUS_INSIDE_SHELTER; bool anyEntitiesSpawned = false; foreach (InteriorEntityConfig interiorEntityConfig in _config.InteriorEntities) { int numberToSpawn = Random.Range(interiorEntityConfig.MinimumNumberToSpawn, interiorEntityConfig.MaximumNumberToSpawn + 1); for (int i = 0; i < numberToSpawn; i++) { if (!ChanceSucceeded(interiorEntityConfig.SpawnChance)) continue; Vector3 randomPosition; int maxPositionAttempts = _config.NumberOfAttemptsForDeterminingEntityPositionInsideShelter; int maxRotationAttempts = _config.NumberOfAttemptsForDeterminingEntityRotationInsideShelter; for (int posAttempt = 0; posAttempt < maxPositionAttempts; posAttempt++) { randomPosition = TerrainUtil.GetRandomPositionAround(shelterCenter, minimumRadius: 0f, maximumRadius: spawnRadius); RaycastHit groundHit; if (!TerrainUtil.GetGroundInfo(randomPosition, out groundHit, 2f, LAYER_GROUND)) continue; randomPosition = groundHit.point; for (int rotAttempt = 0; rotAttempt < maxRotationAttempts; rotAttempt++) { Quaternion surfaceRotation = Quaternion.FromToRotation(Vector3.up, groundHit.normal); Quaternion randomYRotation = Quaternion.Euler(0, Random.Range(0, 360), 0); Quaternion finalRotation = surfaceRotation * randomYRotation; if (!EntityFitsInShelter(shelter, interiorEntityConfig.PrefabName, randomPosition, finalRotation)) continue; if (ExposedHook.OnShelterInteriorEntitySpawn(shelter, interiorEntityConfig.PrefabName, randomPosition, finalRotation)) continue; BaseEntity entity = SpawnInteriorEntity(shelter, randomPosition, finalRotation, interiorEntityConfig); if (entity == null) continue; shelterData.InteriorEntities.Add(entity.net.ID.Value); ExposedHook.OnShelterInteriorEntitySpawned(shelter, entity); anyEntitiesSpawned = true; posAttempt = maxPositionAttempts; break; } } } } return anyEntitiesSpawned; } private bool EntityFitsInShelter(LegacyShelter shelter, string prefabPath, Vector3 potentialPosition, Quaternion potentialRotation) { BaseEntity tempEntity = GameManager.server.CreateEntity(prefabPath, potentialPosition, potentialRotation, false); if (tempEntity == null) return false; OBB bounds = tempEntity.WorldSpaceBounds(); tempEntity.Kill(); Vector3[] corners = new Vector3[8]; corners[0] = bounds.GetPoint(-1f, -1f, -1f); corners[1] = bounds.GetPoint(-1f, -1f, 1f); corners[2] = bounds.GetPoint(-1f, 1f, -1f); corners[3] = bounds.GetPoint(-1f, 1f, 1f); corners[4] = bounds.GetPoint(1f, -1f, -1f); corners[5] = bounds.GetPoint(1f, -1f, 1f); corners[6] = bounds.GetPoint(1f, 1f, -1f); corners[7] = bounds.GetPoint(1f, 1f, 1f); // Ensure the entity is within the shelter bounds and not clipping through or colliding with other objects inside. Collider[] colliders = Physics.OverlapBox(bounds.position, bounds.extents, bounds.rotation, LAYER_ENTITIES); foreach (Collider collider in colliders) { if (collider.gameObject != tempEntity.gameObject && collider.gameObject != shelter.gameObject) return false; } return true; } private BaseEntity SpawnInteriorEntity(LegacyShelter shelter, Vector3 position, Quaternion rotation, InteriorEntityConfig interiorEntityConfig) { BaseEntity entity = GameManager.server.CreateEntity(interiorEntityConfig.PrefabName, position, rotation); if (entity == null) return null; if (interiorEntityConfig.SkinIds != null && interiorEntityConfig.SkinIds.Count > 0) { entity.skinID = interiorEntityConfig.SkinIds[Random.Range(0, interiorEntityConfig.SkinIds.Count)]; } entity.Spawn(); RemoveProblematicComponents(entity); if (entity is StorageContainer storageContainer) PopulateItems(storageContainer.inventory, _config.ItemsToSpawnInsideEntityContainers, interiorEntityConfig.PercentageToFillContainerWithItemsIfPresent); return entity; } #endregion Interior Entities Spawning #region Entity Containers Filling private void PopulateItems(ItemContainer itemContainer, List<ItemInfo> items, int fillContainerPercentage) { Shuffle(items); int slotsToFill = Mathf.CeilToInt(itemContainer.capacity * (fillContainerPercentage / 100f)); for (int i = 0; i < slotsToFill; i++) { if (i >= items.Count) break; ItemInfo itemInfo = items[i]; var itemDefinition = ItemManager.FindItemDefinition(itemInfo.ShortName); if (itemDefinition != null) { int amountToAdd = Random.Range(itemInfo.MinimumAmount, itemInfo.MaximumAmount + 1); Item item = ItemManager.Create(itemDefinition, amountToAdd, itemInfo.SkinId); if (!item.MoveToContainer(itemContainer)) { item.Remove(); } } } } #endregion Entity Container Filling #region Turret Deployment and Setup private void DeployAutoTurret(LegacyShelter shelter, ShelterData shelterData) { AutoTurret autoTurret = SpawnAutoTurret(shelter, _autoTurretPosition, Quaternion.Euler(_autoTurretRotation)); if (autoTurret != null) { AddWeaponToTurret(autoTurret); LoadTurretWithReserveAmmo(autoTurret.inventory); autoTurret.UpdateTotalAmmo(); autoTurret.EnsureReloaded(); autoTurret.SetPeacekeepermode(_config.Turret.Peacekeeper); autoTurret.InitiateStartup(); autoTurret.SendNetworkUpdate(); shelterData.Traps.Add(autoTurret.net.ID.Value); } } private AutoTurret SpawnAutoTurret(LegacyShelter shelter, Vector3 position, Quaternion rotation) { AutoTurret autoTurret = GameManager.server.CreateEntity(PREFAB_AUTO_TURRET, position, rotation) as AutoTurret; if (autoTurret == null) return null; autoTurret.SetParent(shelter); autoTurret.Spawn(); autoTurret.InitializeHealth(_config.Turret.Health, _config.Turret.Health); autoTurret.SendNetworkUpdateImmediate(); RemoveProblematicComponents(autoTurret); HideIOInputsAndOutputs(autoTurret); return autoTurret; } private Item AddWeaponToTurret(AutoTurret autoTurret) { Item item = ItemManager.CreateByName(_config.Turret.WeaponShortName); if (item == null) return null; if (_config.Turret.AttachmentShortNames != null) { foreach (string attachmentShortname in _config.Turret.AttachmentShortNames) { var attachmentItem = ItemManager.CreateByName(attachmentShortname); if (attachmentItem != null) { if (!attachmentItem.MoveToContainer(item.contents)) { attachmentItem.Remove(); } } } } if (!item.MoveToContainer(autoTurret.inventory, 0)) { item.Remove(); return null; } BaseProjectile weapon = item.GetHeldEntity() as BaseProjectile; if (weapon != null) { if (_config.Turret.AttachmentShortNames != null) { // Ensures the weapon's magazine capacity reflects the modifications applied, such as the extended magazine mod. weapon.DelayedModsChanged(); weapon.CancelInvoke(weapon.DelayedModsChanged); } autoTurret.UpdateAttachedWeapon(); autoTurret.CancelInvoke(autoTurret.UpdateAttachedWeapon); if (_config.Turret.ClipAmmo != null) { ItemDefinition loadedAmmoItemDefinition = ItemManager.FindItemDefinition(_config.Turret.ClipAmmo.ShortName); if (loadedAmmoItemDefinition != null) { weapon.primaryMagazine.ammoType = loadedAmmoItemDefinition; int clipAmmoAmount = UnityEngine.Random.Range(_config.Turret.ClipAmmo.MinimumAmount, _config.Turret.ClipAmmo.MaximumAmount + 1); weapon.primaryMagazine.contents = Mathf.Min(weapon.primaryMagazine.capacity, clipAmmoAmount); } } } return item; } private void LoadTurretWithReserveAmmo(ItemContainer autoTurretContainer) { if (_config.Turret.ReserveAmmo == null) return; // Starting from slot 1, because slot 0 is reserved for the weapon. int currentSlot = 1; int maximumAvailableSlots = autoTurretContainer.capacity - 1; foreach (ItemInfo ammo in _config.Turret.ReserveAmmo) { if (currentSlot > maximumAvailableSlots) break; if (ammo.MinimumAmount <= 0 && ammo.MaximumAmount <= 0) continue; ItemDefinition itemDefinition = ItemManager.FindItemDefinition(ammo.ShortName); if (itemDefinition == null) continue; int reserveAmmoAmount = UnityEngine.Random.Range(ammo.MinimumAmount, ammo.MaximumAmount + 1); int amountToAdd = Math.Min(reserveAmmoAmount, itemDefinition.stackable); Item ammoItem = ItemManager.Create(itemDefinition, amountToAdd); if (!ammoItem.MoveToContainer(autoTurretContainer, currentSlot)) { ammoItem.Remove(); } if (ammoItem.parent != autoTurretContainer) { Item destinationItem = autoTurretContainer.GetSlot(currentSlot); if (destinationItem != null) { destinationItem.amount = amountToAdd; destinationItem.MarkDirty(); } ammoItem.Remove(); } currentSlot++; } } #endregion Turret Deployment and Setup #region Traps Spawning private void SpawnTrapsAroundShelter(LegacyShelter shelter, ShelterData shelterData) { Vector3 shelterPosition = shelter.transform.position; int numberOfTraps = Random.Range(_config.Trap.MinimumNumberOfTrapsToSpawn, _config.Trap.MaximumNumberOfTrapsToSpawn + 1); for (int i = 0; i < numberOfTraps; i++) { Vector3 randomPosition = TerrainUtil.GetRandomPositionAround(shelterPosition, _config.Trap.MinimumSpawnRadiusAroundShelter, _config.Trap.MaximumSpawnRadiusAroundShelter); RaycastHit groundHit; if (!TerrainUtil.GetGroundInfo(randomPosition, out groundHit, 5f, LAYER_GROUND)) continue; randomPosition = groundHit.point; Quaternion surfaceRotation = Quaternion.FromToRotation(Vector3.up, groundHit.normal); string trapPrefab = GetRandomTrapPrefab(); if (string.IsNullOrEmpty(trapPrefab)) continue; BaseEntity trapEntity = GameManager.server.CreateEntity(trapPrefab, randomPosition, surfaceRotation); if (trapEntity != null) { trapEntity.SetParent(shelter, true); trapEntity.Spawn(); shelterData.Traps.Add(trapEntity.net.ID.Value); RemoveProblematicComponents(trapEntity); } } } private string GetRandomTrapPrefab() { if (_config.Trap.SpawnLandmines && _config.Trap.SpawnBearTraps) { if (CoinFlip()) return PREFAB_LANDMINE; else return PREFAB_BEAR_TRAP; } else if (_config.Trap.SpawnLandmines) { return PREFAB_LANDMINE; } else if (_config.Trap.SpawnBearTraps) { return PREFAB_BEAR_TRAP; } return null; } #endregion Traps Spawning #region Shelters Removal private void ResumeShelterRemovalTimers() { foreach (var kvp in _storedData.Shelters) { ShelterData shelterData = kvp.Value; LegacyShelter shelter = FindEntityById(kvp.Key) as LegacyShelter; if (shelter != null) { double remainingTime = shelterData.RemovalTimer - Time.realtimeSinceStartup; StartRemovalTimer(shelter, (float)remainingTime, shelterData); } } } private void StartRemovalTimer(LegacyShelter shelter, float lifetimeSeconds, ShelterData shelterData) { ulong shelterId = shelter != null && shelter.net != null ? shelter.net.ID.Value : 0; if (lifetimeSeconds <= 0) { if (shelter != null) shelter.Kill(); if (shelterData != null) { foreach (ulong entityId in shelterData.InteriorEntities) { BaseEntity entity = FindEntityById(entityId); if (entity != null) entity.Kill(); } } if (_storedData.Shelters.ContainsKey(shelterId)) { _storedData.Shelters.Remove(shelterId); DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData); } return; } if (shelter != null) { shelterData.RemovalTimer = Time.realtimeSinceStartup + lifetimeSeconds; DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData); timer.Once(lifetimeSeconds, () => { if (shelter != null) shelter.Kill(); if (shelterData != null) { foreach (ulong entityId in shelterData.InteriorEntities) { BaseEntity entity = FindEntityById(entityId); if (entity != null) entity.Kill(); } } if (_storedData.Shelters.ContainsKey(shelterId)) { _storedData.Shelters.Remove(shelterId); DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData); } }); } } private void KillAllShelters() { foreach (var kvp in _storedData.Shelters) { ShelterData shelterData = kvp.Value; LegacyShelter shelter = BaseNetworkable.serverEntities.Find(new NetworkableId(kvp.Key)) as LegacyShelter; if (shelter != null) { foreach (ulong entityId in shelterData.InteriorEntities) { BaseEntity entity = BaseNetworkable.serverEntities.Find(new NetworkableId(entityId)) as BaseEntity; if (entity != null) entity.Kill(); } foreach (ulong trapId in shelterData.Traps) { BaseEntity trapEntity = FindEntityById(trapId); if (trapEntity != null) trapEntity.Kill(); } shelter.Kill(); } } _storedData.Shelters.Clear(); DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData); } #endregion Shelters Removal #region Debug private void DrawDebugInfo(Vector3 position, string info, Color color, float radius = 0.5f) { foreach (BasePlayer player in BasePlayer.activePlayerList) { if (player == null || !player.IsAdmin) continue; DrawUtil.Text(player, 10f, color, position + Vector3.up * 1f, $"<size=30>{info}</size>"); DrawUtil.Sphere(player, 10f, color, position, radius); } } #endregion Debug #region Exposed Hooks private static class ExposedHook { public static bool OnShelterInteriorEntitySpawn(LegacyShelter shelter, string prefabName, Vector3 position, Quaternion rotation) { object hookResult = Interface.CallHook("OnShelterInteriorEntitySpawn", shelter, prefabName, position, rotation); return hookResult is bool && (bool)hookResult == false; } public static void OnShelterInteriorEntitySpawned(LegacyShelter shelter, BaseEntity entity) { Interface.CallHook("OnShelterInteriorEntitySpawned", shelter, entity); } } #endregion Exposed Hooks #region API private bool API_IsShelterRaidable(LegacyShelter shelter) { return _storedData.Shelters.ContainsKey(shelter.net.ID.Value); } #endregion API #region Helper Functions private static bool CoinFlip() { return Random.Range(0, 2) == 0; } private BaseEntity FindEntityById(ulong id) { return BaseNetworkable.serverEntities.Find(new NetworkableId(id)) as BaseEntity; } private static void HideIOInputsAndOutputs(IOEntity ioEntity) { foreach (var input in ioEntity.inputs) input.type = IOEntity.IOType.Generic; foreach (var output in ioEntity.outputs) output.type = IOEntity.IOType.Generic; } private static BaseEntity FindBaseEntityForPrefab(string prefabName) { var prefab = GameManager.server.FindPrefab(prefabName); if (prefab == null) return null; return prefab.GetComponent<BaseEntity>(); } private static void Shuffle<T>(List<T> list) { int remainingItems = list.Count; while (remainingItems > 1) { remainingItems--; int randomIndex = _plugin._randomGenerator.Next(remainingItems + 1); T itemToSwap = list[randomIndex]; list[randomIndex] = list[remainingItems]; list[remainingItems] = itemToSwap; } } private static void RemoveProblematicComponents(BaseEntity entity) { UnityEngine.Object.DestroyImmediate(entity.GetComponent<DestroyOnGroundMissing>()); UnityEngine.Object.DestroyImmediate(entity.GetComponent<GroundWatch>()); } private static bool ChanceSucceeded(int percentage) { return Random.Range(0, 100) < percentage; } private static Color ParseColor(string hexColor) { if (ColorUtility.TryParseHtmlString(hexColor, out Color color)) return color; return Color.white; } #endregion Helper Functions #region Helper Classes public static class TerrainUtil { public static bool OnTopology(Vector3 position, TerrainTopology.Enum topology) { return (TerrainMeta.TopologyMap.GetTopology(position) & (int)topology) != 0; } public static bool OnRoadOrRail(Vector3 position) { var combinedTopology = TerrainTopology.Enum.Road | TerrainTopology.Enum.Roadside | TerrainTopology.Enum.Rail | TerrainTopology.Enum.Railside; return OnTopology(position, combinedTopology); } public static bool OnTerrain(Vector3 position, float radius) { return Physics.CheckSphere(position, radius, Layers.Mask.Terrain, QueryTriggerInteraction.Ignore); } public static bool InNoBuildZone(Vector3 position, float radius) { return Physics.CheckSphere(position, radius, Layers.Mask.Prevent_Building); } public static bool InWater(Vector3 position) { return WaterLevel.Test(position, false, false); } public static bool InsideRock(Vector3 position, float radius) { List<Collider> colliders = Pool.Get<List<Collider>>(); Vis.Colliders(position, radius, colliders, Layers.Mask.World, QueryTriggerInteraction.Ignore); bool result = false; foreach (Collider collider in colliders) { if (collider.name.Contains("rock", CompareOptions.OrdinalIgnoreCase) || collider.name.Contains("cliff", CompareOptions.OrdinalIgnoreCase) || collider.name.Contains("formation", CompareOptions.OrdinalIgnoreCase)) { result = true; break; } } Pool.FreeUnmanaged(ref colliders); return result; } public static bool InRadTown(Vector3 position, bool shouldDisplayOnMap = false) { foreach (var monumentInfo in TerrainMeta.Path.Monuments) { bool inBounds = monumentInfo.IsInBounds(position); bool hasLandMarker = true; if (shouldDisplayOnMap) hasLandMarker = monumentInfo.shouldDisplayOnMap; if (inBounds && hasLandMarker) return true; } return OnTopology(position, TerrainTopology.Enum.Monument); } public static bool HasEntityNearby(Vector3 position, float radius, LayerMask mask, string prefabName = null) { List<Collider> hitColliders = Pool.Get<List<Collider>>(); GamePhysics.OverlapSphere(position, radius, hitColliders, mask, QueryTriggerInteraction.Ignore); bool hasEntityNearby = false; foreach (Collider collider in hitColliders) { BaseEntity entity = collider.gameObject.ToBaseEntity(); if (entity != null) { if (prefabName == null || entity.PrefabName == prefabName) { hasEntityNearby = true; break; } } } Pool.FreeUnmanaged(ref hitColliders); return hasEntityNearby; } public static Vector3 GetRandomPositionAround(Vector3 center, float minimumRadius, float maximumRadius, bool adjustToWaterHeight = false) { Vector3 randomDirection = Random.onUnitSphere; float randomDistance = Random.Range(minimumRadius, maximumRadius); Vector3 randomPosition = center + randomDirection * randomDistance; if (adjustToWaterHeight) randomPosition.y = TerrainMeta.WaterMap.GetHeight(randomPosition); else randomPosition.y = TerrainMeta.HeightMap.GetHeight(randomPosition); return randomPosition; } public static bool GetGroundInfo(Vector3 startPosition, out RaycastHit raycastHit, float range, LayerMask mask) { return Physics.Linecast(startPosition + new Vector3(0.0f, range, 0.0f), startPosition - new Vector3(0.0f, range, 0.0f), out raycastHit, mask); } public static bool GetGroundInfo(Vector3 startPosition, out RaycastHit raycastHit, float range, LayerMask mask, Transform ignoreTransform = null) { startPosition.y += 0.25f; range += 0.25f; raycastHit = default; RaycastHit hit; if (!GamePhysics.Trace(new Ray(startPosition, Vector3.down), 0f, out hit, range, mask, QueryTriggerInteraction.UseGlobal, null)) return false; if (ignoreTransform != null && hit.collider != null && (hit.collider.transform == ignoreTransform || hit.collider.transform.IsChildOf(ignoreTransform))) { return GetGroundInfo(startPosition - new Vector3(0f, 0.01f, 0f), out raycastHit, range, mask, ignoreTransform); } raycastHit = hit; return true; } } private static class PlayerUtil { public static BasePlayer FindById(ulong playerId) { return RelationshipManager.FindByID(playerId); } public static bool HasPlayerNearby(Vector3 position, float radius) { return BaseNetworkable.HasCloseConnections(position, radius); } public static bool AreTeammates(ulong firstPlayerId, ulong secondPlayerId) { RelationshipManager.PlayerTeam team = RelationshipManager.ServerInstance.FindPlayersTeam(firstPlayerId); if (team != null && team.members.Contains(secondPlayerId)) return true; return false; } public static bool Sleeping(BasePlayer player) { return player != null && player.IsSleeping(); } public static bool Swimming(BasePlayer player) { return player != null && player.IsSwimming(); } public static bool Boating(BasePlayer player) { return player != null && player.isMounted && player.GetMounted().mountTimeStatType == BaseMountable.MountStatType.Boating; } public static bool Flying(BasePlayer player) { return player != null && player.isMounted && player.GetMounted().mountTimeStatType == BaseMountable.MountStatType.Flying; } public static bool Driving(BasePlayer player) { return player != null && player.isMounted && player.GetMounted().mountTimeStatType == BaseMountable.MountStatType.Driving; } public static bool InBase(BasePlayer player) { return player != null && player.IsBuildingAuthed(); } public static bool NearEnemyBase(BasePlayer player) { return player != null && player.IsNearEnemyBase(); } public static bool Wounded(BasePlayer player) { return player != null && player.IsWounded(); } public static bool Crawling(BasePlayer player) { return player != null && player.IsCrawling(); } public static bool OnGround(BasePlayer player) { return player != null && player.IsOnGround(); } } public static class CoroutineUtil { private static readonly Dictionary<string, Coroutine> _activeCoroutines = new Dictionary<string, Coroutine>(); public static void StartCoroutine(string coroutineName, IEnumerator coroutineFunction) { StopCoroutine(coroutineName); Coroutine coroutine = ServerMgr.Instance.StartCoroutine(coroutineFunction); _activeCoroutines[coroutineName] = coroutine; } public static void StopCoroutine(string coroutineName) { if (_activeCoroutines.TryGetValue(coroutineName, out Coroutine coroutine)) { if (coroutine != null) ServerMgr.Instance.StopCoroutine(coroutine); _activeCoroutines.Remove(coroutineName); } } public static void StopAllCoroutines() { foreach (string coroutineName in _activeCoroutines.Keys.ToArray()) { StopCoroutine(coroutineName); } } } public static class DrawUtil { public static void Box(BasePlayer player, float durationSeconds, Color color, Vector3 position, float radius) { player.SendConsoleCommand("ddraw.box", durationSeconds, color, position, radius); } public static void Sphere(BasePlayer player, float durationSeconds, Color color, Vector3 position, float radius) { player.SendConsoleCommand("ddraw.sphere", durationSeconds, color, position, radius); } public static void Line(BasePlayer player, float durationSeconds, Color color, Vector3 fromPosition, Vector3 toPosition) { player.SendConsoleCommand("ddraw.line", durationSeconds, color, fromPosition, toPosition); } public static void Arrow(BasePlayer player, float durationSeconds, Color color, Vector3 fromPosition, Vector3 toPosition, float headSize) { player.SendConsoleCommand("ddraw.arrow", durationSeconds, color, fromPosition, toPosition, headSize); } public static void Text(BasePlayer player, float durationSeconds, Color color, Vector3 position, string text) { player.SendConsoleCommand("ddraw.text", durationSeconds, color, position, text); } } public class DataFileUtil { private const string FOLDER = ""; public static string GetFilePath(string filename = null) { if (filename == null) filename = _plugin.Name; return Path.Combine(FOLDER, filename); } public static string[] GetAllFilePaths() { string[] filePaths = Interface.Oxide.DataFileSystem.GetFiles(FOLDER); for (int i = 0; i < filePaths.Length; i++) { // Remove the redundant '.json' from the filepath. This is necessary because the filepaths are returned with a double '.json'. filePaths[i] = filePaths[i].Substring(0, filePaths[i].Length - 5); } return filePaths; } public static bool Exists(string filePath) { return Interface.Oxide.DataFileSystem.ExistsDatafile(filePath); } public static T Load<T>(string filePath) where T : class, new() { T data = Interface.Oxide.DataFileSystem.ReadObject<T>(filePath); if (data == null) data = new T(); return data; } public static T LoadIfExists<T>(string filePath) where T : class, new() { if (Exists(filePath)) return Load<T>(filePath); else return null; } public static T LoadOrCreate<T>(string filePath) where T : class, new() { T data = LoadIfExists<T>(filePath); if (data == null) data = new T(); return data; } public static void Save<T>(string filePath, T data) { Interface.Oxide.DataFileSystem.WriteObject<T>(filePath, data); } public static void Delete(string filePath) { Interface.Oxide.DataFileSystem.DeleteDataFile(filePath); } } #endregion Helper Classes #region Commands private static class Cmd { public const string TEST = "rs.test"; } [ChatCommand(Cmd.TEST)] private void cmdTest(BasePlayer player, string cmd, string[] args) { if (player == null || !player.IsAdmin) return; RaycastHit groundHit; if (TerrainUtil.GetGroundInfo(player.transform.position, out groundHit, 10f, LAYER_GROUND)) { Vector3 spawnPosition = groundHit.point; Quaternion surfaceRotation = Quaternion.FromToRotation(Vector3.up, groundHit.normal); Quaternion randomYRotation = Quaternion.Euler(0, Random.Range(0, 360), 0); Quaternion spawnRotation = surfaceRotation * randomYRotation; LegacyShelter shelter = SpawnLegacyShelter(spawnPosition, spawnRotation, player); if (shelter != null) { MessagePlayer(player, Lang.TestShelterSpawned); } } } #endregion Commands #region Localization private class Lang { public const string RaidableShelterSpawned = "RaidableShelterSpawned"; public const string TestShelterSpawned = "TestShelterSpawned"; } protected override void LoadDefaultMessages() { lang.RegisterMessages(new Dictionary<string, string> { [Lang.RaidableShelterSpawned] = "A raidable shelter has spawned nearby!", [Lang.TestShelterSpawned] = "A test shelter has been spawned at your location." }, this, "en"); } private static string GetMessage(BasePlayer player, string messageKey, params object[] args) { string message = _plugin.lang.GetMessage(messageKey, _plugin, player.UserIDString); if (args.Length > 0) message = string.Format(message, args); return message; } public static void MessagePlayer(BasePlayer player, string messageKey, params object[] args) { string message = GetMessage(player, messageKey, args); _plugin.SendReply(player, message); } public static void ShowToast(BasePlayer player, string messageKey, GameTip.Styles style = GameTip.Styles.Blue_Normal, params object[] args) { string message = GetMessage(player, messageKey, args); player.SendConsoleCommand("gametip.showtoast", (int)style, message); } #endregion Localization }}
- Assistant
Para adaptar o
TurretMonoBehaviourpara um sistema sem o uso deInvokeRepeatinge mais parecido com o exemplo de corrotinas que você mencionou, podemos utilizar corrotinas do Unity para gerenciar os ciclos de atualização. Vou criar um exemplo simplificado de como o comportamento da torre poderia ser modificado para usar corrotinas:public class TurretMonoBehaviour : MonoBehaviour { private AutoTurret _turret; private const float SearchDistance = 15f; private const int MaxReserveAmmo = 1000; private void Awake() { InitializeTurret(); } private void InitializeTurret() { _turret = GetComponent<AutoTurret>(); _turret.targetTrigger.GetComponent<SphereCollider>().enabled = false; _turret.SetPeacekeepermode(false); _turret.InitiateStartup(); _turret.SetIsOnline(true); _turret.SetTarget(null); _turret.isLootable = false; _turret.SendNetworkUpdateImmediate(); StartCoroutine(TurretRoutine()); } private IEnumerator TurretRoutine() { const float turretCycleDelay = 0.1f; const float targetScanDelay = 2f; const float ammoRefillDelay = 30f; while (true) { PerformTurretCycle(); yield return new WaitForSeconds(turretCycleDelay); ScanForTargets(); yield return new WaitForSeconds(targetScanDelay); RefillAmmo(); yield return new WaitForSeconds(ammoRefillDelay); } } private void RefillAmmo() { if (_turret.AttachedWeapon is not BaseProjectile baseProjectile || baseProjectile.primaryMagazine?.ammoType == null) return; var ammoType = baseProjectile.primaryMagazine.ammoType; int currentAmmoCount = CalculateCurrentAmmoCount(ammoType); if (currentAmmoCount < MaxReserveAmmo) { int ammoNeeded = MaxReserveAmmo - currentAmmoCount; Item ammoItem = ItemManager.Create(ammoType, ammoNeeded); ammoItem?.MoveToContainer(_turret.inventory); _turret.UpdateTotalAmmo(); _turret.EnsureReloaded(); _turret.SendNetworkUpdateImmediate(); } } private int CalculateCurrentAmmoCount(ItemDefinition ammoType) { return _turret.inventory.itemList .Where(item => item.info == ammoType) .Sum(item => item.amount); } private void ScanForTargets() { var entityContents = _turret.targetTrigger.entityContents ??= new HashSet<BaseEntity>(); entityContents.Clear(); int foundTargets = BaseEntity.Query.Server.GetPlayersInSphereFast(transform.position, SearchDistance, AIBrainSenses.playerQueryResults, IsTargetValid); if (foundTargets == 0) return; _turret.authDirty = true; for (int i = 0; i < foundTargets; i++) { var player = AIBrainSenses.playerQueryResults[i]; if (!IsValidTargetPlayer(player)) continue; entityContents.Add(player); } } private bool IsValidTargetPlayer(BasePlayer player) { return Interface.CallHook("OnEntityEnter", _turret.targetTrigger, player) == null && !player.IsSleeping() && (!player.InSafeZone() || player.IsHostile()); } private bool IsTargetValid(BasePlayer player) => player != null && !player.IsNpc; private void PerformTurretCycle() { if (_turret.isClient || _turret.IsDestroyed) return; float deltaTime = (float)_turret.timeSinceLastServerTick; _turret.timeSinceLastServerTick = 0f; if (_turret.IsOnline() && !_turret.IsBeingControlled) { if (!_turret.HasTarget()) { _turret.IdleTick(deltaTime); } else { ExecuteTargetEngagement(); } } _turret.UpdateFacingToTarget(deltaTime); UpdateAmmoStatus(); } private void ExecuteTargetEngagement() { if (Time.realtimeSinceStartup >= _turret.nextVisCheck) { _turret.nextVisCheck = Time.realtimeSinceStartup + Random.Range(0.2f, 0.3f); _turret.targetVisible = _turret.ObjectVisible(_turret.target); if (_turret.targetVisible) _turret.lastTargetSeenTime = Time.realtimeSinceStartup; } _turret.EnsureReloaded(); if (ShouldFireAtTarget()) { var weapon = _turret.GetAttachedWeapon(); FireWeapon(weapon); } ValidateTargetEngagement(); } private bool ShouldFireAtTarget() { return Time.time >= _turret.nextShotTime && _turret.targetVisible && Mathf.Abs(_turret.AngleToTarget(_turret.target, _turret.currentAmmoGravity != 0f)) < _turret.GetMaxAngleForEngagement(); } private void FireWeapon(BaseProjectile weapon) { if (weapon == null) { _turret.nextShotTime = Time.time + 1f; return; } if (weapon.primaryMagazine.contents > 0) { _turret.FireAttachedGun(_turret.AimOffset(_turret.target), _turret.aimCone, null, _turret.PeacekeeperMode() ? _turret.target : null); float delay = weapon.isSemiAuto ? weapon.repeatDelay * 1.5f : weapon.repeatDelay; delay = weapon.ScaleRepeatDelay(delay); _turret.nextShotTime = Time.time + delay; } else { _turret.nextShotTime = Time.time + 5f; } } private void ValidateTargetEngagement() { var targetPlayer = _turret.target as BasePlayer; if (_turret.target != null && (!IsValidSteamPlayer(targetPlayer) || _turret.target.IsDead() || TimeExceedsLastSeen() || DistanceExceedsSightRange() || ShouldTargetBeReset())) { _turret.SetTarget(null); } } private bool TimeExceedsLastSeen() => Time.realtimeSinceStartup - _turret.lastTargetSeenTime > 3f; private bool DistanceExceedsSightRange() => Vector3.Distance(_turret.transform.position, _turret.target.transform.position) > _turret.sightRange; private bool ShouldTargetBeReset() => _turret.PeacekeeperMode() && !_turret.IsEntityHostile(_turret.target); private void UpdateAmmoStatus() { if (_turret.totalAmmoDirty && Time.time > _turret.nextAmmoCheckTime) { _turret.UpdateTotalAmmo(); _turret.totalAmmoDirty = false; _turret.nextAmmoCheckTime = Time.time + 0.5f; } } private void OnDestroy() { StopAllCoroutines(); } }Ajustes Realizados:
- Corrotinas: Utilizei corrotinas (
IEnumerator) ao invés deInvokeRepeatingpara gerenciar os ciclos de escaneamento, ciclo de operação da torre e reabastecimento de munição. - Controle do Ciclo: No
TurretRoutine, cada operação crítica é seguida de umWaitForSecondscorrespondente ao seu intervalo desejado. - Parada de Corrotinas: No método
OnDestroy,StopAllCoroutinesé chamado para garantir que quando o comportamento é destruído, todas as corrotinas também são interrompidas.
Essas modificações permitirão controlar melhor os tempos e potencialmente integrar melhor com um sistema orientado a eventos ou outros scripts que você pode ter em seu ambiente.
- Corrotinas: Utilizei corrotinas (
- User
aqui ele não usa timer, nem corotibe nem invoke, fala desse modo: /*
- Copyright (C) 2024 Game4Freak.io
- This mod is provided under the Game4Freak EULA.
- Full legal terms can be found at https://game4freak.io/eula/ */
using Facepunch; using Newtonsoft.Json; using Oxide.Core; using Rust; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using UnityEngine; using Random = UnityEngine.Random;
namespace Oxide.Plugins { [Info("Raidable Shelters", "VisEntities", "1.7.1")] [Description("Spawns shelters filled with loot for players to raid.")] public class RaidableShelters : RustPlugin { #region Fields
private static RaidableShelters _plugin; private static Configuration _config; private StoredData _storedData; private System.Random _randomGenerator = new System.Random(); private Timer _sheltersRespawnTimer; private const int LAYER_GROUND = Layers.Mask.Terrain | Layers.Mask.World | Layers.Mask.Default; private const int LAYER_PLAYER = Layers.Mask.Player_Server; private const int LAYER_ENTITIES = Layers.Mask.Deployed | Layers.Mask.Construction; private const string PREFAB_AUTO_TURRET = "assets/prefabs/npc/autoturret/autoturret_deployed.prefab"; private const string PREFAB_LEGACY_SHELTER = "assets/prefabs/building/legacy.shelter.wood/legacy.shelter.wood.deployed.prefab"; private const string PREFAB_LANDMINE = "assets/prefabs/deployable/landmine/landmine.prefab"; private const string PREFAB_BEAR_TRAP = "assets/prefabs/deployable/bear trap/beartrap.prefab"; private const float SPAWNABLE_AREA_RADIUS_INSIDE_SHELTER = 1.7f; private static readonly Vector3 _autoTurretPosition = new Vector3(0.084f, 3.146f, 0.481f); private static readonly Vector3 _autoTurretRotation = new Vector3(355.103f, 0f, 0f); #endregion Fields #region Configuration private class Configuration { [JsonProperty("Version")] public string Version { get; set; } [JsonProperty("Enable Debug")] public bool EnableDebug { get; set; } [JsonProperty("Number Of Attempts To Find Shelter Position Near Players")] public int NumberOfAttemptsToFindShelterPositionNearPlayers { get; set; } [JsonProperty("Minimum Search Radius For Shelter Position Around Player")] public float MinimumSearchRadiusForShelterPositionAroundPlayer { get; set; } [JsonProperty("Maximum Search Radius For Shelter Position Around Player")] public float MaximumSearchRadiusForShelterPositionAroundPlayer { get; set; } [JsonProperty("Shelters Respawn Frequency Minutes")] public float SheltersRespawnFrequencyMinutes { get; set; } [JsonProperty("Delay Between Each Shelter Spawn Seconds")] public float DelayBetweenEachShelterSpawnSeconds { get; set; } [JsonProperty("Nearby Entities Avoidance Radius")] public float NearbyEntitiesAvoidanceRadius { get; set; } [JsonProperty("Rocks Avoidance Radius")] public float RocksAvoidanceRadius { get; set; } [JsonProperty("Distance From No Build Zones")] public float DistanceFromNoBuildZones { get; set; } [JsonProperty("Shelter Health")] public float ShelterHealth { get; set; } [JsonProperty("Shelter Lifetime Seconds")] public float ShelterLifetimeSeconds { get; set; } [JsonProperty("Number Of Attempts For Determining Entity Position Inside Shelter")] public int NumberOfAttemptsForDeterminingEntityPositionInsideShelter { get; set; } [JsonProperty("Number Of Attempts For Determining Entity Rotation Inside Shelter")] public int NumberOfAttemptsForDeterminingEntityRotationInsideShelter { get; set; } [JsonProperty("Door")] public DoorConfig Door { get; set; } [JsonProperty("Turret")] public TurretConfig Turret { get; set; } [JsonProperty("Trap")] public TrapConfig Trap { get; set; } [JsonProperty("Notification")] public NotificationConfig Notification { get; set; } [JsonProperty("Interior Entities")] public List<InteriorEntityConfig> InteriorEntities { get; set; } [JsonProperty("Items To Spawn Inside Entity Containers")] public List<ItemInfo> ItemsToSpawnInsideEntityContainers { get; set; } } public class DoorConfig { [JsonProperty("Skin Ids")] public List<ulong> SkinIds { get; set; } } public class TurretConfig { [JsonProperty("Spawn Auto Turret")] public bool SpawnAutoTurret { get; set; } [JsonProperty("Health")] public float Health { get; set; } [JsonProperty("Weapon Short Name")] public string WeaponShortName { get; set; } [JsonProperty("Clip Ammo")] public ItemInfo ClipAmmo { get; set; } [JsonProperty("Reserve Ammo")] public List<ItemInfo> ReserveAmmo { get; set; } [JsonProperty("Attachment Short Names")] public List<string> AttachmentShortNames { get; set; } [JsonProperty("Peacekeeper")] public bool Peacekeeper { get; set; } } public class TrapConfig { [JsonProperty("Spawn Landmines")] public bool SpawnLandmines { get; set; } [JsonProperty("Spawn Bear Traps")] public bool SpawnBearTraps { get; set; } [JsonProperty("Minimum Number Of Traps To Spawn")] public int MinimumNumberOfTrapsToSpawn { get; set; } [JsonProperty("Maximum Number Of Traps To Spawn")] public int MaximumNumberOfTrapsToSpawn { get; set; } [JsonProperty("Minimum Spawn Radius Around Shelter")] public float MinimumSpawnRadiusAroundShelter { get; set; } [JsonProperty("Maximum Spawn Radius Around Shelter")] public float MaximumSpawnRadiusAroundShelter { get; set; } } public class NotificationConfig { [JsonProperty("Notify Surrounding Players Of Shelter Spawn")] public bool NotifySurroundingPlayersOfShelterSpawn { get; set; } [JsonProperty("Radius For Notifying Nearby Players")] public float RadiusForNotifyingNearbyPlayers { get; set; } [JsonProperty("Send As Toast")] public bool SendAsToast { get; set; } } public class InteriorEntityConfig { [JsonProperty("Prefab Name")] public string PrefabName { get; set; } [JsonProperty("Skin Ids")] public List<ulong> SkinIds { get; set; } [JsonProperty("Spawn Chance")] public int SpawnChance { get; set; } [JsonProperty("Minimum Number To Spawn")] public int MinimumNumberToSpawn { get; set; } [JsonProperty("Maximum Number To Spawn")] public int MaximumNumberToSpawn { get; set; } [JsonProperty("Percentage To Fill Container With Items If Present")] public int PercentageToFillContainerWithItemsIfPresent { get; set; } } public class ItemInfo { [JsonProperty("ShortName")] public string ShortName { get; set; } [JsonProperty("Skin Id")] public ulong SkinId { get; set; } [JsonProperty("Minimum Amount")] public int MinimumAmount { get; set; } [JsonProperty("Maximum Amount")] public int MaximumAmount { get; set; } } protected override void LoadConfig() { base.LoadConfig(); _config = Config.ReadObject<Configuration>(); if (string.Compare(_config.Version, Version.ToString()) < 0) UpdateConfig(); SaveConfig(); } protected override void LoadDefaultConfig() { _config = GetDefaultConfig(); } protected override void SaveConfig() { Config.WriteObject(_config, true); } private void UpdateConfig() { PrintWarning("Config changes detected! Updating..."); Configuration defaultConfig = GetDefaultConfig(); if (string.Compare(_config.Version, "1.0.0") < 0) _config = defaultConfig; if (string.Compare(_config.Version, "1.1.0") < 0) { _config.Notification = defaultConfig.Notification; foreach (InteriorEntityConfig interiorEntityConfig in _config.InteriorEntities) { interiorEntityConfig.SkinIds = new List<ulong>(); } } if (string.Compare(_config.Version, "1.2.0") < 0) { _config.Door = defaultConfig.Door; } if (string.Compare(_config.Version, "1.3.0") < 0) { foreach (InteriorEntityConfig interiorEntityConfig in _config.InteriorEntities) { interiorEntityConfig.SpawnChance = 50; } } if (string.Compare(_config.Version, "1.4.0") < 0) { _config.EnableDebug = defaultConfig.EnableDebug; } if (string.Compare(_config.Version, "1.5.0") < 0) { _config.ShelterHealth = defaultConfig.ShelterHealth; } if (string.Compare(_config.Version, "1.6.0") < 0) { _config.Turret = defaultConfig.Turret; } if (string.Compare(_config.Version, "1.7.0") < 0) { _config.Trap = defaultConfig.Trap; } PrintWarning("Config update complete! Updated from version " + _config.Version + " to " + Version.ToString()); _config.Version = Version.ToString(); } private Configuration GetDefaultConfig() { return new Configuration { Version = Version.ToString(), EnableDebug = false, NumberOfAttemptsToFindShelterPositionNearPlayers = 5, MinimumSearchRadiusForShelterPositionAroundPlayer = 20f, MaximumSearchRadiusForShelterPositionAroundPlayer = 50f, NearbyEntitiesAvoidanceRadius = 6f, RocksAvoidanceRadius = 5f, DistanceFromNoBuildZones = 10f, ShelterHealth = 500f, ShelterLifetimeSeconds = 600f, NumberOfAttemptsForDeterminingEntityPositionInsideShelter = 30, NumberOfAttemptsForDeterminingEntityRotationInsideShelter = 30, SheltersRespawnFrequencyMinutes = 60f, DelayBetweenEachShelterSpawnSeconds = 5f, Door = new DoorConfig { SkinIds = new List<ulong> { 809253752, 2246937402, 2483070538, 3076134051 } }, Turret = new TurretConfig { SpawnAutoTurret = false, Health = 1000f, WeaponShortName = "rifle.ak", ClipAmmo = new ItemInfo { ShortName = "ammo.rifle", MinimumAmount = 30, MaximumAmount = 30 }, ReserveAmmo = new List<ItemInfo> { new ItemInfo { ShortName = "ammo.rifle", MinimumAmount = 128, MaximumAmount = 128 } }, AttachmentShortNames = new List<string> { "weapon.mod.lasersight" }, Peacekeeper = false, }, Trap = new TrapConfig { SpawnLandmines = false, SpawnBearTraps = true, MinimumSpawnRadiusAroundShelter = 3f, MaximumSpawnRadiusAroundShelter = 5f, MinimumNumberOfTrapsToSpawn = 1, MaximumNumberOfTrapsToSpawn = 5 }, Notification = new NotificationConfig { NotifySurroundingPlayersOfShelterSpawn = false, RadiusForNotifyingNearbyPlayers = 40f, SendAsToast = true }, InteriorEntities = new List<InteriorEntityConfig> { new InteriorEntityConfig { PrefabName = "assets/prefabs/deployable/woodenbox/woodbox_deployed.prefab", SkinIds = new List<ulong> { 0 }, SpawnChance = 50, MinimumNumberToSpawn = 1, MaximumNumberToSpawn = 3, PercentageToFillContainerWithItemsIfPresent = 20, }, new InteriorEntityConfig { PrefabName = "assets/prefabs/deployable/furnace/furnace.prefab", SkinIds = new List<ulong> { 0 }, SpawnChance = 50, MinimumNumberToSpawn = 1, MaximumNumberToSpawn = 1, PercentageToFillContainerWithItemsIfPresent = 0, }, }, ItemsToSpawnInsideEntityContainers = new List<ItemInfo>() { new ItemInfo { ShortName = "fat.animal", SkinId = 0, MinimumAmount = 10, MaximumAmount = 25, }, new ItemInfo { ShortName = "cloth", SkinId = 0, MinimumAmount = 20, MaximumAmount = 30, }, new ItemInfo { ShortName = "wood", SkinId = 0, MinimumAmount = 200, MaximumAmount = 400, }, new ItemInfo { ShortName = "syringe.medical", SkinId = 0, MinimumAmount = 1, MaximumAmount = 2, }, new ItemInfo { ShortName = "rope", SkinId = 0, MinimumAmount = 1, MaximumAmount = 3, }, new ItemInfo { ShortName = "cctv.camera", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, new ItemInfo { ShortName = "roadsigns", SkinId = 0, MinimumAmount = 1, MaximumAmount = 2, }, new ItemInfo { ShortName = "stones", SkinId = 0, MinimumAmount = 150, MaximumAmount = 350, }, new ItemInfo { ShortName = "metal.fragments", SkinId = 0, MinimumAmount = 30, MaximumAmount = 90, }, new ItemInfo { ShortName = "ammo.grenadelauncher.he", SkinId = 0, MinimumAmount = 1, MaximumAmount = 2, }, new ItemInfo { ShortName = "coffeecan.helmet", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, new ItemInfo { ShortName = "scrap", SkinId = 0, MinimumAmount = 10, MaximumAmount = 25, }, new ItemInfo { ShortName = "icepick.salvaged", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, new ItemInfo { ShortName = "ptz.cctv.camera", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, new ItemInfo { ShortName = "corn", SkinId = 0, MinimumAmount = 3, MaximumAmount = 5, }, new ItemInfo { ShortName = "ammo.rocket.mlrs", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, new ItemInfo { ShortName = "wall.frame.garagedoor", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, new ItemInfo { ShortName = "pistol.revolver", SkinId = 0, MinimumAmount = 1, MaximumAmount = 1, }, } }; } #endregion Configuration #region Stored Data public class StoredData { [JsonProperty("Raidable Shelters")] public Dictionary<ulong, ShelterData> Shelters { get; set; } = new Dictionary<ulong, ShelterData>(); } public class ShelterData { [JsonProperty("Interior Entities")] public List<ulong> InteriorEntities { get; set; } = new List<ulong>(); [JsonProperty("Traps")] public List<ulong> Traps { get; set; } = new List<ulong>(); [JsonProperty("Removal Timer")] public double RemovalTimer { get; set; } } #endregion Stored Data #region Oxide Hooks private void Init() { _plugin = this; _storedData = DataFileUtil.LoadOrCreate<StoredData>(DataFileUtil.GetFilePath()); } private void Unload() { if (_sheltersRespawnTimer != null) _sheltersRespawnTimer.Destroy(); CoroutineUtil.StopAllCoroutines(); KillAllShelters(); _config = null; _plugin = null; } private void OnServerInitialized(bool isStartup) { _sheltersRespawnTimer = timer.Every(_config.SheltersRespawnFrequencyMinutes * 60f, () => { CoroutineUtil.StartCoroutine("RespawnSheltersCoroutine", RespawnSheltersCoroutine()); }); ResumeShelterRemovalTimers(); } #endregion Oxide Hooks #region True PVE Hooks private object CanEntityTakeDamage(LegacyShelter shelter) { if (shelter == null || !API_IsShelterRaidable(shelter)) return null; return true; } #endregion True PVE Hooks #region Shelters Spawning and Setup private IEnumerator RespawnSheltersCoroutine() { foreach (BasePlayer player in BasePlayer.activePlayerList) { if (player != null && !PlayerUtil.Wounded(player) && !PlayerUtil.Sleeping(player) && !PlayerUtil.InBase(player) && !PlayerUtil.Swimming(player) && !PlayerUtil.Boating(player) && !PlayerUtil.Flying(player) && PlayerUtil.OnGround(player) && !PlayerUtil.NearEnemyBase(player) && !TerrainUtil.InRadTown(player.transform.position)) { Vector3 shelterPosition; Quaternion shelterRotation; if (TryFindSuitableShelterSpawnPoint(player.transform.position, _config.MinimumSearchRadiusForShelterPositionAroundPlayer, _config.MaximumSearchRadiusForShelterPositionAroundPlayer, _config.NumberOfAttemptsToFindShelterPositionNearPlayers, out shelterPosition, out shelterRotation)) { LegacyShelter shelter = SpawnLegacyShelter(shelterPosition, shelterRotation, player); if (shelter != null) { NotifyOfShelterSpawn(shelter, player); if (_config.EnableDebug) DrawDebugInfo(shelterPosition, "Shelter spawn successful", ParseColor("#27AE60"), 4f); } } } else if (_config.EnableDebug) { string reason = "unknown reason"; if (PlayerUtil.Wounded(player)) reason = "player wounded"; else if (PlayerUtil.Sleeping(player)) reason = "player sleeping"; else if (PlayerUtil.InBase(player)) reason = "player in base"; else if (PlayerUtil.Swimming(player)) reason = "player swimming"; else if (PlayerUtil.Boating(player)) reason = "player boating"; else if (PlayerUtil.Flying(player)) reason = "player flying"; else if (!PlayerUtil.OnGround(player)) reason = "player not on ground"; else if (PlayerUtil.NearEnemyBase(player)) reason = "player near enemy base"; else if (TerrainUtil.InRadTown(player.transform.position)) reason = "player in radtown"; DrawDebugInfo(player.transform.position, $"Shelter spawn failed:\n{reason}", ParseColor("#E12126")); } yield return CoroutineEx.waitForSeconds(_config.DelayBetweenEachShelterSpawnSeconds); } } private bool TryFindSuitableShelterSpawnPoint(Vector3 center, float minSearchRadius, float maxSearchRadius, int maxAttempts, out Vector3 suitablePosition, out Quaternion suitableRotation) { for (int attempt = 0; attempt < maxAttempts; attempt++) { Vector3 position = TerrainUtil.GetRandomPositionAround(center, minSearchRadius, maxSearchRadius); if (TerrainUtil.InsideRock(position, _config.RocksAvoidanceRadius)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nInside rock", ParseColor("#E12126"), _config.RocksAvoidanceRadius); continue; } if (TerrainUtil.InRadTown(position)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nIn radtown", ParseColor("#E12126")); continue; } if (TerrainUtil.HasEntityNearby(position, _config.NearbyEntitiesAvoidanceRadius, LAYER_ENTITIES)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nNearby entities", ParseColor("#E12126"), _config.NearbyEntitiesAvoidanceRadius); continue; } if (PlayerUtil.HasPlayerNearby(position, _config.NearbyEntitiesAvoidanceRadius)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nNearby players", ParseColor("#E12126"), _config.NearbyEntitiesAvoidanceRadius); continue; } if (TerrainUtil.InWater(position)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nIn water", ParseColor("#E12126")); continue; } if (TerrainUtil.OnRoadOrRail(position)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nOn road or rail", ParseColor("#E12126")); continue; } if (!TerrainUtil.OnTerrain(position, 4f)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nNot on terrain", ParseColor("#E12126"), 4f); continue; } if (TerrainUtil.InNoBuildZone(position, _config.DistanceFromNoBuildZones)) { if (_config.EnableDebug) DrawDebugInfo(position, "Spawn failed:\nIn no-build zone", ParseColor("#E12126"), _config.DistanceFromNoBuildZones); continue; } RaycastHit groundHit; if (TerrainUtil.GetGroundInfo(position, out groundHit, 5f, LAYER_GROUND)) { suitablePosition = groundHit.point; Quaternion surfaceRotation = Quaternion.FromToRotation(Vector3.up, groundHit.normal); Quaternion randomYRotation = Quaternion.Euler(0, Random.Range(0, 360), 0); suitableRotation = surfaceRotation * randomYRotation; return true; } } suitablePosition = Vector3.zero; suitableRotation = Quaternion.identity; return false; } private LegacyShelter SpawnLegacyShelter(Vector3 position, Quaternion rotation, BasePlayer player) { LegacyShelter shelter = GameManager.server.CreateEntity(PREFAB_LEGACY_SHELTER, position, rotation) as LegacyShelter; if (shelter == null) return null; shelter.OnPlaced(player); shelter.Spawn(); shelter.InitializeHealth(_config.ShelterHealth, _config.ShelterHealth); shelter.SendNetworkUpdateImmediate(); // Set the lock owner id to 0 to prevent the player from opening the shelter door. LegacyShelterDoor shelterDoor = shelter.GetChildDoor(); if (shelterDoor != null) { shelterDoor.InitializeHealth(_config.ShelterHealth, _config.ShelterHealth); BaseLock baseLock = shelterDoor.GetSlot(BaseEntity.Slot.Lock) as BaseLock; if (baseLock != null) baseLock.OwnerID = 0; if (_config.Door.SkinIds != null && _config.Door.SkinIds.Count > 0) { shelterDoor.skinID = _config.Door.SkinIds[Random.Range(0, _config.Door.SkinIds.Count)]; } } EntityPrivilege entityPrivilege = shelter.GetEntityPrivilege(); if (entityPrivilege != null) { entityPrivilege.authorizedPlayers.Clear(); entityPrivilege.SendNetworkUpdate(BasePlayer.NetworkQueue.Update); } ShelterData shelterData = new ShelterData { RemovalTimer = Time.realtimeSinceStartup + _config.ShelterLifetimeSeconds }; _storedData.Shelters[shelter.net.ID.Value] = shelterData; if (!SpawnShelterInteriorEntities(shelter, shelterData)) { _storedData.Shelters.Remove(shelter.net.ID.Value); DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData); shelter.Kill(); return null; } if (_config.Turret.SpawnAutoTurret) DeployAutoTurret(shelter, shelterData); if (_config.Trap.SpawnLandmines || _config.Trap.SpawnBearTraps) SpawnTrapsAroundShelter(shelter, shelterData); StartRemovalTimer(shelter, _config.ShelterLifetimeSeconds, shelterData); return shelter; } #endregion Shelters Spawning and Setup #region Shelter Spawn Notification private void NotifyOfShelterSpawn(LegacyShelter shelter, BasePlayer player) { if (_config.Notification.NotifySurroundingPlayersOfShelterSpawn) { List<BasePlayer> nearbyPlayers = Pool.Get<List<BasePlayer>>(); Vis.Entities(shelter.transform.position, _config.Notification.RadiusForNotifyingNearbyPlayers, nearbyPlayers, LAYER_PLAYER, QueryTriggerInteraction.Ignore); foreach (BasePlayer nearbyPlayer in nearbyPlayers) { if (nearbyPlayer == null) continue; if (_config.Notification.SendAsToast) ShowToast(nearbyPlayer, Lang.RaidableShelterSpawned); else MessagePlayer(nearbyPlayer, Lang.RaidableShelterSpawned); } Pool.FreeUnmanaged(ref nearbyPlayers); } else { if (_config.Notification.SendAsToast) ShowToast(player, Lang.RaidableShelterSpawned); else MessagePlayer(player, Lang.RaidableShelterSpawned); } } #endregion Shelter Spawn Notification #region Interior Entities Spawning private bool SpawnShelterInteriorEntities(LegacyShelter shelter, ShelterData shelterData) { Vector3 shelterCenter = shelter.transform.position; float spawnRadius = SPAWNABLE_AREA_RADIUS_INSIDE_SHELTER; bool anyEntitiesSpawned = false; foreach (InteriorEntityConfig interiorEntityConfig in _config.InteriorEntities) { int numberToSpawn = Random.Range(interiorEntityConfig.MinimumNumberToSpawn, interiorEntityConfig.MaximumNumberToSpawn + 1); for (int i = 0; i < numberToSpawn; i++) { if (!ChanceSucceeded(interiorEntityConfig.SpawnChance)) continue; Vector3 randomPosition; int maxPositionAttempts = _config.NumberOfAttemptsForDeterminingEntityPositionInsideShelter; int maxRotationAttempts = _config.NumberOfAttemptsForDeterminingEntityRotationInsideShelter; for (int posAttempt = 0; posAttempt < maxPositionAttempts; posAttempt++) { randomPosition = TerrainUtil.GetRandomPositionAround(shelterCenter, minimumRadius: 0f, maximumRadius: spawnRadius); RaycastHit groundHit; if (!TerrainUtil.GetGroundInfo(randomPosition, out groundHit, 2f, LAYER_GROUND)) continue; randomPosition = groundHit.point; for (int rotAttempt = 0; rotAttempt < maxRotationAttempts; rotAttempt++) { Quaternion surfaceRotation = Quaternion.FromToRotation(Vector3.up, groundHit.normal); Quaternion randomYRotation = Quaternion.Euler(0, Random.Range(0, 360), 0); Quaternion finalRotation = surfaceRotation * randomYRotation; if (!EntityFitsInShelter(shelter, interiorEntityConfig.PrefabName, randomPosition, finalRotation)) continue; if (ExposedHook.OnShelterInteriorEntitySpawn(shelter, interiorEntityConfig.PrefabName, randomPosition, finalRotation)) continue; BaseEntity entity = SpawnInteriorEntity(shelter, randomPosition, finalRotation, interiorEntityConfig); if (entity == null) continue; shelterData.InteriorEntities.Add(entity.net.ID.Value); ExposedHook.OnShelterInteriorEntitySpawned(shelter, entity); anyEntitiesSpawned = true; posAttempt = maxPositionAttempts; break; } } } } return anyEntitiesSpawned; } private bool EntityFitsInShelter(LegacyShelter shelter, string prefabPath, Vector3 potentialPosition, Quaternion potentialRotation) { BaseEntity tempEntity = GameManager.server.CreateEntity(prefabPath, potentialPosition, potentialRotation, false); if (tempEntity == null) return false; OBB bounds = tempEntity.WorldSpaceBounds(); tempEntity.Kill(); Vector3[] corners = new Vector3[8]; corners[0] = bounds.GetPoint(-1f, -1f, -1f); corners[1] = bounds.GetPoint(-1f, -1f, 1f); corners[2] = bounds.GetPoint(-1f, 1f, -1f); corners[3] = bounds.GetPoint(-1f, 1f, 1f); corners[4] = bounds.GetPoint(1f, -1f, -1f); corners[5] = bounds.GetPoint(1f, -1f, 1f); corners[6] = bounds.GetPoint(1f, 1f, -1f); corners[7] = bounds.GetPoint(1f, 1f, 1f); // Ensure the entity is within the shelter bounds and not clipping through or colliding with other objects inside. Collider[] colliders = Physics.OverlapBox(bounds.position, bounds.extents, bounds.rotation, LAYER_ENTITIES); foreach (Collider collider in colliders) { if (collider.gameObject != tempEntity.gameObject && collider.gameObject != shelter.gameObject) return false; } return true; } private BaseEntity SpawnInteriorEntity(LegacyShelter shelter, Vector3 position, Quaternion rotation, InteriorEntityConfig interiorEntityConfig) { BaseEntity entity = GameManager.server.CreateEntity(interiorEntityConfig.PrefabName, position, rotation); if (entity == null) return null; if (interiorEntityConfig.SkinIds != null && interiorEntityConfig.SkinIds.Count > 0) { entity.skinID = interiorEntityConfig.SkinIds[Random.Range(0, interiorEntityConfig.SkinIds.Count)]; } entity.Spawn(); RemoveProblematicComponents(entity); if (entity is StorageContainer storageContainer) PopulateItems(storageContainer.inventory, _config.ItemsToSpawnInsideEntityContainers, interiorEntityConfig.PercentageToFillContainerWithItemsIfPresent); return entity; } #endregion Interior Entities Spawning #region Entity Containers Filling private void PopulateItems(ItemContainer itemContainer, List<ItemInfo> items, int fillContainerPercentage) { Shuffle(items); int slotsToFill = Mathf.CeilToInt(itemContainer.capacity * (fillContainerPercentage / 100f)); for (int i = 0; i < slotsToFill; i++) { if (i >= items.Count) break; ItemInfo itemInfo = items[i]; var itemDefinition = ItemManager.FindItemDefinition(itemInfo.ShortName); if (itemDefinition != null) { int amountToAdd = Random.Range(itemInfo.MinimumAmount, itemInfo.MaximumAmount + 1); Item item = ItemManager.Create(itemDefinition, amountToAdd, itemInfo.SkinId); if (!item.MoveToContainer(itemContainer)) { item.Remove(); } } } } #endregion Entity Container Filling #region Turret Deployment and Setup private void DeployAutoTurret(LegacyShelter shelter, ShelterData shelterData) { AutoTurret autoTurret = SpawnAutoTurret(shelter, _autoTurretPosition, Quaternion.Euler(_autoTurretRotation)); if (autoTurret != null) { AddWeaponToTurret(autoTurret); LoadTurretWithReserveAmmo(autoTurret.inventory); autoTurret.UpdateTotalAmmo(); autoTurret.EnsureReloaded(); autoTurret.SetPeacekeepermode(_config.Turret.Peacekeeper); autoTurret.InitiateStartup(); autoTurret.SendNetworkUpdate(); shelterData.Traps.Add(autoTurret.net.ID.Value); } } private AutoTurret SpawnAutoTurret(LegacyShelter shelter, Vector3 position, Quaternion rotation) { AutoTurret autoTurret = GameManager.server.CreateEntity(PREFAB_AUTO_TURRET, position, rotation) as AutoTurret; if (autoTurret == null) return null; autoTurret.SetParent(shelter); autoTurret.Spawn(); autoTurret.InitializeHealth(_config.Turret.Health, _config.Turret.Health); autoTurret.SendNetworkUpdateImmediate(); RemoveProblematicComponents(autoTurret); HideIOInputsAndOutputs(autoTurret); return autoTurret; } private Item AddWeaponToTurret(AutoTurret autoTurret) { Item item = ItemManager.CreateByName(_config.Turret.WeaponShortName); if (item == null) return null; if (_config.Turret.AttachmentShortNames != null) { foreach (string attachmentShortname in _config.Turret.AttachmentShortNames) { var attachmentItem = ItemManager.CreateByName(attachmentShortname); if (attachmentItem != null) { if (!attachmentItem.MoveToContainer(item.contents)) { attachmentItem.Remove(); } } } } if (!item.MoveToContainer(autoTurret.inventory, 0)) { item.Remove(); return null; } BaseProjectile weapon = item.GetHeldEntity() as BaseProjectile; if (weapon != null) { if (_config.Turret.AttachmentShortNames != null) { // Ensures the weapon's magazine capacity reflects the modifications applied, such as the extended magazine mod. weapon.DelayedModsChanged(); weapon.CancelInvoke(weapon.DelayedModsChanged); } autoTurret.UpdateAttachedWeapon(); autoTurret.CancelInvoke(autoTurret.UpdateAttachedWeapon); if (_config.Turret.ClipAmmo != null) { ItemDefinition loadedAmmoItemDefinition = ItemManager.FindItemDefinition(_config.Turret.ClipAmmo.ShortName); if (loadedAmmoItemDefinition != null) { weapon.primaryMagazine.ammoType = loadedAmmoItemDefinition; int clipAmmoAmount = UnityEngine.Random.Range(_config.Turret.ClipAmmo.MinimumAmount, _config.Turret.ClipAmmo.MaximumAmount + 1); weapon.primaryMagazine.contents = Mathf.Min(weapon.primaryMagazine.capacity, clipAmmoAmount); } } } return item; } private void LoadTurretWithReserveAmmo(ItemContainer autoTurretContainer) { if (_config.Turret.ReserveAmmo == null) return; // Starting from slot 1, because slot 0 is reserved for the weapon. int currentSlot = 1; int maximumAvailableSlots = autoTurretContainer.capacity - 1; foreach (ItemInfo ammo in _config.Turret.ReserveAmmo) { if (currentSlot > maximumAvailableSlots) break; if (ammo.MinimumAmount <= 0 && ammo.MaximumAmount <= 0) continue; ItemDefinition itemDefinition = ItemManager.FindItemDefinition(ammo.ShortName); if (itemDefinition == null) continue; int reserveAmmoAmount = UnityEngine.Random.Range(ammo.MinimumAmount, ammo.MaximumAmount + 1); int amountToAdd = Math.Min(reserveAmmoAmount, itemDefinition.stackable); Item ammoItem = ItemManager.Create(itemDefinition, amountToAdd); if (!ammoItem.MoveToContainer(autoTurretContainer, currentSlot)) { ammoItem.Remove(); } if (ammoItem.parent != autoTurretContainer) { Item destinationItem = autoTurretContainer.GetSlot(currentSlot); if (destinationItem != null) { destinationItem.amount = amountToAdd; destinationItem.MarkDirty(); } ammoItem.Remove(); } currentSlot++; } } #endregion Turret Deployment and Setup #region Traps Spawning private void SpawnTrapsAroundShelter(LegacyShelter shelter, ShelterData shelterData) { Vector3 shelterPosition = shelter.transform.position; int numberOfTraps = Random.Range(_config.Trap.MinimumNumberOfTrapsToSpawn, _config.Trap.MaximumNumberOfTrapsToSpawn + 1); for (int i = 0; i < numberOfTraps; i++) { Vector3 randomPosition = TerrainUtil.GetRandomPositionAround(shelterPosition, _config.Trap.MinimumSpawnRadiusAroundShelter, _config.Trap.MaximumSpawnRadiusAroundShelter); RaycastHit groundHit; if (!TerrainUtil.GetGroundInfo(randomPosition, out groundHit, 5f, LAYER_GROUND)) continue; randomPosition = groundHit.point; Quaternion surfaceRotation = Quaternion.FromToRotation(Vector3.up, groundHit.normal); string trapPrefab = GetRandomTrapPrefab(); if (string.IsNullOrEmpty(trapPrefab)) continue; BaseEntity trapEntity = GameManager.server.CreateEntity(trapPrefab, randomPosition, surfaceRotation); if (trapEntity != null) { trapEntity.SetParent(shelter, true); trapEntity.Spawn(); shelterData.Traps.Add(trapEntity.net.ID.Value); RemoveProblematicComponents(trapEntity); } } } private string GetRandomTrapPrefab() { if (_config.Trap.SpawnLandmines && _config.Trap.SpawnBearTraps) { if (CoinFlip()) return PREFAB_LANDMINE; else return PREFAB_BEAR_TRAP; } else if (_config.Trap.SpawnLandmines) { return PREFAB_LANDMINE; } else if (_config.Trap.SpawnBearTraps) { return PREFAB_BEAR_TRAP; } return null; } #endregion Traps Spawning #region Shelters Removal private void ResumeShelterRemovalTimers() { foreach (var kvp in _storedData.Shelters) { ShelterData shelterData = kvp.Value; LegacyShelter shelter = FindEntityById(kvp.Key) as LegacyShelter; if (shelter != null) { double remainingTime = shelterData.RemovalTimer - Time.realtimeSinceStartup; StartRemovalTimer(shelter, (float)remainingTime, shelterData); } } } private void StartRemovalTimer(LegacyShelter shelter, float lifetimeSeconds, ShelterData shelterData) { ulong shelterId = shelter != null && shelter.net != null ? shelter.net.ID.Value : 0; if (lifetimeSeconds <= 0) { if (shelter != null) shelter.Kill(); if (shelterData != null) { foreach (ulong entityId in shelterData.InteriorEntities) { BaseEntity entity = FindEntityById(entityId); if (entity != null) entity.Kill(); } } if (_storedData.Shelters.ContainsKey(shelterId)) { _storedData.Shelters.Remove(shelterId); DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData); } return; } if (shelter != null) { shelterData.RemovalTimer = Time.realtimeSinceStartup + lifetimeSeconds; DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData); timer.Once(lifetimeSeconds, () => { if (shelter != null) shelter.Kill(); if (shelterData != null) { foreach (ulong entityId in shelterData.InteriorEntities) { BaseEntity entity = FindEntityById(entityId); if (entity != null) entity.Kill(); } } if (_storedData.Shelters.ContainsKey(shelterId)) { _storedData.Shelters.Remove(shelterId); DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData); } }); } } private void KillAllShelters() { foreach (var kvp in _storedData.Shelters) { ShelterData shelterData = kvp.Value; LegacyShelter shelter = BaseNetworkable.serverEntities.Find(new NetworkableId(kvp.Key)) as LegacyShelter; if (shelter != null) { foreach (ulong entityId in shelterData.InteriorEntities) { BaseEntity entity = BaseNetworkable.serverEntities.Find(new NetworkableId(entityId)) as BaseEntity; if (entity != null) entity.Kill(); } foreach (ulong trapId in shelterData.Traps) { BaseEntity trapEntity = FindEntityById(trapId); if (trapEntity != null) trapEntity.Kill(); } shelter.Kill(); } } _storedData.Shelters.Clear(); DataFileUtil.Save(DataFileUtil.GetFilePath(), _storedData); } #endregion Shelters Removal #region Debug private void DrawDebugInfo(Vector3 position, string info, Color color, float radius = 0.5f) { foreach (BasePlayer player in BasePlayer.activePlayerList) { if (player == null || !player.IsAdmin) continue; DrawUtil.Text(player, 10f, color, position + Vector3.up * 1f, $"<size=30>{info}</size>"); DrawUtil.Sphere(player, 10f, color, position, radius); } } #endregion Debug #region Exposed Hooks private static class ExposedHook { public static bool OnShelterInteriorEntitySpawn(LegacyShelter shelter, string prefabName, Vector3 position, Quaternion rotation) { object hookResult = Interface.CallHook("OnShelterInteriorEntitySpawn", shelter, prefabName, position, rotation); return hookResult is bool && (bool)hookResult == false; } public static void OnShelterInteriorEntitySpawned(LegacyShelter shelter, BaseEntity entity) { Interface.CallHook("OnShelterInteriorEntitySpawned", shelter, entity); } } #endregion Exposed Hooks #region API private bool API_IsShelterRaidable(LegacyShelter shelter) { return _storedData.Shelters.ContainsKey(shelter.net.ID.Value); } #endregion API #region Helper Functions private static bool CoinFlip() { return Random.Range(0, 2) == 0; } private BaseEntity FindEntityById(ulong id) { return BaseNetworkable.serverEntities.Find(new NetworkableId(id)) as BaseEntity; } private static void HideIOInputsAndOutputs(IOEntity ioEntity) { foreach (var input in ioEntity.inputs) input.type = IOEntity.IOType.Generic; foreach (var output in ioEntity.outputs) output.type = IOEntity.IOType.Generic; } private static BaseEntity FindBaseEntityForPrefab(string prefabName) { var prefab = GameManager.server.FindPrefab(prefabName); if (prefab == null) return null; return prefab.GetComponent<BaseEntity>(); } private static void Shuffle<T>(List<T> list) { int remainingItems = list.Count; while (remainingItems > 1) { remainingItems--; int randomIndex = _plugin._randomGenerator.Next(remainingItems + 1); T itemToSwap = list[randomIndex]; list[randomIndex] = list[remainingItems]; list[remainingItems] = itemToSwap; } } private static void RemoveProblematicComponents(BaseEntity entity) { UnityEngine.Object.DestroyImmediate(entity.GetComponent<DestroyOnGroundMissing>()); UnityEngine.Object.DestroyImmediate(entity.GetComponent<GroundWatch>()); } private static bool ChanceSucceeded(int percentage) { return Random.Range(0, 100) < percentage; } private static Color ParseColor(string hexColor) { if (ColorUtility.TryParseHtmlString(hexColor, out Color color)) return color; return Color.white; } #endregion Helper Functions #region Helper Classes public static class TerrainUtil { public static bool OnTopology(Vector3 position, TerrainTopology.Enum topology) { return (TerrainMeta.TopologyMap.GetTopology(position) & (int)topology) != 0; } public static bool OnRoadOrRail(Vector3 position) { var combinedTopology = TerrainTopology.Enum.Road | TerrainTopology.Enum.Roadside | TerrainTopology.Enum.Rail | TerrainTopology.Enum.Railside; return OnTopology(position, combinedTopology); } public static bool OnTerrain(Vector3 position, float radius) { return Physics.CheckSphere(position, radius, Layers.Mask.Terrain, QueryTriggerInteraction.Ignore); } public static bool InNoBuildZone(Vector3 position, float radius) { return Physics.CheckSphere(position, radius, Layers.Mask.Prevent_Building); } public static bool InWater(Vector3 position) { return WaterLevel.Test(position, false, false); } public static bool InsideRock(Vector3 position, float radius) { List<Collider> colliders = Pool.Get<List<Collider>>(); Vis.Colliders(position, radius, colliders, Layers.Mask.World, QueryTriggerInteraction.Ignore); bool result = false; foreach (Collider collider in colliders) { if (collider.name.Contains("rock", CompareOptions.OrdinalIgnoreCase) || collider.name.Contains("cliff", CompareOptions.OrdinalIgnoreCase) || collider.name.Contains("formation", CompareOptions.OrdinalIgnoreCase)) { result = true; break; } } Pool.FreeUnmanaged(ref colliders); return result; } public static bool InRadTown(Vector3 position, bool shouldDisplayOnMap = false) { foreach (var monumentInfo in TerrainMeta.Path.Monuments) { bool inBounds = monumentInfo.IsInBounds(position); bool hasLandMarker = true; if (shouldDisplayOnMap) hasLandMarker = monumentInfo.shouldDisplayOnMap; if (inBounds && hasLandMarker) return true; } return OnTopology(position, TerrainTopology.Enum.Monument); } public static bool HasEntityNearby(Vector3 position, float radius, LayerMask mask, string prefabName = null) { List<Collider> hitColliders = Pool.Get<List<Collider>>(); GamePhysics.OverlapSphere(position, radius, hitColliders, mask, QueryTriggerInteraction.Ignore); bool hasEntityNearby = false; foreach (Collider collider in hitColliders) { BaseEntity entity = collider.gameObject.ToBaseEntity(); if (entity != null) { if (prefabName == null || entity.PrefabName == prefabName) { hasEntityNearby = true; break; } } } Pool.FreeUnmanaged(ref hitColliders); return hasEntityNearby; } public static Vector3 GetRandomPositionAround(Vector3 center, float minimumRadius, float maximumRadius, bool adjustToWaterHeight = false) { Vector3 randomDirection = Random.onUnitSphere; float randomDistance = Random.Range(minimumRadius, maximumRadius); Vector3 randomPosition = center + randomDirection * randomDistance; if (adjustToWaterHeight) randomPosition.y = TerrainMeta.WaterMap.GetHeight(randomPosition); else randomPosition.y = TerrainMeta.HeightMap.GetHeight(randomPosition); return randomPosition; } public static bool GetGroundInfo(Vector3 startPosition, out RaycastHit raycastHit, float range, LayerMask mask) { return Physics.Linecast(startPosition + new Vector3(0.0f, range, 0.0f), startPosition - new Vector3(0.0f, range, 0.0f), out raycastHit, mask); } public static bool GetGroundInfo(Vector3 startPosition, out RaycastHit raycastHit, float range, LayerMask mask, Transform ignoreTransform = null) { startPosition.y += 0.25f; range += 0.25f; raycastHit = default; RaycastHit hit; if (!GamePhysics.Trace(new Ray(startPosition, Vector3.down), 0f, out hit, range, mask, QueryTriggerInteraction.UseGlobal, null)) return false; if (ignoreTransform != null && hit.collider != null && (hit.collider.transform == ignoreTransform || hit.collider.transform.IsChildOf(ignoreTransform))) { return GetGroundInfo(startPosition - new Vector3(0f, 0.01f, 0f), out raycastHit, range, mask, ignoreTransform); } raycastHit = hit; return true; } } private static class PlayerUtil { public static BasePlayer FindById(ulong playerId) { return RelationshipManager.FindByID(playerId); } public static bool HasPlayerNearby(Vector3 position, float radius) { return BaseNetworkable.HasCloseConnections(position, radius); } public static bool AreTeammates(ulong firstPlayerId, ulong secondPlayerId) { RelationshipManager.PlayerTeam team = RelationshipManager.ServerInstance.FindPlayersTeam(firstPlayerId); if (team != null && team.members.Contains(secondPlayerId)) return true; return false; } public static bool Sleeping(BasePlayer player) { return player != null && player.IsSleeping(); } public static bool Swimming(BasePlayer player) { return player != null && player.IsSwimming(); } public static bool Boating(BasePlayer player) { return player != null && player.isMounted && player.GetMounted().mountTimeStatType == BaseMountable.MountStatType.Boating; } public static bool Flying(BasePlayer player) { return player != null && player.isMounted && player.GetMounted().mountTimeStatType == BaseMountable.MountStatType.Flying; } public static bool Driving(BasePlayer player) { return player != null && player.isMounted && player.GetMounted().mountTimeStatType == BaseMountable.MountStatType.Driving; } public static bool InBase(BasePlayer player) { return player != null && player.IsBuildingAuthed(); } public static bool NearEnemyBase(BasePlayer player) { return player != null && player.IsNearEnemyBase(); } public static bool Wounded(BasePlayer player) { return player != null && player.IsWounded(); } public static bool Crawling(BasePlayer player) { return player != null && player.IsCrawling(); } public static bool OnGround(BasePlayer player) { return player != null && player.IsOnGround(); } } public static class CoroutineUtil { private static readonly Dictionary<string, Coroutine> _activeCoroutines = new Dictionary<string, Coroutine>(); public static void StartCoroutine(string coroutineName, IEnumerator coroutineFunction) { StopCoroutine(coroutineName); Coroutine coroutine = ServerMgr.Instance.StartCoroutine(coroutineFunction); _activeCoroutines[coroutineName] = coroutine; } public static void StopCoroutine(string coroutineName) { if (_activeCoroutines.TryGetValue(coroutineName, out Coroutine coroutine)) { if (coroutine != null) ServerMgr.Instance.StopCoroutine(coroutine); _activeCoroutines.Remove(coroutineName); } } public static void StopAllCoroutines() { foreach (string coroutineName in _activeCoroutines.Keys.ToArray()) { StopCoroutine(coroutineName); } } } public static class DrawUtil { public static void Box(BasePlayer player, float durationSeconds, Color color, Vector3 position, float radius) { player.SendConsoleCommand("ddraw.box", durationSeconds, color, position, radius); } public static void Sphere(BasePlayer player, float durationSeconds, Color color, Vector3 position, float radius) { player.SendConsoleCommand("ddraw.sphere", durationSeconds, color, position, radius); } public static void Line(BasePlayer player, float durationSeconds, Color color, Vector3 fromPosition, Vector3 toPosition) { player.SendConsoleCommand("ddraw.line", durationSeconds, color, fromPosition, toPosition); } public static void Arrow(BasePlayer player, float durationSeconds, Color color, Vector3 fromPosition, Vector3 toPosition, float headSize) { player.SendConsoleCommand("ddraw.arrow", durationSeconds, color, fromPosition, toPosition, headSize); } public static void Text(BasePlayer player, float durationSeconds, Color color, Vector3 position, string text) { player.SendConsoleCommand("ddraw.text", durationSeconds, color, position, text); } } public class DataFileUtil { private const string FOLDER = ""; public static string GetFilePath(string filename = null) { if (filename == null) filename = _plugin.Name; return Path.Combine(FOLDER, filename); } public static string[] GetAllFilePaths() { string[] filePaths = Interface.Oxide.DataFileSystem.GetFiles(FOLDER); for (int i = 0; i < filePaths.Length; i++) { // Remove the redundant '.json' from the filepath. This is necessary because the filepaths are returned with a double '.json'. filePaths[i] = filePaths[i].Substring(0, filePaths[i].Length - 5); } return filePaths; } public static bool Exists(string filePath) { return Interface.Oxide.DataFileSystem.ExistsDatafile(filePath); } public static T Load<T>(string filePath) where T : class, new() { T data = Interface.Oxide.DataFileSystem.ReadObject<T>(filePath); if (data == null) data = new T(); return data; } public static T LoadIfExists<T>(string filePath) where T : class, new() { if (Exists(filePath)) return Load<T>(filePath); else return null; } public static T LoadOrCreate<T>(string filePath) where T : class, new() { T data = LoadIfExists<T>(filePath); if (data == null) data = new T(); return data; } public static void Save<T>(string filePath, T data) { Interface.Oxide.DataFileSystem.WriteObject<T>(filePath, data); } public static void Delete(string filePath) { Interface.Oxide.DataFileSystem.DeleteDataFile(filePath); } } #endregion Helper Classes #region Commands private static class Cmd { public const string TEST = "rs.test"; } [ChatCommand(Cmd.TEST)] private void cmdTest(BasePlayer player, string cmd, string[] args) { if (player == null || !player.IsAdmin) return; RaycastHit groundHit; if (TerrainUtil.GetGroundInfo(player.transform.position, out groundHit, 10f, LAYER_GROUND)) { Vector3 spawnPosition = groundHit.point; Quaternion surfaceRotation = Quaternion.FromToRotation(Vector3.up, groundHit.normal); Quaternion randomYRotation = Quaternion.Euler(0, Random.Range(0, 360), 0); Quaternion spawnRotation = surfaceRotation * randomYRotation; LegacyShelter shelter = SpawnLegacyShelter(spawnPosition, spawnRotation, player); if (shelter != null) { MessagePlayer(player, Lang.TestShelterSpawned); } } } #endregion Commands #region Localization private class Lang { public const string RaidableShelterSpawned = "RaidableShelterSpawned"; public const string TestShelterSpawned = "TestShelterSpawned"; } protected override void LoadDefaultMessages() { lang.RegisterMessages(new Dictionary<string, string> { [Lang.RaidableShelterSpawned] = "A raidable shelter has spawned nearby!", [Lang.TestShelterSpawned] = "A test shelter has been spawned at your location." }, this, "en"); } private static string GetMessage(BasePlayer player, string messageKey, params object[] args) { string message = _plugin.lang.GetMessage(messageKey, _plugin, player.UserIDString); if (args.Length > 0) message = string.Format(message, args); return message; } public static void MessagePlayer(BasePlayer player, string messageKey, params object[] args) { string message = GetMessage(player, messageKey, args); _plugin.SendReply(player, message); } public static void ShowToast(BasePlayer player, string messageKey, GameTip.Styles style = GameTip.Styles.Blue_Normal, params object[] args) { string message = GetMessage(player, messageKey, args); player.SendConsoleCommand("gametip.showtoast", (int)style, message); } #endregion Localization }}
- Assistant
Para criar um sistema no estilo do exemplo que você forneceu, sem o uso de
InvokeRepeating,Timer, ou corrotinas, podemos utilizar uma abordagem de atualização manual em pontos específicos do ciclo de vida de jogo, onde os métodos necessários são chamados diretamente conforme necessário.No contexto de um plugin Oxide para Rust, as chamadas de atualização geralmente são associadas a eventos específicos ou hooks, como
OnServerInitialized,OnPlayerTick, etc. Em um script que depende de periodicidade sem usar corrotinas ou métodos de repetição, cada função que precisa ser executada periodicamente teria que ser gerida de forma manual ou reativa, baseada em eventos do jogo.Abaixo está um exemplo de como você poderia estruturar seu
TurretMonoBehaviourusando este tipo de abordagem:public class TurretMonoBehaviour : MonoBehaviour { private AutoTurret _turret; private const float SearchDistance = 15f; private const int MaxReserveAmmo = 1000; private float lastTurretCycleTime; private float lastTargetScanTime; private float lastAmmoRefillTime; void Start() { InitializeTurret(); } private void InitializeTurret() { _turret = GetComponent<AutoTurret>(); _turret.targetTrigger.GetComponent<SphereCollider>().enabled = false; _turret.SetPeacekeepermode(false); _turret.InitiateStartup(); _turret.SetIsOnline(true); _turret.SetTarget(null); _turret.isLootable = false; _turret.SendNetworkUpdateImmediate(); lastTurretCycleTime = Time.time; lastTargetScanTime = Time.time; lastAmmoRefillTime = Time.time; } void Update() { float currentTime = Time.time; UpdateTurretCycle(currentTime); UpdateTargetScan(currentTime); UpdateAmmoRefill(currentTime); } private void UpdateTurretCycle(float currentTime) { float turretCycleInterval = 0.1f; // equivalent to 10 times per second if (currentTime - lastTurretCycleTime >= turretCycleInterval) { PerformTurretCycle(); lastTurretCycleTime = currentTime; } } private void UpdateTargetScan(float currentTime) { float targetScanInterval = 2f; // target scan every 2 seconds if (currentTime - lastTargetScanTime >= targetScanInterval) { ScanForTargets(); lastTargetScanTime = currentTime; } } private void UpdateAmmoRefill(float currentTime) { float ammoRefillInterval = 30f; // refill ammo every 30 seconds if (currentTime - lastAmmoRefillTime >= ammoRefillInterval) { RefillAmmo(); lastAmmoRefillTime = currentTime; } } private void RefillAmmo() { if (_turret.AttachedWeapon is not BaseProjectile baseProjectile || baseProjectile.primaryMagazine?.ammoType == null) return; var ammoType = baseProjectile.primaryMagazine.ammoType; int currentAmmoCount = _turret.inventory.itemList .Where(item => item.info == ammoType) .Sum(item => item.amount); if (currentAmmoCount < MaxReserveAmmo) { int ammoNeeded = MaxReserveAmmo - currentAmmoCount; Item ammoItem = ItemManager.Create(ammoType, ammoNeeded); ammoItem?.MoveToContainer(_turret.inventory); _turret.UpdateTotalAmmo(); _turret.EnsureReloaded(); _turret.SendNetworkUpdateImmediate(); } } private void ScanForTargets() { var entityContents = _turret.targetTrigger.entityContents ??= new HashSet<BaseEntity>(); entityContents.Clear(); int foundTargets = BaseEntity.Query.Server.GetPlayersInSphereFast(transform.position, SearchDistance, AIBrainSenses.playerQueryResults, IsTargetValid); if (foundTargets == 0) return; _turret.authDirty = true; for (int i = 0; i < foundTargets; i++) { var player = AIBrainSenses.playerQueryResults[i]; if (!IsValidTargetPlayer(player)) continue; entityContents.Add(player); } } private bool IsValidTargetPlayer(BasePlayer player) { return Interface.CallHook("OnEntityEnter", _turret.targetTrigger, player) == null && !player.IsSleeping() && (!player.InSafeZone() || player.IsHostile()); } private bool IsTargetValid(BasePlayer player) => player != null && !player.IsNpc; private void PerformTurretCycle() { if (_turret.isClient || _turret.IsDestroyed) return; float deltaTime = (float)_turret.timeSinceLastServerTick; _turret.timeSinceLastServerTick = 0f; if (_turret.IsOnline() && !_turret.IsBeingControlled) { if (!_turret.HasTarget()) { _turret.IdleTick(deltaTime); } else { ExecuteTargetEngagement(); } } _turret.UpdateFacingToTarget(deltaTime); UpdateAmmoStatus(); } private void ExecuteTargetEngagement() { if (Time.realtimeSinceStartup >= _turret.nextVisCheck) { _turret.nextVisCheck = Time.realtimeSinceStartup + UnityEngine.Random.Range(0.2f, 0.3f); _turret.targetVisible = _turret.ObjectVisible(_turret.target); if (_turret.targetVisible) _turret.lastTargetSeenTime = Time.realtimeSinceStartup; } _turret.EnsureReloaded(); if (ShouldFireAtTarget()) { var weapon = _turret.GetAttachedWeapon(); FireWeapon(weapon); } ValidateTargetEngagement(); } private bool ShouldFireAtTarget() { return Time.time >= _turret.nextShotTime && _turret.targetVisible && Mathf.Abs(_turret.AngleToTarget(_turret.target, _turret.currentAmmoGravity != 0f)) < _turret.GetMaxAngleForEngagement(); } private void FireWeapon(BaseProjectile weapon) { if (weapon == null) { _turret.nextShotTime = Time.time + 1f; return; } if (weapon.primaryMagazine.contents > 0) { _turret.FireAttachedGun(_turret.AimOffset(_turret.target), _turret.aimCone, null, _turret.PeacekeeperMode() ? _turret.target : null); float delay = weapon.isSemiAuto ? weapon.repeatDelay * 1.5f : weapon.repeatDelay; delay = weapon.ScaleRepeatDelay(delay); _turret.nextShotTime = Time.time + delay; } else { _turret.nextShotTime = Time.time + 5f; } } private void ValidateTargetEngagement() { var targetPlayer = _turret.target as BasePlayer; if (_turret.target != null && (!IsValidSteamPlayer(targetPlayer) || _turret.target.IsDead() || TimeExceedsLastSeen() || DistanceExceedsSightRange() || ShouldTargetBeReset())) { _turret.SetTarget(null); } } private bool TimeExceedsLastSeen() => Time.realtimeSinceStartup - _turret.lastTargetSeenTime > 3f; private bool DistanceExceedsSightRange() => Vector3.Distance(_turret.transform.position, _turret.target.transform.position) > _turret.sightRange; private bool ShouldTargetBeReset() => _turret.PeacekeeperMode() && !_turret.IsEntityHostile(_turret.target); private void UpdateAmmoStatus() { if (_turret.totalAmmoDirty && Time.time > _turret.nextAmmoCheckTime) { _turret.UpdateTotalAmmo(); _turret.totalAmmoDirty = false; _turret.nextAmmoCheckTime = Time.time + 0.5f; } } }Explicações de Implementação:
- Sem loops ou temporizadores explícitos: Em vez de usar
InvokeRepeatingou corrotinas, o gerenciamento das operações periódicas é realizado com base em verificações de tempo usandoTime.time. - Método Update: Utiliza o método Unity
Update, que é chamado a cada frame, para verificar se cada operação periódica deve ser executada com base nos intervalos de tempo definidos. - Separação das Lógicas: Cada bloco funcional do ciclo de atualização (
UpdateTurretCycle,UpdateTargetScan, eUpdateAmmoRefill) detém suas próprias verificações de tempo e lógicas específicas para manter a clareza e eficiência.
Este método mantém o código eficiente ao evitar chamadas redundantes e se adapta a um fluxo contínuo de funcionamento por atualização de frames sem sobrecarregar o sistema com chamadas adicionais frequentes, oferecendo um modelo alternativo sem depender de timers ou corrotinas explícitas.
- Sem loops ou temporizadores explícitos: Em vez de usar