using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
///
/// StructuralFix - repairs the two structural defects the world audit found in
/// the ground plane, plus the Core/chunk spawn-cell overlap bookkeeping.
///
/// 1. ONE SLAB, 121 TIMES OVER THE SAME PLACE.
/// Every Chunk_*.unity shipped a Ground cube of scale (5000,2,5000) parked at
/// local (0,-1,0). Chunk roots are never repositioned by ChunkSceneManager,
/// so all 121 slabs landed on the same spot: they covered only the 5x5 cells
/// around the world origin, leaving 96 of the 121 cells floating over empty
/// space, and 121 identical co-planar surfaces fighting each other for depth.
///
/// Fix: each slab now covers exactly its own 1000x1000 cell, centred on that
/// cell's centre (-5000+1000*gx, -5000+1000*gz), top still at y = 0. Cells
/// tile edge to edge - no gaps, no overlap, no z-fighting, and every cell
/// keeps its own biome ground material.
///
/// 2. NOTHING UNDER THE CAR WHILE A CHUNK IS STREAMING IN.
/// The 3x3 window follows the car, so a cell can be a few frames away from
/// being loaded when the car reaches its border. Core.unity therefore gets a
/// permanent "WorldFloor" plane at y = -0.5 covering the whole 12000x12000
/// world: it sits half a unit under every cell slab, so it is invisible
/// wherever cells are loaded (no z-fighting at 0.5 units separation) but the
/// car always lands on something instead of the void.
///
/// 3. Core.unity's own Ground (a 900x900 Plane) is resized to exactly one cell
/// (1000x1000) so it tiles with the neighbours instead of overlapping them.
/// Chunk_5_5_City is never streamed (see ChunkSceneManager.SpawnCell), so
/// Core owns cell (5,5) and supplies both the city and its ground.
///
/// Idempotent - re-running leaves an already correct world untouched.
///
/// Batch: Unity.exe -batchmode -quit -projectPath .. -executeMethod StructuralFix.Run
///
public static class StructuralFix
{
public static void Run()
{
int groundsResized = 0, coresTouched = 0, floorsCreated = 0, failed = 0;
// ---------------- 1+2 : the 121 chunk scenes ----------------
var sceneGuids = AssetDatabase.FindAssets("t:Scene", new[] { "Assets/Scenes/World" });
var scenes = new List();
foreach (var g in sceneGuids)
scenes.Add(Path.GetFileNameWithoutExtension(AssetDatabase.GUIDToAssetPath(g)));
scenes.Sort(System.StringComparer.Ordinal);
foreach (var name in scenes)
{
string path = "Assets/Scenes/World/" + name + ".unity";
if (!File.Exists(path)) continue;
string[] p = name.Split('_');
int gx, gz;
if (p.Length < 4 || !int.TryParse(p[1], out gx) || !int.TryParse(p[2], out gz))
{
Debug.LogWarning("[StructuralFix] unexpected scene name " + name);
continue;
}
float cx = -5000f + 1000f * gx;
float cz = -5000f + 1000f * gz;
try
{
var scene = EditorSceneManager.OpenScene(path, OpenSceneMode.Single);
Transform anchor = null;
foreach (var r in scene.GetRootGameObjects())
if (r.name == name) { anchor = r.transform; break; }
if (anchor == null)
{
Debug.LogError("[StructuralFix] " + name + ": no root named like the scene");
failed++;
continue;
}
Transform ground = null;
foreach (Transform c in anchor)
if (c.name == "Ground") { ground = c; break; }
if (ground == null)
{
Debug.LogError("[StructuralFix] " + name + ": no Ground child");
failed++;
continue;
}
bool changed = false;
var lp = ground.localPosition;
if (lp.x != cx || lp.z != cz || lp.y != -1f)
{
ground.localPosition = new Vector3(cx, -1f, cz);
changed = true;
}
var ls = ground.localScale;
if (ls.x != 1000f || ls.z != 1000f || ls.y != 2f)
{
ground.localScale = new Vector3(1000f, 2f, 1000f);
changed = true;
}
// The slab is what you drive on - make sure its collider is live.
foreach (var col in ground.GetComponents())
if (!col.enabled) { col.enabled = true; changed = true; }
if (changed)
{
groundsResized++;
EditorSceneManager.MarkSceneDirty(scene);
EditorSceneManager.SaveScene(scene);
Debug.Log("[StructuralFix] " + name + " Ground -> cell (" + cx + "," + cz + ") 1000x1000");
}
}
catch (System.Exception ex)
{
failed++;
Debug.LogError("[StructuralFix] " + name + " FAILED: " + ex.Message);
}
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
Resources.UnloadUnusedAssets();
System.GC.Collect();
}
// ---------------- 3 : Core ----------------
try
{
const string corePath = "Assets/Scenes/Core/Core.unity";
var core = EditorSceneManager.OpenScene(corePath, OpenSceneMode.Single);
Transform coreGround = null;
foreach (var r in core.GetRootGameObjects())
if (r.name == "Ground") { coreGround = r.transform; break; }
if (coreGround != null)
{
var ls = coreGround.localScale;
if (ls.x != 100f || ls.z != 100f) // builtin Plane is 10x10 units
{
coreGround.localScale = new Vector3(100f, 1f, 100f);
coresTouched++;
}
var lp = coreGround.localPosition;
if (lp != Vector3.zero)
{
coreGround.localPosition = Vector3.zero;
coresTouched = Mathf.Max(coresTouched, 1);
}
}
else
{
Debug.LogError("[StructuralFix] Core.unity has no root named Ground");
failed++;
}
// ---- WorldFloor: the safety net under the whole 12000x12000 world ----
Transform existingFloor = null;
foreach (var r in core.GetRootGameObjects())
if (r.name == "WorldFloor") { existingFloor = r.transform; break; }
if (existingFloor == null)
{
var floor = GameObject.CreatePrimitive(PrimitiveType.Plane);
floor.name = "WorldFloor";
var t = floor.transform;
t.position = new Vector3(0f, -0.5f, 0f);
t.rotation = Quaternion.identity;
t.localScale = new Vector3(1200f, 1f, 1200f); // Plane = 10 units -> 12000
// Same material as the spawn ground so the fallback reads as ground.
if (coreGround != null)
{
var src = coreGround.GetComponent();
var dst = floor.GetComponent();
if (src != null && dst != null && src.sharedMaterial != null)
dst.sharedMaterial = src.sharedMaterial;
}
var col = floor.GetComponent();
if (col != null) col.enabled = true;
floorsCreated++;
coresTouched++;
Debug.Log("[StructuralFix] Core.unity: WorldFloor created at y=-0.5, 12000x12000");
}
if (coresTouched > 0 || floorsCreated > 0)
{
EditorSceneManager.MarkSceneDirty(core);
EditorSceneManager.SaveScene(core);
}
}
catch (System.Exception ex)
{
failed++;
Debug.LogError("[StructuralFix] Core.unity FAILED: " + ex.Message);
}
Debug.Log("[StructuralFix] DONE chunkGroundsResized=" + groundsResized +
" coreTouched=" + coresTouched +
" worldFloorsCreated=" + floorsCreated +
" failed=" + failed);
}
}