C#:
using System;
using Facepunch;
using Newtonsoft.Json.Linq;
using Oxide.Core.Plugins;
using Rust;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Oxide.Core;
using UnityEngine;
using UnityEngine.AI;
using System.IO;
using ProtoBuf;
using Oxide.Plugins.NpcSpawnExtensionMethods;
namespace Oxide.Plugins {
[Info("NpcSpawn", "KpucTaJl", "2.6.0")]
internal class NpcSpawn : RustPlugin {
#region Config
internal class NpcBelt {
public string ShortName;
public int Amount;
public ulong SkinID;
public HashSet<string> Mods;
public string Ammo;
}
internal class NpcWear {
public string ShortName;
public ulong SkinID;
}
internal class NpcConfig {
public string Name {
get;
set;
}
public HashSet<NpcWear> WearItems {
get;
set;
}
public HashSet<NpcBelt> BeltItems {
get;
set;
}
public string Kit {
get;
set;
}
public float Health {
get;
set;
}
public float RoamRange {
get;
set;
}
public float ChaseRange {
get;
set;
}
public float SenseRange {
get;
set;
}
public float ListenRange {
get;
set;
}
public float AttackRangeMultiplier {
get;
set;
}
public bool CheckVisionCone {
get;
set;
}
public float VisionCone {
get;
set;
}
public bool HostileTargetsOnly {
get;
set;
}
public float DamageScale {
get;
set;
}
public float TurretDamageScale {
get;
set;
}
public float AimConeScale {
get;
set;
}
public bool DisableRadio {
get;
set;
}
public bool CanRunAwayWater {
get;
set;
}
public bool CanSleep {
get;
set;
}
public float SleepDistance {
get;
set;
}
public float Speed {
get;
set;
}
public int AreaMask {
get;
set;
}
public int AgentTypeID {
get;
set;
}
public string HomePosition {
get;
set;
}
public float MemoryDuration {
get;
set;
}
public HashSet<string> States {
get;
set;
}
}
#endregion Config
#region Methods
private static bool IsCustomScientist(BaseEntity entity) => entity != null && entity.skinID == 11162132011012;
private ScientistNPC SpawnNpc(Vector3 position, JObject configJson) {
CustomScientistNpc npc = CreateCustomNpc(position, configJson.ToObject<NpcConfig>());
if (npc != null) {
npc.skinID = 11162132011012;
_scientists.Add(npc.net.ID.Value, npc);
}
return npc;
}
private static CustomScientistNpc CreateCustomNpc(Vector3 position, NpcConfig config) {
ScientistNPC scientistNpc = GameManager.server.CreateEntity("assets/rust.ai/agents/npcplayer/humannpc/scientist/scientistnpc_heavy.prefab", position, Quaternion.identity, false) as ScientistNPC;
ScientistBrain scientistBrain = scientistNpc.GetComponent<ScientistBrain>();
CustomScientistNpc customScientist = scientistNpc.gameObject.AddComponent<CustomScientistNpc>();
CustomScientistBrain customScientistBrain = scientistNpc.gameObject.AddComponent<CustomScientistBrain>();
CopySerializableFields(scientistNpc, customScientist);
CopySerializableFields(scientistBrain, customScientistBrain);
UnityEngine.Object.DestroyImmediate(scientistNpc, true);
UnityEngine.Object.DestroyImmediate(scientistBrain, true);
customScientist.Config = config;
customScientist.Brain = customScientistBrain;
customScientist.enableSaving = false;
customScientist.gameObject.AwakeFromInstantiate();
customScientist.Spawn();
return customScientist;
}
private static void CopySerializableFields<T>(T src, T dst) {
FieldInfo[] srcFields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in srcFields) {
object value = field.GetValue(src);
field.SetValue(dst, value);
}
}
private void AddTargetRaid(CustomScientistNpc npc, HashSet<BuildingBlock> foundations) {
if (IsCustomScientist(npc)) npc.Foundations = foundations;
}
private void AddTargetGuard(CustomScientistNpc npc, BaseEntity target) {
if (IsCustomScientist(npc) && target != null) npc.AddTargetGuard(target);
}
private void SetParentEntity(CustomScientistNpc npc, BaseEntity parent, Vector3 pos) {
if (IsCustomScientist(npc) && parent != null) npc.SetParentEntity(parent, pos);
}
private void SetHomePosition(CustomScientistNpc npc, Vector3 pos) {
if (IsCustomScientist(npc)) npc.HomePosition = pos;
}
private void SetCurrentWeapon(CustomScientistNpc npc, Item weapon) {
if (IsCustomScientist(npc)) npc.EquipCurrentWeapon(weapon);
}
private void SetCustomNavMesh(CustomScientistNpc npc, Transform transform, string navMeshName) {
if (!IsCustomScientist(npc) || transform == null || !_allNavMeshes.ContainsKey(navMeshName)) return;
Dictionary<int, Dictionary<int, PointNavMeshFile>> navMesh = _allNavMeshes[navMeshName];
for (int i = 0; i < navMesh.Count; i++) {
if (!npc.CustomNavMesh.ContainsKey(i)) npc.CustomNavMesh.Add(i, new Dictionary<int, PointNavMesh>());
for (int j = 0; j < navMesh[i].Count; j++) {
PointNavMeshFile pointNavMesh = navMesh[i][j];
npc.CustomNavMesh[i].Add(j, new PointNavMesh {
Position = transform.TransformPoint(pointNavMesh.Position.ToVector3()), Enabled = pointNavMesh.Enabled
}
);
}
}
npc.InitCustomNavMesh();
}
private BasePlayer GetCurrentTarget(CustomScientistNpc npc) => IsCustomScientist(npc) && npc.IsBasePlayerTarget ? npc.GetBasePlayerTarget : null;
#endregion Methods
#region Controller
internal class DefaultSettings {
public float EffectiveRange;
public float AttackLengthMin;
public float AttackLengthMax;
}
private static readonly Dictionary<string, DefaultSettings> Weapons = new Dictionary<string, DefaultSettings> {
["rifle.bolt"]
= new DefaultSettings {
EffectiveRange = 150f, AttackLengthMin = -1f, AttackLengthMax = -1f
}
, ["speargun"] = new DefaultSettings {
EffectiveRange = 15f, AttackLengthMin = -1f, AttackLengthMax = -1f
}
, ["bow.compound"] = new DefaultSettings {
EffectiveRange = 15f, AttackLengthMin = -1f, AttackLengthMax = -1f
}
, ["crossbow"] = new DefaultSettings {
EffectiveRange = 15f, AttackLengthMin = -1f, AttackLengthMax = -1f
}
, ["bow.hunting"] = new DefaultSettings {
EffectiveRange = 15f, AttackLengthMin = -1f, AttackLengthMax = -1f
}
, ["smg.2"] = new DefaultSettings {
EffectiveRange = 20f, AttackLengthMin = 0.4f, AttackLengthMax = 0.4f
}
, ["shotgun.double"] = new DefaultSettings {
EffectiveRange = 10f, AttackLengthMin = 0.3f, AttackLengthMax = 1f
}
, ["pistol.eoka"] = new DefaultSettings {
EffectiveRange = 10f, AttackLengthMin = -1f, AttackLengthMax = -1f
}
, ["rifle.l96"] = new DefaultSettings {
EffectiveRange = 150f, AttackLengthMin = -1f, AttackLengthMax = -1f
}
, ["pistol.nailgun"] = new DefaultSettings {
EffectiveRange = 15f, AttackLengthMin = 0f, AttackLengthMax = 0.46f
}
, ["pistol.python"] = new DefaultSettings {
EffectiveRange = 15f, AttackLengthMin = 0.175f, AttackLengthMax = 0.525f
}
, ["pistol.semiauto"] = new DefaultSettings {
EffectiveRange = 15f, AttackLengthMin = 0f, AttackLengthMax = 0.46f
}
, ["pistol.prototype17"] = new DefaultSettings {
EffectiveRange = 15f, AttackLengthMin = 0f, AttackLengthMax = 0.46f
}
, ["smg.thompson"] = new DefaultSettings {
EffectiveRange = 20f, AttackLengthMin = 0.4f, AttackLengthMax = 0.4f
}
, ["shotgun.waterpipe"] = new DefaultSettings {
EffectiveRange = 10f, AttackLengthMin = -1f, AttackLengthMax = -1f
}
, ["multiplegrenadelauncher"] = new DefaultSettings {
EffectiveRange = 20f, AttackLengthMin = -1f, AttackLengthMax = -1f
}
, ["snowballgun"] = new DefaultSettings {
EffectiveRange = 5f, AttackLengthMin = 2f, AttackLengthMax = 2f
}
}
;
private static readonly HashSet<string> MeleeWeapons = new HashSet<string> {
"bone.club", "knife.bone", "knife.butcher", "candycaneclub", "knife.combat", "longsword", "mace", "machete", "paddle", "pitchfork", "salvaged.cleaver", "salvaged.sword", "spear.stone", "spear.wooden", "chainsaw", "hatchet", "jackhammer", "pickaxe", "axe.salvaged", "hammer.salvaged", "icepick.salvaged", "stonehatchet", "stone.pickaxe", "torch", "sickle", "rock", "snowball", "mace.baseballbat", "concretepickaxe", "concretehatchet", "lumberjack.hatchet", "lumberjack.pickaxe", "diverhatchet", "diverpickaxe"
}
;
private static readonly HashSet<string> FirstDistanceWeapons = new HashSet<string> {
"speargun", "bow.compound", "crossbow", "bow.hunting", "shotgun.double", "pistol.eoka", "flamethrower", "pistol.m92", "pistol.nailgun", "multiplegrenadelauncher", "shotgun.pump", "pistol.python", "pistol.revolver", "pistol.semiauto", "pistol.prototype17", "snowballgun", "shotgun.spas12", "shotgun.waterpipe"
}
;
private static readonly HashSet<string> SecondDistanceWeapons = new HashSet<string> {
"smg.2", "smg.mp5", "rifle.semiauto", "smg.thompson"
}
;
private static readonly HashSet<string> ThirdDistanceWeapons = new HashSet<string> {
"rifle.ak", "rifle.lr300", "lmg.m249", "rifle.m39", "hmlmg", "rifle.ak.ice", "rifle.ak.diver"
}
;
private static readonly HashSet<string> FourthDistanceWeapons = new HashSet<string> {
"rifle.bolt", "rifle.l96"
}
;
public class CustomScientistNpc : ScientistNPC {
public NpcConfig Config {
get;
set;
}
public Vector3 HomePosition {
get;
set;
}
public float DistanceFromBase => Vector3.Distance(transform.position, HomePosition);
public override void ServerInit() {
base.ServerInit();
HomePosition = string.IsNullOrEmpty(Config.HomePosition) ? transform.position : Config.HomePosition.ToVector3();
if (NavAgent == null) NavAgent = GetComponent<NavMeshAgent>();
if (NavAgent != null) {
NavAgent.areaMask = Config.AreaMask;
NavAgent.agentTypeID = Config.AgentTypeID;
}
startHealth = Config.Health;
_health = Config.Health;
damageScale = Config.DamageScale;
if (Config.DisableRadio) {
CancelInvoke(PlayRadioChatter);
RadioChatterEffects = Array.Empty<GameObjectRef>();
DeathEffects = Array.Empty<GameObjectRef>();
}
inventory.containerWear.ClearItemsContainer();
inventory.containerBelt.ClearItemsContainer();
if (!string.IsNullOrEmpty(Config.Kit) && _ins.Kits != null) _ins.Kits.Call("GiveKit", this, Config.Kit);
else UpdateInventory();
displayName = Config.Name;
if (IsBomber) {
_bomberTimedExplosive = GameManager.server.CreateEntity("assets/prefabs/tools/c4/explosive.timed.deployed.prefab") as RFTimedExplosive;
_bomberTimedExplosive.enableSaving = false;
_bomberTimedExplosive.timerAmountMin = float.PositiveInfinity;
_bomberTimedExplosive.timerAmountMax = float.PositiveInfinity;
_bomberTimedExplosive.transform.localPosition = new Vector3(0f, 1f, 0f);
_bomberTimedExplosive.SetParent(this);
_bomberTimedExplosive.Spawn();
}
InvokeRepeating(LightCheck, 1f, 30f);
InvokeRepeating(UpdateTick, 1f, 2f);
}
private void UpdateInventory() {
if (Config.WearItems.Count > 0) {
foreach (Item item in Config.WearItems.Select(x => ItemManager.CreateByName(x.ShortName, 1, x.SkinID))) {
if (item == null) continue;
if (!item.MoveToContainer(inventory.containerWear)) item.Remove();
}
}
if (Config.BeltItems.Count > 0) {
foreach (NpcBelt npcItem in Config.BeltItems) {
Item item = ItemManager.CreateByName(npcItem.ShortName, npcItem.Amount, npcItem.SkinID);
if (item == null) continue;
foreach (ItemDefinition itemDefinition in npcItem.Mods.Select(ItemManager.FindItemDefinition)) if (itemDefinition != null) item.contents.AddItem(itemDefinition, 1);
if (!item.MoveToContainer(inventory.containerBelt)) item.Remove();
}
}
}
private void OnDestroy() {
if (_healCoroutine != null) ServerMgr.Instance.StopCoroutine(_healCoroutine);
if (_fireC4Coroutine != null) ServerMgr.Instance.StopCoroutine(_fireC4Coroutine);
if (_fireRocketLauncherCoroutine != null) ServerMgr.Instance.StopCoroutine(_fireRocketLauncherCoroutine);
CancelInvoke();
if (_bomberTimedExplosive.IsExists()) _bomberTimedExplosive.Kill();
}
private void UpdateTick() {
if (CanRunAwayWater()) RunAwayWater();
if (CanThrownGrenade()) ThrownGrenade(CurrentTarget.transform.position);
if (CanHeal()) _healCoroutine = ServerMgr.Instance.StartCoroutine(Heal());
EquipWeapon();
if (IsRaidState && Foundations.Count == 0) {
if (CurrentTarget == null || CurrentTarget is Drone) {
PlayerTarget = null;
CurrentRaidTarget = null;
}
else if (IsBasePlayerTarget) {
bool isNull = true;
BuildingBlock block = GetNearEntity<BuildingBlock>(CurrentTarget.transform.position, 0.1f, 1 << 21);
if (block.IsExists() && IsTeam(GetBasePlayerTarget.userID, block.OwnerID)) {
PlayerTarget = block;
isNull = false;
}
Tugboat tugboat = CurrentTarget.GetParentEntity() as Tugboat;
if (tugboat.IsExists()) {
PlayerTarget = tugboat;
isNull = false;
}
BaseVehicle vehicle = GetBasePlayerTarget.GetMountedVehicle();
if (vehicle.IsExists() && (vehicle is SubmarineDuo || vehicle is BaseSubmarine)) {
PlayerTarget = vehicle;
isNull = false;
}
if (isNull) {
PlayerTarget = null;
CurrentRaidTarget = null;
}
}
}
if (_beforeGuardHomePosition != Vector3.zero) {
if (_guardTarget.IsExists()) HomePosition = _guardTarget.transform.position;
else {
HomePosition = _beforeGuardHomePosition;
_beforeGuardHomePosition = Vector3.zero;
_guardTarget = null;
Interface.Oxide.CallHook("OnCustomNpcGuardTargetEnd", this);
}
}
if (Config.CanSleep) {
bool sleep = Query.Server.PlayerGrid.Query(transform.position.x, transform.position.z, Config.SleepDistance, AIBrainSenses.playerQueryResults, x => x.IsPlayer() && !x.IsSleeping()) == 0;
if (Brain.sleeping != sleep) {
Brain.sleeping = sleep;
if (Brain.sleeping) SetDestination(HomePosition, 2f, BaseNavigator.NavigationSpeed.Fast);
else NavAgent.enabled = true;
}
}
}
#region Targeting
public new BaseEntity GetBestTarget() {
BaseEntity target = null;
float single = -1f;
foreach (BaseEntity entity in Brain.Senses.Players) {
if (!CanTargetEntity(entity)) continue;
float single2 = 1f - Mathf.InverseLerp(1f, Brain.SenseRange, Vector3.Distance(entity.transform.position, transform.position));
single2 += Mathf.InverseLerp(Brain.VisionCone, 1f, Vector3.Dot((entity.transform.position - eyes.position).normalized, eyes.BodyForward())) / 2f;
single2 += Brain.Senses.Memory.IsLOS(entity) ? 2f : 0f;
if (single2 <= single) continue;
target = entity;
single = single2;
}
return target;
}
internal bool CanTargetEntity(BaseEntity target) {
if (target == null || target.Health() <= 0f) return false;
if (target is BasePlayer) {
BasePlayer basePlayer = target as BasePlayer;
object hook = Interface.CallHook("OnCustomNpcTarget", this, basePlayer);
if (hook is bool) return (bool)hook;
if (basePlayer.IsDead()) return false;
if (basePlayer.skinID != 0 && _ins.SkinIDs.Contains(basePlayer.skinID)) return true;
if (basePlayer.userID.IsSteamId()) return CanTargetPlayer(basePlayer);
else if (basePlayer is NPCPlayer) return CanTargetNpcPlayer(basePlayer as NPCPlayer);
else return false;
}
else if (target is Drone) return CanTargetDrone(target as Drone);
else return false;
}
internal bool CanTargetNpcPlayer(NPCPlayer target) {
if (target is FrankensteinPet) return true;
else if (target.skinID == 11162132011012) {
if (target.displayName == "Vagos" || target.displayName == "Ballas") return true;
else return false;
}
else return _ins.CanTargetOtherNpc;
}
internal bool CanTargetPlayer(BasePlayer target) => !(target.IsSleeping() || target.IsWounded() || target._limitedNetworking || target.InSafeZone());
internal bool CanTargetDrone(Drone target) => !(CurrentWeapon is BaseMelee);
public BaseEntity CurrentTarget {
get;
set;
}
public float DistanceToTarget => Vector3.Distance(transform.position, CurrentTarget.transform.position);
public bool IsBasePlayerTarget => CurrentTarget is BasePlayer;
internal BasePlayer GetBasePlayerTarget => CurrentTarget as BasePlayer;
#endregion Targeting
#region Equip Weapons
public AttackEntity CurrentWeapon {
get;
set;
}
private bool _isEquiping {
get;
set;
}
= false;
private bool CanEquipWeapon() {
if (inventory == null || inventory.containerBelt == null) return false;
if (_isEquiping) return false;
if (IsFireRocketLauncher) return false;
if (_isHealing) return false;
return true;
}
public override void EquipWeapon(bool skipDeployDelay = false) {
if (!CanEquipWeapon()) return;
Item weapon = null;
if (CurrentTarget == null) {
if (CurrentWeapon == null) {
Dictionary<int, List<Item>> weapons = new Dictionary<int, List<Item>> {
[0]
= new List<Item>(), [1] = new List<Item>(), [2] = new List<Item>(), [3] = new List<Item>(), [4] = new List<Item>()
}
;
foreach (Item item in inventory.containerBelt.itemList) {
int type = GetTypeWeaponItem(item);
if (type == -1) continue;
weapons[type].Add(item);
}
if (weapons[3].Count > 0) weapon = weapons[3].GetRandom();
else if (weapons[2].Count > 0) weapon = weapons[2].GetRandom();
else if (weapons[1].Count > 0) weapon = weapons[1].GetRandom();
else if (weapons[4].Count > 0) weapon = weapons[4].GetRandom();
else if (weapons[0].Count > 0) weapon = weapons[0].GetRandom();
}
else return;
}
else {
float distanceToTarget = DistanceToTarget;
int type = -1;
foreach (Item item in inventory.containerBelt.itemList) {
int currentType = GetTypeWeaponItem(item);
if (currentType == -1) continue;
if (type == -1) {
weapon = item;
type = currentType;
}
else {
if (type == currentType) continue;
float oldDistance = type > 0 ? Config.AttackRangeMultiplier * type * 10f : 2f;
float newDistance = currentType > 0 ? Config.AttackRangeMultiplier * currentType * 10f : 2f;
if ((oldDistance > distanceToTarget && newDistance > distanceToTarget && newDistance < oldDistance) || (oldDistance < distanceToTarget && newDistance > distanceToTarget) || (oldDistance < distanceToTarget && newDistance < distanceToTarget && newDistance > oldDistance)) {
weapon = item;
type = currentType;
}
}
}
}
EquipCurrentWeapon(weapon);
}
internal void EquipCurrentWeapon(Item weapon) {
if (weapon == null) return;
AttackEntity attackEntity = weapon.GetHeldEntity() as AttackEntity;
if (attackEntity == null) return;
if (CurrentWeapon == attackEntity) return;
_isEquiping = true;
UpdateActiveItem(weapon.uid);
CurrentWeapon = attackEntity;
attackEntity.TopUpAmmo();
if (attackEntity is Chainsaw) (attackEntity as Chainsaw).ServerNPCStart();
if (attackEntity is BaseProjectile) {
if (Weapons.ContainsKey(weapon.info.shortname)) {
attackEntity.effectiveRange = Weapons[weapon.info.shortname].EffectiveRange;
attackEntity.attackLengthMin = Weapons[weapon.info.shortname].AttackLengthMin;
attackEntity.attackLengthMax = Weapons[weapon.info.shortname].AttackLengthMax;
}
attackEntity.aiOnlyInRange = true;
BaseProjectile baseProjectile = attackEntity as BaseProjectile;
if (baseProjectile.MuzzlePoint == null) baseProjectile.MuzzlePoint = baseProjectile.transform;
string ammo = Config.BeltItems.FirstOrDefault(x => x.ShortName == weapon.info.shortname).Ammo;
if (!string.IsNullOrEmpty(ammo)) {
baseProjectile.primaryMagazine.ammoType = ItemManager.FindItemDefinition(ammo);
baseProjectile.SendNetworkUpdateImmediate();
}
}
Invoke(FinishEquiping, 1.5f);
}
private void FinishEquiping() => _isEquiping = false;
private static int GetTypeWeaponItem(Item item) {
if (MeleeWeapons.Contains(item.info.shortname)) return 0;
if (FirstDistanceWeapons.Contains(item.info.shortname)) return 1;
if (SecondDistanceWeapons.Contains(item.info.shortname)) return 2;
if (ThirdDistanceWeapons.Contains(item.info.shortname)) return 3;
if (FourthDistanceWeapons.Contains(item.info.shortname)) return 4;
return -1;
}
#endregion Equip Weapons
public override void AttackerInfo(PlayerLifeStory.DeathInfo info) {
base.AttackerInfo(info);
if (CurrentWeapon != null) info.inflictorName = CurrentWeapon.ShortPrefabName;
info.attackerName = displayName;
}
protected override string OverrideCorpseName() => displayName;
public override float GetAimConeScale() => Config.AimConeScale;
#region Heal
private Coroutine _healCoroutine = null;
private bool _isHealing {
get;
set;
}
= false;
private bool CanHeal() {
if (_isHealing || health >= Config.Health || CurrentTarget != null || IsFireC4 || IsFireRocketLauncher || _isEquiping || inventory == null || inventory.containerBelt == null) return false;
return inventory.containerBelt.itemList.Any(x => x.info.shortname == "syringe.medical");
}
private IEnumerator Heal() {
_isHealing = true;
Item syringe = inventory.containerBelt.itemList.FirstOrDefault(x => x.info.shortname == "syringe.medical");
CurrentWeapon = null;
UpdateActiveItem(syringe.uid);
MedicalTool medicalTool = syringe.GetHeldEntity() as MedicalTool;
yield return CoroutineEx.waitForSeconds(1.5f);
if (medicalTool != null) medicalTool.ServerUse();
InitializeHealth(health + 15f > Config.Health ? Config.Health : health + 15f, Config.Health);
yield return CoroutineEx.waitForSeconds(2f);
_isHealing = false;
EquipWeapon();
}
#endregion Heal
#region Grenades
private readonly HashSet<string> _barricades = new HashSet<string> {
"barricade.cover.wood", "barricade.sandbags", "barricade.concrete", "barricade.stone"
}
;
private bool _isReloadGrenade {
get;
set;
}
= false;
private bool _isReloadSmoke {
get;
set;
}
= false;
private void FinishReloadGrenade() => _isReloadGrenade = false;
private void FinishReloadSmoke() => _isReloadSmoke = false;
private bool CanThrownGrenade() {
if (_isReloadGrenade || CurrentTarget == null || !IsBasePlayerTarget || inventory == null || inventory.containerBelt == null) return false;
return DistanceToTarget < 15f && inventory.containerBelt.itemList.Any(x => x.info.shortname == "grenade.f1" || x.info.shortname == "grenade.beancan" || x.info.shortname == "grenade.molotov" || x.info.shortname == "grenade.flashbang") && (!CanSeeTarget(CurrentTarget) || IsBehindBarricade());
}
internal bool IsBehindBarricade() => CanSeeTarget(CurrentTarget) && IsBarricade();
private bool IsBarricade() {
SetAimDirection((CurrentTarget.transform.position - transform.position).normalized);
RaycastHit[] hits = Physics.RaycastAll(eyes.HeadRay());
GamePhysics.Sort(hits);
return hits.Select(x => x.GetEntity() as Barricade).Any(x => x != null && _barricades.Contains(x.ShortPrefabName) && Vector3.Distance(transform.position, x.transform.position) < DistanceToTarget);
}
private void ThrownGrenade(Vector3 target) {
Item item = inventory.containerBelt.itemList.FirstOrDefault(x => x.info.shortname == "grenade.f1" || x.info.shortname == "grenade.beancan" || x.info.shortname == "grenade.molotov" || x.info.shortname == "grenade.flashbang");
if (item != null) {
GrenadeWeapon weapon = item.GetHeldEntity() as GrenadeWeapon;
if (weapon != null) {
Brain.Navigator.Stop();
SetAimDirection((target - transform.position).normalized);
weapon.ServerThrow(target);
_isReloadGrenade = true;
Invoke(FinishReloadGrenade, 10f);
}
}
}
internal void ThrownSmoke() {
if (!_isReloadSmoke) {
Item item = inventory.containerBelt.itemList.FirstOrDefault(x => x.info.shortname == "grenade.smoke");
if (item != null) {
GrenadeWeapon weapon = item.GetHeldEntity() as GrenadeWeapon;
if (weapon != null) {
weapon.ServerThrow(transform.position);
_isReloadSmoke = true;
Invoke(FinishReloadSmoke, 30f);
}
}
}
}
#endregion Grenades
#region Run Away Water
internal bool IsRunAwayWater {
get;
set;
}
= false;
private bool CanRunAwayWater() {
if (!Config.CanRunAwayWater || IsRunAwayWater) return false;
if (CurrentTarget == null) {
if (transform.position.y < -0.25f) return true;
else return false;
}
if (transform.position.y > -0.25f || TerrainMeta.HeightMap.GetHeight(CurrentTarget.transform.position) > -0.25f) return false;
if (CurrentWeapon is BaseProjectile && DistanceToTarget < EngagementRange()) return false;
if (CurrentWeapon is BaseMelee && DistanceToTarget < CurrentWeapon.effectiveRange) return false;
return true;
}
private void RunAwayWater() {
IsRunAwayWater = true;
CurrentTarget = null;
Invoke(FinishRunAwayWater, 20f);
}
private void FinishRunAwayWater() => IsRunAwayWater = false;
#endregion Run Away Water
#region Raid
internal bool IsRaidState {
get;
set;
}
= false;
internal bool IsRaidStateMelee {
get;
set;
}
= false;
internal bool IsReloadC4 {
get;
set;
}
= false;
internal bool IsReloadRocketLauncher {
get;
set;
}
= false;
internal bool IsFireRocketLauncher {
get;
set;
}
= false;
internal bool IsFireC4 {
get;
set;
}
= false;
private Coroutine _fireC4Coroutine = null;
private Coroutine _fireRocketLauncherCoroutine = null;
internal BaseCombatEntity Turret {
get;
set;
}
= null;
internal BaseCombatEntity PlayerTarget {
get;
set;
}
= null;
internal HashSet<BuildingBlock> Foundations {
get;
set;
}
= new HashSet<BuildingBlock>();
internal BaseCombatEntity CurrentRaidTarget {
get;
set;
}
= null;
internal float DistanceToCurrentRaidTarget => Vector3.Distance(transform.position, CurrentRaidTarget.transform.position);
internal void AddTurret(BaseCombatEntity turret) {
if (!Turret.IsExists() || Vector3.Distance(transform.position, turret.transform.position) < Vector3.Distance(transform.position, Turret.transform.position)) {
Turret = turret;
BuildingBlock block = GetNearEntity<BuildingBlock>(Turret.transform.position, 0.1f, 1 << 21);
CurrentRaidTarget = block.IsExists() ? block : Turret;
}
}
private static T GetNearEntity<T>(Vector3 position, float radius, int layerMask) where T : BaseCombatEntity {
List<T> list = Pool.GetList<T>();
Vis.Entities<T>(position, radius, list, layerMask);
T result = list.Count == 0 ? null : list.Min(s => Vector3.Distance(position, s.transform.position));
Pool.FreeList(ref list);
return result;
}
internal BaseCombatEntity GetRaidTarget() {
UpdateTargets();
BaseCombatEntity main = null;
if (IsRaidState) {
if (Turret != null) {
BuildingBlock block = GetNearEntity<BuildingBlock>(Turret.transform.position, 0.1f, 1 << 21);
main = block.IsExists() ? block : Turret;
}
else if (Foundations.Count > 0) main = Foundations.Min(x => Vector3.Distance(transform.position, x.transform.position));
else if (PlayerTarget != null) main = PlayerTarget;
}
else if (IsRaidStateMelee) {
if (Foundations.Count > 0) main = Foundations.Min(x => Vector3.Distance(transform.position, x.transform.position));
}
if (main == null) return null;
if (IsMounted()) return main;
NavMeshHit navMeshHit;
if (IsRaidState) {
float heightGround = TerrainMeta.HeightMap.GetHeight(main.transform.position);
if (main.transform.position.y - heightGround > 15f) {
main = GetNearEntity<BuildingBlock>(new Vector3(main.transform.position.x, heightGround, main.transform.position.z), 15f, 1 << 21);
if (main == null) return null;
}
if (NavMesh.SamplePosition(main.transform.position, out navMeshHit, 30f, NavAgent.areaMask)) {
NavMeshPath path = new NavMeshPath();
if (NavMesh.CalculatePath(transform.position, navMeshHit.position, NavAgent.areaMask, path)) {
if (path.status == NavMeshPathStatus.PathComplete) return main;
else return GetNearEntity<BaseCombatEntity>(path.corners.Last(), 5f, 1 << 8 | 1 << 21);
}
}
Vector2 pos1 = new Vector2(transform.position.x, transform.position.z);
Vector2 pos2 = new Vector2(main.transform.position.x, main.transform.position.z);
Vector2 pos3 = pos1 + (pos2 - pos1).normalized * (Vector2.Distance(pos1, pos2) - 30f);
Vector3 pos = new Vector3(pos3.x, 0f, pos3.y);
pos.y = TerrainMeta.HeightMap.GetHeight(pos);
main = GetNearEntity<BuildingBlock>(pos, 15f, 1 << 21);
if (main == null) return null;
if (NavMesh.SamplePosition(main.transform.position, out navMeshHit, 30f, NavAgent.areaMask)) {
NavMeshPath path = new NavMeshPath();
if (NavMesh.CalculatePath(transform.position, navMeshHit.position, NavAgent.areaMask, path)) {
if (path.status == NavMeshPathStatus.PathComplete) return main;
else return GetNearEntity<BaseCombatEntity>(path.corners.Last(), 5f, 1 << 8 | 1 << 21);
}
}
}
else if (IsRaidStateMelee) {
if (NavMesh.SamplePosition(main.transform.position, out navMeshHit, 30f, NavAgent.areaMask)) {
NavMeshPath path = new NavMeshPath();
if (NavMesh.CalculatePath(transform.position, navMeshHit.position, NavAgent.areaMask, path)) {
if (path.status == NavMeshPathStatus.PathComplete && Vector3.Distance(navMeshHit.position, main.transform.position) < 6f) return main;
else return GetNearEntity<BaseCombatEntity>(path.corners.Last(), 6f, 1 << 8 | 1 << 21);
}
}
}
return main;
}
private void UpdateTargets() {
if (!Turret.IsExists()) Turret = null;
if (!PlayerTarget.IsExists()) PlayerTarget = null;
foreach (BuildingBlock ent in Foundations.Where(x => !x.IsExists())) Foundations.Remove(ent);
if (!CurrentRaidTarget.IsExists()) CurrentRaidTarget = null;
}
internal bool StartExplosion(BaseCombatEntity target) {
if (target == null) return false;
if (CanThrownC4(target)) {
_fireC4Coroutine = ServerMgr.Instance.StartCoroutine(ThrownC4(target));
return true;
}
if (CanRaidRocketLauncher(target)) {
ThrownSmoke();
_fireRocketLauncherCoroutine = ServerMgr.Instance.StartCoroutine(ProcessFireRocketLauncher(target));
return true;
}
return false;
}
internal bool HasRocketLauncher() => inventory.containerBelt.itemList.Any(x => x.info.shortname == "rocket.launcher");
private bool CanRaidRocketLauncher(BaseCombatEntity target) => !IsReloadRocketLauncher && !IsFireRocketLauncher && !_isEquiping && !_isHealing && HasRocketLauncher() && Vector3.Distance(transform.position, target.transform.position) < 30f;
private IEnumerator ProcessFireRocketLauncher(BaseCombatEntity target) {
IsFireRocketLauncher = true;
EquipRocketLauncher();
if (!IsMounted()) SetDucked(true);
Brain.Navigator.Stop();
Brain.Navigator.SetFacingDirectionEntity(target);
yield return CoroutineEx.waitForSeconds(1.5f);
if (target.IsExists()) {
if (target.ShortPrefabName.Contains("foundation")) {
Brain.Navigator.ClearFacingDirectionOverride();
SetAimDirection((target.transform.position - new Vector3(0f, 1.5f, 0f) - transform.position).normalized);
}
FireRocketLauncher();
IsReloadRocketLauncher = true;
Invoke(FinishReloadRocketLauncher, 6f);
}
IsFireRocketLauncher = false;
EquipWeapon();
Brain.Navigator.ClearFacingDirectionOverride();
if (!IsMounted()) SetDucked(false);
}
private void EquipRocketLauncher() {
Item item = inventory.containerBelt.itemList.FirstOrDefault(x => x.info.shortname == "rocket.launcher");
CurrentWeapon = null;
UpdateActiveItem(item.uid);
}
private void FireRocketLauncher() {
RaycastHit raycastHit;
SignalBroadcast(Signal.Attack, string.Empty);
Vector3 vector3 = IsMounted() ? eyes.position + new Vector3(0f, 0.5f, 0f) : eyes.position;
Vector3 modifiedAimConeDirection = AimConeUtil.GetModifiedAimConeDirection(2.25f, eyes.BodyForward());
float single = 1f;
if (Physics.Raycast(vector3, modifiedAimConeDirection, out raycastHit, single, 1236478737)) single = raycastHit.distance - 0.1f;
TimedExplosive rocket = GameManager.server.CreateEntity("assets/prefabs/ammo/rocket/rocket_basic.prefab", vector3 + modifiedAimConeDirection * single) as TimedExplosive;
rocket.creatorEntity = this;
ServerProjectile serverProjectile = rocket.GetComponent<ServerProjectile>();
serverProjectile.InitializeVelocity(GetInheritedProjectileVelocity(modifiedAimConeDirection) + modifiedAimConeDirection * serverProjectile.speed * 2f);
rocket.Spawn();
}
private void FinishReloadRocketLauncher() => IsReloadRocketLauncher = false;
internal bool HasC4() => inventory.containerBelt.itemList.Any(x => x.info.shortname == "explosive.timed");
private bool CanThrownC4(BaseCombatEntity target) => !IsReloadC4 && !IsFireC4 && HasC4() && Vector3.Distance(transform.position, target.transform.position) < 5f;
private IEnumerator ThrownC4(BaseCombatEntity target) {
Item item = inventory.containerBelt.itemList.FirstOrDefault(x => x.info.shortname == "explosive.timed");
IsFireC4 = true;
Brain.Navigator.Stop();
Brain.Navigator.SetFacingDirectionEntity(target);
yield return CoroutineEx.waitForSeconds(1.5f);
if (target.IsExists()) {
(item.GetHeldEntity() as ThrownWeapon).ServerThrow(target.transform.position);
IsReloadC4 = true;
Invoke(FinishReloadC4, 15f);
}
IsFireC4 = false;
Brain.Navigator.ClearFacingDirectionOverride();
}
private void FinishReloadC4() => IsReloadC4 = false;
private static bool IsTeam(ulong playerId, ulong targetId) {
if (playerId == 0 || targetId == 0) return false;
if (playerId == targetId) return true;
RelationshipManager.PlayerTeam playerTeam = RelationshipManager.ServerInstance.FindPlayersTeam(playerId);
if (playerTeam != null && playerTeam.members.Contains(targetId)) return true;
if (_ins.plugins.Exists("Friends") && (bool)_ins.Friends.Call("AreFriends", playerId, targetId)) return true;
if (_ins.plugins.Exists("Clans") && _ins.Clans.Author == "k1lly0u" && (bool)_ins.Clans.Call("IsMemberOrAlly", playerId.ToString(), targetId.ToString())) return true;
return false;
}
#endregion Raid
#region Guard
private Vector3 _beforeGuardHomePosition {
get;
set;
}
= Vector3.zero;
private BaseEntity _guardTarget {
get;
set;
}
= null;
internal void AddTargetGuard(BaseEntity target) {
_beforeGuardHomePosition = HomePosition;
_guardTarget = target;
}
#endregion Guard
#region Parent
private BaseEntity _parentEntity {
get;
set;
}
= null;
private Vector3 _localPos {
get;
set;
}
= Vector3.zero;
internal void SetParentEntity(BaseEntity parent, Vector3 pos) {
_parentEntity = parent;
_localPos = pos;
InvokeRepeating(UpdateHomePositionParent, 0f, 1f);
}
private void UpdateHomePositionParent() {
if (_parentEntity != null) HomePosition = _parentEntity.transform.TransformPoint(_localPos);
else {
_localPos = Vector3.zero;
CancelInvoke(UpdateHomePositionParent);
}
}
#endregion Parent
#region Multiple Grenade Launcher
internal bool IsReloadGrenadeLauncher {
get;
set;
}
= false;
private int _countAmmoInGrenadeLauncher {
get;
set;
}
= 6;
internal void FireGrenadeLauncher() {
RaycastHit raycastHit;
SignalBroadcast(Signal.Attack, string.Empty);
Vector3 vector3 = IsMounted() ? eyes.position + new Vector3(0f, 0.5f, 0f) : eyes.position;
Vector3 modifiedAimConeDirection = AimConeUtil.GetModifiedAimConeDirection(0.675f, eyes.BodyForw
// ... [Code preview truncated due to length. Full source in attached file] ...