Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
c9a0c12
feat(performance): add performance budget profile
pes7 Jul 27, 2026
be6a9d1
chore(performance): add profile meta
pes7 Jul 27, 2026
bcefd66
chore(performance): add folder meta
pes7 Jul 27, 2026
5704032
feat(performance): add performance sample model
pes7 Jul 27, 2026
435236b
feat(performance): add budget evaluator
pes7 Jul 27, 2026
2ecbbb6
feat(performance): add stress scenario definition
pes7 Jul 27, 2026
c53f026
feat(performance): add runtime performance monitor
pes7 Jul 27, 2026
1260011
build(performance): add runtime assembly
pes7 Jul 27, 2026
f72fb8f
chore(performance): add sample meta
pes7 Jul 27, 2026
b7c5b73
chore(performance): add evaluator meta
pes7 Jul 27, 2026
6a983d0
chore(performance): add stress definition meta
pes7 Jul 27, 2026
5327d58
chore(performance): add assembly meta
pes7 Jul 27, 2026
12c0475
chore(performance): add monitor meta
pes7 Jul 27, 2026
010e95a
test(performance): add budget evaluator coverage
pes7 Jul 27, 2026
dce9c79
chore(performance): add test meta
pes7 Jul 27, 2026
26b7758
test(performance): reference performance assembly
pes7 Jul 27, 2026
3db1cc0
feat(performance): add repeatable stress runner
pes7 Jul 27, 2026
e9c1db3
fix(performance): keep stress capture interval bounded
pes7 Jul 27, 2026
71d12a2
chore(performance): add stress runner meta
pes7 Jul 27, 2026
e9616cd
feat(editor): add performance scene setup tools
pes7 Jul 27, 2026
46fc9a7
chore(editor): add performance tools meta
pes7 Jul 27, 2026
056b91f
feat(performance): add csv performance capture
pes7 Jul 27, 2026
b1f4c76
fix(performance): write complete stress reports
pes7 Jul 27, 2026
aa862e2
fix(performance): read pool diagnostics from runtime pool
pes7 Jul 27, 2026
24bbea8
fix(performance): release stress objects through runtime pool
pes7 Jul 27, 2026
ebba860
docs(performance): add budgets and stress testing guide
pes7 Jul 27, 2026
788f155
chore(performance): add documentation meta
pes7 Jul 27, 2026
5cbd50c
feat(performance): add capture statistics
pes7 Jul 27, 2026
62d6906
fix(performance): keep percentile calculation Unity compatible
pes7 Jul 27, 2026
3a72f48
chore(performance): add statistics meta
pes7 Jul 27, 2026
5eb8c73
test(performance): cover capture statistics
pes7 Jul 27, 2026
bf9decc
ci(performance): add capture budget checker
pes7 Jul 27, 2026
ea2a08c
docs(performance): document capture checker
pes7 Jul 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 135 additions & 0 deletions Assets/Script/PerformanceStressRunner.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ZoneUA.Performance;

public sealed class PerformanceStressRunner : MonoBehaviour
{
[SerializeField] private StressScenarioDefinition scenario;
[SerializeField] private RuntimePerformanceMonitor monitor;
[SerializeField] private MapGenerator mapGenerator;
[SerializeField] private GameObject npcPrefab;
[SerializeField] private GameObject projectilePrefab;
[SerializeField, Tooltip("Optional lightweight prefab used to reach the requested generated-object load.")]
private GameObject generatedLoadPrefab;
[SerializeField] private Transform spawnRoot;
[SerializeField, Min(0.1f)] private float spawnRadius = 20f;
[SerializeField] private bool runOnStart;

private readonly List<GameObject> spawnedObjects = new List<GameObject>();
private Coroutine routine;

public bool IsRunning => routine != null;

private void Start()
{
if (runOnStart) Run();
}

[ContextMenu("Run Stress Scenario")]
public void Run()
{
if (routine != null || scenario == null) return;
routine = StartCoroutine(RunRoutine());
}

[ContextMenu("Stop Stress Scenario")]
public void Stop()
{
if (routine != null)
{
StopCoroutine(routine);
routine = null;
}
CleanupSpawnedObjects();
}

private IEnumerator RunRoutine()
{
if (scenario.RegenerateWorldBeforeCapture && mapGenerator != null)
{
mapGenerator.Regenerate();
}

SpawnNpcLoad(scenario.RequestedNpcCount);
SpawnGeneratedObjectLoad(scenario.RequestedGeneratedObjectCount);

float warmupEnd = Time.realtimeSinceStartup + scenario.WarmupSeconds;
while (Time.realtimeSinceStartup < warmupEnd)
{
SpawnProjectileLoad(Time.unscaledDeltaTime);
yield return null;
}

float captureEnd = Time.realtimeSinceStartup + scenario.CaptureSeconds;
while (Time.realtimeSinceStartup < captureEnd)
{
SpawnProjectileLoad(Time.unscaledDeltaTime);
yield return null;
}

monitor?.CaptureSample();
monitor?.WriteReports();
CleanupSpawnedObjects();
routine = null;
}

private void SpawnNpcLoad(int count)
{
if (npcPrefab == null) return;
for (int i = 0; i < count; i++)
{
Vector2 offset = Random.insideUnitCircle * spawnRadius;
SpawnTracked(npcPrefab, transform.position + (Vector3)offset, Quaternion.identity);
}
}

private void SpawnGeneratedObjectLoad(int count)
{
if (generatedLoadPrefab == null) return;
for (int i = 0; i < count; i++)
{
Vector2 offset = Random.insideUnitCircle * spawnRadius;
SpawnTracked(generatedLoadPrefab, transform.position + (Vector3)offset, Quaternion.identity);
}
}

private void SpawnProjectileLoad(float deltaTime)
{
if (projectilePrefab == null || scenario.RequestedProjectileBurstsPerSecond <= 0) return;
float expected = scenario.RequestedProjectileBurstsPerSecond * deltaTime;
int count = Mathf.FloorToInt(expected);
if (Random.value < expected - count) count++;

for (int i = 0; i < count; i++)
{
float angle = Random.Range(0f, 360f);
SpawnTracked(projectilePrefab, transform.position, Quaternion.Euler(0f, 0f, angle));
}
}

private void SpawnTracked(GameObject prefab, Vector3 position, Quaternion rotation)
{
GameObject instance = GlobalSystem.Instance != null
? GlobalSystem.Instance.Spawn(prefab, position, rotation, spawnRoot)
: Instantiate(prefab, position, rotation, spawnRoot);
if (instance != null) spawnedObjects.Add(instance);
}

private void CleanupSpawnedObjects()
{
RuntimeObjectPool pool = GlobalSystem.Instance != null ? GlobalSystem.Instance.ObjectPool : null;
for (int i = 0; i < spawnedObjects.Count; i++)
{
GameObject instance = spawnedObjects[i];
if (instance == null) continue;
if (pool != null && pool.Owns(instance))
GlobalSystem.Instance.Release(instance);
else
Destroy(instance);
}
spawnedObjects.Clear();
}

private void OnDisable() => Stop();
}
11 changes: 11 additions & 0 deletions Assets/Script/PerformanceStressRunner.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

149 changes: 149 additions & 0 deletions Assets/Script/RuntimePerformanceMonitor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using Unity.Profiling;
using UnityEngine;
using ZoneUA.Performance;

public sealed class RuntimePerformanceMonitor : MonoBehaviour
{
[SerializeField] private PerformanceBudgetProfile budgetProfile;
[SerializeField, Min(0.1f)] private float sampleInterval = 1f;
[SerializeField] private bool showOverlay = true;
[SerializeField] private bool writeReportsOnDisable;
[SerializeField] private string outputBaseName = "performance-capture";

private readonly List<PerformanceSample> samples = new List<PerformanceSample>();
private ProfilerRecorder mainThreadRecorder;
private ProfilerRecorder renderThreadRecorder;
private ProfilerRecorder gcAllocatedRecorder;
private ProfilerRecorder reservedMemoryRecorder;
private float timer;
private PerformanceSample latest;

[Serializable]
private sealed class SampleCollection
{
public List<PerformanceSample> samples = new List<PerformanceSample>();
}

public PerformanceSample Latest => latest;
public IReadOnlyList<PerformanceSample> Samples => samples;

private void OnEnable()
{
mainThreadRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Internal, "Main Thread", 15);
renderThreadRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Internal, "Render Thread", 15);
gcAllocatedRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Memory, "GC Allocated In Frame", 15);
reservedMemoryRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Memory, "Total Reserved Memory", 15);
}

private void Update()
{
timer += Time.unscaledDeltaTime;
if (timer < sampleInterval) return;
timer = 0f;
CaptureSample();
}

private void OnDisable()
{
mainThreadRecorder.Dispose();
renderThreadRecorder.Dispose();
gcAllocatedRecorder.Dispose();
reservedMemoryRecorder.Dispose();
if (writeReportsOnDisable) WriteReports();
}

[ContextMenu("Capture Performance Sample")]
public void CaptureSample()
{
RuntimeObjectPool pool = GlobalSystem.Instance != null ? GlobalSystem.Instance.ObjectPool : null;
latest = new PerformanceSample
{
timestampSeconds = Time.realtimeSinceStartupAsDouble,
framesPerSecond = Time.unscaledDeltaTime > 0f ? 1f / Time.unscaledDeltaTime : 0f,
mainThreadMilliseconds = ToMilliseconds(mainThreadRecorder.LastValue),
renderThreadMilliseconds = ToMilliseconds(renderThreadRecorder.LastValue),
gcAllocatedBytes = gcAllocatedRecorder.LastValue,
totalReservedMemoryBytes = reservedMemoryRecorder.LastValue,
trackedPoolInstances = pool != null ? pool.TrackedInstanceCount : 0,
scheduledPoolReleases = pool != null ? pool.ScheduledReleaseCount : 0,
activeNpcCount = FindObjectsByType<NPCController>(FindObjectsSortMode.None).Length,
activeProjectileCount = FindObjectsByType<Bullet>(FindObjectsSortMode.None).Length,
generatedObjectCount = FindObjectsByType<ChunkManager>(FindObjectsSortMode.None).Length > 0
? CountGeneratedObjects()
: 0
};
samples.Add(latest);
}

[ContextMenu("Write Performance Reports")]
public void WriteReports()
{
WriteJson();
WriteCsv();
}

public void WriteJson()
{
string path = GetOutputPath("json");
var collection = new SampleCollection { samples = new List<PerformanceSample>(samples) };
File.WriteAllText(path, JsonUtility.ToJson(collection, true));
Debug.Log($"Performance JSON written to {path}", this);
}

public void WriteCsv()
{
string path = GetOutputPath("csv");
var builder = new StringBuilder();
builder.AppendLine("timestampSeconds,fps,mainThreadMs,renderThreadMs,gcAllocatedBytes,reservedMemoryBytes,trackedPoolInstances,scheduledPoolReleases,activeNpcCount,activeProjectileCount,generatedObjectCount");
foreach (PerformanceSample sample in samples)
{
builder.Append(sample.timestampSeconds.ToString("0.###", CultureInfo.InvariantCulture)).Append(',')
.Append(sample.framesPerSecond.ToString("0.###", CultureInfo.InvariantCulture)).Append(',')
.Append(sample.mainThreadMilliseconds.ToString("0.###", CultureInfo.InvariantCulture)).Append(',')
.Append(sample.renderThreadMilliseconds.ToString("0.###", CultureInfo.InvariantCulture)).Append(',')
.Append(sample.gcAllocatedBytes).Append(',')
.Append(sample.totalReservedMemoryBytes).Append(',')
.Append(sample.trackedPoolInstances).Append(',')
.Append(sample.scheduledPoolReleases).Append(',')
.Append(sample.activeNpcCount).Append(',')
.Append(sample.activeProjectileCount).Append(',')
.Append(sample.generatedObjectCount).AppendLine();
}
File.WriteAllText(path, builder.ToString());
Debug.Log($"Performance CSV written to {path}", this);
}

private string GetOutputPath(string extension)
{
string safeBaseName = string.IsNullOrWhiteSpace(outputBaseName) ? "performance-capture" : outputBaseName.Trim();
return Path.Combine(Application.persistentDataPath, $"{safeBaseName}.{extension}");
}

private void OnGUI()
{
if (!showOverlay || budgetProfile == null) return;
IReadOnlyList<PerformanceBudgetResult> results = PerformanceBudgetEvaluator.Evaluate(latest, budgetProfile);
GUILayout.BeginArea(new Rect(10f, 10f, 360f, 420f), GUI.skin.box);
GUILayout.Label("Zone UA Performance");
foreach (PerformanceBudgetResult result in results)
{
GUILayout.Label($"{result.Status}: {result.Metric} {result.Value:0.##} / {result.Budget:0.##}");
}
GUILayout.EndArea();
}

private static float ToMilliseconds(long nanoseconds) => nanoseconds / 1_000_000f;

private static int CountGeneratedObjects()
{
int count = 0;
MapGenerator[] generators = FindObjectsByType<MapGenerator>(FindObjectsSortMode.None);
foreach (MapGenerator generator in generators) count += generator.transform.childCount;
return count;
}
}
11 changes: 11 additions & 0 deletions Assets/Script/RuntimePerformanceMonitor.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

67 changes: 67 additions & 0 deletions Assets/_ZoneUA/Editor/ZoneUAPerformanceTools.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace ZoneUA.EditorValidation
{
public static class ZoneUAPerformanceTools
{
[MenuItem("Zone UA/Performance/Create Stress Harness In Open Scene", priority = 40)]
public static void CreateStressHarness()
{
Scene scene = SceneManager.GetActiveScene();
if (!scene.IsValid() || !scene.isLoaded)
{
EditorUtility.DisplayDialog("Zone UA Performance", "Open a scene before creating the stress harness.", "OK");
return;
}

Type monitorType = ResolveType("RuntimePerformanceMonitor");
Type runnerType = ResolveType("PerformanceStressRunner");
if (monitorType == null || runnerType == null)
{
EditorUtility.DisplayDialog("Zone UA Performance", "Runtime performance types are not available. Resolve compilation errors first.", "OK");
return;
}

GameObject existing = GameObject.Find("ZoneUA_PerformanceStressHarness");
GameObject root = existing != null ? existing : new GameObject("ZoneUA_PerformanceStressHarness");
Undo.RegisterCreatedObjectUndo(root, "Create performance stress harness");

if (root.GetComponent(monitorType) == null) Undo.AddComponent(root, monitorType);
if (root.GetComponent(runnerType) == null) Undo.AddComponent(root, runnerType);

Selection.activeGameObject = root;
EditorGUIUtility.PingObject(root);
EditorSceneManager.MarkSceneDirty(scene);
}

[MenuItem("Zone UA/Performance/Select Stress Harness", priority = 41)]
public static void SelectStressHarness()
{
GameObject root = GameObject.Find("ZoneUA_PerformanceStressHarness");
if (root == null)
{
EditorUtility.DisplayDialog("Zone UA Performance", "No stress harness exists in the open scene.", "OK");
return;
}

Selection.activeGameObject = root;
EditorGUIUtility.PingObject(root);
}

private static Type ResolveType(string name)
{
return AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly =>
{
try { return assembly.GetTypes(); }
catch { return Array.Empty<Type>(); }
})
.FirstOrDefault(type => type.Name == name);
}
}
}
11 changes: 11 additions & 0 deletions Assets/_ZoneUA/Editor/ZoneUAPerformanceTools.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions Assets/_ZoneUA/Runtime/Performance.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading