using System; using System.Collections.Generic; using GazeLab.Combat; using GazeLab.Core; using GazeLab.Data; using GazeLab.InputSystem; using UnityEngine; namespace GazeLab.Entities { [Serializable] public class StationTurretSlotState { public int slotIndex; public bool isUnlocked; public WeaponDefinition equippedWeapon; public TurretController runtimeTurret; public TurretTargetPriority priority = TurretTargetPriority.NearestThreat; } [Serializable] public class StationAbilitySlotState { public StationAbilityDefinition definition; public bool isUnlocked; public int currentTier = 1; public float cooldownRemaining; } public sealed class SpaceStationController : MonoBehaviour { public static SpaceStationController Instance { get; private set; } [Header("Station Evolution Tiers (Level 1 to 8)")] public StationLevelDefinition[] levelDefinitions; [Range(1, 8)] public int currentLevel = 1; [Header("Starting Loadout & Available Tech")] public WeaponDefinition startingPrimaryWeapon; public WeaponDefinition[] rootPurchaseableWeapons; [Header("Station Abilities (Keys 1, 2, 3, 4)")] public StationAbilityDefinition[] abilityDefinitions; [Header("Dwell Lock-On & Hover Tractor Parameters")] [Range(0.25f, 1.5f)] public float baseDwellLockDuration = 0.65f; [Range(0.15f, 0.85f)] public float gazeTrackingGraceSeconds = 0.25f; [Range(0.5f, 3.0f)] public float cursorResourceHoverRadius = 1.35f; [Range(0.35f, 2.0f)] public float cursorCombatAcquireRadius = 0.75f; [Header("Auto-Turret Balance Multipliers")] [Tooltip("Global damage multiplier applied specifically to autonomous turrets (slots 1+). Set lower if auto-turrets are doing too much damage.")] [Range(0.1f, 2.0f)] public float autoTurretDamageMultiplier = 0.65f; [Tooltip("Global fire rate multiplier applied specifically to autonomous turrets (slots 1+).")] [Range(0.1f, 2.0f)] public float autoTurretFireRateMultiplier = 0.75f; [Header("Runtime References")] public SpriteRenderer stationHullRenderer; public DamageableEntity stationDamageable; private readonly List turretSlots = new List(); private readonly List abilitySlots = new List(); private readonly List unlockedWeapons = new List(); private readonly StationStatsModel statsModel = new StationStatsModel(); // Runtime targeting & firing state private DamageableEntity currentHoveredTarget; private float dwellHeldSeconds; private float lastTargetSeenTime; private float nextLockedPrimaryShotTime; private Vector3 currentCursorWorldPos; private bool isCursorValid; public DamageableEntity StationDamageable => stationDamageable; public DamageableEntity CurrentHoveredTarget => currentHoveredTarget; public Vector3 CurrentCursorWorldPos => currentCursorWorldPos; public bool IsCursorValid => isCursorValid; public IReadOnlyList TurretSlots => turretSlots; public IReadOnlyList AbilitySlots => abilitySlots; public IReadOnlyList UnlockedWeapons => unlockedWeapons; public StationStatsModel Stats => statsModel; public float abilityCooldownReductionBonus => statsModel.AbilityCooldownReduction; public float resourceDropBonusMultiplier => statsModel.ResourceDropBonusMultiplier; public float BonusAsteroidSplitChance => statsModel.BonusAsteroidSplitChance; public float GlobalDamageMultiplier => statsModel.EffectiveDamageMultiplier; public float GlobalFireRateMultiplier => statsModel.EffectiveFireRateMultiplier; public StationLevelDefinition CurrentLevelDef { get { if (levelDefinitions == null || levelDefinitions.Length == 0) return null; int idx = Mathf.Clamp(currentLevel - 1, 0, levelDefinitions.Length - 1); return levelDefinitions[idx]; } } public StationLevelDefinition NextLevelDef { get { if (levelDefinitions == null || currentLevel >= levelDefinitions.Length) return null; return levelDefinitions[currentLevel]; } } public float CurrentWorldScale => CurrentLevelDef != null ? CurrentLevelDef.worldEntityScaleMultiplier : 1f; public float CurrentMagnetRadius => statsModel.ComputeTotalMagnetRadius(CurrentLevelDef) + GazeLab.Core.MetaProgressionManager.Instance.GetActiveRunBonuses().bonusMagnetRadius; public float CurrentDwellDuration => statsModel.ComputeDwellDuration(baseDwellLockDuration); public float DwellProgress => currentHoveredTarget != null ? Mathf.Clamp01(dwellHeldSeconds / CurrentDwellDuration) : 0f; public bool IsTargetLocked => currentHoveredTarget != null && dwellHeldSeconds >= CurrentDwellDuration; public event Action OnStationLevelChanged; public event Action OnLoadoutChanged; private void Awake() { Instance = this; if (stationHullRenderer == null) { stationHullRenderer = GetComponent(); if (stationHullRenderer == null) stationHullRenderer = gameObject.AddComponent(); } if (stationDamageable == null) { stationDamageable = GetComponent(); if (stationDamageable == null) stationDamageable = gameObject.AddComponent(); } stationHullRenderer.sortingOrder = 8; stationDamageable.category = EntityCategory.PlayerStation; stationDamageable.displayName = "Orbital Command Station"; stationDamageable.mainSpriteRenderer = stationHullRenderer; } public void InitializeStationForNewGame() { gameObject.SetActive(true); if (stationDamageable != null) { stationDamageable.gameObject.SetActive(true); stationDamageable.category = EntityCategory.PlayerStation; } currentLevel = 1; statsModel.Reset(); // Apply persistent Rogue-Lite Meta Run Bonuses GazeLab.Core.MetaRunBonuses meta = GazeLab.Core.MetaProgressionManager.Instance.GetActiveRunBonuses(); statsModel.MetaHullMultiplier = meta.baseHullMultiplier; statsModel.MetaFlatBonusHull = meta.flatBonusHull; statsModel.MetaShieldMultiplier = meta.baseShieldMultiplier; statsModel.MetaBonusShieldRegen = meta.bonusShieldRegen; statsModel.MetaDamageMultiplier = meta.baseDamageMultiplier; statsModel.MetaFireRateMultiplier = meta.baseFireRateMultiplier; statsModel.MetaDwellReductionFraction = meta.gazeDwellReductionFraction; statsModel.MetaFlatDamageReduction = meta.flatDamageReductionFraction; autoTurretFireRateMultiplier = meta.autoTurretSpeedMultiplier; unlockedWeapons.Clear(); if (startingPrimaryWeapon != null) { unlockedWeapons.Add(startingPrimaryWeapon); } InitializeAbilitySlots(); if (meta.unlockHarpoonAtStart) { UnlockAbilityRobust(null, "harpoon", 1); } RebuildHardpointsForCurrentLevel(resetToStartingState: true); ApplyStationLevelStats(fullHeal: true); OnLoadoutChanged?.Invoke(); } private void InitializeAbilitySlots() { abilitySlots.Clear(); if (abilityDefinitions == null || abilityDefinitions.Length == 0) { #if UNITY_EDITOR abilityDefinitions = new[] { UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/GazeLab/ScriptableObjects/Abilities/Ability_HarpoonGrapple.asset"), UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/GazeLab/ScriptableObjects/Abilities/Ability_EmpShockwave.asset"), UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/GazeLab/ScriptableObjects/Abilities/Ability_AegisOvercharge.asset"), UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/GazeLab/ScriptableObjects/Abilities/Ability_MissileSwarm.asset") }; #endif } if (abilityDefinitions == null) return; for (int i = 0; i < abilityDefinitions.Length; i++) { if (abilityDefinitions[i] == null) continue; abilitySlots.Add(new StationAbilitySlotState { definition = abilityDefinitions[i], isUnlocked = false, currentTier = 1, cooldownRemaining = 0f }); } } public void UpgradeStationToNextLevel() { if (NextLevelDef == null) return; currentLevel++; RebuildHardpointsForCurrentLevel(resetToStartingState: false); ApplyStationLevelStats(fullHeal: false); ShockwaveExplosionController.Spawn(transform.position, null, null, 1.85f, new Color(0.35f, 0.95f, 1f)); DamageableEntity.OnSpawnFloatingText?.Invoke( transform.position + Vector3.up * 1.1f, $"STATION UPGRADED: LVL {currentLevel} ({(CurrentLevelDef != null ? CurrentLevelDef.title.ToUpper() : "CITADEL")})!", new Color(0.35f, 1f, 0.85f), 1.25f); BroadcastWorldScaleToActiveEntities(); OnStationLevelChanged?.Invoke(currentLevel, CurrentWorldScale); OnLoadoutChanged?.Invoke(); } private void ApplyStationLevelStats(bool fullHeal) { StationLevelDefinition def = CurrentLevelDef; if (def == null) return; if (stationHullRenderer != null && def.stationSprite != null) { stationHullRenderer.sprite = def.stationSprite; } transform.localScale = Vector3.one * def.stationVisualScale; float prevHullPct = stationDamageable != null && stationDamageable.maxHull > 0f ? stationDamageable.HullRatio : 1f; float totalMaxHull = statsModel.ComputeTotalMaxHull(def); float totalMaxShield = statsModel.ComputeTotalMaxShield(def); float totalShieldRegen = statsModel.ComputeTotalShieldRegen(def); stationDamageable.targetHitRadius = 0.95f; stationDamageable.shieldRegenDelay = def.shieldRegenDelay; if (fullHeal) { stationDamageable.InitializeStats( totalMaxHull, totalMaxShield, totalShieldRegen, armored: (currentLevel >= 4) || (statsModel.MetaFlatDamageReduction > 0f), armorReduction: Mathf.Clamp(Mathf.Min(0.45f, (currentLevel - 1) * 0.06f) + statsModel.MetaFlatDamageReduction, 0f, 0.75f), neededChains: 99, shieldProfile: def.shieldCentroidProfile); } else { stationDamageable.isArmored = (currentLevel >= 4) || (statsModel.MetaFlatDamageReduction > 0f); stationDamageable.armorDamageReduction = Mathf.Clamp(Mathf.Min(0.45f, (currentLevel - 1) * 0.06f) + statsModel.MetaFlatDamageReduction, 0f, 0.75f); float healBonus = Mathf.Max(40f, (totalMaxHull - stationDamageable.maxHull) + 35f); float shieldBonus = Mathf.Max(0f, totalMaxShield - stationDamageable.maxShield); stationDamageable.SyncMaxStatsWithBonus( totalMaxHull, totalMaxShield, totalShieldRegen, healBonus, shieldBonus, def.shieldCentroidProfile); stationDamageable.currentHull = Mathf.Max(stationDamageable.currentHull, totalMaxHull * Mathf.Max(0.55f, prevHullPct)); } } private Vector2[] GetEffectiveHardpointsForCurrentLevel(StationLevelDefinition def) { if (def == null || def.turretHardpoints == null || def.turretHardpoints.Length == 0) { return new[] { new Vector2(0f, 0.45f) }; } return def.turretHardpoints; } private void RebuildHardpointsForCurrentLevel(bool resetToStartingState) { StationLevelDefinition def = CurrentLevelDef; Vector2[] points = GetEffectiveHardpointsForCurrentLevel(def); if (resetToStartingState) { for (int i = 0; i < turretSlots.Count; i++) { if (turretSlots[i].runtimeTurret != null) Destroy(turretSlots[i].runtimeTurret.gameObject); } turretSlots.Clear(); } float mountScale = def != null ? def.mountedTurretScaleMultiplier : 0.85f; for (int i = 0; i < points.Length; i++) { StationTurretSlotState slot; if (i < turretSlots.Count) { slot = turretSlots[i]; slot.isUnlocked = true; } else { // Auto-assign any unused unlocked weapon to newly unlocked hardpoints, or fallback to starting weapon WeaponDefinition initialWeapon = (i == 0) ? startingPrimaryWeapon : PickDefaultWeaponForNewSlot(i); slot = new StationTurretSlotState { slotIndex = i, isUnlocked = true, equippedWeapon = initialWeapon, priority = (TurretTargetPriority)(i % 4) }; turretSlots.Add(slot); } if (slot.runtimeTurret == null) { GameObject tGo = new GameObject($"StationTurretSlot_{i}"); tGo.transform.SetParent(transform, false); slot.runtimeTurret = tGo.AddComponent(); } slot.runtimeTurret.transform.localPosition = new Vector3(points[i].x, points[i].y, 0f); RefreshTurretSlot(slot, mountScale); } // Remove any excess turret slots if the new level has fewer hardpoints than previously spawned slots while (turretSlots.Count > points.Length) { int lastIdx = turretSlots.Count - 1; if (turretSlots[lastIdx].runtimeTurret != null) { Destroy(turretSlots[lastIdx].runtimeTurret.gameObject); } turretSlots.RemoveAt(lastIdx); } } private WeaponDefinition PickDefaultWeaponForNewSlot(int slotIndex) { // Prefer an unlocked weapon not currently mounted in another slot for (int w = unlockedWeapons.Count - 1; w >= 0; w--) { WeaponDefinition cand = unlockedWeapons[w]; if (cand == null) continue; bool alreadyMounted = false; for (int s = 0; s < turretSlots.Count; s++) { if (turretSlots[s].equippedWeapon == cand) { alreadyMounted = true; break; } } if (!alreadyMounted) return cand; } return unlockedWeapons.Count > 0 ? unlockedWeapons[unlockedWeapons.Count - 1] : startingPrimaryWeapon; } public void RefreshTurretSlot(StationTurretSlotState slot, float? overrideMountScale = null) { if (slot == null || slot.runtimeTurret == null) return; float mountScale = overrideMountScale ?? (CurrentLevelDef != null ? CurrentLevelDef.mountedTurretScaleMultiplier : 0.85f); if (!slot.isUnlocked || slot.equippedWeapon == null) { slot.runtimeTurret.gameObject.SetActive(false); return; } slot.runtimeTurret.gameObject.SetActive(true); bool autoFire = slot.slotIndex > 0 || currentLevel >= 3; slot.runtimeTurret.targetPriority = slot.priority; slot.runtimeTurret.ConfigureTurret( slot.equippedWeapon, playerOwned: true, autoFire: autoFire, scaleMult: mountScale, defaultRestAngle: 90f, owner: stationDamageable, sortingOrder: stationHullRenderer.sortingOrder + 3 + slot.slotIndex); slot.runtimeTurret.SetGlobalBuffs(GlobalDamageMultiplier, GlobalFireRateMultiplier, CurrentWorldScale, autoTurretDamageMultiplier, autoTurretFireRateMultiplier); } public void RefreshAllTurretSlots() { for (int i = 0; i < turretSlots.Count; i++) { RefreshTurretSlot(turretSlots[i]); } } public void EquipOrUpgradeWeaponInSlot(int slotIndex, WeaponDefinition newWeapon) { if (slotIndex < 0 || slotIndex >= turretSlots.Count || newWeapon == null) return; if (!unlockedWeapons.Contains(newWeapon)) { unlockedWeapons.Add(newWeapon); } StationTurretSlotState slot = turretSlots[slotIndex]; slot.isUnlocked = true; slot.equippedWeapon = newWeapon; RefreshTurretSlot(slot); OnLoadoutChanged?.Invoke(); } public void CycleSlotEquippedWeapon(int slotIndex) { if (slotIndex < 0 || slotIndex >= turretSlots.Count || unlockedWeapons.Count == 0) return; StationTurretSlotState slot = turretSlots[slotIndex]; int curIdx = unlockedWeapons.IndexOf(slot.equippedWeapon); int nextIdx = (curIdx + 1) % unlockedWeapons.Count; slot.equippedWeapon = unlockedWeapons[nextIdx]; RefreshTurretSlot(slot); OnLoadoutChanged?.Invoke(); } public void CycleSlotTargetPriority(int slotIndex) { if (slotIndex < 0 || slotIndex >= turretSlots.Count) return; StationTurretSlotState slot = turretSlots[slotIndex]; slot.priority = (TurretTargetPriority)(((int)slot.priority + 1) % 4); if (slot.runtimeTurret != null) slot.runtimeTurret.targetPriority = slot.priority; OnLoadoutChanged?.Invoke(); } public void ApplyTechTreeNode(UpgradeTreeNodeSO node, int rank = 1) { if (node == null) return; float statStep = node.GetSingleRankStatStep(); switch (node.category) { case TechNodeCategory.StatBuff: statsModel.ApplyStatIncrement(node.statType, statStep, out float addedHull, out float addedShield); if (stationDamageable != null && CurrentLevelDef != null) { stationDamageable.SyncMaxStatsWithBonus( statsModel.ComputeTotalMaxHull(CurrentLevelDef), statsModel.ComputeTotalMaxShield(CurrentLevelDef), statsModel.ComputeTotalShieldRegen(CurrentLevelDef), addedHull, addedShield, CurrentLevelDef.shieldCentroidProfile); } RefreshAllTurretSlots(); break; case TechNodeCategory.WeaponUnlock: WeaponDefinition targetWep = node.GetWeaponForRank(rank); UnlockWeaponRobust(targetWep, node.nodeId); break; case TechNodeCategory.AbilityUnlock: UnlockAbilityRobust(node.unlockedAbility, node.nodeId, rank); break; case TechNodeCategory.StationEvolution: UpgradeStationToNextLevel(); break; } } public void UnlockAbilityRobust(StationAbilityDefinition targetDef, string nodeId, int targetRank = 1) { int desiredTier = Mathf.Max(1, targetRank); if (targetDef != null) { for (int i = 0; i < abilitySlots.Count; i++) { if (abilitySlots[i].definition == targetDef || (abilitySlots[i].definition != null && abilitySlots[i].definition.abilityId == targetDef.abilityId)) { abilitySlots[i].isUnlocked = true; int maxT = abilitySlots[i].definition != null ? Mathf.Max(1, abilitySlots[i].definition.maxAbilityTier) : 3; abilitySlots[i].currentTier = Mathf.Clamp(Mathf.Max(abilitySlots[i].currentTier, desiredTier), 1, maxT); OnLoadoutChanged?.Invoke(); return; } } } string id = (nodeId ?? "").ToLowerInvariant(); StationAbilityType matchType = StationAbilityType.HarpoonGrappleChain; int fallbackIdx = 0; if (id.Contains("harpoon")) { matchType = StationAbilityType.HarpoonGrappleChain; fallbackIdx = 0; } else if (id.Contains("emp")) { matchType = StationAbilityType.EmpShockwave; fallbackIdx = 1; } else if (id.Contains("aegis")) { matchType = StationAbilityType.AegisShieldOvercharge; fallbackIdx = 2; } else if (id.Contains("missile") || id.Contains("swarm")) { matchType = StationAbilityType.MissileSwarm; fallbackIdx = 3; } for (int i = 0; i < abilitySlots.Count; i++) { if (abilitySlots[i].definition != null && abilitySlots[i].definition.abilityType == matchType) { abilitySlots[i].isUnlocked = true; int maxT = Mathf.Max(1, abilitySlots[i].definition.maxAbilityTier); abilitySlots[i].currentTier = Mathf.Clamp(Mathf.Max(abilitySlots[i].currentTier, desiredTier), 1, maxT); OnLoadoutChanged?.Invoke(); return; } } if (fallbackIdx >= 0 && fallbackIdx < abilitySlots.Count) { abilitySlots[fallbackIdx].isUnlocked = true; abilitySlots[fallbackIdx].currentTier = Mathf.Max(abilitySlots[fallbackIdx].currentTier, desiredTier); OnLoadoutChanged?.Invoke(); } } public void UnlockWeaponRobust(WeaponDefinition wep, string nodeId) { if (wep == null) { #if UNITY_EDITOR string id = (nodeId ?? "").ToLowerInvariant(); if (id.Contains("vulcan") || id.Contains("phys") || id.Contains("core")) wep = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/GazeLab/ScriptableObjects/Weapons/Wep_Phys_Lv1.asset"); else if (id.Contains("tesla") || id.Contains("electro")) wep = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/GazeLab/ScriptableObjects/Weapons/Wep_Electro_Lv1.asset"); else if (id.Contains("plasma")) wep = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/GazeLab/ScriptableObjects/Weapons/Wep_Plasma_Lv1.asset"); else if (id.Contains("microwave") || id.Contains("wave")) wep = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/GazeLab/ScriptableObjects/Weapons/Wep_Wave_Lv1.asset"); else if (id.Contains("gauss")) wep = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/GazeLab/ScriptableObjects/Weapons/Wep_Gauss_Lv1.asset"); else if (id.Contains("rocket")) wep = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/GazeLab/ScriptableObjects/Weapons/Wep_Special_RocketLauncher.asset"); else if (id.Contains("void")) wep = UnityEditor.AssetDatabase.LoadAssetAtPath("Assets/GazeLab/ScriptableObjects/Weapons/Wep_Special_Void.asset"); #endif } if (wep == null) return; // Replace lower-tier weapon of same family in unlockedWeapons list, or add new weapon bool replacedInInventory = false; for (int i = 0; i < unlockedWeapons.Count; i++) { WeaponDefinition existing = unlockedWeapons[i]; if (existing != null && existing.family == wep.family && existing.family != WeaponFamily.Special && wep.tierLevel > existing.tierLevel) { unlockedWeapons[i] = wep; replacedInInventory = true; break; } } if (!replacedInInventory && !unlockedWeapons.Contains(wep)) { unlockedWeapons.Add(wep); } // 1. If a turret slot already has an older tier of the same WeaponFamily equipped, upgrade that slot in-place! for (int i = 0; i < turretSlots.Count; i++) { WeaponDefinition cur = turretSlots[i].equippedWeapon; if (cur != null && cur.family == wep.family && cur.family != WeaponFamily.Special && wep.tierLevel >= cur.tierLevel) { EquipOrUpgradeWeaponInSlot(i, wep); return; } } // 2. Otherwise, if there is an empty unlocked hardpoint slot, equip the new weapon there! for (int i = 0; i < turretSlots.Count; i++) { if (!turretSlots[i].isUnlocked || turretSlots[i].equippedWeapon == null) { EquipOrUpgradeWeaponInSlot(i, wep); return; } } // 3. If the player only has 1 slot unlocked (Level 1 Station) and unlocked a brand-new weapon, equip it in Slot 0; // if they have multiple slots all occupied, equip into the last auxiliary slot (never silently overwriting Slot 0!) int targetSlot = turretSlots.Count > 1 ? turretSlots.Count - 1 : 0; EquipOrUpgradeWeaponInSlot(targetSlot, wep); } private void BroadcastWorldScaleToActiveEntities() { float scale = CurrentWorldScale; for (int i = 0; i < AsteroidController.ActiveAsteroids.Count; i++) { if (AsteroidController.ActiveAsteroids[i] != null) AsteroidController.ActiveAsteroids[i].ApplyWorldScale(scale); } for (int i = 0; i < EnemyShipController.ActiveShips.Count; i++) { if (EnemyShipController.ActiveShips[i] != null) EnemyShipController.ActiveShips[i].ApplyWorldScale(scale); } for (int i = 0; i < ResourcePickupController.ActivePickups.Count; i++) { if (ResourcePickupController.ActivePickups[i] != null) ResourcePickupController.ActivePickups[i].SetWorldScale(scale); } } private void Update() { if (stationDamageable == null || !stationDamageable.IsAlive) return; if (Time.timeScale <= 0.001f) return; float dt = Time.deltaTime; // Update Ability Cooldowns & Hotkeys for (int i = 0; i < abilitySlots.Count; i++) { StationAbilitySlotState ab = abilitySlots[i]; if (!ab.isUnlocked || ab.definition == null) continue; if (ab.cooldownRemaining > 0f) ab.cooldownRemaining = Mathf.Max(0f, ab.cooldownRemaining - dt); if (ab.cooldownRemaining <= 0f && UnityEngine.Input.GetKeyDown(ab.definition.hotkey)) { TryActivateAbility(i); } } UpdateCursorAndDwellTargeting(dt); } private void UpdateCursorAndDwellTargeting(float dt) { IAimInputSource input = InputModeManager.Instance; Vector2 screenPos = Vector2.zero; isCursorValid = input != null && input.TryGetScreenPosition(out screenPos); if (!isCursorValid) { if (currentHoveredTarget != null && (Time.time - lastTargetSeenTime) > gazeTrackingGraceSeconds) { SwitchHoveredTarget(null); } return; } if (CameraViewportService.MainCamera == null) return; Vector3 worldPt = CameraViewportService.ScreenToWorldPoint2D(screenPos); currentCursorWorldPos = worldPt; // 1. Instant Resource Tractor Suction on Hover TriggerHoverResourceSuction(worldPt); // 2. Timed Dwell Lock-On for Combat Targets DamageableEntity hitTarget = FindBestCombatTargetAtPoint(worldPt); if (hitTarget != null && hitTarget == currentHoveredTarget) { dwellHeldSeconds += dt; lastTargetSeenTime = Time.time; } else if (hitTarget != null) { SwitchHoveredTarget(hitTarget); } else if (currentHoveredTarget != null && (Time.time - lastTargetSeenTime) > gazeTrackingGraceSeconds) { SwitchHoveredTarget(null); } // 3. Point Primary Turret toward Predicted Target (when locked) or Cursor if (turretSlots.Count > 0 && turretSlots[0].runtimeTurret != null) { if (IsTargetLocked && currentHoveredTarget != null && currentHoveredTarget.IsAlive) { float projSpeed = (turretSlots[0].equippedWeapon != null && turretSlots[0].equippedWeapon.projectile != null) ? turretSlots[0].equippedWeapon.projectile.speed : 12f; Vector3 leadAim = CalculateLeadAimPoint(turretSlots[0].runtimeTurret.transform.position, currentHoveredTarget, projSpeed); turretSlots[0].runtimeTurret.AimTowardWorldPoint(leadAim, dt); } else { turretSlots[0].runtimeTurret.AimTowardWorldPoint(worldPt, dt); } } // 4. Fire Primary Turret & Command Focus-Fire when Dwell Lock-On is complete if (IsTargetLocked && currentHoveredTarget != null && currentHoveredTarget.IsAlive) { for (int i = 0; i < turretSlots.Count; i++) { if (turretSlots[i].isUnlocked && turretSlots[i].runtimeTurret != null) { turretSlots[i].runtimeTurret.SetFocusTarget(currentHoveredTarget, 1.5f); } } if (turretSlots.Count > 0 && turretSlots[0].runtimeTurret != null && Time.time >= nextLockedPrimaryShotTime) { WeaponDefinition pWep = turretSlots[0].equippedWeapon; float rate = (pWep != null ? pWep.shotsPerSecond : 3.0f) * GlobalFireRateMultiplier; nextLockedPrimaryShotTime = Time.time + (1f / Mathf.Max(0.2f, rate)); turretSlots[0].runtimeTurret.TriggerWeaponFire(currentHoveredTarget); } } } public static Vector3 CalculateLeadAimPoint(Vector3 origin, DamageableEntity target, float projectileSpeed) { if (target == null) return origin; Vector3 targetPos = target.transform.position; Vector3 targetVel = target.EstimatedVelocity; float dist = Vector3.Distance(origin, targetPos); float leadTime = dist / Mathf.Max(1f, projectileSpeed); Vector3 predicted = targetPos + targetVel * leadTime; predicted.z = 0f; return predicted; } private void TriggerHoverResourceSuction(Vector3 worldPt) { float radSq = cursorResourceHoverRadius * cursorResourceHoverRadius; var list = ResourcePickupController.ActivePickups; for (int i = 0; i < list.Count; i++) { ResourcePickupController pickup = list[i]; if (pickup == null || pickup.IsBeingSucked) continue; Vector3 diff = pickup.transform.position - worldPt; diff.z = 0f; if (diff.sqrMagnitude <= radSq) { pickup.ActivateTractorSuction(transform); } } } private DamageableEntity FindBestCombatTargetAtPoint(Vector3 worldPt) { var list = DamageableEntity.ActiveEntities; DamageableEntity best = null; float bestDistSq = float.MaxValue; for (int i = 0; i < list.Count; i++) { DamageableEntity ent = list[i]; if (ent == null || !ent.IsAlive || ent.IsPlayerStation) continue; float hitRad = ent.targetHitRadius + cursorCombatAcquireRadius; Vector3 diff = ent.transform.position - worldPt; diff.z = 0f; float dSq = diff.sqrMagnitude; if (dSq <= hitRad * hitRad) { float weightedDist = ent.category == EntityCategory.BossSubTurret ? dSq * 0.45f : dSq; if (weightedDist < bestDistSq) { bestDistSq = weightedDist; best = ent; } } } return best; } private void SwitchHoveredTarget(DamageableEntity next) { if (currentHoveredTarget != null) currentHoveredTarget.SetHoveredHighlight(false); currentHoveredTarget = next; dwellHeldSeconds = 0f; lastTargetSeenTime = Time.time; if (currentHoveredTarget != null) currentHoveredTarget.SetHoveredHighlight(true); } public bool TryActivateAbility(int slotIndex) { if (slotIndex < 0 || slotIndex >= abilitySlots.Count) return false; StationAbilitySlotState state = abilitySlots[slotIndex]; if (!state.isUnlocked || state.definition == null || state.cooldownRemaining > 0f) return false; StationAbilityDefinition def = state.definition; state.cooldownRemaining = def.cooldownSeconds * Mathf.Max(0.15f, 1f - abilityCooldownReductionBonus); switch (def.abilityType) { case StationAbilityType.HarpoonGrappleChain: ExecuteHarpoonAbility(state); break; case StationAbilityType.EmpShockwave: ExecuteEmpShockwaveAbility(state); break; case StationAbilityType.AegisShieldOvercharge: ExecuteAegisOverchargeAbility(state); break; case StationAbilityType.MissileSwarm: ExecuteMissileSwarmAbility(state); break; } if (def.activationSfx != null) { SpaceAudioController.Instance?.PlaySfx(def.activationSfx, 0.95f, 0.03f); } return true; } private void ExecuteHarpoonAbility(StationAbilitySlotState state) { StationAbilityDefinition def = state.definition; DamageableEntity target = currentHoveredTarget; if (target == null || !target.IsAlive || target.IsPlayerStation) { float bestScore = float.MinValue; var list = DamageableEntity.ActiveEntities; for (int i = 0; i < list.Count; i++) { DamageableEntity ent = list[i]; if (ent == null || !ent.IsAlive || ent.IsPlayerStation) continue; float score = (ent.category == EntityCategory.BossHull ? 5000f : (ent.category == EntityCategory.EnemyShip ? 2000f : 100f)) + ent.currentHull; if (score > bestScore) { bestScore = score; target = ent; } } } if (target == null) { state.cooldownRemaining = 1.0f; return; } int totalChainsToFire = def.baseChainCount + (state.currentTier - 1); float duration = def.activeDurationSeconds + (state.currentTier - 1) * 1.25f; if (def.projectilePrefabDefinition != null) { Vector3 dir = (target.transform.position - transform.position).normalized; var proj = ProjectileController.Spawn( def.projectilePrefabDefinition, transform.position + Vector3.up * 0.55f, dir, true, GlobalDamageMultiplier, CurrentWorldScale, target, transform); if (proj != null) { proj.harpoonChainsPayload = totalChainsToFire; proj.harpoonDuration = duration; proj.harpoonPullDist = def.pullInStandOffDistance; proj.harpoonPullSpeed = def.pullSpeed; proj.harpoonFocusBonus = def.focusFireDamageBonusMultiplier + (state.currentTier - 1) * 0.15f; } } else { target.AttachHarpoonChain( transform, Vector3.up * 0.45f, totalChainsToFire, duration, def.pullInStandOffDistance, def.pullSpeed, def.focusFireDamageBonusMultiplier); } for (int i = 0; i < turretSlots.Count; i++) { if (turretSlots[i].isUnlocked && turretSlots[i].runtimeTurret != null) turretSlots[i].runtimeTurret.SetFocusTarget(target, duration); } } private void ExecuteEmpShockwaveAbility(StationAbilitySlotState state) { StationAbilityDefinition def = state.definition; ShockwaveExplosionController.Spawn( transform.position, def.visualEffectProfile != null ? def.visualEffectProfile.previewSprite : null, def.visualEffectProfile, 4.8f, new Color(0.3f, 0.92f, 1f, 0.95f)); // Recycle all hostile projectiles cleanly back into the pool for (int i = ProjectileController.ActiveProjectiles.Count - 1; i >= 0; i--) { ProjectileController p = ProjectileController.ActiveProjectiles[i]; if (p != null && !p.firedByPlayer) { p.Recycle(); } } var list = DamageableEntity.ActiveEntities; for (int i = list.Count - 1; i >= 0; i--) { if (i >= list.Count) continue; DamageableEntity ent = list[i]; if (ent == null || !ent.IsAlive || ent.IsPlayerStation) continue; ProceduralChainRenderer.SpawnElectricArc(transform.position, ent.transform.position, new Color(0.35f, 0.95f, 1f)); if (def.projectilePrefabDefinition != null) { ent.ApplyProjectileHit(def.projectilePrefabDefinition, ent.transform.position, 1f + (state.currentTier - 1) * 0.35f); } } DamageableEntity.OnSpawnFloatingText?.Invoke(transform.position + Vector3.up * 1.1f, "EMP SHOCKWAVE!", new Color(0.35f, 0.95f, 1f), 1.25f); } private void ExecuteAegisOverchargeAbility(StationAbilitySlotState state) { if (stationDamageable == null) return; float bonusShield = 60f * state.currentTier; if (stationDamageable.maxShield < 30f) { stationDamageable.maxShield = 60f; } stationDamageable.currentShield = Mathf.Min( stationDamageable.maxShield + bonusShield, stationDamageable.currentShield + stationDamageable.maxShield * 0.5f + bonusShield); if (CurrentLevelDef != null && CurrentLevelDef.shieldCentroidProfile != null) { stationDamageable.EnsureShieldRenderer(CurrentLevelDef.shieldCentroidProfile); } if (stationDamageable.shieldVisualRenderer != null) { stationDamageable.shieldVisualRenderer.RestoreShield(); stationDamageable.shieldVisualRenderer.shieldHealthRatio = 1f; stationDamageable.shieldVisualRenderer.TriggerDirectionalHit(transform.position + Vector3.up, 2.2f); } DamageableEntity.OnSpawnFloatingText?.Invoke(transform.position + Vector3.up * 1.0f, "AEGIS SHIELD OVERCHARGED!", new Color(0.35f, 1f, 0.75f), 1.2f); } private void ExecuteMissileSwarmAbility(StationAbilitySlotState state) { StationAbilityDefinition def = state.definition; if (def.projectilePrefabDefinition == null) return; int missileCount = 6 + (state.currentTier - 1) * 3; var enemies = DamageableEntity.ActiveEntities; for (int i = 0; i < missileCount; i++) { float spreadAngle = 90f + Mathf.Lerp(-55f, 55f, missileCount > 1 ? (float)i / (missileCount - 1) : 0.5f); float rad = spreadAngle * Mathf.Deg2Rad; Vector3 dir = new Vector3(Mathf.Cos(rad), Mathf.Sin(rad), 0f); DamageableEntity lockTarget = null; if (enemies.Count > 1) { for (int k = 0; k < enemies.Count; k++) { var cand = enemies[(i + k) % enemies.Count]; if (cand != null && !cand.IsPlayerStation && cand.IsAlive) { lockTarget = cand; break; } } } ProjectileController.Spawn( def.projectilePrefabDefinition, transform.position + new Vector3(Mathf.Cos(rad) * 0.4f, 0.4f, 0f), dir, true, GlobalDamageMultiplier, CurrentWorldScale, lockTarget, transform); } DamageableEntity.OnSpawnFloatingText?.Invoke(transform.position + Vector3.up * 1.0f, "MISSILE SWARM LAUNCHED!", new Color(1f, 0.7f, 0.25f), 1.2f); } public void ApplyCollisionDamage(float rawDmg, Vector3 hitPos) { if (stationDamageable == null || !stationDamageable.IsAlive) return; stationDamageable.ApplyDirectDamage(rawDmg, hitPos); } } }