MD111 / Assets /Editor /Distributeworld
Dido599999's picture
Upload missing building/character/environment assets + refresh stale files (part 4)
443cb74 verified
Raw History Blame Contribute Delete
19.3 kB
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
// Builds a deterministic 55km x 55km world inside SampleScene, then
// DELETES ITSELF automatically once the save is verified. This script has
// NO runtime dependencies — it does not require, create, or reference any
// other script (no WorldChunk, no ChunkStreamer, nothing). It only creates
// plain GameObjects (ground cubes + spawned prefabs) directly in the scene.
//
// Run:
// Unity.exe -batchmode -projectPath <proj> -executeMethod DistributeWorld.Run -quit -logFile world.log
//
// After it finishes, WorldAuditor.Run() (a separate, non-self-deleting
// script) checks the result for empty chunks or missing asset pools and
// prints a report to the same log. WorldAuditor also has no runtime
// dependencies — it only reads GameObject names and child counts.
public static class DistributeWorld
{
// ============================================================
// WORLD SETTINGS
// ============================================================
const int Grid = 11;
const float Chunk = 5000f;
// Objects per square km. 12/km^2 = 300 objects/chunk.
const float PerKm2 = 12f;
// Hard safety cap so a bad density value can never blow up object count.
const int MaxObjectsPerChunk = 320;
const int PeopleEveryNObjects = 18;
const int MinimumPeoplePerChunk = 2;
const int MaximumPeoplePerChunk = 18;
const string ScenePath = "Assets/Scenes/SampleScene.unity";
const string SelfPath = "Assets/Editor/DistributeWorld.cs";
public const string Root = "WorldMap";
// ============================================================
// ASSET FOLDERS
// ============================================================
static readonly string[] CityDirs = { "Assets/SimplePoly City - Low Poly Assets" };
static readonly string[] ForestDirs = { "Assets/Nature", "Assets/InnerverseInteractive" };
static readonly string[] DesertDirs = { "Assets/Nature" };
static readonly string[] SeaDirs = { "Assets/HQ Boats" };
static readonly string[] AlienDirs = { "Assets/_Creepy_Cat", "Assets/FlexUnit", "Assets/SciFi_Space_Soldier", "Assets/Mech" };
static readonly string[] PeopleDirs = { "Assets/npc_casual_set_00/Prefabs" };
public enum Biome { City, Forest, Desert, Sea, Alien }
static readonly Dictionary<int, float> SeaYOffsetCache = new Dictionary<int, float>();
static readonly Dictionary<int, bool> RendererCache = new Dictionary<int, bool>();
// Per-chunk info kept only in local memory during this run — nothing is
// attached to any GameObject as a component. WorldAuditor instead reads
// the chunk name (which encodes grid position and biome) and counts
// actual children directly.
class ChunkResult
{
public string name;
public int objectCount;
}
// ============================================================
// ENTRY
// ============================================================
public static void Run()
{
try
{
UnityEngine.Random.InitState(20260920);
if (!File.Exists(ScenePath)) { Fail("Scene not found: " + ScenePath, 2); return; }
var scene = EditorSceneManager.OpenScene(ScenePath, OpenSceneMode.Single);
var old = GameObject.Find(Root);
if (old != null)
{
Debug.Log("[DistributeWorld] Removing previous WorldMap...");
UnityEngine.Object.DestroyImmediate(old);
}
var root = new GameObject(Root);
var pools = new Dictionary<Biome, GameObject[]>
{
{ Biome.City, Load(CityDirs) },
{ Biome.Forest, Load(ForestDirs) },
{ Biome.Desert, Load(DesertDirs) },
{ Biome.Sea, Load(SeaDirs) },
{ Biome.Alien, Load(AlienDirs) }
};
var people = Load(PeopleDirs);
Debug.Log(
"[DistributeWorld] pools: " +
"city=" + pools[Biome.City].Length +
" forest=" + pools[Biome.Forest].Length +
" desert=" + pools[Biome.Desert].Length +
" sea=" + pools[Biome.Sea].Length +
" alien=" + pools[Biome.Alien].Length +
" people=" + people.Length
);
var mats = MakeMaterials();
float half = Grid * Chunk / 2f;
float objectsPerChunkFloat = PerKm2 * (Chunk / 1000f) * (Chunk / 1000f);
int objectsPerChunk = Mathf.Clamp(Mathf.RoundToInt(objectsPerChunkFloat), 1, MaxObjectsPerChunk);
int totalObjects = 0;
int totalPeople = 0;
var chunkResults = new List<ChunkResult>();
for (int gx = 0; gx < Grid; gx++)
{
for (int gz = 0; gz < Grid; gz++)
{
Biome biome = BiomeAt(gx, gz);
float cx = -half + (gx + 0.5f) * Chunk;
float cz = -half + (gz + 0.5f) * Chunk;
string chunkName = $"Chunk_{gx}_{gz}_{biome}";
var chunk = new GameObject(chunkName);
chunk.transform.SetParent(root.transform, false);
chunk.transform.position = new Vector3(cx, 0f, cz);
CreateGround(chunk.transform, biome, mats);
int objectsSpawnedThisChunk = 0;
GameObject[] pool = pools[biome];
if (pool.Length > 0)
{
// Deterministic per-chunk seed, both terms well within
// int range so this can never overflow.
int seed = unchecked(20260920 + gx * 92821 + gz * 68917);
UnityEngine.Random.InitState(seed);
for (int i = 0; i < objectsPerChunk; i++)
{
GameObject prefab = pool[UnityEngine.Random.Range(0, pool.Length)];
Vector2 r = UnityEngine.Random.insideUnitCircle * (Chunk * 0.48f);
float y = biome == Biome.Sea ? SeaSurfaceYFor(prefab) : 0f;
float rotation = UnityEngine.Random.Range(0f, 360f);
float scale = UnityEngine.Random.Range(0.92f, 1.08f);
Spawn(chunk.transform, prefab, new Vector3(cx + r.x, y, cz + r.y), rotation, scale);
totalObjects++;
objectsSpawnedThisChunk++;
}
}
if ((biome == Biome.City || biome == Biome.Alien) && people.Length > 0)
{
int peopleCount = Mathf.Clamp(
Mathf.RoundToInt(objectsPerChunk / (float)PeopleEveryNObjects),
MinimumPeoplePerChunk,
MaximumPeoplePerChunk
);
int seed = unchecked(800000 + gx * 51197 + gz * 40427);
UnityEngine.Random.InitState(seed);
for (int i = 0; i < peopleCount; i++)
{
GameObject prefab = people[UnityEngine.Random.Range(0, people.Length)];
Vector2 r = UnityEngine.Random.insideUnitCircle * (Chunk * 0.42f);
Spawn(chunk.transform, prefab, new Vector3(cx + r.x, 0f, cz + r.y),
UnityEngine.Random.Range(0f, 360f), UnityEngine.Random.Range(0.95f, 1.05f));
totalPeople++;
objectsSpawnedThisChunk++;
}
}
chunkResults.Add(new ChunkResult { name = chunkName, objectCount = objectsSpawnedThisChunk });
if (!Application.isBatchMode)
EditorUtility.DisplayProgressBar(
"Building World",
$"Chunk {gx + 1},{gz + 1} / {Grid},{Grid}",
(gx * Grid + gz + 1) / (float)(Grid * Grid)
);
}
}
if (!Application.isBatchMode) EditorUtility.ClearProgressBar();
int emptyChunks = chunkResults.Count(c => c.objectCount == 0);
Debug.Log(
"[DistributeWorld] generated: objects=" + totalObjects +
" people=" + totalPeople +
" chunks=" + (Grid * Grid) +
" emptyChunks=" + emptyChunks +
" world=" + (Grid * Chunk) + "m x " + (Grid * Chunk) + "m"
);
EditorSceneManager.MarkSceneDirty(scene);
bool saved = EditorSceneManager.SaveScene(scene, ScenePath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
bool rootExists = GameObject.Find(Root) != null;
bool validCounts = totalObjects > 0;
bool ok = saved && rootExists && validCounts;
if (!ok)
{
Fail("Save NOT verified. Script kept. saved=" + saved + " root=" + rootExists + " objects=" + totalObjects, 3);
return;
}
Debug.Log("[DistributeWorld] VERIFIED. World saved successfully.");
// Run the audit right away so problems are visible in the same
// log, before this script deletes itself. WorldAuditor.cs stays
// in the project (it is not self-deleting) so it can be re-run
// any time from Tools > World > Audit World.
WorldAuditor.Run();
if (File.Exists(SelfPath))
{
AssetDatabase.DeleteAsset(SelfPath);
AssetDatabase.Refresh();
Debug.Log("[DistributeWorld] Script removed (self-delete complete).");
}
if (Application.isBatchMode) EditorApplication.Exit(0);
}
catch (Exception e)
{
if (!Application.isBatchMode) EditorUtility.ClearProgressBar();
Fail("Unhandled exception: " + e, 10);
}
}
// ============================================================
// GROUND
// ============================================================
static void CreateGround(Transform parent, Biome biome, Dictionary<Biome, Material> mats)
{
var ground = GameObject.CreatePrimitive(PrimitiveType.Cube);
ground.name = "Ground";
ground.transform.SetParent(parent, false);
ground.transform.localPosition = new Vector3(0f, -1f, 0f);
ground.transform.localScale = new Vector3(Chunk, 2f, Chunk);
ground.isStatic = true;
if (mats.TryGetValue(biome, out Material material) && material != null)
{
var renderer = ground.GetComponent<Renderer>();
if (renderer != null) renderer.sharedMaterial = material;
}
}
// ============================================================
// BIOME LAYOUT
// ============================================================
static Biome BiomeAt(int x, int z)
{
int center = Grid / 2;
int dx = x - center;
int dz = z - center;
if (Mathf.Abs(dx) <= 1 && Mathf.Abs(dz) <= 1) return Biome.City;
if (x == 0 || z == 0 || x == Grid - 1 || z == Grid - 1) return Biome.Sea;
if (dz >= 3) return Biome.Alien;
if (dx <= -2) return Biome.Forest;
if (dx >= 2) return Biome.Desert;
return Biome.City;
}
// ============================================================
// ASSET LOADING
// ============================================================
static GameObject[] Load(string[] dirs)
{
var list = new List<GameObject>();
var valid = dirs.Where(AssetDatabase.IsValidFolder).ToArray();
if (valid.Length == 0) return Array.Empty<GameObject>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string guid in AssetDatabase.FindAssets("t:GameObject", valid))
{
string path = AssetDatabase.GUIDToAssetPath(guid);
string ext = Path.GetExtension(path).ToLowerInvariant();
if (ext != ".prefab" && ext != ".fbx") continue;
string lower = path.ToLowerInvariant();
if (lower.Contains("/editor/") || lower.Contains("/demo/") ||
lower.Contains("/sample/") || lower.Contains("/samples/")) continue;
if (!seen.Add(path)) continue;
GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(path);
if (go == null) continue;
int id = go.GetInstanceID();
if (RendererCache.TryGetValue(id, out bool cachedHasRenderer))
{
if (!cachedHasRenderer) continue;
}
else
{
bool hasRenderer = go.GetComponentInChildren<Renderer>(true) != null;
RendererCache[id] = hasRenderer;
if (!hasRenderer) continue;
}
list.Add(go);
}
return list.ToArray();
}
// ============================================================
// SPAWN
// ============================================================
static void Spawn(Transform parent, GameObject prefab, Vector3 position, float yRotation, float scale)
{
GameObject go = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
if (go == null) return;
go.transform.SetParent(parent, true);
go.transform.position = position;
go.transform.rotation = Quaternion.Euler(0f, yRotation, 0f);
go.transform.localScale = Vector3.one * scale;
// Plain instantiated prefab. No extra component is attached — this
// script has zero runtime dependencies by design.
}
// ============================================================
// BOAT / SEA HEIGHT
// ============================================================
// Estimates how far a prefab's own pivot sits above its lowest visible
// point, using the prefab ASSET's own local hierarchy (not a live scene
// instance). This only reads each renderer's local bounds and its
// transform relative to the prefab root, which is well-defined for a
// prefab asset on disk and does not depend on it being placed in a scene.
static float SeaSurfaceYFor(GameObject prefab)
{
if (prefab == null) return 0f;
int id = prefab.GetInstanceID();
if (SeaYOffsetCache.TryGetValue(id, out float cached)) return cached;
Renderer[] renderers = prefab.GetComponentsInChildren<Renderer>(true);
if (renderers == null || renderers.Length == 0)
{
SeaYOffsetCache[id] = 0f;
return 0f;
}
float minY = float.PositiveInfinity;
foreach (Renderer renderer in renderers)
{
if (renderer == null) continue;
Bounds b = renderer.localBounds;
Vector3[] corners =
{
new Vector3(b.min.x, b.min.y, b.min.z),
new Vector3(b.min.x, b.min.y, b.max.z),
new Vector3(b.max.x, b.min.y, b.min.z),
new Vector3(b.max.x, b.min.y, b.max.z),
new Vector3(b.min.x, b.max.y, b.min.z),
new Vector3(b.min.x, b.max.y, b.max.z),
new Vector3(b.max.x, b.max.y, b.min.z),
new Vector3(b.max.x, b.max.y, b.max.z),
};
foreach (Vector3 corner in corners)
{
Vector3 worldPoint = renderer.transform.TransformPoint(corner);
Vector3 rootLocal = prefab.transform.InverseTransformPoint(worldPoint);
minY = Mathf.Min(minY, rootLocal.y);
}
}
if (float.IsInfinity(minY)) minY = 0f;
float offset = Mathf.Clamp(-minY, -20f, 20f);
SeaYOffsetCache[id] = offset;
return offset;
}
// ============================================================
// MATERIALS
// ============================================================
static Dictionary<Biome, Material> MakeMaterials()
{
const string dir = "Assets/_Game/World";
if (!AssetDatabase.IsValidFolder("Assets/_Game")) AssetDatabase.CreateFolder("Assets", "_Game");
if (!AssetDatabase.IsValidFolder(dir)) AssetDatabase.CreateFolder("Assets/_Game", "World");
Shader shader = Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard");
if (shader == null)
Debug.LogWarning("[DistributeWorld] No URP/Lit or Standard shader found.");
var colors = new Dictionary<Biome, Color>
{
{ Biome.City, new Color(0.42f, 0.42f, 0.45f) },
{ Biome.Forest, new Color(0.22f, 0.45f, 0.20f) },
{ Biome.Desert, new Color(0.87f, 0.75f, 0.47f) },
{ Biome.Sea, new Color(0.10f, 0.35f, 0.65f) },
{ Biome.Alien, new Color(0.28f, 0.16f, 0.38f) },
};
var result = new Dictionary<Biome, Material>();
foreach (var kv in colors)
{
string path = $"{dir}/Ground_{kv.Key}.mat";
Material material = null;
try
{
material = AssetDatabase.LoadAssetAtPath<Material>(path);
if (material == null && shader != null)
{
var created = new Material(shader);
if (created.HasProperty("_BaseColor")) created.SetColor("_BaseColor", kv.Value);
if (created.HasProperty("_Color")) created.SetColor("_Color", kv.Value);
AssetDatabase.CreateAsset(created, path);
material = AssetDatabase.LoadAssetAtPath<Material>(path);
}
}
catch (Exception e)
{
Debug.LogWarning("[DistributeWorld] Material failed: " + path + " : " + e.Message);
}
if (material == null)
Debug.LogWarning($"[DistributeWorld] Ground material for {kv.Key} is null.");
result[kv.Key] = material;
}
return result;
}
static void Fail(string message, int code)
{
Debug.LogError("[DistributeWorld] " + message);
if (!Application.isBatchMode) EditorUtility.ClearProgressBar();
if (Application.isBatchMode) EditorApplication.Exit(code);
}
}