sing Facepunch;
using Network;
using ProtoBuf;
using Rust;
using UnityEngine;
public class HitInfo : Pool.IPooled
{
public BaseEntity Initiator;
code
public BaseEntity WeaponPrefab;
public AttackEntity Weapon;
public bool DoHitEffects = true;
public bool DoDecals = true;
public bool IsPredicting;
public bool UseProtection = true;
public Connection Predicted;
public bool DidHit;
public BaseEntity HitEntity;
public uint HitBone;
public uint HitPart;
public uint HitMaterial;
public Vector3 HitPositionWorld;
public Vector3 HitPositionLocal;
public Vector3 HitNormalWorld;
public Vector3 HitNormalLocal;
public Vector3 PointStart;
public Vector3 PointEnd;
public int ProjectileID;
public int ProjectileHits;
public float ProjectileDistance;
public float ProjectileIntegrity;
public float ProjectileTravelTime;
public float ProjectileTrajectoryMismatch;
public Vector3 ProjectileVelocity;
public Projectile ProjectilePrefab;
public PhysicMaterial material;
public DamageProperties damageProperties;
public DamageTypeList damageTypes = new DamageTypeList();
public bool CanGather;
public bool DidGather;
public float gatherScale = 1f;
public BasePlayer InitiatorPlayer
{
get
{
if (!Initiator)
{
return null;
}
return Initiator.ToPlayer();
}
}
public Vector3 attackNormal => (PointEnd - PointStart).normalized;
public bool hasDamage => damageTypes.Total() > 0f;
public bool InitiatorParented
{
get
{
if (Initiator != null && Initiator.GetParentEntity() != null)
{
return Initiator.GetParentEntity().IsValid();
}
return false;
}
}
public bool HitEntityParented
{
get
{
if (HitEntity != null && HitEntity.GetParentEntity() != null)
{
return HitEntity.GetParentEntity().IsValid();
}
return false;
}
}
public bool isHeadshot
{
get
{
if (HitEntity == null)
{
return false;
}
BaseCombatEntity baseCombatEntity = HitEntity as BaseCombatEntity;
if (baseCombatEntity == null)
{
return false;
}
if (baseCombatEntity.skeletonProperties == null)
{
return false;
}
SkeletonProperties.BoneProperty boneProperty = baseCombatEntity.skeletonProperties.FindBone(HitBone);
if (boneProperty == null)
{
return false;
}
return boneProperty.area == HitArea.Head;
}
}
public Translate.Phrase bonePhrase
{
get
{
if (HitEntity == null)
{
return null;
}
BaseCombatEntity baseCombatEntity = HitEntity as BaseCombatEntity;
if (baseCombatEntity == null)
{
return null;
}
if (baseCombatEntity.skeletonProperties == null)
{
return null;
}
return baseCombatEntity.skeletonProperties.FindBone(HitBone)?.name;
}
}
public string boneName
{
get
{
Translate.Phrase phrase = bonePhrase;
if (phrase != null)
{
return phrase.english;
}
return "N/A";
}
}
public HitArea boneArea
{
get
{
if (HitEntity == null)
{
return (HitArea)(-1);
}
BaseCombatEntity baseCombatEntity = HitEntity as BaseCombatEntity;
if (baseCombatEntity == null)
{
return (HitArea)(-1);
}
return baseCombatEntity.SkeletonLookup(HitBone);
}
}
public void EnterPool()
{
Clear();
}
public void LeavePool()
{
}
public void Clear()
{
Initiator = null;
WeaponPrefab = null;
Weapon = null;
DoHitEffects = true;
DoDecals = true;
IsPredicting = false;
UseProtection = true;
Predicted = null;
DidHit = false;
HitEntity = null;
HitBone = 0u;
HitPart = 0u;
HitMaterial = 0u;
HitPositionWorld = default(Vector3);
HitPositionLocal = default(Vector3);
HitNormalWorld = default(Vector3);
HitNormalLocal = default(Vector3);
PointStart = default(Vector3);
PointEnd = default(Vector3);
ProjectileID = 0;
ProjectileHits = 0;
ProjectileDistance = 0f;
ProjectileIntegrity = 0f;
ProjectileTravelTime = 0f;
ProjectileTrajectoryMismatch = 0f;
ProjectileVelocity = default(Vector3);
ProjectilePrefab = null;
material = null;
damageProperties = null;
damageTypes.Clear();
CanGather = false;
DidGather = false;
gatherScale = 1f;
}
public void CopyFrom(HitInfo other)
{
Initiator = other.Initiator;
WeaponPrefab = other.WeaponPrefab;
Weapon = other.Weapon;
DoHitEffects = other.DoHitEffects;
DoDecals = other.DoDecals;
IsPredicting = other.IsPredicting;
UseProtection = other.UseProtection;
Predicted = other.Predicted;
DidHit = other.DidHit;
HitEntity = other.HitEntity;
HitBone = other.HitBone;
HitPart = other.HitPart;
HitMaterial = other.HitMaterial;
HitPositionWorld = other.HitPositionWorld;
HitPositionLocal = other.HitPositionLocal;
HitNormalWorld = other.HitNormalWorld;
HitNormalLocal = other.HitNormalLocal;
PointStart = other.PointStart;
PointEnd = other.PointEnd;
ProjectileID = other.ProjectileID;
ProjectileHits = other.ProjectileHits;
ProjectileDistance = other.ProjectileDistance;
ProjectileIntegrity = other.ProjectileIntegrity;
ProjectileTravelTime = other.ProjectileTravelTime;
ProjectileTrajectoryMismatch = other.ProjectileTrajectoryMismatch;
ProjectileVelocity = other.ProjectileVelocity;
ProjectilePrefab = other.ProjectilePrefab;
material = other.material;
damageProperties = other.damageProperties;
for (int i = 0; i < damageTypes.types.Length; i++)
{
damageTypes.types[i] = other.damageTypes.types[i];
}
CanGather = other.CanGather;
DidGather = other.DidGather;
gatherScale = other.gatherScale;
}
public bool IsProjectile()
{
return ProjectileID != 0;
}
public void Init(BaseEntity attacker, BaseEntity target, DamageType type, float damageAmount, Vector3 vhitPosition)
{
Initiator = attacker;
HitEntity = target;
HitPositionWorld = vhitPosition;
if (attacker != null)
{
PointStart = attacker.transform.position;
}
damageTypes.Add(type, damageAmount);
}
public HitInfo()
{
}
public HitInfo(BaseEntity attacker, BaseEntity target, DamageType type, float damageAmount, Vector3 vhitPosition)
{
Init(attacker, target, type, damageAmount, vhitPosition);
}
public HitInfo(BaseEntity attacker, BaseEntity target, DamageType type, float damageAmount)
{
Init(attacker, target, type, damageAmount, target.transform.position);
}
public void LoadFromAttack(Attack attack, bool serverSide)
{
HitEntity = null;
PointStart = attack.pointStart;
PointEnd = attack.pointEnd;
if (attack.hitID.IsValid)
{
DidHit = true;
if (serverSide)
{
HitEntity = BaseNetworkable.serverEntities.Find(attack.hitID) as BaseEntity;
}
if ((bool)HitEntity)
{
HitBone = attack.hitBone;
HitPart = attack.hitPartID;
}
}
DidHit = true;
HitPositionLocal = attack.hitPositionLocal;
HitPositionWorld = attack.hitPositionWorld;
HitNormalLocal = attack.hitNormalLocal.normalized;
HitNormalWorld = attack.hitNormalWorld.normalized;
HitMaterial = attack.hitMaterialID;
if (attack.srcParentID.IsValid)
{
BaseEntity baseEntity = null;
if (serverSide)
{
baseEntity = BaseNetworkable.serverEntities.Find(attack.srcParentID) as BaseEntity;
}
if (baseEntity.IsValid())
{
PointStart = baseEntity.transform.TransformPoint(PointStart);
}
}
if (attack.dstParentID.IsValid)
{
BaseEntity baseEntity2 = null;
if (serverSide)
{
baseEntity2 = BaseNetworkable.serverEntities.Find(attack.dstParentID) as BaseEntity;
}
if (baseEntity2.IsValid())
{
PointEnd = baseEntity2.transform.TransformPoint(PointEnd);
HitPositionWorld = baseEntity2.transform.TransformPoint(HitPositionWorld);
HitNormalWorld = baseEntity2.transform.TransformDirection(HitNormalWorld);
}
}
}
public Vector3 PositionOnRay(Vector3 position)
{
Ray ray = new Ray(PointStart, attackNormal);
if (ProjectilePrefab == null)
{
return RayEx.ClosestPoint(ray, position);
}
if (new Sphere(position, ProjectilePrefab.thickness).Trace(ray, out var hit))
{
return hit.point;
}
return position;
}
public Vector3 HitPositionOnRay()
{
return PositionOnRay(HitPositionWorld);
}
public bool IsNaNOrInfinity()
{
if (PointStart.IsNaNOrInfinity())
{
return true;
}
if (PointEnd.IsNaNOrInfinity())
{
return true;
}
if (HitPositionWorld.IsNaNOrInfinity())
{
return true;
}
if (HitPositionLocal.IsNaNOrInfinity())
{
return true;
}
if (HitNormalWorld.IsNaNOrInfinity())
{
return true;
}
if (HitNormalLocal.IsNaNOrInfinity())
{
return true;
}
if (ProjectileVelocity.IsNaNOrInfinity())
{
return true;
}
if (float.IsNaN(ProjectileDistance))
{
return true;
}
if (float.IsInfinity(ProjectileDistance))
{
return true;
}
if (float.IsNaN(ProjectileIntegrity))
{
return true;
}
if (float.IsInfinity(ProjectileIntegrity))
{
return true;
}
if (float.IsNaN(ProjectileTravelTime))
{
return true;
}
if (float.IsInfinity(ProjectileTravelTime))
{
return true;
}
if (float.IsNaN(ProjectileTrajectoryMismatch))
{
return true;
}
if (float.IsInfinity(ProjectileTrajectoryMismatch))
{
return true;
}
return false;
}
}
Assistant
The code you've shared appears to be a C# class definition for a game, possibly related to a combat or physics system, given its focus on handling hit information and damage interactions. Here's a breakdown of some key aspects of the HitInfo class:
Fields and Properties:
The class contains a variety of fields and properties to store information about an attack or hit event, such as the attacker (Initiator), the weapon used (Weapon), the entity that was hit (HitEntity), hit location (HitPositionWorld), and more.
It also provides computed properties like InitiatorPlayer to easily access the player who initiated the attack if applicable.
Hit Details:
It keeps detailed information about the hit, such as whether it was a headshot (isHeadshot) or if the attacker or hit entity is parented to another entity.
Damage Handling:
Manages damage information through the damageTypes list, which stores the types and amounts of damage dealt.
Pooling System:
Implements Pool.IPooled, indicating it might be part of a pooling system to manage memory efficiently in environments like game engines.
Utility Methods:
Includes methods for copying data from another HitInfo instance (CopyFrom), checking if the event involved a projectile (IsProjectile), and initializing hit information (Init).
LoadFromAttack method appears to load state from an Attack instance, which provides information about an attempted attack.
Validation:
IsNaNOrInfinity checks numerical fields to ensure they contain valid numbers, preventing computational errors due to invalid data.
Using this class in a game engine like Unity would involve creating instances during combat events or physics interactions to track and process details about what happened, who was involved, and the outcomes of those interactions. The use of pooling can help manage performance by reusing instances rather than constantly allocating and deallocating memory.
If you have any specific questions or need further explanation about a part of the code, feel free to ask!
User
using ConVar;
using Oxide.Core;
using UnityEngine;
public class AttackEntity : HeldEntity
{
[Header("Attack Entity")]
public float deployDelay = 1f;
code
Assistant
The code you posted is another C# class definition, AttackEntity, which builds on a HeldEntity class. This particular class seems to handle various functionalities related to an attack-capable entity in a game, likely built within Unity. Here are the key components and functionality embedded in this class:
Key Features and Functionalities
Attack Mechanics:
Parameters for controlling attack behavior such as deployDelay, repeatDelay, and animationDelay.
A nextAttackTime parameter to handle attack cooldowns, preventing players from attacking too frequently.
NPC Interaction:
Configuration for how NPCs (non-player characters) might use the entity, with fields like effectiveRange and npcDamageScale.
Combat Control:
Methods like StartAttackCooldown, ResetAttackCooldown, and HasAttackCooldown manage the cooldown periods between successive attacks.
Methods like VerifyClientRPC and VerifyClientAttack involve validating player actions, presumably to prevent cheating hacks or exploits.
Anti-Cheat Measures:
Comprehensive anti-cheat validation (VerifyClientRPC, ValidateEyePos) to ensure players aren't exploiting unintended mechanics, like attacking from abnormal positions or manipulating attack cooldowns.
Integration with an AntiHack system to log and potentially act upon detected anomalies or suspicious player behaviors.
Attack Stats and AI:
Methods to retrieve and modify attack stats: GetAttackStats, ModifyAIAim.
UsingInfiniteAmmoCheat property checks for whether the player has admin privileges and an "infinite ammo" cheat enabled.
Sound and Feedback:
Use of sound definitions for reloading and providing third-person auditory feedback upon melees (reloadSounds, thirdPersonMeleeSound).
Handling Equipment and State Changes:
Using to manage state transitions and cooldown related to equipping or using the attack entity.
User
using System;
using System.Collections.Generic;
using ConVar;
using Rust;
using UnityEngine;
public class Projectile : BaseMonoBehaviour
{
public struct Modifier
{
public float damageScale;
code
Assistant
The code you've shared is a C# class definition for a Projectile in a game, probably from a game engine like Unity. This class is responsible for simulating the behavior and interaction of projectiles, such as arrows or bullets, in the game environment. Here's an overview of its main features and functionalities:
Key Features
Attributes and Physics:
Initial Velocity and Drag: Defines how fast the projectile moves initially and how much it slows down due to air resistance.
Gravity Modifier: Adjusts how gravity affects the projectile, allowing for varying trajectory arcs.
Thickness: Could be used for collision detection, representing the "size" of the projectile in terms of its impact area.
Impact and Interaction Rules:
Remain in World: If true, the projectile will stay in the world upon hitting a target instead of despawning immediately.
Stick Probability, Break Probability, and Condition Loss: Probabilities and rules governing how the projectile behaves upon hitting a surface (e.g., whether it sticks, breaks, or loses condition).
Ricochet and Penetration: Determines the chance of ricocheting off surfaces and its power to penetrate objects/materials.
Damage System:
Utilizes properties such as damageProperties, damageDistances, and damageMultipliers to calculate the potential damage a projectile can inflict based on distance and other modifiers.
Includes methods to calculate and apply damage with different multipliers and offsets (CalculateDamage).
Rendering and Effects:
Configurations for how the projectile is rendered (rendererToScale, firstPersonRenderer) and whether it creates decals.
Handles audio effects, like flyby or impact sounds, using SoundDefinition.
Special Modifiers and Settings:
Use of Modifier struct for scaling damage and distance.
Handles special conditions like "no headshots" or invisibility for certain projectile types.
Advanced Behaviors:
Tumble and Swim: Provides for spinning or undulating motions via parameters such as , , , and .
User
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using UnityEngine.Bindings;
namespace UnityEngine;
[NativeHeader("Modules/Physics/PhysicMaterial.h")]
public class PhysicMaterial : Object
{
public extern float bounciness
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
code
public extern float dynamicFriction
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
public extern float staticFriction
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
public extern PhysicMaterialCombine frictionCombine
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
public extern PhysicMaterialCombine bounceCombine
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
[Obsolete("Use PhysicMaterial.bounciness instead (UnityUpgradable) -> bounciness")]
public float bouncyness
{
get
{
return bounciness;
}
set
{
bounciness = value;
}
}
[Obsolete("Anisotropic friction is no longer supported since Unity 5.0.", true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public Vector3 frictionDirection2
{
get
{
return Vector3.zero;
}
set
{
}
}
[Obsolete("Anisotropic friction is no longer supported since Unity 5.0.", true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public float dynamicFriction2
{
get
{
return 0f;
}
set
{
}
}
[Obsolete("Anisotropic friction is no longer supported since Unity 5.0.", true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public float staticFriction2
{
get
{
return 0f;
}
set
{
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Anisotropic friction is no longer supported since Unity 5.0.", true)]
public Vector3 frictionDirection
{
get
{
return Vector3.zero;
}
set
{
}
}
public PhysicMaterial()
{
Internal_CreateDynamicsMaterial(this, "DynamicMaterial");
}
public PhysicMaterial(string name)
{
Internal_CreateDynamicsMaterial(this, name);
}
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void Internal_CreateDynamicsMaterial([Writable] PhysicMaterial mat, string name);
Assistant
The C# code you've shared is a class definition for PhysicMaterial, which is a part of Unity's physics system. This class is used to define the physical properties of materials in Unity, affecting how they interact with other objects in the physics engine. Here's a detailed look at its components and functionality:
Key Features
Properties:
Bounciness: Controls the "bounciness" of an object, essentially how much it will bounce off surfaces.
Dynamic Friction: The friction force when an object is moving.
Static Friction: The friction force required to start moving a stationary object.
Friction Combine and Bounce Combine: Define how the friction and bounciness are computed when two materials interact. This can typically be set to average, multiply, minimum, or maximum, affecting the results of physical interactions.
Obsolete Features:
The class contains some deprecated settings, such as bouncyness, frictionDirection2, dynamicFriction2, and staticFriction2. These properties are maintained for backward compatibility but are not used in newer versions of Unity.
Anisotropic friction (direction-dependent friction) is no longer supported, so the related fields are marked as obsolete and are not functional.
Constructors:
Offers two constructors to initialize a PhysicMaterial. One creates a default "DynamicMaterial," and the other allows specifying a name for the material.
Internal Callbacks:
Uses [MethodImpl(MethodImplOptions.InternalCall)] for property accessors and methods. This indicates that the actual functionality is implemented in the Unity engine's native code, not directly in C#.
Native Integration:
Marked with attributes like [NativeHeader], linking it to Unity's underlying C++ implementation. This integration is what enables Unity's powerful real-time physics calculations.
Usage Context
PhysicMaterial is typically used in Unity to adjust how objects physically behave in a scene — for example, how they slide, roll, or bounce off each other. You can assign a PhysicMaterial to a Collider component on objects to dictate their physical interactions.
User
using System;
using UnityEngine;
[CreateAssetMenu(menuName = "Rust/Damage Properties")]
public class DamageProperties : ScriptableObject
{
[Serializable]
public class HitAreaProperty
{
public HitArea area = HitArea.Head;
code
public float damage = 1f;
}
public DamageProperties fallback;
[Horizontal(1, 0)]
public HitAreaProperty[] bones;
public float GetMultiplier(HitArea area)
{
for (int i = 0; i < bones.Length; i++)
{
HitAreaProperty hitAreaProperty = bones[i];
if (hitAreaProperty.area == area)
{
return hitAreaProperty.damage;
}
}
if (!fallback)
{
return 1f;
}
return fallback.GetMultiplier(area);
}
public void ScaleDamage(HitInfo info)
{
HitArea boneArea = info.boneArea;
if (boneArea != (HitArea)(-1) && boneArea != 0)
{
info.damageTypes.ScaleAll(GetMultiplier(boneArea));
}
}
}
using System.Collections.Generic;
namespace Rust;
public class DamageTypeList
{
public float[] types = new float[25];
code
Assistant
The code you've provided is a collection of classes from a C# project, likely part of a game engine or a complex game system such as Rust. Here’s a breakdown of the classes and their functionalities:
DamageProperties Class
Purpose: Defines damage characteristics for different body parts (hit areas) in a game.
Components:
HitAreaProperty: Nested class that associates hit areas (like head, torso) with damage multipliers.
fallback: A reference to another DamageProperties for default fallback values.
GetMultiplier(area): Retrieves the damage multiplier for a specific hit area.
ScaleDamage(info): Scales damage on a HitInfo object based on the hit area.
DamageTypeList Class
Purpose: Manages a list of different damage types and their respective amounts.
Features:
Methods to set, get, add, and scale damage amounts for each type.
Functions to check existence (Has), compute total damage (Total), and clear all damage values (Clear).
Methods to handle complex operations like determining the majority damage type, checking if it's melee-type, and cloning the list.
BaseCombatEntity Class
Purpose: Represents entities that can engage in combat, like players or NPCs (non-player characters), including handling health, damage, and interaction rules.
Components:
LifeState: Enum managing alive or dead states.
Faction: Enum for entity classification (Player, Bandit, etc.).
Health Management: Fields and properties to handle health (_health, _maxHealth) and methods to manage it (Health, MaxHealth, Hurt).
Pickup and Repair: Mechanics for items associated with the entity, including pickup rules and repair methodologies.
Damage Handling: Functions like OnAttacked, Hurt, ScaleDamage manage how the entity processes incoming damage.
RPC and Event Handling: Manages networked function calls (RPC_PickupStart) and state saving/loading for persistence.
User
using System;
using System.Collections.Generic;
using System.Linq;
using ConVar;
using Facepunch;
using Facepunch.Rust;
using Network;
using Oxide.Core;
using ProtoBuf;
using Rust;
using UnityEngine;
using UnityEngine.Assertions;
public class AutoTurret : ContainerIOEntity, IRemoteControllable
{
public static class TurretFlags
{
public const Flags Peacekeeper = Flags.Reserved1;
}
code
Assistant
The C# class you've shared appears to be an implementation of an AutoTurret for the game Rust, which is an entity in the game world capable of detecting, targeting, and engaging enemies. This class is quite extensive and involves multiple aspects of functionality related to detection, targeting, firing, and interaction with players. Here's a detailed look at its key components and systems:
Key Features and Functionalities
Core Components:
Turret Configuration: Includes various GameObject references for effects (gun_fire_effect, bulletEffect), sound definitions (turnLoopDef, focusCameraDef), and toggle sounds like peacekeeperToggleSound.
Transforms and Positions: Important components like eyePos, muzzlePos, and aiming controls (gun_yaw, gun_pitch) govern how the turret physically aims and fires.
Authorization and RPC Calls:
Authorized Players: A HashSet of PlayerNameID for managing which players can access or modify the turret settings.
RPC Handling: Methods to handle remote procedure calls from players (OnRpcMessage, AddSelfAuthorize, RemoveSelfAuthorize) to perform actions such as authorizing a player or toggling settings.
Targeting System:
Targeting: Methods to scan for potential targets (TargetScan), validate targets as visible (ObjectVisible), and determine potential hostile entities (IsEntityHostile).
Aim and Fire Logic: A complex system for adjusting the turret's aim using methods like UpdateAiming and firing logic via FireAttachedGun and FireGun.
State and Control:
Online/Offline States: Control methods like SetIsOnline and InitiateShutdown manage the operational state of the turret.
Remote Controllability: Implements IRemoteControllable, allowing for manual control over the network and interactions with clients remote controlling the turret.
User
quero calcular o total de dano que a autoturret vai levar, e diminuir o dano da vida dela manualmente aqui:
object OnEntityTakeDamage(AutoTurret autoTurret, HitInfo hitInfo)
{
code
return true;
}
Assistant
To calculate the total damage an AutoTurret will take from the HitInfo and manually apply that damage to its health, you'll need to modify the OnEntityTakeDamage method. This method is presumably a hook that gets called whenever the AutoTurret takes damage. Here’s how you could implement it:
Access the Damage: Retrieve the total amount of damage from the HitInfo object.
Apply Damage to the Turret's Health: Reduce the AutoTurret's health by this amount.
Handle Health Updates: Ensure the turret's health is updated and that any necessary checks (like whether the turret is destroyed) are performed.
Here's a basic implementation of how this might look:
csharp
object OnEntityTakeDamage(AutoTurret autoTurret, HitInfo hitInfo)
{
if (autoTurret == null || hitInfo == null)
{
return null; // Ensure you don't process null objects
}
// Calculate the total damage from the HitInfo
float totalDamage = hitInfo.damageTypes.Total();
// Access the turret's current health
float currentHealth = autoTurret.health;
// Calculate the new health by subtracting the damage
float newHealth = currentHealth - totalDamage;
// Clamp the health to a minimum of 0 (prevent negative health)
newHealth = Mathf.Max(0, newHealth);
// Update the turret's health
autoTurret.health = newHealth;
// Check if the turret should be destroyed
if (autoTurret.health <= 0)
{
// The turret is destroyed, handle destruction logic
autoTurret.Die(hitInfo);
}
else
{
// If the turret is not dead, handle any additional logic (e.g., updating UI, logging)
autoTurret.SendNetworkUpdate();
}
return true; // Indicate the event was handled
}
public float repeatDelay = 0.5f;
public float animationDelay;
[Header("NPCUsage")]
public float effectiveRange = 1f;
public float npcDamageScale = 1f;
public float attackLengthMin = -1f;
public float attackLengthMax = -1f;
public float attackSpacing;
public float aiAimSwayOffset;
public float aiAimCone;
public bool aiOnlyInRange;
public float CloseRangeAddition;
public float MediumRangeAddition;
public float LongRangeAddition;
public bool CanUseAtMediumRange = true;
public bool CanUseAtLongRange = true;
public SoundDefinition[] reloadSounds;
public SoundDefinition thirdPersonMeleeSound;
[Header("Recoil Compensation")]
public float recoilCompDelayOverride;
public bool wantsRecoilComp;
public bool showCrosshairOnTutorial;
public bool noHeadshots;
public EncryptedValue<float> nextAttackTime = float.NegativeInfinity;
protected bool UsingInfiniteAmmoCheat
{
get
{
BasePlayer ownerPlayer = GetOwnerPlayer();
if (ownerPlayer == null || (!ownerPlayer.IsAdmin && !ownerPlayer.IsDeveloper))
{
return false;
}
return ownerPlayer.GetInfoBool("player.infiniteammo", defaultVal: false);
}
}
public float NextAttackTime => nextAttackTime;
public virtual Vector3 GetInheritedVelocity(BasePlayer player, Vector3 direction)
{
return Vector3.zero;
}
public virtual float AmmoFraction()
{
return 0f;
}
public virtual bool CanReload()
{
return false;
}
public virtual bool ServerIsReloading()
{
return false;
}
public virtual void ServerReload()
{
}
public virtual bool ServerTryReload(IAmmoContainer ammoSource)
{
return true;
}
public virtual void TopUpAmmo()
{
}
public virtual Vector3 ModifyAIAim(Vector3 eulerInput, float swayModifier = 1f)
{
return eulerInput;
}
public virtual void GetAttackStats(HitInfo info)
{
}
public void StartAttackCooldownRaw(float cooldown)
{
nextAttackTime = UnityEngine.Time.time + cooldown;
}
public void StartAttackCooldown(float cooldown)
{
nextAttackTime = CalculateCooldownTime(nextAttackTime, cooldown, catchup: true);
}
public void ResetAttackCooldown()
{
nextAttackTime = float.NegativeInfinity;
}
public bool HasAttackCooldown()
{
return UnityEngine.Time.time < (float)nextAttackTime;
}
protected float GetAttackCooldown()
{
return Mathf.Max((float)nextAttackTime - UnityEngine.Time.time, 0f);
}
protected float GetAttackIdle()
{
return Mathf.Max(UnityEngine.Time.time - (float)nextAttackTime, 0f);
}
protected float CalculateCooldownTime(float nextTime, float cooldown, bool catchup)
{
float time = UnityEngine.Time.time;
float num = 0f;
if (base.isServer)
{
BasePlayer ownerPlayer = GetOwnerPlayer();
num += 0.1f;
num += cooldown * 0.1f;
num += (ownerPlayer ? ownerPlayer.desyncTimeClamped : 0.1f);
num += Mathf.Max(UnityEngine.Time.deltaTime, UnityEngine.Time.smoothDeltaTime);
}
nextTime = ((nextTime < 0f) ? Mathf.Max(0f, time + cooldown - num) : ((!(time - nextTime <= num)) ? Mathf.Max(nextTime + cooldown, time + cooldown - num) : Mathf.Min(nextTime + cooldown, time + cooldown)));
return nextTime;
}
protected bool VerifyClientRPC(BasePlayer player)
{
if (player == null)
{
Debug.LogWarning("Received RPC from null player");
return false;
}
BasePlayer ownerPlayer = GetOwnerPlayer();
if (ownerPlayer == null)
{
AntiHack.Log(player, AntiHackType.AttackHack, "Owner not found (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "owner_missing");
return false;
}
if (ownerPlayer != player)
{
AntiHack.Log(player, AntiHackType.AttackHack, "Player mismatch (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "player_mismatch");
return false;
}
if (player.IsDead())
{
AntiHack.Log(player, AntiHackType.AttackHack, "Player dead (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "player_dead");
return false;
}
if (player.IsWounded())
{
AntiHack.Log(player, AntiHackType.AttackHack, "Player down (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "player_down");
return false;
}
if (player.IsSleeping())
{
AntiHack.Log(player, AntiHackType.AttackHack, "Player sleeping (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "player_sleeping");
return false;
}
if (player.desyncTimeRaw > ConVar.AntiHack.maxdesync)
{
AntiHack.Log(player, AntiHackType.AttackHack, "Player stalled (" + base.ShortPrefabName + " with " + player.desyncTimeRaw + "s)");
player.stats.combat.LogInvalid(player, this, "player_stalled");
return false;
}
Item ownerItem = GetOwnerItem();
if (ownerItem == null)
{
AntiHack.Log(player, AntiHackType.AttackHack, "Item not found (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "item_missing");
return false;
}
if (ownerItem.isBroken)
{
AntiHack.Log(player, AntiHackType.AttackHack, "Item broken (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "item_broken");
return false;
}
return true;
}
protected virtual bool VerifyClientAttack(BasePlayer player)
{
if (!VerifyClientRPC(player))
{
return false;
}
if (HasAttackCooldown())
{
AntiHack.Log(player, AntiHackType.CooldownHack, "T-" + GetAttackCooldown() + "s (" + base.ShortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "attack_cooldown");
return false;
}
return true;
}
protected bool ValidateEyePos(BasePlayer player, Vector3 eyePos, bool checkLineOfSight = true)
{
object obj = Interface.CallHook("OnEyePosValidate", this, player, eyePos, checkLineOfSight);
if (obj is bool)
{
return (bool)obj;
}
bool flag = true;
if (eyePos.IsNaNOrInfinity())
{
string shortPrefabName = base.ShortPrefabName;
AntiHack.Log(player, AntiHackType.EyeHack, "Contains NaN (" + shortPrefabName + ")");
player.stats.combat.LogInvalid(player, this, "eye_nan");
flag = false;
}
if (ConVar.AntiHack.eye_protection > 0)
{
if (ConVar.AntiHack.eye_protection >= 1)
{
float num = player.GetParentVelocity().magnitude + player.GetMountVelocity().magnitude;
float num2 = ((((player.HasParent() || player.isMounted) ? ConVar.AntiHack.eye_distance_parented_mounted_forgiveness : 0f) + player.estimatedSpeed > 0f) ? ConVar.AntiHack.eye_forgiveness : 0f);
float num3 = num + num2;
float num4 = player.tickHistory.Distance(player, eyePos);
if (num4 > num3)
{
string shortPrefabName2 = base.ShortPrefabName;
AntiHack.Log(player, AntiHackType.EyeHack, "Distance (" + shortPrefabName2 + " on attack with " + num4 + "m > " + num3 + "m)");
player.stats.combat.LogInvalid(player, this, "eye_distance");
flag = false;
}
}
if (ConVar.AntiHack.eye_protection >= 3)
{
float num5 = Mathf.Abs(player.GetMountVelocity().y + player.GetParentVelocity().y) + player.GetJumpHeight();
float num6 = Mathf.Abs(player.eyes.position.y - eyePos.y);
if (num6 > num5)
{
string shortPrefabName3 = base.ShortPrefabName;
AntiHack.Log(player, AntiHackType.EyeHack, "Altitude (" + shortPrefabName3 + " on attack with " + num6 + "m > " + num5 + "m)");
player.stats.combat.LogInvalid(player, this, "eye_altitude");
flag = false;
}
}
if (checkLineOfSight)
{
int num7 = 2162688;
if (ConVar.AntiHack.eye_terraincheck)
{
num7 |= 0x800000;
}
if (ConVar.AntiHack.eye_vehiclecheck)
{
num7 |= 0x8000000;
}
if (ConVar.AntiHack.eye_protection >= 2)
{
Vector3 center = player.eyes.center;
Vector3 position = player.eyes.position;
Vector3 vector = eyePos;
if (!GamePhysics.LineOfSightRadius(center, position, num7, ConVar.AntiHack.eye_losradius) || !GamePhysics.LineOfSightRadius(position, vector, num7, ConVar.AntiHack.eye_losradius))
{
string shortPrefabName4 = base.ShortPrefabName;
string[] obj2 = new string[8] { "Line of sight (", shortPrefabName4, " on attack) ", null, null, null, null, null };
Vector3 vector2 = center;
obj2[3] = vector2.ToString();
obj2[4] = " ";
vector2 = position;
obj2[5] = vector2.ToString();
obj2[6] = " ";
vector2 = vector;
obj2[7] = vector2.ToString();
AntiHack.Log(player, AntiHackType.EyeHack, string.Concat(obj2));
player.stats.combat.LogInvalid(player, this, "eye_los");
flag = false;
}
}
if (ConVar.AntiHack.eye_protection >= 4 && !player.HasParent())
{
Vector3 position2 = player.eyes.position;
Vector3 vector3 = eyePos;
float num8 = Vector3.Distance(position2, vector3);
Collider col;
if (num8 > ConVar.AntiHack.eye_noclip_cutoff)
{
if (AntiHack.TestNoClipping(player, position2, vector3, player.NoClipRadius(ConVar.AntiHack.eye_noclip_margin), ConVar.AntiHack.eye_noclip_backtracking, out col))
{
string shortPrefabName5 = base.ShortPrefabName;
string[] obj3 = new string[6] { "NoClip (", shortPrefabName5, " on attack) ", null, null, null };
Vector3 vector2 = position2;
obj3[3] = vector2.ToString();
obj3[4] = " ";
vector2 = vector3;
obj3[5] = vector2.ToString();
AntiHack.Log(player, AntiHackType.EyeHack, string.Concat(obj3));
player.stats.combat.LogInvalid(player, this, "eye_noclip");
flag = false;
}
}
else if (num8 > 0.01f && AntiHack.TestNoClipping(player, position2, vector3, 0.1f, ConVar.AntiHack.eye_noclip_backtracking, out col))
{
string shortPrefabName6 = base.ShortPrefabName;
string[] obj4 = new string[6] { "NoClip (", shortPrefabName6, " on attack) ", null, null, null };
Vector3 vector2 = position2;
obj4[3] = vector2.ToString();
obj4[4] = " ";
vector2 = vector3;
obj4[5] = vector2.ToString();
AntiHack.Log(player, AntiHackType.EyeHack, string.Concat(obj4));
player.stats.combat.LogInvalid(player, this, "eye_noclip");
flag = false;
}
}
}
if (!flag)
{
AntiHack.AddViolation(player, AntiHackType.EyeHack, ConVar.AntiHack.eye_penalty);
}
else if (ConVar.AntiHack.eye_protection >= 5 && !player.HasParent() && !player.isMounted)
{
player.eyeHistory.PushBack(eyePos);
}
}
return flag;
}
public override void OnHeldChanged()
{
base.OnHeldChanged();
StartAttackCooldown(deployDelay * 0.9f);
}
}
OnHeldChanged
Server-Specific Validations:
Checks like IsAdmin and IsDeveloper ensure that certain functionalities or cheats are only available to designated users.
ServerTryReload and related methods provide interfaces for managing ammo and reloading behavior server-side.
Integration Context
The class likely plays an integral role in managing both player and NPC combat interactions within the game environment, ensuring a balance between fair play and responsiveness. It highlights a robust attempt to manage various aspects like cooldown timing, effective range, AI usage, and anti-cheat mechanisms. With its dependencies on BasePlayer, AntiHack, and GamePhysics, along with its sound systems integration, it appears to be well-crafted for a nuanced gameplay experience.
If you need a further breakdown of certain functionalities or components within this class, feel free to ask!
public float damageOffset;
public float distanceScale;
public float distanceOffset;
public static Modifier Default = new Modifier
{
damageScale = 1f,
damageOffset = 0f,
distanceScale = 1f,
distanceOffset = 0f
};
}
public const float moveDeltaTime = 1f / 32f;
public const float lifeTime = 8f;
[Header("Attributes")]
public Vector3 initialVelocity;
public float drag;
public float gravityModifier = 1f;
public float thickness;
[Tooltip("This projectile will raycast for this many units, and then become a projectile. This is typically done for bullets.")]
public float initialDistance;
[Header("Impact Rules")]
public bool remainInWorld;
[Range(0f, 1f)]
public float stickProbability = 1f;
[Range(0f, 1f)]
public float breakProbability;
[Range(0f, 1f)]
public float conditionLoss;
[Range(0f, 1f)]
public float ricochetChance;
public float penetrationPower = 1f;
[Range(0f, 1f)]
public float waterIntegrityLoss = 0.1f;
[Header("Damage")]
public DamageProperties damageProperties;
[Horizontal(2, -1)]
public MinMax damageDistances = new MinMax(10f, 100f);
[Horizontal(2, -1)]
public MinMax damageMultipliers = new MinMax(1f, 0.8f);
public List<DamageTypeEntry> damageTypes = new List<DamageTypeEntry>();
[Header("Rendering")]
public ScaleRenderer rendererToScale;
public ScaleRenderer firstPersonRenderer;
public bool createDecals = true;
[Header("Effects")]
public bool doDefaultHitEffects = true;
[Header("Audio")]
public SoundDefinition flybySound;
public float flybySoundDistance = 7f;
public SoundDefinition closeFlybySound;
public float closeFlybyDistance = 3f;
[Header("Tumble")]
public float tumbleSpeed;
public Vector3 tumbleAxis = Vector3.right;
[Header("Swim")]
public Vector3 swimScale;
public Vector3 swimSpeed;
[NonSerialized]
public BasePlayer owner;
[NonSerialized]
public AttackEntity sourceWeaponPrefab;
[NonSerialized]
public Projectile sourceProjectilePrefab;
[NonSerialized]
public ItemModProjectile mod;
[NonSerialized]
public int projectileID;
[NonSerialized]
public int seed;
[NonSerialized]
public bool clientsideEffect;
[NonSerialized]
public bool clientsideAttack;
[NonSerialized]
public float integrity = 1f;
[NonSerialized]
public float maxDistance = float.PositiveInfinity;
[NonSerialized]
public Modifier modifier = Modifier.Default;
[NonSerialized]
public bool invisible;
[NonSerialized]
public bool noheadshots;
[NonSerialized]
public float currentThickness;
private static uint _fleshMaterialID;
private static uint _waterMaterialID;
private static uint cachedWaterString;
public void CalculateDamage(HitInfo info, Modifier mod, float scale)
{
float num = damageMultipliers.Lerp(mod.distanceOffset + mod.distanceScale * damageDistances.x, mod.distanceOffset + mod.distanceScale * damageDistances.y, info.ProjectileDistance);
float num2 = scale * (mod.damageOffset + mod.damageScale * num);
foreach (DamageTypeEntry damageType in damageTypes)
{
info.damageTypes.Add(damageType.type, damageType.amount * num2);
}
if (ConVar.Global.developer > 0)
{
Debug.Log(" Projectile damage: " + info.damageTypes.Total() + " (scalar=" + num2 + ")");
}
}
public static uint FleshMaterialID()
{
if (_fleshMaterialID == 0)
{
_fleshMaterialID = StringPool.Get("flesh");
}
return _fleshMaterialID;
}
public static uint WaterMaterialID()
{
if (_waterMaterialID == 0)
{
_waterMaterialID = StringPool.Get("Water");
}
return _waterMaterialID;
}
public static bool IsWaterMaterial(string hitMaterial)
{
if (cachedWaterString == 0)
{
cachedWaterString = StringPool.Get("Water");
}
if (StringPool.Get(hitMaterial) == cachedWaterString)
{
return true;
}
return false;
}
public static bool ShouldStopProjectile(RaycastHit hit)
{
BaseEntity entity = RaycastHitEx.GetEntity(hit);
if (entity != null && !entity.ShouldBlockProjectiles())
{
return false;
}
return true;
}
}
tumbleSpeed
tumbleAxis
swimScale
swimSpeed
Integrity Management: Tracks the projectile's "health," which decreases over time or depending on interactions (e.g., water integrity loss).
Helper Methods:
Methods like FleshMaterialID, WaterMaterialID, IsWaterMaterial, and ShouldStopProjectile provide utility functions for material interactions and determining projectile stopping conditions.
NPC and AI Integration:
Uses attributes like owner, sourceWeaponPrefab, and sourceProjectilePrefab to connect the projectile to the player or AI entity that fired it.
Usage Context
In a game, this class would be used to simulate and control the behavior of projectiles from the moment they are fired until they hit a target or their lifetime expires (lifeTime). It handles physics simulations, damage calculations, and environmental interactions (like passing through materials). The code also enforces rules for how projectiles respond upon collision, whether sticking, breaking, or penetrating surfaces.
This class plays a critical role in determining how combat feels in a game—whether it's precise, dramatic, or realistic—and supports a wide range of interactions and customizations for different types of projectiles.
If you have specific questions or need further explanations about any part of this code, feel free to ask!
}
For instance, a high bounciness value might be set on a "rubber ball" object to make it bounce realistically when dropped. Adjusting dynamicFriction and staticFriction helps simulate realistic sliding or sticking behaviors between surfaces.
This class encapsulates the parameters that can be fine-tuned to develop a comprehensive, physics-driven experience, supporting everything from basic movement mechanics to advanced physical simulations in games or simulations built with Unity.
If you have specific questions about any part of this class or how it would be used in a Unity project, feel free to ask!
public void Set(DamageType index, float amount)
{
types[(int)index] = amount;
}
public float Get(DamageType index)
{
return types[(int)index];
}
public void Add(DamageType index, float amount)
{
Set(index, Get(index) + amount);
}
public void Scale(DamageType index, float amount)
{
Set(index, Get(index) * amount);
}
public bool Has(DamageType index)
{
return Get(index) > 0f;
}
public float Total()
{
float num = 0f;
for (int i = 0; i < types.Length; i++)
{
float num2 = types[i];
if (!float.IsNaN(num2) && !float.IsInfinity(num2))
{
num += num2;
}
}
return num;
}
public void Clear()
{
for (int i = 0; i < types.Length; i++)
{
types[i] = 0f;
}
}
public void Add(List<DamageTypeEntry> entries)
{
foreach (DamageTypeEntry entry in entries)
{
Add(entry.type, entry.amount);
}
}
public void ScaleAll(float amount)
{
for (int i = 0; i < types.Length; i++)
{
Scale((DamageType)i, amount);
}
}
public DamageType GetMajorityDamageType()
{
int result = 0;
float num = 0f;
for (int i = 0; i < types.Length; i++)
{
float num2 = types[i];
if (!float.IsNaN(num2) && !float.IsInfinity(num2) && !(num2 < num))
{
result = i;
num = num2;
}
}
return (DamageType)result;
}
public bool Contains(DamageType damage)
{
if (damage < DamageType.Generic || (int)damage >= types.Length)
{
return false;
}
float num = types[(int)damage];
if (!float.IsNaN(num) && !float.IsInfinity(num))
{
return num > 0f;
}
return false;
}
public bool IsMeleeType()
{
return GetMajorityDamageType().IsMeleeType();
}
public bool IsBleedCausing()
{
return GetMajorityDamageType().IsBleedCausing();
}
public bool IsConsideredAnAttack()
{
return GetMajorityDamageType().IsConsideredAnAttack();
}
public DamageTypeList Clone()
{
DamageTypeList damageTypeList = new DamageTypeList();
for (int i = 0; i < types.Length; i++)
{
damageTypeList.types[i] = types[i];
}
return damageTypeList;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using ConVar;
using Facepunch;
using Facepunch.Rust;
using Network;
using Oxide.Core;
using ProtoBuf;
using Rust;
using UnityEngine;
using UnityEngine.Assertions;
public class BaseCombatEntity : BaseEntity
{
public enum LifeState
{
Alive,
Dead
}
code
[Serializable]
public enum Faction
{
Default,
Player,
Bandit,
Scientist,
Horror
}
[Serializable]
public struct Pickup
{
public bool enabled;
[ItemSelector(ItemCategory.All)]
public ItemDefinition itemTarget;
public int itemCount;
[Tooltip("Should we set the condition of the item based on the health of the picked up entity")]
public bool setConditionFromHealth;
[Tooltip("How much to reduce the item condition when picking up")]
public float subtractCondition;
[Tooltip("Must have building access to pick up")]
public bool requireBuildingPrivilege;
[Tooltip("Must have hammer equipped to pick up")]
public bool requireHammer;
[Tooltip("Inventory Must be empty (if applicable) to be picked up")]
public bool requireEmptyInv;
[Tooltip("If set, pickup will take this long in seconds")]
public float overridePickupTime;
}
[Serializable]
public struct Repair
{
public bool enabled;
[ItemSelector(ItemCategory.All)]
public ItemDefinition itemTarget;
[ItemSelector(ItemCategory.All)]
public ItemDefinition ignoreForRepair;
public GameObjectRef repairEffect;
public GameObjectRef repairFullEffect;
public GameObjectRef repairFailedEffect;
}
public enum ActionVolume
{
Quiet,
Normal,
Loud
}
[Header("BaseCombatEntity")]
public SkeletonProperties skeletonProperties;
public ProtectionProperties baseProtection;
public float startHealth;
public Pickup pickup;
public Repair repair;
public bool ShowHealthInfo = true;
[ReadOnly]
public LifeState lifestate;
public bool sendsHitNotification;
public bool sendsMeleeHitNotification = true;
public bool markAttackerHostile = true;
public float _health;
public float _maxHealth = 100f;
public Faction faction;
[NonSerialized]
public float lastAttackedTime = float.NegativeInfinity;
[NonSerialized]
public float lastDealtDamageTime = float.NegativeInfinity;
public int lastNotifyFrame;
private const float MAX_HEALTH_REPAIR = 50f;
public static readonly Translate.Phrase RecentlyDamagedError = new Translate.Phrase("error_recentlydamaged", "Recently damaged, repairable in {0} seconds");
public static readonly Translate.Phrase NotDamagedError = new Translate.Phrase("error_notdamaged", "Not damaged");
[NonSerialized]
public DamageType lastDamage;
[NonSerialized]
public BaseEntity lastAttacker;
[NonSerialized]
public BaseEntity lastDealtDamageTo;
[NonSerialized]
public bool ResetLifeStateOnSpawn = true;
public DirectionProperties[] propDirection;
public float unHostileTime;
public float lastNoiseTime;
public Vector3 LastAttackedDir { get; set; }
public float SecondsSinceAttacked => UnityEngine.Time.time - lastAttackedTime;
public float SecondsSinceDealtDamage => UnityEngine.Time.time - lastDealtDamageTime;
public float healthFraction => Health() / MaxHealth();
public float health
{
get
{
return _health;
}
set
{
float num = _health;
_health = Mathf.Clamp(value, 0f, MaxHealth());
if (base.isServer && _health != num)
{
OnHealthChanged(num, _health);
}
}
}
public float TimeSinceLastNoise => UnityEngine.Time.time - lastNoiseTime;
public ActionVolume LastNoiseVolume { get; private set; }
public Vector3 LastNoisePosition { get; private set; }
public override bool OnRpcMessage(BasePlayer player, uint rpc, Message msg)
{
using (TimeWarning.New("BaseCombatEntity.OnRpcMessage"))
{
if (rpc == 1191093595 && 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() + " - RPC_PickupStart ");
}
using (TimeWarning.New("RPC_PickupStart"))
{
using (TimeWarning.New("Conditions"))
{
if (!RPC_Server.MaxDistance.Test(1191093595u, "RPC_PickupStart", 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;
RPC_PickupStart(rpc2);
}
}
catch (Exception exception)
{
Debug.LogException(exception);
player.Kick("RPC Error in RPC_PickupStart");
}
}
return true;
}
}
return base.OnRpcMessage(player, rpc, msg);
}
public virtual bool IsDead()
{
return lifestate == LifeState.Dead;
}
public virtual bool IsAlive()
{
return lifestate == LifeState.Alive;
}
public Faction GetFaction()
{
return faction;
}
public virtual bool IsFriendly(BaseCombatEntity other)
{
return false;
}
public override void ResetState()
{
base.ResetState();
health = MaxHealth();
if (base.isServer)
{
lastAttackedTime = float.NegativeInfinity;
lastDealtDamageTime = float.NegativeInfinity;
}
}
public override void DestroyShared()
{
base.DestroyShared();
if (base.isServer)
{
UpdateSurroundings();
}
}
public virtual float GetThreatLevel()
{
return 0f;
}
public override float PenetrationResistance(HitInfo info)
{
if (!baseProtection)
{
return 100f;
}
return baseProtection.density;
}
public virtual void ScaleDamage(HitInfo info)
{
if (info.UseProtection && baseProtection != null)
{
baseProtection.Scale(info.damageTypes);
}
}
public HitArea SkeletonLookup(uint boneID)
{
if (skeletonProperties == null)
{
return (HitArea)(-1);
}
return skeletonProperties.FindBone(boneID)?.area ?? ((HitArea)(-1));
}
public override void Save(SaveInfo info)
{
base.Save(info);
info.msg.baseCombat = Facepunch.Pool.Get<BaseCombat>();
info.msg.baseCombat.state = (int)lifestate;
info.msg.baseCombat.health = Health();
}
public override void PostServerLoad()
{
base.PostServerLoad();
if (Health() > MaxHealth())
{
health = MaxHealth();
}
if (float.IsNaN(Health()))
{
health = MaxHealth();
}
}
public void SetJustAttacked()
{
lastAttackedTime = UnityEngine.Time.time;
}
public override void Load(LoadInfo info)
{
if (base.isServer)
{
lifestate = LifeState.Alive;
}
if (info.msg.baseCombat != null)
{
lifestate = (LifeState)info.msg.baseCombat.state;
_health = info.msg.baseCombat.health;
}
base.Load(info);
}
public override float Health()
{
return _health;
}
public override float MaxHealth()
{
return _maxHealth;
}
public virtual float StartHealth()
{
return startHealth;
}
public virtual float StartMaxHealth()
{
return StartHealth();
}
public void SetMaxHealth(float newMax)
{
_maxHealth = newMax;
_health = Mathf.Min(_health, newMax);
}
public void DoHitNotify(HitInfo info)
{
using (TimeWarning.New("DoHitNotify"))
{
if (sendsHitNotification && !(info.Initiator == null) && info.Initiator is BasePlayer && !(this == info.Initiator) && (!info.isHeadshot || !(info.HitEntity is BasePlayer)) && UnityEngine.Time.frameCount != lastNotifyFrame)
{
lastNotifyFrame = UnityEngine.Time.frameCount;
bool flag = info.Weapon is BaseMelee;
if (base.isServer && (!flag || sendsMeleeHitNotification))
{
bool arg = info.Initiator.net.connection == info.Predicted;
ClientRPC(RpcTarget.PlayerAndSpectators("HitNotify", info.Initiator as BasePlayer), arg);
}
}
}
}
public override void OnAttacked(HitInfo info)
{
using (TimeWarning.New("BaseCombatEntity.OnAttacked"))
{
if (!IsDead())
{
DoHitNotify(info);
}
if (base.isServer)
{
Hurt(info);
}
}
base.OnAttacked(info);
}
protected virtual int GetPickupCount()
{
return pickup.itemCount;
}
public virtual bool CanPickup(BasePlayer player)
{
object obj = Interface.CallHook("CanPickupEntity", player, this);
if (obj is bool)
{
return (bool)obj;
}
if (pickup.enabled && (!pickup.requireBuildingPrivilege || player.CanBuild()) && (!pickup.requireHammer || player.IsHoldingEntity<Hammer>()))
{
if (player != null)
{
return !player.IsInTutorial;
}
return false;
}
return false;
}
public virtual void OnPickedUp(Item createdItem, BasePlayer player)
{
Interface.CallHook("OnEntityPickedUp", this, createdItem, player);
}
public virtual void OnPickedUpPreItemMove(Item createdItem, BasePlayer player)
{
}
[RPC_Server]
[RPC_Server.MaxDistance(3f)]
private void RPC_PickupStart(RPCMessage rpc)
{
if (rpc.player.CanInteract() && CanPickup(rpc.player))
{
Item item = ItemManager.Create(pickup.itemTarget, GetPickupCount(), skinID);
if (pickup.setConditionFromHealth && item.hasCondition)
{
item.conditionNormalized = Mathf.Clamp01(healthFraction - pickup.subtractCondition);
}
OnPickedUpPreItemMove(item, rpc.player);
rpc.player.GiveItem(item, GiveItemReason.PickedUp);
OnPickedUp(item, rpc.player);
Facepunch.Rust.Analytics.Azure.OnEntityPickedUp(rpc.player, this);
Kill();
}
}
public virtual List<ItemAmount> BuildCost()
{
if (repair.itemTarget == null)
{
return null;
}
ItemBlueprint itemBlueprint = ItemManager.FindBlueprint(repair.itemTarget);
if (itemBlueprint == null)
{
return null;
}
return itemBlueprint.ingredients;
}
public virtual float RepairCostFraction()
{
return 0.5f;
}
public List<ItemAmount> RepairCost(float healthMissingFraction)
{
List<ItemAmount> list = BuildCost();
if (list == null)
{
return null;
}
List<ItemAmount> list2 = new List<ItemAmount>();
foreach (ItemAmount item in list)
{
if (!(repair.ignoreForRepair != null) || item.itemDef.itemid != repair.ignoreForRepair.itemid)
{
list2.Add(new ItemAmount(item.itemDef, Mathf.Max(Mathf.RoundToInt(item.amount * RepairCostFraction() * healthMissingFraction), 1)));
}
}
RepairBench.StripComponentRepairCost(list2, RepairCostFraction() * healthMissingFraction);
return list2;
}
public virtual void OnRepair()
{
Effect.server.Run(repair.repairEffect.isValid ? repair.repairEffect.resourcePath : "assets/bundled/prefabs/fx/build/repair.prefab", this, 0u, Vector3.zero, Vector3.zero);
}
public virtual void OnRepairFinished()
{
Effect.server.Run(repair.repairFullEffect.isValid ? repair.repairFullEffect.resourcePath : "assets/bundled/prefabs/fx/build/repair_full.prefab", this, 0u, Vector3.zero, Vector3.zero);
}
public virtual void OnRepairFailed(BasePlayer player, Translate.Phrase reason, params string[] args)
{
Effect.server.Run(repair.repairFailedEffect.isValid ? repair.repairFailedEffect.resourcePath : "assets/bundled/prefabs/fx/build/repair_failed.prefab", this, 0u, Vector3.zero, Vector3.zero);
if (player != null && !string.IsNullOrEmpty(reason.token))
{
player.ShowToast(GameTip.Styles.Error, reason, overlay: false, args);
}
}
public virtual void OnRepairFailedResources(BasePlayer player, List<ItemAmount> requirements)
{
Effect.server.Run(repair.repairFailedEffect.isValid ? repair.repairFailedEffect.resourcePath : "assets/bundled/prefabs/fx/build/repair_failed.prefab", this, 0u, Vector3.zero, Vector3.zero);
if (player != null)
{
using (ItemAmountList arg = ItemAmount.SerialiseList(requirements))
{
player.ClientRPC(RpcTarget.Player("Client_OnRepairFailedResources", player), arg);
}
}
}
public virtual void DoRepair(BasePlayer player)
{
BasePlayer player2 = player;
if (!repair.enabled || Interface.CallHook("OnStructureRepair", this, player) != null)
{
return;
}
float num = 30f;
if (player2.IsInCreativeMode && Creative.freeRepair)
{
num = 0f;
}
if (SecondsSinceAttacked <= num)
{
OnRepairFailed(player2, RecentlyDamagedError, (num - SecondsSinceAttacked).ToString("N0"));
return;
}
float num2 = MaxHealth() - Health();
float num3 = num2 / MaxHealth();
if (num2 <= 0f || num3 <= 0f)
{
OnRepairFailed(player2, NotDamagedError);
return;
}
List<ItemAmount> list = RepairCost(num3);
if (list == null)
{
return;
}
float num4 = list.Sum((ItemAmount x) => x.amount);
float healthBefore = health;
if (player2.IsInCreativeMode && Creative.freeRepair)
{
num4 = 0f;
}
if (num4 > 0f)
{
float num5 = list.Min((ItemAmount x) => Mathf.Clamp01((float)player2.inventory.GetAmount(x.itemid) / x.amount));
if (float.IsNaN(num5))
{
num5 = 0f;
}
num5 = Mathf.Min(num5, 50f / num2);
if (num5 <= 0f)
{
OnRepairFailedResources(player2, list);
return;
}
int num6 = 0;
foreach (ItemAmount item in list)
{
int amount = Mathf.CeilToInt(num5 * item.amount);
int num7 = player2.inventory.Take(null, item.itemid, amount);
Facepunch.Rust.Analytics.Azure.LogResource(Facepunch.Rust.Analytics.Azure.ResourceMode.Consumed, "repair_entity", item.itemDef.shortname, num7, this, null, safezone: false, null, player2.userID);
if (num7 > 0)
{
num6 += num7;
player2.Command("note.inv", item.itemid, num7 * -1);
}
}
float num8 = (float)num6 / num4;
health += num2 * num8;
SendNetworkUpdate();
}
else
{
health += num2;
SendNetworkUpdate();
}
Facepunch.Rust.Analytics.Azure.OnEntityRepaired(player2, this, healthBefore, health);
if (Health() >= MaxHealth())
{
OnRepairFinished();
}
else
{
OnRepair();
}
}
public virtual void InitializeHealth(float newhealth, float newmax)
{
_maxHealth = newmax;
_health = newhealth;
lifestate = LifeState.Alive;
}
public override void ServerInit()
{
propDirection = PrefabAttribute.server.FindAll<DirectionProperties>(prefabID);
if (ResetLifeStateOnSpawn)
{
InitializeHealth(StartHealth(), StartMaxHealth());
lifestate = LifeState.Alive;
}
base.ServerInit();
}
public virtual void OnHealthChanged(float oldvalue, float newvalue)
{
}
public void Hurt(float amount)
{
Hurt(Mathf.Abs(amount), DamageType.Generic);
}
public void Hurt(float amount, DamageType type, BaseEntity attacker = null, bool useProtection = true)
{
using (TimeWarning.New("Hurt"))
{
HitInfo obj = Facepunch.Pool.Get<HitInfo>();
obj.Init(attacker, this, type, amount, base.transform.position);
obj.UseProtection = useProtection;
Hurt(obj);
Facepunch.Pool.Free(ref obj);
}
}
public virtual void Hurt(HitInfo info)
{
Assert.IsTrue(base.isServer, "This should be called serverside only");
if (IsDead() || IsTransferProtected())
{
return;
}
using (TimeWarning.New("Hurt( HitInfo )", 50))
{
float num = health;
ScaleDamage(info);
if (info.PointStart != Vector3.zero)
{
for (int i = 0; i < propDirection.Length; i++)
{
if (!(propDirection[i].extraProtection == null) && !propDirection[i].IsWeakspot(base.transform, info))
{
propDirection[i].extraProtection.Scale(info.damageTypes);
}
}
}
info.damageTypes.Scale(DamageType.Arrow, ConVar.Server.arrowdamage);
info.damageTypes.Scale(DamageType.Bullet, ConVar.Server.bulletdamage);
info.damageTypes.Scale(DamageType.Slash, ConVar.Server.meleedamage);
info.damageTypes.Scale(DamageType.Blunt, ConVar.Server.meleedamage);
info.damageTypes.Scale(DamageType.Stab, ConVar.Server.meleedamage);
info.damageTypes.Scale(DamageType.Bleeding, ConVar.Server.bleedingdamage);
if (!(this is BasePlayer))
{
info.damageTypes.Scale(DamageType.Fun_Water, 0f);
}
if (Interface.CallHook("IOnBaseCombatEntityHurt", this, info) != null)
{
return;
}
DebugHurt(info);
float num2 = info.damageTypes.Total();
health = num - num2;
SendNetworkUpdate();
LogEntry(RustLog.EntryType.Combat, 2, "hurt {0}/{1} - {2} health left", info.damageTypes.GetMajorityDamageType(), num2, health.ToString("0"));
lastDamage = info.damageTypes.GetMajorityDamageType();
lastAttacker = info.Initiator;
if (lastAttacker != null)
{
BaseCombatEntity baseCombatEntity = lastAttacker as BaseCombatEntity;
if (baseCombatEntity != null)
{
baseCombatEntity.lastDealtDamageTime = UnityEngine.Time.time;
baseCombatEntity.lastDealtDamageTo = this;
}
if (this.IsValid() && lastAttacker is BasePlayer basePlayer)
{
basePlayer.ProcessMissionEvent(BaseMission.MissionEventType.HURT_ENTITY, net.ID, num2);
}
}
BaseCombatEntity baseCombatEntity2 = lastAttacker as BaseCombatEntity;
if (markAttackerHostile && baseCombatEntity2 != null && baseCombatEntity2 != this)
{
baseCombatEntity2.MarkHostileFor();
}
if (lastDamage.IsConsideredAnAttack())
{
SetJustAttacked();
if (lastAttacker != null)
{
LastAttackedDir = (lastAttacker.transform.position - base.transform.position).normalized;
}
}
bool flag = Health() <= 0f;
Facepunch.Rust.Analytics.Azure.OnEntityTakeDamage(info, flag);
if (flag)
{
Die(info);
}
BasePlayer initiatorPlayer = info.InitiatorPlayer;
if ((bool)initiatorPlayer)
{
if (IsDead())
{
initiatorPlayer.stats.combat.LogAttack(info, "killed", num);
}
else
{
initiatorPlayer.stats.combat.LogAttack(info, "", num);
}
}
}
}
public virtual bool IsHostile()
{
object obj = Interface.CallHook("CanEntityBeHostile", this);
if (obj is bool)
{
return (bool)obj;
}
return unHostileTime > UnityEngine.Time.realtimeSinceStartup;
}
public virtual void MarkHostileFor(float duration = 60f)
{
if (Interface.CallHook("OnEntityMarkHostile", this, duration) == null)
{
float b = UnityEngine.Time.realtimeSinceStartup + duration;
unHostileTime = Mathf.Max(unHostileTime, b);
}
}
private void DebugHurt(HitInfo info)
{
if (!ConVar.Vis.damage)
{
return;
}
if (info.PointStart != info.PointEnd)
{
ConsoleNetwork.BroadcastToAllClients("ddraw.arrow", 60, Color.cyan, info.PointStart, info.PointEnd, 0.1f);
ConsoleNetwork.BroadcastToAllClients("ddraw.sphere", 60, Color.cyan, info.HitPositionWorld, 0.01f);
}
string text = "";
for (int i = 0; i < info.damageTypes.types.Length; i++)
{
float num = info.damageTypes.types[i];
if (num != 0f)
{
string[] obj = new string[5] { text, " ", null, null, null };
DamageType damageType = (DamageType)i;
obj[2] = damageType.ToString().PadRight(10);
obj[3] = num.ToString("0.00");
obj[4] = "\n";
text = string.Concat(obj);
}
}
string text2 = "<color=lightblue>Damage:</color>".PadRight(10) + info.damageTypes.Total().ToString("0.00") + "\n<color=lightblue>Health:</color>".PadRight(10) + health.ToString("0.00") + " / " + ((health - info.damageTypes.Total() <= 0f) ? "<color=red>" : "<color=green>") + (health - info.damageTypes.Total()).ToString("0.00") + "</color>" + "\n<color=lightblue>HitEnt:</color>".PadRight(10) + this?.ToString() + "\n<color=lightblue>HitBone:</color>".PadRight(10) + info.boneName + "\n<color=lightblue>Attacker:</color>".PadRight(10) + info.Initiator?.ToString() + "\n<color=lightblue>WeaponPrefab:</color>".PadRight(10) + info.WeaponPrefab?.ToString() + "\n<color=lightblue>Damages:</color>\n" + text;
ConsoleNetwork.BroadcastToAllClients("ddraw.text", 60, Color.white, info.HitPositionWorld, text2);
}
public void SetHealth(float hp)
{
if (health != hp)
{
health = hp;
SendNetworkUpdate();
}
}
public virtual void Heal(float amount)
{
LogEntry(RustLog.EntryType.Combat, 2, "healed {0}", amount);
health = _health + amount;
SendNetworkUpdate();
}
public virtual void OnKilled(HitInfo info)
{
Kill(DestroyMode.Gib);
}
public virtual void Die(HitInfo info = null)
{
if (IsDead())
{
return;
}
LogEntry(RustLog.EntryType.Combat, 2, "died");
health = 0f;
lifestate = LifeState.Dead;
Interface.CallHook("OnEntityDeath", this, info);
if (info != null && (bool)info.InitiatorPlayer)
{
BasePlayer initiatorPlayer = info.InitiatorPlayer;
if (initiatorPlayer != null && initiatorPlayer.GetActiveMission() != -1 && !initiatorPlayer.IsNpc)
{
initiatorPlayer.ProcessMissionEvent(BaseMission.MissionEventType.KILL_ENTITY, prefabID, 1f);
}
}
using (TimeWarning.New("OnKilled"))
{
OnKilled(info);
}
}
public void DieInstantly()
{
if (!IsDead())
{
LogEntry(RustLog.EntryType.Combat, 2, "died");
health = 0f;
lifestate = LifeState.Dead;
OnKilled(null);
}
}
public void UpdateSurroundings()
{
BaseEntity baseEntity = GetParentEntity();
if (baseEntity != null && baseEntity.GetWorldVelocity().sqrMagnitude > 5f)
{
StabilityEntity.UpdateSurroundingsQueue.NotifyNeighbours(WorldSpaceBounds().ToBounds());
}
else
{
StabilityEntity.updateSurroundingsQueue.Add(WorldSpaceBounds().ToBounds());
}
}
public void MakeNoise(Vector3 position, ActionVolume loudness)
{
LastNoisePosition = position;
LastNoiseVolume = loudness;
lastNoiseTime = UnityEngine.Time.time;
}
public bool CanLastNoiseBeHeard(Vector3 listenPosition, float listenRange)
{
if (listenRange <= 0f)
{
return false;
}
return Vector3.Distance(listenPosition, LastNoisePosition) <= listenRange;
}
}
Anti-Cheat Mechanics: Contains technical hooks such as MarkHostileFor and IsHostile for managing combat legality and aggressiveness.
Logging and Debugging: Integration for detailed logging of damage processes and entity state changes.
General Overview
These classes appear to form part of a larger combat and damage system within a Rust-like game, providing a structured way to handle entities that can receive and deal damage, engage in combat, and interact with their environment.
Customization & Extendability:
By using Unity's ScriptableObject, DamageProperties allows for menu-based customization of damage-related attributes.
The modular design enables extensions, making it easy to add new damage types, hit areas, or entity types without altering existing implementations dramatically.
Integration Points:
These classes are heavily integrated with Unity's game framework, using game components and systems like prefabs, RPC messages, and network synchronization.
The classes also show strong support for server-side operations, ensuring entity states are maintained and synchronized in multiplayer setups.
The code you provided offers a robust model for managing combat interactions, complete with damage calculations, state management, and network interactions. It likely serves as a core component in the combat mechanics of a multiplayer or real-time battle scenario. If you have further questions about specific parts of this code or how it integrates with other systems, feel free to ask!
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.IsVisible(3f)]
[RPC_Server]
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]
[RPC_Server.IsVisible(3f)]
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]
[RPC_Server.IsVisible(3f)]
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;
}
}
Ammo and Weapon Handling:
Ammo Management: Responsible for checking ammo (HasClipAmmo, HasReserveAmmo) and reloading (Reload).
Weapon Integration: Functions to attach and update weapons, checking if they are usable (IsValidWeapon) and compatible with the turret.
Interference and Coordination:
Inter-Turret Connectivity: Methods exist to deal with interference between turrets (UpdateInterference, TryRegisterForInterferenceUpdate) and arrange cooperative targeting.
Nearby Turrets Management: Manages coordination and interference between neighboring turrets, updating them as needed.
Engagement and Combat Handling:
Peacekeeper Mode: A mode of operation where the turret only engages entities deemed hostile.
Combat Interaction: The turret responds to attacks (OnAttacked) and updates its target behavior based on visibility and hostile status.
Performance and Debugging:
Optimization: Queues for processes like target scanning (UpdateAutoTurretScanQueue) help manage the computational load by scheduling tasks.
Debugging and Logs: Extensive use of debug logs and warnings facilitate tracking operations and diagnosing issues during development and runtime.
Usage Context
In Rust or similar sandbox-survival games, the AutoTurret class provides autonomous defense capabilities to players, allowing them to deploy turrets that automatically detect and engage enemies within range. Its ability to control weapons, manage resources, and respect player authorizations makes it a crucial component for base defense strategies.
Integration with the broader game world involves player interactions, resource management, and network synchronization, ensuring that the auto turret remains an effective tool in both PvE (Player versus Environment) and PvP (Player versus Player) scenarios.
The script's complexity highlights Rust's need to balance engaging mechanics with system resource efficiency, providing seamless multiplayer interactions and tactical gameplay elements. If you need further breakdowns or explanations of specific functions or logic within this class, feel free to ask!
Key Points:
Input Validation: It's crucial to check that both autoTurret and hitInfo are not null to prevent errors during execution.
Damage Calculation: Leverages hitInfo.damageTypes.Total() to aggregate the damage from all types specified in DamageTypeList.
Health Management: Directly manipulates the autoTurret.health field, ensuring no negative values.
Destruction Logic: Uses a method like autoTurret.Die(hitInfo) to appropriately handle the turret's destruction when its health reaches zero.
Network Update: Ensures the network state is updated so that the change in health is synchronized across the server and clients.
This example assumes you have access to methods SendNetworkUpdate and Die for handling network sync and destruction logic, respectively. Ensure you adjust based on the actual available methods in your AutoTurret class or its ancestors.
If this hook is part of a plugin or a modding API (such as Oxide for Rust), ensure it integrates with any provided event systems or APIs correctly. If you have other specifications or nuances in your code structure, adjust accordingly.