This commit is contained in:
Scove
2026-03-26 20:27:19 +07:00
parent a94ab0e3f6
commit f42ef22a13
129 changed files with 5517 additions and 1134 deletions

View File

@@ -0,0 +1,49 @@
using UnityEngine;
namespace OnlyScove.Scripts
{
/// <summary>
/// A version of PlayerStateMachine that simulates constant forward or backward input.
/// </summary>
public class AutoPlayerStateMachine : PlayerStateMachine
{
[Header("Auto Pilot Settings")]
public bool alwaysMoveForward = true;
public bool alwaysRun = true;
public bool isRed = false; // New property to differentiate movement direction
private class FakeInputReader : InputReader
{
public Vector2 ForcedMove { get; set; }
public bool ForcedSprint { get; set; }
public override Vector2 MoveInput => ForcedMove;
public override bool IsSprintHeld => ForcedSprint;
}
private FakeInputReader fakeInput;
public override InputReader Input => fakeInput;
protected override void Awake()
{
fakeInput = gameObject.AddComponent<FakeInputReader>();
base.Awake();
}
protected override void Update()
{
if (fakeInput != null)
{
// Logic updated: isRed moves backward (Vector2.down), others move forward (Vector2.up)
fakeInput.ForcedMove = (isRed)
? (alwaysMoveForward ? Vector2.down : Vector2.zero)
: (alwaysMoveForward ? Vector2.up : Vector2.zero);
fakeInput.ForcedSprint = alwaysRun;
}
base.Update();
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: dbe8532b2e328a249bf61ae957c92486

View File

@@ -0,0 +1,129 @@
using UnityEngine;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine.Jobs;
using Unity.Burst;
namespace Elbyss.Optimization
{
/// <summary>
/// Manages 10,000+ objects using C# Job System and Burst Compiler.
/// This avoids the overhead of 10,000 individual Update() calls.
/// </summary>
public class JobsMovementManager : MonoBehaviour
{
[Header("Spawn Settings")]
public GameObject prefab;
public int objectCount = 10000;
public float spacing = 1.5f;
[Header("Movement Settings")]
public float speed = 5f;
private TransformAccessArray transformAccessArray;
private NativeArray<Vector3> directions;
private bool isInitialized = false;
private void Start()
{
// Optional: Start automatically or via Context Menu
// Setup(objectCount);
}
[ContextMenu("Setup 10k Objects")]
public void InitialSetup()
{
Setup(objectCount);
}
public void Setup(int count)
{
if (isInitialized) Cleanup();
objectCount = count;
Transform[] transforms = new Transform[objectCount];
directions = new NativeArray<Vector3>(objectCount, Allocator.Persistent);
int rowSize = Mathf.CeilToInt(Mathf.Sqrt(objectCount));
for (int i = 0; i < objectCount; i++)
{
float x = (i % rowSize) * spacing;
float z = (i / rowSize) * spacing;
Vector3 pos = transform.position + new Vector3(x, 0, z);
GameObject go = Instantiate(prefab, pos, Quaternion.identity, this.transform);
transforms[i] = go.transform;
// Set alternating directions
directions[i] = (i % 2 == 0) ? Vector3.forward : Vector3.back;
// CRITICAL OPTIMIZATION: Disable components that are too heavy for 10k objects
if (go.TryGetComponent<Animator>(out var anim)) anim.enabled = false;
if (go.TryGetComponent<CharacterController>(out var cc)) cc.enabled = false;
// Disable all other custom scripts
MonoBehaviour[] scripts = go.GetComponents<MonoBehaviour>();
foreach (var s in scripts)
{
if (s != this) s.enabled = false;
}
}
transformAccessArray = new TransformAccessArray(transforms);
isInitialized = true;
Debug.Log($"Initialized {objectCount} objects with Job System.");
}
private void Update()
{
if (!isInitialized) return;
// Create the movement job
var job = new MovementJob
{
DeltaTime = Time.deltaTime,
Speed = speed,
Directions = directions
};
// Schedule the job to run in parallel on all available CPU cores
// transformAccessArray allows the job to modify Transform data directly
JobHandle handle = job.Schedule(transformAccessArray);
// This ensures the job is finished before the frame ends
// In a real scenario, you might want to call Complete() in LateUpdate or next frame
// but for simple movement, scheduling and completing in Update is fine.
handle.Complete();
}
private void OnDestroy()
{
Cleanup();
}
private void Cleanup()
{
if (isInitialized)
{
if (transformAccessArray.isCreated) transformAccessArray.Dispose();
if (directions.IsCreated) directions.Dispose();
isInitialized = false;
}
}
[BurstCompile] // This attribute tells the Burst compiler to optimize this job into machine code
struct MovementJob : IJobParallelForTransform
{
public float DeltaTime;
public float Speed;
[ReadOnly] public NativeArray<Vector3> Directions;
public void Execute(int index, TransformAccess transform)
{
// Directly modify the transform position in parallel
transform.position += Directions[index] * Speed * DeltaTime;
}
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 41899df442467714dbee462ae451773a

View File

@@ -0,0 +1,153 @@
// using GPUInstancerPro;
// using Unity.Burst;
// using Unity.Collections;
// using Unity.Jobs;
// using Unity.Mathematics;
// using UnityEngine;
//
// namespace Elbyss.Optimization
// {
// public class MassiveSpawner : MonoBehaviour
// {
// [Header("Spawn Settings")]
// public GameObject prefab;
// public GPUIProfile profile;
// public int instanceCount = 100000;
// public float spacing = 1.5f;
//
// [Header("Update Settings")]
// public bool runUpdate = true;
// public float movementSpeed = 1.0f;
// public float amplitude = 2.0f;
//
// private int _rendererKey;
// private NativeArray<Matrix4x4> _matrices;
// private JobHandle _jobHandle;
// private bool _isInitialized;
//
// private void OnEnable()
// {
// Initialize();
// }
//
// private void OnDisable()
// {
// Dispose();
// }
//
// private void OnValidate()
// {
// if (Application.isPlaying && _isInitialized)
// {
// // Re-initialize if count changes during play (optional, but good for testing)
// Initialize();
// }
// }
//
// public void Initialize()
// {
// Dispose();
// if (prefab == null) return;
//
// if (GPUICoreAPI.RegisterRenderer(this, prefab, profile, out _rendererKey))
// {
// _matrices = new NativeArray<Matrix4x4>(instanceCount, Allocator.Persistent);
//
// // Initial generation
// GenerateMatrices(0);
// _jobHandle.Complete();
// GPUICoreAPI.SetTransformBufferData(_rendererKey, _matrices);
//
// _isInitialized = true;
// Debug.Log($"[MassiveSpawner] Registered {instanceCount} instances with key {_rendererKey}");
// }
// else
// {
// Debug.LogError("[MassiveSpawner] Failed to register renderer!");
// }
// }
//
// private void Update()
// {
// if (!_isInitialized || _rendererKey == 0) return;
//
// if (runUpdate)
// {
// // Complete previous frame's work if any
// _jobHandle.Complete();
//
// // Apply updated matrices to GPUI
// GPUICoreAPI.SetTransformBufferData(_rendererKey, _matrices);
//
// // Schedule next frame's work
// GenerateMatrices(Time.time);
// }
// }
//
// private void GenerateMatrices(float time)
// {
// int side = Mathf.CeilToInt(Mathf.Sqrt(instanceCount));
//
// var job = new MatrixUpdateJob
// {
// matrices = _matrices,
// side = side,
// spacing = spacing,
// time = time,
// speed = movementSpeed,
// amplitude = amplitude,
// origin = transform.position
// };
//
// _jobHandle = job.Schedule(instanceCount, 64);
// }
//
// public void Dispose()
// {
// _jobHandle.Complete();
// if (_rendererKey != 0)
// {
// GPUICoreAPI.DisposeRenderer(_rendererKey);
// _rendererKey = 0;
// }
//
// if (_matrices.IsCreated)
// {
// _matrices.Dispose();
// }
// _isInitialized = false;
// }
//
// [BurstCompile]
// struct MatrixUpdateJob : IJobParallelFor
// {
// public NativeArray<Matrix4x4> matrices;
// public int side;
// public float spacing;
// public float time;
// public float speed;
// public float amplitude;
// public Vector3 origin;
//
// public void Execute(int index)
// {
// int x = index % side;
// int z = index / side;
//
// float xPos = x * spacing;
// float zPos = z * spacing;
//
// // Add some animation to prove it's updating
// float yPos = math.sin(time * speed + (xPos + zPos) * 0.1f) * amplitude;
//
// Vector3 pos = origin + new Vector3(xPos, yPos, zPos);
//
// // Simple rotation based on time
// float angle = (time * speed * 10f + index) % 360f;
// Quaternion rot = Quaternion.Euler(0, angle, 0);
//
// matrices[index] = Matrix4x4.TRS(pos, rot, Vector3.one);
// }
// }
// }
// }

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 50831f537cbccac4c9bf4067b6b158c7

View File

@@ -0,0 +1,34 @@
using UnityEngine;
using TMPro;
namespace Elbyss.Optimization
{
public class PerformanceHUD : MonoBehaviour
{
private float deltaTime = 0.0f;
private string displayFormat = "{0:0.0} ms ({1:0.} fps)";
private void Update()
{
deltaTime += (Time.unscaledDeltaTime - deltaTime) * 0.1f;
}
private void OnGUI()
{
int w = Screen.width, h = Screen.height;
GUIStyle style = new GUIStyle();
Rect rect = new Rect(10, 10, w, h * 2 / 100);
style.alignment = TextAnchor.UpperLeft;
style.fontSize = h * 2 / 50;
style.normal.textColor = new Color(0.0f, 1.0f, 0.5f, 1.0f);
float msec = deltaTime * 1000.0f;
float fps = 1.0f / deltaTime;
string text = string.Format(displayFormat, msec, fps);
GUI.Label(rect, text, style);
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9c9a374a3ab089d41a6784b1ffad3b6f

View File

@@ -0,0 +1,85 @@
using System.Collections.Generic;
using UnityEngine;
using OnlyScove.Scripts;
namespace Elbyss.Optimization
{
public class StressTestSpawner : MonoBehaviour
{
[Header("Spawn Settings")]
public GameObject prefabToSpawn;
public int spawnLimit = 1000;
public int spawnsPerFrame = 10;
public float spacing = 2.0f;
[Header("Testing Mode")]
public bool useAutoStateMachine = true;
[Header("Optimization Options")]
public bool stripHeavyComponents = false;
private List<GameObject> spawnedObjects = new List<GameObject>();
private int currentSpawnCount = 0;
private bool isSpawning = false;
private void Update()
{
if (isSpawning && currentSpawnCount < spawnLimit)
{
for (int i = 0; i < spawnsPerFrame && currentSpawnCount < spawnLimit; i++)
{
SpawnObject();
}
}
}
[ContextMenu("Start Stress Test")]
public void StartStressTest() => isSpawning = true;
[ContextMenu("Clear All")]
public void ClearAll()
{
foreach (var obj in spawnedObjects) if (obj != null) Destroy(obj);
spawnedObjects.Clear();
currentSpawnCount = 0;
isSpawning = false;
}
private void SpawnObject()
{
if (prefabToSpawn == null) return;
int rowSize = Mathf.CeilToInt(Mathf.Sqrt(spawnLimit));
float x = (currentSpawnCount % rowSize) * spacing;
float z = (currentSpawnCount / rowSize) * spacing;
Vector3 spawnPos = transform.position + new Vector3(x, 0, z);
GameObject newObj = Instantiate(prefabToSpawn, spawnPos, transform.rotation);
if (useAutoStateMachine)
{
var realInput = newObj.GetComponent<InputReader>();
if (realInput != null) realInput.enabled = false;
var originalSM = newObj.GetComponent<PlayerStateMachine>();
if (originalSM != null)
{
DestroyImmediate(originalSM);
var autoSM = newObj.AddComponent<AutoPlayerStateMachine>();
autoSM.alwaysMoveForward = true;
autoSM.alwaysRun = true;
}
}
if (stripHeavyComponents)
{
if (newObj.TryGetComponent<Animator>(out var anim)) anim.enabled = false;
if (newObj.TryGetComponent<CharacterController>(out var cc)) cc.enabled = false;
if (newObj.TryGetComponent<PlayerStateMachine>(out var sm)) sm.enabled = false;
}
spawnedObjects.Add(newObj);
currentSpawnCount++;
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4a7c5ef310b7f354685dc6706be2d530