diff --git a/.github/workflows/unity-validation.yml b/.github/workflows/unity-validation.yml index 9601a75..c5039b5 100644 --- a/.github/workflows/unity-validation.yml +++ b/.github/workflows/unity-validation.yml @@ -30,6 +30,17 @@ jobs: - name: Validate Unity repository run: python scripts/validate_unity_repo.py + - name: Check legacy integration usage + run: python scripts/check_legacy_usage.py + + - name: Upload repository reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: repository-validation-reports + path: Logs/*.json + if-no-files-found: warn + unity-editmode-tests: name: Unity EditMode tests if: ${{ vars.RUN_UNITY_TESTS == 'true' }} diff --git a/Assets/Script/ArrowController.cs b/Assets/Script/ArrowController.cs index 636ec60..687d349 100644 --- a/Assets/Script/ArrowController.cs +++ b/Assets/Script/ArrowController.cs @@ -1,4 +1,5 @@ using UnityEngine; +using UnityEngine.InputSystem; public sealed class ArrowController : MonoBehaviour { @@ -31,7 +32,12 @@ private void Update() return; } - Vector3 mousePosition = mainCamera.ScreenToWorldPoint(Input.mousePosition); + if (Mouse.current == null) + { + return; + } + + Vector3 mousePosition = mainCamera.ScreenToWorldPoint(Mouse.current.position.ReadValue()); mousePosition.z = transform.position.z; transform.position = mousePosition; } diff --git a/Assets/Script/CameraFollow.cs b/Assets/Script/CameraFollow.cs index 5ab3588..b2b9d01 100644 --- a/Assets/Script/CameraFollow.cs +++ b/Assets/Script/CameraFollow.cs @@ -1,4 +1,5 @@ using UnityEngine; +using UnityEngine.InputSystem; public sealed class CameraFollow : MonoBehaviour { @@ -32,12 +33,12 @@ private void LateUpdate() desiredPosition.z = staticZPosition; transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed); - if (!Input.GetMouseButton(1) || controlledCamera == null) + if (Mouse.current == null || !Mouse.current.rightButton.isPressed || controlledCamera == null) { return; } - Vector3 mouseWorldPosition = controlledCamera.ScreenToWorldPoint(Input.mousePosition); + Vector3 mouseWorldPosition = controlledCamera.ScreenToWorldPoint(Mouse.current.position.ReadValue()); mouseWorldPosition.z = staticZPosition; Vector3 moveDirection = mouseWorldPosition - transform.position; diff --git a/Assets/Script/GlobalSystem.cs b/Assets/Script/GlobalSystem.cs index a60c38c..bb0d4e9 100644 --- a/Assets/Script/GlobalSystem.cs +++ b/Assets/Script/GlobalSystem.cs @@ -1,3 +1,4 @@ +using System; using UnityEngine; using UnityEngine.Serialization; @@ -35,8 +36,13 @@ public sealed class GlobalSystem : MonoBehaviour public float BloodImpulseDuration => bloodImpulseDuration; public ParticleSystem BloodParticleSystem => bloodParticleSystem; public Transform RuntimeContainer => runtimeContainer; + + [Obsolete("Gameplay code must use WeaponAmmoPresenter events instead of accessing UI through GlobalSystem.")] public UIAmmoSystem AmmoUI => ammoUI; + public RuntimeObjectPool ObjectPool => objectPool; + public int TrackedInstanceCount => objectPool != null ? objectPool.TrackedInstanceCount : 0; + public int ScheduledReleaseCount => objectPool != null ? objectPool.ScheduledReleaseCount : 0; private void Awake() { @@ -53,19 +59,12 @@ private void Awake() private void OnDestroy() { - if (Instance == this) - { - Instance = null; - } + if (Instance == this) Instance = null; } public GameObject Spawn(GameObject prefab, Vector3 position, Quaternion rotation, Transform parent = null) { - if (prefab == null) - { - return null; - } - + if (prefab == null) return null; EnsureRuntimeInfrastructure(); return objectPool.Spawn(prefab, position, rotation, parent); } @@ -73,21 +72,14 @@ public GameObject Spawn(GameObject prefab, Vector3 position, Quaternion rotation public T Spawn(T prefab, Vector3 position, Quaternion rotation, Transform parent = null) where T : Component { - if (prefab == null) - { - return null; - } - + if (prefab == null) return null; EnsureRuntimeInfrastructure(); return objectPool.Spawn(prefab, position, rotation, parent); } public void Release(GameObject instance) { - if (instance == null) - { - return; - } + if (instance == null) return; EnsureRuntimeInfrastructure(); if (objectPool.Owns(instance)) @@ -101,10 +93,7 @@ public void Release(GameObject instance) public void ReleaseAfter(GameObject instance, float delay) { - if (instance == null) - { - return; - } + if (instance == null) return; EnsureRuntimeInfrastructure(); if (objectPool.Owns(instance)) @@ -118,28 +107,27 @@ public void ReleaseAfter(GameObject instance, float delay) public void Prewarm(GameObject prefab, int count) { - if (prefab == null || count <= 0) - { - return; - } - + if (prefab == null || count <= 0) return; EnsureRuntimeInfrastructure(); objectPool.Prewarm(prefab, count); } + public bool Owns(GameObject instance) + { + EnsureRuntimeInfrastructure(); + return objectPool.Owns(instance); + } + public bool TryGetRandomBlood(out GameObject prefab) { prefab = null; + if (bloodPrefabs == null || bloodPrefabs.Length == 0) return false; - if (bloodPrefabs == null || bloodPrefabs.Length == 0) - { - return false; - } - - prefab = bloodPrefabs[Random.Range(0, bloodPrefabs.Length)]; + prefab = bloodPrefabs[UnityEngine.Random.Range(0, bloodPrefabs.Length)]; return prefab != null; } + [Obsolete("Use TryGetRandomBlood(out GameObject) and handle an empty configuration explicitly.")] public GameObject getRandomBlood() { TryGetRandomBlood(out GameObject prefab); diff --git a/Assets/Script/Health.cs b/Assets/Script/Health.cs index 6ddeb07..6507b97 100644 --- a/Assets/Script/Health.cs +++ b/Assets/Script/Health.cs @@ -62,28 +62,19 @@ private void Start() public void SetHealth(int health) { - if (deathRaised) - { - return; - } + if (deathRaised) return; int previous = state.CurrentHealth; state.SetHealth(health); SyncSerializedState(); RaiseHealthChanged(previous); - if (!state.IsAlive) - { - DieOnce(); - } + if (!state.IsAlive) DieOnce(); } public void SetMaximumHealth(int maximumHealth, bool preserveRatio = false) { - if (deathRaised) - { - return; - } + if (deathRaised) return; int previous = state.CurrentHealth; state.SetMaximumHealth(maximumHealth, preserveRatio); @@ -91,19 +82,13 @@ public void SetMaximumHealth(int maximumHealth, bool preserveRatio = false) SyncSerializedState(); RaiseHealthChanged(previous, force: true); - if (!state.IsAlive) - { - DieOnce(); - } + if (!state.IsAlive) DieOnce(); } public void RestoreHealth(int amount) { int restored = state.Heal(amount); - if (restored <= 0) - { - return; - } + if (restored <= 0) return; int previous = state.CurrentHealth - restored; SyncSerializedState(); @@ -111,17 +96,11 @@ public void RestoreHealth(int amount) RaiseHealthChanged(previous); } - public void RestoreFullHealth() - { - RestoreHealth(state.MaximumHealth - state.CurrentHealth); - } + public void RestoreFullHealth() => RestoreHealth(state.MaximumHealth - state.CurrentHealth); public void ReceiveDamage(in DamageInfo damageInfo) { - if (!state.IsAlive || isImunable || damageInfo.Amount <= 0f) - { - return; - } + if (!state.IsAlive || isImunable || damageInfo.Amount <= 0f) return; float resistance = resistanceProfile != null ? resistanceProfile.GetResistance(damageInfo.DamageType) @@ -132,29 +111,21 @@ public void ReceiveDamage(in DamageInfo damageInfo) incomingDamageMultiplier); DamageResolved?.Invoke(damageInfo, resolution); - if (resolution.AppliedAmount <= 0) - { - return; - } + if (resolution.AppliedAmount <= 0) return; int previous = state.CurrentHealth; int applied = state.ApplyDamage(resolution.AppliedAmount); - if (applied <= 0) - { - return; - } + if (applied <= 0) return; SyncSerializedState(); Damaged?.Invoke(damageInfo); RaiseHealthChanged(previous); damageEffectsPresenter?.Present(in damageInfo, applied); - if (!state.IsAlive) - { - DieOnce(); - } + if (!state.IsAlive) DieOnce(); } + [Obsolete("Use ReceiveDamage(in DamageInfo) so source, type, position and impulse are preserved.")] public void ReceiveDamage(int damageAmount) { DamageInfo damageInfo = new DamageInfo( @@ -169,10 +140,7 @@ public void ReceiveDamage(int damageAmount) private void DieOnce() { - if (deathRaised) - { - return; - } + if (deathRaised) return; deathRaised = true; state.SetHealth(0); @@ -189,25 +157,31 @@ private void RaiseHealthChanged(int previousHealth, bool force = false) } } - private void SyncSerializedState() - { - currentHeals = state.CurrentHealth; - } + private void SyncSerializedState() => currentHeals = state.CurrentHealth; + [Obsolete("Health state is evaluated immediately. Subscribe to Died or use IsAlive instead.")] public void HealthLogic() { - if (!state.IsAlive) - { - DieOnce(); - } + if (!state.IsAlive) DieOnce(); } - // Compatibility API retained until scenes, prefabs and UnityEvents are audited. + // Compatibility API retained only for serialized UnityEvents during prefab migration. + [Obsolete("Use SetHealth(int).")] public void setHeals(int heals) => SetHealth(heals); + + [Obsolete("Use RestoreHealth(int).")] public void restoreSomeHeals(int amount) => RestoreHealth(amount); + + [Obsolete("Use RestoreFullHealth().")] public void restoreDefaultHeals() => RestoreFullHealth(); + + [Obsolete("Use CurrentHealth.")] public int getHeals() => CurrentHealth; + + [Obsolete("Use ReceiveDamage(in DamageInfo).")] public void receiveDamage(int damageAmount) => ReceiveDamage(damageAmount); + + [Obsolete("Use IsAlive.")] public bool getIsAlive() => IsAlive; private void OnValidate() diff --git a/Assets/Script/WeaponController.cs b/Assets/Script/WeaponController.cs index 4e21832..61b9e7d 100644 --- a/Assets/Script/WeaponController.cs +++ b/Assets/Script/WeaponController.cs @@ -1,6 +1,7 @@ using Assets.Script; using System; using UnityEngine; +using UnityEngine.InputSystem; using ZoneUA.Combat; [RequireComponent(typeof(Weapon))] @@ -178,10 +179,17 @@ private void Update() private void HandleLegacyPlayerInput() { - if (Input.GetButtonDown("Fire1")) StartFire(); - if (Input.GetButtonUp("Fire1")) StopFire(); - if (Input.GetKeyDown(KeyCode.B)) SwitchFireMode(); - if (Input.GetKeyDown(KeyCode.R)) Reload(); + if (Mouse.current != null) + { + if (Mouse.current.leftButton.wasPressedThisFrame) StartFire(); + if (Mouse.current.leftButton.wasReleasedThisFrame) StopFire(); + } + + if (Keyboard.current != null) + { + if (Keyboard.current.bKey.wasPressedThisFrame) SwitchFireMode(); + if (Keyboard.current.rKey.wasPressedThisFrame) Reload(); + } } public void SetExternalInputEnabled(bool enabled) @@ -556,7 +564,12 @@ public Vector3 CalculateDirectionForPlayerMouse() return Vector3.zero; } - Vector3 mousePosition = mainCamera.ScreenToWorldPoint(Input.mousePosition); + if (Mouse.current == null) + { + return Vector3.zero; + } + + Vector3 mousePosition = mainCamera.ScreenToWorldPoint(Mouse.current.position.ReadValue()); mousePosition.z = transform.position.z; return mousePosition - transform.position; } diff --git a/Assets/Script/World/GrassSorting.cs b/Assets/Script/World/GrassSorting.cs index efde2e6..bdfcef2 100644 --- a/Assets/Script/World/GrassSorting.cs +++ b/Assets/Script/World/GrassSorting.cs @@ -75,7 +75,7 @@ private void OnTriggerStay2D(Collider2D other) private void CachePlayer(Collider2D other) { - if (!other.CompareTag("Player")) + if (other.GetComponentInParent() == null) { return; } diff --git a/Assets/_ZoneUA/Editor/LegacyUsageRule.cs b/Assets/_ZoneUA/Editor/LegacyUsageRule.cs new file mode 100644 index 0000000..3177cf8 --- /dev/null +++ b/Assets/_ZoneUA/Editor/LegacyUsageRule.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; + +namespace ZoneUA.EditorValidation +{ + public enum LegacyUsageSeverity + { + Info, + Warning, + Error + } + + [Serializable] + public sealed class LegacyUsageRule + { + public string Code { get; } + public string Description { get; } + public LegacyUsageSeverity Severity { get; } + public IReadOnlyList Tokens { get; } + public IReadOnlyList AllowedPathFragments { get; } + + public LegacyUsageRule( + string code, + string description, + LegacyUsageSeverity severity, + string[] tokens, + string[] allowedPathFragments = null) + { + Code = code ?? throw new ArgumentNullException(nameof(code)); + Description = description ?? throw new ArgumentNullException(nameof(description)); + Severity = severity; + Tokens = tokens ?? Array.Empty(); + AllowedPathFragments = allowedPathFragments ?? Array.Empty(); + } + + public bool IsAllowedPath(string path) + { + if (string.IsNullOrEmpty(path)) return false; + for (int i = 0; i < AllowedPathFragments.Count; i++) + { + if (path.IndexOf(AllowedPathFragments[i], StringComparison.OrdinalIgnoreCase) >= 0) + { + return true; + } + } + return false; + } + } + + public static class LegacyUsageCatalog + { + private static readonly LegacyUsageRule[] RulesInternal = + { + new LegacyUsageRule( + "LEGACY_INPUT", + "Gameplay code must use PlayerInputRouter/Input System instead of UnityEngine.Input polling.", + LegacyUsageSeverity.Error, + new[] { "Input.GetAxis", "Input.GetAxisRaw", "Input.GetButton", "Input.GetButtonDown", "Input.GetKey", "Input.GetKeyDown", "Input.mousePosition" }, + new[] { "/Editor/", "/Tests/", "LegacyUsageRule.cs" }), + new LegacyUsageRule( + "DIRECT_HUD_DEPENDENCY", + "Gameplay code must publish events instead of accessing the ammo HUD directly.", + LegacyUsageSeverity.Error, + new[] { "GlobalSystem.Instance.AmmoUI", ".AmmoUI." }, + new[] { "/Editor/", "/Tests/" }), + new LegacyUsageRule( + "TAG_BASED_COMBAT", + "Combat targeting and damage filtering must use factions rather than Player/Enemy tags.", + LegacyUsageSeverity.Warning, + new[] { "CompareTag(\"Player\")", "CompareTag(\"Enemy\")", "FindGameObjectWithTag(\"Player\")", "FindGameObjectsWithTag(\"Enemy\")", "whoRecieveDamage" }, + new[] { "/Editor/", "/Tests/", "Bullet.cs" }), + new LegacyUsageRule( + "LEGACY_HEALTH_API", + "New code must use SetHealth, RestoreHealth, CurrentHealth, IsAlive and ReceiveDamage(DamageInfo).", + LegacyUsageSeverity.Warning, + new[] { ".setHeals(", ".restoreSomeHeals(", ".restoreDefaultHeals(", ".getHeals(", ".receiveDamage(", ".getIsAlive(" }, + new[] { "/Editor/", "/Tests/", "Health.cs" }), + new LegacyUsageRule( + "GLOBAL_FIND", + "Runtime hot paths should use serialized references, registration or events instead of scene-wide searches.", + LegacyUsageSeverity.Warning, + new[] { "FindObjectOfType<", "FindObjectsOfType<", "GameObject.Find(" }, + new[] { "/Editor/", "/Tests/", "RuntimePerformanceMonitor.cs" }), + new LegacyUsageRule( + "LEGACY_POOL_API", + "Use TryGetRandomBlood and typed pool methods instead of legacy aliases.", + LegacyUsageSeverity.Info, + new[] { ".getRandomBlood(" }, + new[] { "/Editor/", "/Tests/", "GlobalSystem.cs" }) + }; + + public static IReadOnlyList Rules => RulesInternal; + } +} diff --git a/Assets/_ZoneUA/Editor/LegacyUsageRule.cs.meta b/Assets/_ZoneUA/Editor/LegacyUsageRule.cs.meta new file mode 100644 index 0000000..8243484 --- /dev/null +++ b/Assets/_ZoneUA/Editor/LegacyUsageRule.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6d2c5e6a431d4fe0a87c322c9e823e54 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Editor/ZoneUALegacyUsageScanner.cs b/Assets/_ZoneUA/Editor/ZoneUALegacyUsageScanner.cs new file mode 100644 index 0000000..ef77438 --- /dev/null +++ b/Assets/_ZoneUA/Editor/ZoneUALegacyUsageScanner.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEditor.Build; +using UnityEditor.Build.Reporting; +using UnityEngine; + +namespace ZoneUA.EditorValidation +{ + [Serializable] + public sealed class LegacyUsageFinding + { + public string code; + public LegacyUsageSeverity severity; + public string assetPath; + public int line; + public string message; + public string source; + } + + [Serializable] + public sealed class LegacyUsageReport + { + public string generatedAtUtc; + public List findings = new List(); + + public int ErrorCount => findings.Count(item => item.severity == LegacyUsageSeverity.Error); + public int WarningCount => findings.Count(item => item.severity == LegacyUsageSeverity.Warning); + public bool IsValid => ErrorCount == 0; + } + + public static class ZoneUALegacyUsageScanner + { + private static readonly string[] RuntimeRoots = + { + "Assets/Script", + "Assets/_ZoneUA/Runtime" + }; + + [MenuItem("Zone UA/Validation/Scan Legacy Integration", priority = 30)] + public static void ScanMenu() + { + LegacyUsageReport report = ScanProject(); + WriteReport(report, "Logs/ZoneUALegacyUsage.json"); + LogReport(report); + EditorUtility.DisplayDialog( + "Legacy integration scan", + $"Errors: {report.ErrorCount}\nWarnings: {report.WarningCount}\nTotal: {report.findings.Count}\n\nReport: Logs/ZoneUALegacyUsage.json", + "OK"); + } + + public static LegacyUsageReport ScanProject() + { + var report = new LegacyUsageReport { generatedAtUtc = DateTime.UtcNow.ToString("O") }; + foreach (string file in EnumerateRuntimeSourceFiles()) + { + ScanFile(file, File.ReadAllLines(file), report); + } + return report; + } + + public static void ScanFile(string assetPath, IReadOnlyList lines, LegacyUsageReport report) + { + if (report == null || lines == null || string.IsNullOrWhiteSpace(assetPath)) return; + + string normalisedPath = assetPath.Replace('\\', '/'); + foreach (LegacyUsageRule rule in LegacyUsageCatalog.Rules) + { + if (rule.IsAllowedPath(normalisedPath)) continue; + + for (int lineIndex = 0; lineIndex < lines.Count; lineIndex++) + { + string source = lines[lineIndex] ?? string.Empty; + string trimmed = source.TrimStart(); + if (trimmed.StartsWith("//", StringComparison.Ordinal)) continue; + + for (int tokenIndex = 0; tokenIndex < rule.Tokens.Count; tokenIndex++) + { + string token = rule.Tokens[tokenIndex]; + if (source.IndexOf(token, StringComparison.Ordinal) < 0) continue; + + report.findings.Add(new LegacyUsageFinding + { + code = rule.Code, + severity = rule.Severity, + assetPath = normalisedPath, + line = lineIndex + 1, + message = rule.Description, + source = source.Trim() + }); + break; + } + } + } + } + + public static void WriteReport(LegacyUsageReport report, string outputPath) + { + string directory = Path.GetDirectoryName(outputPath); + if (!string.IsNullOrEmpty(directory)) Directory.CreateDirectory(directory); + File.WriteAllText(outputPath, JsonUtility.ToJson(report, true)); + } + + private static IEnumerable EnumerateRuntimeSourceFiles() + { + foreach (string root in RuntimeRoots) + { + if (!Directory.Exists(root)) continue; + foreach (string path in Directory.GetFiles(root, "*.cs", SearchOption.AllDirectories)) + { + string normalised = path.Replace('\\', '/'); + if (normalised.Contains("/Editor/") || normalised.Contains("/Tests/")) continue; + yield return normalised; + } + } + } + + private static void LogReport(LegacyUsageReport report) + { + foreach (LegacyUsageFinding finding in report.findings) + { + string message = $"[{finding.code}] {finding.assetPath}:{finding.line} — {finding.message}\n{finding.source}"; + switch (finding.severity) + { + case LegacyUsageSeverity.Error: + Debug.LogError(message); + break; + case LegacyUsageSeverity.Warning: + Debug.LogWarning(message); + break; + default: + Debug.Log(message); + break; + } + } + + Debug.Log($"Legacy integration scan complete. Errors: {report.ErrorCount}; warnings: {report.WarningCount}; total: {report.findings.Count}."); + } + } + + public sealed class ZoneUALegacyUsageBuildValidator : IPreprocessBuildWithReport + { + public int callbackOrder => -700; + + public void OnPreprocessBuild(BuildReport buildReport) + { + LegacyUsageReport report = ZoneUALegacyUsageScanner.ScanProject(); + ZoneUALegacyUsageScanner.WriteReport(report, "Logs/ZoneUALegacyUsage.json"); + if (!report.IsValid) + { + throw new BuildFailedException( + $"Zone UA legacy integration scan found {report.ErrorCount} blocking error(s). See Logs/ZoneUALegacyUsage.json."); + } + } + } +} diff --git a/Assets/_ZoneUA/Editor/ZoneUALegacyUsageScanner.cs.meta b/Assets/_ZoneUA/Editor/ZoneUALegacyUsageScanner.cs.meta new file mode 100644 index 0000000..6a15d17 --- /dev/null +++ b/Assets/_ZoneUA/Editor/ZoneUALegacyUsageScanner.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 72fd7df4fb5d4f429f23608d9e6cf504 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Tests/Editor/LegacyUsageScannerTests.cs b/Assets/_ZoneUA/Tests/Editor/LegacyUsageScannerTests.cs new file mode 100644 index 0000000..d178880 --- /dev/null +++ b/Assets/_ZoneUA/Tests/Editor/LegacyUsageScannerTests.cs @@ -0,0 +1,58 @@ +using NUnit.Framework; + +namespace ZoneUA.EditorValidation.Tests +{ + public sealed class LegacyUsageScannerTests + { + [Test] + public void ScanFile_LegacyInput_AddsBlockingFinding() + { + var report = new LegacyUsageReport(); + ZoneUALegacyUsageScanner.ScanFile( + "Assets/Script/TestController.cs", + new[] { "float x = Input.GetAxisRaw(\"Horizontal\");" }, + report); + + Assert.That(report.ErrorCount, Is.EqualTo(1)); + Assert.That(report.findings[0].code, Is.EqualTo("LEGACY_INPUT")); + Assert.That(report.findings[0].line, Is.EqualTo(1)); + } + + [Test] + public void ScanFile_AllowedEditorPath_IsIgnored() + { + var report = new LegacyUsageReport(); + ZoneUALegacyUsageScanner.ScanFile( + "Assets/_ZoneUA/Editor/InputDebug.cs", + new[] { "Input.GetKey(KeyCode.Space);" }, + report); + + Assert.That(report.findings, Is.Empty); + } + + [Test] + public void ScanFile_CommentedToken_IsIgnored() + { + var report = new LegacyUsageReport(); + ZoneUALegacyUsageScanner.ScanFile( + "Assets/Script/TestController.cs", + new[] { "// Input.GetKey(KeyCode.Space);" }, + report); + + Assert.That(report.findings, Is.Empty); + } + + [Test] + public void ScanFile_DirectHudDependency_IsBlocking() + { + var report = new LegacyUsageReport(); + ZoneUALegacyUsageScanner.ScanFile( + "Assets/Script/TestWeapon.cs", + new[] { "GlobalSystem.Instance.AmmoUI.Refresh();" }, + report); + + Assert.That(report.IsValid, Is.False); + Assert.That(report.findings[0].code, Is.EqualTo("DIRECT_HUD_DEPENDENCY")); + } + } +} diff --git a/Assets/_ZoneUA/Tests/Editor/LegacyUsageScannerTests.cs.meta b/Assets/_ZoneUA/Tests/Editor/LegacyUsageScannerTests.cs.meta new file mode 100644 index 0000000..cc80789 --- /dev/null +++ b/Assets/_ZoneUA/Tests/Editor/LegacyUsageScannerTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 869647a744b94863882956a47a34dc41 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Docs/LEGACY_CLEANUP_INTEGRATION_HARDENING.md b/Docs/LEGACY_CLEANUP_INTEGRATION_HARDENING.md new file mode 100644 index 0000000..e93814b --- /dev/null +++ b/Docs/LEGACY_CLEANUP_INTEGRATION_HARDENING.md @@ -0,0 +1,102 @@ +# Legacy cleanup and integration hardening + +This module prevents new gameplay code from reintroducing integration paths that the professionalisation refactor has replaced. + +## What is blocked + +The Editor and repository scanners report blocking errors for: + +- legacy `UnityEngine.Input` polling in runtime gameplay code; +- direct access from gameplay code to the ammo HUD through `GlobalSystem`. + +The scanners report migration warnings for: + +- Player/Enemy tag-based combat decisions; +- legacy lowercase Health API calls; +- scene-wide `FindObjectOfType`, `FindObjectsOfType` and `GameObject.Find` usage; +- other explicitly catalogued compatibility paths. + +Warnings remain non-blocking because some existing prefab and UnityEvent migrations must be completed in the Unity Editor before those APIs can be removed safely. + +## Unity Editor workflow + +Run: + +`Zone UA -> Validation -> Scan Legacy Integration` + +The scan writes: + +`Logs/ZoneUALegacyUsage.json` + +Each finding includes: + +- rule code; +- severity; +- source path; +- line number; +- source line; +- required migration direction. + +The same blocking scan runs before a Unity build. + +## Repository workflow + +Run without Unity: + +```bash +python scripts/check_legacy_usage.py +``` + +The script writes: + +`Logs/legacy-usage.json` + +It returns a non-zero exit code when blocking findings are present and is executed by the repository-integrity GitHub Actions job. + +## Deprecated compatibility APIs + +The following methods remain temporarily available for serialized UnityEvents but now produce compiler warnings when called from C#: + +- `Health.ReceiveDamage(int)`; +- `Health.HealthLogic()`; +- `Health.setHeals(int)`; +- `Health.restoreSomeHeals(int)`; +- `Health.restoreDefaultHeals()`; +- `Health.getHeals()`; +- `Health.receiveDamage(int)`; +- `Health.getIsAlive()`; +- `GlobalSystem.getRandomBlood()`; +- `GlobalSystem.AmmoUI`. + +New code must use the modern event-driven and typed APIs. + +## Removal process + +Do not delete compatibility methods until all of the following are true: + +1. production prefabs have been migrated with the composition migration tooling; +2. production scenes have been migrated and saved in Unity; +3. UnityEvent persistent calls have been reviewed for missing methods; +4. the legacy scan contains no usages of the API outside the compatibility declaration itself; +5. EditMode and Play Mode smoke tests pass; +6. a full project validation and build complete without errors. + +After those checks, remove one compatibility group per PR. Do not remove Health, weapon, input and scene compatibility bridges in one bulk change. + +## Final stacked-series verification + +Before merging the stacked refactor series: + +1. open the project in Unity 6000.5.5f1; +2. generate and review the scene architecture; +3. run production composition migration; +4. assign definitions and serialized references; +5. run all validation menus; +6. run `python scripts/validate_unity_repo.py`; +7. run `python scripts/check_legacy_usage.py`; +8. run the complete EditMode suite; +9. run player, NPC, combat, world, pooling, scene transition and HUD Play Mode smoke tests; +10. record a representative performance capture; +11. merge stacked PRs in dependency order or squash the verified final branch into a clean integration PR. + +This module is a regression gate. It does not claim that every old serialized UnityEvent has already been migrated; that verification requires the Unity Editor. diff --git a/Docs/LEGACY_CLEANUP_INTEGRATION_HARDENING.md.meta b/Docs/LEGACY_CLEANUP_INTEGRATION_HARDENING.md.meta new file mode 100644 index 0000000..43a079b --- /dev/null +++ b/Docs/LEGACY_CLEANUP_INTEGRATION_HARDENING.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 3441589700c64a849959eb70f9cf99df +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/scripts/check_legacy_usage.py b/scripts/check_legacy_usage.py new file mode 100644 index 0000000..7014765 --- /dev/null +++ b/scripts/check_legacy_usage.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + + +@dataclass(frozen=True) +class Rule: + code: str + severity: str + message: str + tokens: tuple[str, ...] + allowed_fragments: tuple[str, ...] = () + + +RULES = ( + Rule("LEGACY_INPUT", "error", "Use PlayerInputRouter/Input System.", ( + "Input.GetAxis", "Input.GetAxisRaw", "Input.GetButton", "Input.GetButtonDown", + "Input.GetKey", "Input.GetKeyDown", "Input.mousePosition", + ), ("/Editor/", "/Tests/", "LegacyUsageRule.cs")), + Rule("DIRECT_HUD_DEPENDENCY", "error", "Gameplay must publish events instead of touching ammo HUD.", ( + "GlobalSystem.Instance.AmmoUI", ".AmmoUI.", + ), ("/Editor/", "/Tests/")), + Rule("TAG_BASED_COMBAT", "warning", "Use faction relationships instead of Player/Enemy tags.", ( + 'CompareTag("Player")', 'CompareTag("Enemy")', 'FindGameObjectWithTag("Player")', + 'FindGameObjectsWithTag("Enemy")', "whoRecieveDamage", + ), ("/Editor/", "/Tests/", "Bullet.cs")), + Rule("LEGACY_HEALTH_API", "warning", "Use the modern Health API.", ( + ".setHeals(", ".restoreSomeHeals(", ".restoreDefaultHeals(", ".getHeals(", + ".receiveDamage(", ".getIsAlive(", + ), ("/Editor/", "/Tests/", "Health.cs")), + Rule("GLOBAL_FIND", "warning", "Use serialized composition, registration or events.", ( + "FindObjectOfType<", "FindObjectsOfType<", "GameObject.Find(", + ), ("/Editor/", "/Tests/", "RuntimePerformanceMonitor.cs")), +) + + +def iter_sources(root: Path) -> Iterable[Path]: + for relative in (Path("Assets/Script"), Path("Assets/_ZoneUA/Runtime")): + folder = root / relative + if not folder.exists(): + continue + for path in folder.rglob("*.cs"): + normalised = path.as_posix() + if "/Editor/" in normalised or "/Tests/" in normalised: + continue + yield path + + +def scan(root: Path) -> list[dict[str, object]]: + findings: list[dict[str, object]] = [] + for path in iter_sources(root): + relative = path.relative_to(root).as_posix() + lines = path.read_text(encoding="utf-8", errors="replace").splitlines() + for rule in RULES: + if any(fragment.lower() in relative.lower() for fragment in rule.allowed_fragments): + continue + for number, source in enumerate(lines, start=1): + if source.lstrip().startswith("//"): + continue + if any(token in source for token in rule.tokens): + findings.append({ + "code": rule.code, + "severity": rule.severity, + "path": relative, + "line": number, + "message": rule.message, + "source": source.strip(), + }) + return findings + + +def main() -> int: + parser = argparse.ArgumentParser(description="Check Zone UA runtime code for deprecated integration paths.") + parser.add_argument("--root", type=Path, default=Path.cwd()) + parser.add_argument("--output", type=Path, default=Path("Logs/legacy-usage.json")) + args = parser.parse_args() + + root = args.root.resolve() + findings = scan(root) + output = args.output if args.output.is_absolute() else root / args.output + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(json.dumps({"findings": findings}, indent=2), encoding="utf-8") + + for finding in findings: + print(f"{finding['severity'].upper()} {finding['code']} {finding['path']}:{finding['line']} {finding['message']}") + + errors = sum(1 for finding in findings if finding["severity"] == "error") + warnings = sum(1 for finding in findings if finding["severity"] == "warning") + print(f"Legacy usage scan: {errors} error(s), {warnings} warning(s), {len(findings)} total.") + return 1 if errors else 0 + + +if __name__ == "__main__": + raise SystemExit(main())