231 lines
9.6 KiB
C#
231 lines
9.6 KiB
C#
using System;
|
||
using UnityEngine;
|
||
using Object = UnityEngine.Object;
|
||
using Random = System.Random;
|
||
|
||
namespace _Project.Scripts.LevelGenerating
|
||
{
|
||
// =====================================================================
|
||
// Расставляет PropEntry в одной комнате по сетке модулей (0.5 м).
|
||
// - не ставит предметы в зоне перед дверями;
|
||
// - не накладывает предметы друг на друга (padding);
|
||
// - габариты берёт из Renderer.bounds префаба, пивот не важен;
|
||
// - пишет занятые прямоугольники в view.PropFootprints (чтобы враги не спавнились внутри).
|
||
// Предполагается: перед модели смотрит в +Z (иначе frontYawOffset), пол на Y = 0.
|
||
// =====================================================================
|
||
public class PropPlacer
|
||
{
|
||
private const float M = LevelGrid.Module;
|
||
private const int Attempts = 40;
|
||
|
||
private readonly RoomView _view;
|
||
private readonly Transform _parent;
|
||
private readonly Random _rng;
|
||
private readonly bool[,] _blocked; // [x, z] в клетках от левого нижнего угла комнаты
|
||
private readonly int _len, _wid; // клеток по X и по Z
|
||
|
||
public PropPlacer(RoomView view, FloorData floor, Transform parent, float doorClearance)
|
||
{
|
||
_view = view;
|
||
_parent = parent;
|
||
_len = view.Data.Length;
|
||
_wid = view.Data.Width;
|
||
_blocked = new bool[_len, _wid];
|
||
_rng = new Random(unchecked(floor.Seed * 397 + view.Index * 7919 + 17));
|
||
|
||
BlockDoorways(floor, doorClearance);
|
||
}
|
||
|
||
public int Place(PropEntry e, Func<Transform, Random, GameObject> factory = null)
|
||
{
|
||
if (e == null || (e.prefab == null && factory == null)) return 0;
|
||
|
||
Vector3 s = _view.SizeMeters;
|
||
if (s.x * s.z < e.minRoomArea) return 0;
|
||
|
||
int count = _rng.Next(e.minCount, Mathf.Max(e.minCount, e.maxCount) + 1);
|
||
if (e.areaPerExtra > 0f)
|
||
count += Mathf.FloorToInt(s.x * s.z / e.areaPerExtra);
|
||
int placed = 0;
|
||
for (int i = 0; i < count; i++)
|
||
{
|
||
if (!TryPlaceOne(e, factory)) break; // места не нашлось — дальше нет смысла
|
||
placed++;
|
||
}
|
||
return placed;
|
||
}
|
||
|
||
// ---------- Двери ----------
|
||
|
||
private void BlockDoorways(FloorData floor, float clearance)
|
||
{
|
||
int c = Mathf.CeilToInt(clearance / M);
|
||
Vector2Int pos = _view.Data.Position;
|
||
|
||
foreach (var dw in floor.Doorways)
|
||
{
|
||
if (dw.RoomIndex != _view.Index) continue;
|
||
|
||
int sx = dw.Start.x - pos.x;
|
||
int sz = dw.Start.y - pos.y;
|
||
|
||
switch (dw.Facing)
|
||
{
|
||
case WallFacing.ZP: Block(sx - 1, sz, sx + dw.Length + 1, sz + c); break;
|
||
case WallFacing.ZN: Block(sx - 1, sz - c, sx + dw.Length + 1, sz); break;
|
||
case WallFacing.XP: Block(sx, sz - 1, sx + c, sz + dw.Length + 1); break;
|
||
default: Block(sx - c, sz - 1, sx, sz + dw.Length + 1); break;
|
||
}
|
||
}
|
||
}
|
||
|
||
private void Block(int x0, int z0, int x1, int z1) // x1, z1 не включительно
|
||
{
|
||
for (int x = Mathf.Max(0, x0); x < Mathf.Min(_len, x1); x++)
|
||
for (int z = Mathf.Max(0, z0); z < Mathf.Min(_wid, z1); z++)
|
||
_blocked[x, z] = true;
|
||
}
|
||
|
||
// ---------- Размещение одного предмета ----------
|
||
|
||
private bool TryPlaceOne(PropEntry e, Func<Transform, Random, GameObject> factory)
|
||
{
|
||
var go = factory != null ? factory(_parent, _rng) : Object.Instantiate(e.prefab, _parent);
|
||
go.name = string.IsNullOrEmpty(e.name) ? (e.prefab != null ? e.prefab.name : go.name) : e.name;
|
||
go.transform.localScale = new Vector3(1f, Mathf.Max(0.1f, e.heightScale), 1f);
|
||
|
||
if (!TryGetBounds(go, out Bounds b))
|
||
{
|
||
Debug.LogWarning($"PropPlacer: у префаба {e.prefab.name} нет Renderer, пропускаю");
|
||
go.SetActive(false);
|
||
Object.Destroy(go);
|
||
return false;
|
||
}
|
||
|
||
Vector3 centerOffset = b.center; // объект стоит в нуле
|
||
float baseMinY = b.min.y;
|
||
var size = new Vector2(b.size.x, b.size.z);
|
||
|
||
for (int attempt = 0; attempt < Attempts; attempt++)
|
||
{
|
||
if (!TryPick(e, size, out int yaw, out int x0, out int z0, out int cx, out int cz)) continue;
|
||
if (!IsFree(x0, z0, cx, cz, e.padding)) continue;
|
||
|
||
// Занимаем клетки
|
||
for (int x = x0; x < x0 + cx; x++)
|
||
for (int z = z0; z < z0 + cz; z++)
|
||
_blocked[x, z] = true;
|
||
|
||
Vector3 origin = _view.OriginMeters;
|
||
float wx = origin.x + (x0 + cx * 0.5f) * M;
|
||
float wz = origin.z + (z0 + cz * 0.5f) * M;
|
||
|
||
Quaternion extra = Quaternion.Euler(0f, yaw, 0f);
|
||
Vector3 off = extra * centerOffset;
|
||
|
||
go.transform.SetPositionAndRotation(
|
||
new Vector3(wx - off.x, -baseMinY, wz - off.z),
|
||
extra * Quaternion.Euler(0f, e.frontYawOffset, 0f));
|
||
|
||
_view.PropFootprints.Add(new Rect(origin.x + x0 * M, origin.z + z0 * M, cx * M, cz * M));
|
||
return true;
|
||
}
|
||
|
||
go.SetActive(false);
|
||
Object.Destroy(go);
|
||
return false;
|
||
}
|
||
|
||
// Стены: 0 = южная (перед в +Z), 1 = западная (+X), 2 = северная (-Z), 3 = восточная (-X). yaw = индекс * 90
|
||
private bool TryPick(PropEntry e, Vector2 size, out int yaw, out int x0, out int z0, out int cx, out int cz)
|
||
{
|
||
x0 = z0 = cx = cz = 0;
|
||
int gap = Mathf.Max(0, e.wallGap);
|
||
|
||
switch (e.placement)
|
||
{
|
||
case PropPlacement.AlongWall:
|
||
{
|
||
int w = _rng.Next(4);
|
||
yaw = w * 90;
|
||
Footprint(size, yaw, out cx, out cz);
|
||
switch (w)
|
||
{
|
||
case 0: z0 = gap; x0 = R(0, _len - cx); break;
|
||
case 1: x0 = gap; z0 = R(0, _wid - cz); break;
|
||
case 2: z0 = _wid - cz - gap; x0 = R(0, _len - cx); break;
|
||
default: x0 = _len - cx - gap; z0 = R(0, _wid - cz); break;
|
||
}
|
||
break;
|
||
}
|
||
case PropPlacement.Corner:
|
||
{
|
||
int sx = _rng.Next(2), sz = _rng.Next(2);
|
||
int w = _rng.Next(2) == 0 ? (sz == 0 ? 0 : 2) : (sx == 0 ? 1 : 3);
|
||
yaw = w * 90;
|
||
Footprint(size, yaw, out cx, out cz);
|
||
x0 = sx == 0 ? gap : _len - cx - gap;
|
||
z0 = sz == 0 ? gap : _wid - cz - gap;
|
||
break;
|
||
}
|
||
case PropPlacement.Center:
|
||
{
|
||
yaw = e.randomYaw ? _rng.Next(4) * 90 : 0;
|
||
Footprint(size, yaw, out cx, out cz);
|
||
int margin = Mathf.Max(3, gap);
|
||
x0 = R(margin, _len - cx - margin);
|
||
z0 = R(margin, _wid - cz - margin);
|
||
break;
|
||
}
|
||
default: // Anywhere
|
||
{
|
||
yaw = e.randomYaw ? _rng.Next(4) * 90 : 0;
|
||
Footprint(size, yaw, out cx, out cz);
|
||
x0 = R(0, _len - cx);
|
||
z0 = R(0, _wid - cz);
|
||
break;
|
||
}
|
||
}
|
||
|
||
return x0 >= 0 && z0 >= 0 && x0 + cx <= _len && z0 + cz <= _wid;
|
||
}
|
||
|
||
private static void Footprint(Vector2 size, int yaw, out int cx, out int cz)
|
||
{
|
||
bool swap = (yaw / 90) % 2 == 1;
|
||
float fx = swap ? size.y : size.x;
|
||
float fz = swap ? size.x : size.y;
|
||
cx = Mathf.Max(1, Mathf.CeilToInt(fx / M - 0.05f));
|
||
cz = Mathf.Max(1, Mathf.CeilToInt(fz / M - 0.05f));
|
||
}
|
||
|
||
private int R(int lo, int hi) => hi < lo ? -1 : _rng.Next(lo, hi + 1);
|
||
|
||
private bool IsFree(int x0, int z0, int cx, int cz, int padding)
|
||
{
|
||
int p = Mathf.Max(0, padding);
|
||
for (int x = x0 - p; x < x0 + cx + p; x++)
|
||
{
|
||
for (int z = z0 - p; z < z0 + cz + p; z++)
|
||
{
|
||
if (x < 0 || z < 0 || x >= _len || z >= _wid) continue; // за пределами комнаты — стена
|
||
if (_blocked[x, z]) return false;
|
||
}
|
||
}
|
||
return true;
|
||
}
|
||
|
||
private static bool TryGetBounds(GameObject go, out Bounds bounds)
|
||
{
|
||
bounds = default;
|
||
bool has = false;
|
||
foreach (var r in go.GetComponentsInChildren<Renderer>())
|
||
{
|
||
if (r is ParticleSystemRenderer || r is TrailRenderer || r is LineRenderer) continue;
|
||
if (!has) { bounds = r.bounds; has = true; }
|
||
else bounds.Encapsulate(r.bounds);
|
||
}
|
||
return has;
|
||
}
|
||
}
|
||
} |