using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
///
/// One belt from A to B, up to 30 m, at any height. The piece stands at A with +Z toward B; the bed, the rails and the posts
/// down to the ground are generated to fit, so they can only be built once the ends are known. Where it meets another belt
/// at an angle the two of them sweep round one arc between them, and where it comes out of (or goes into) a machine's port
/// at an angle it leaves the way the port faces and bends round to the run. Cargo rides the same curve the belt is drawn on.
///
public class BeltRun : Conveyor
{
float _len = 1f;
BeltShape _shape;
protected override float Surface => 0f;
protected override bool Sides => true;
protected override float Length(int route) => _shape != null ? _shape.PathLength : _len;
protected override Vector2 PathAt(float d, int route) => _shape != null ? _shape.PathAt(d) : new Vector2(0f, d);
protected override float HeightAt(float d, int route) => _shape != null ? _shape.HeightAt(d) : 0f;
protected override void Project(Vector2 local, out int route, out float d)
{
route = 0;
d = _shape != null ? _shape.Project(local) : Mathf.Clamp(local.y, 0f, _len);
}
public float Metres => _len;
/// Where the run was laid to. Belts and machines join here, however the belt itself bends round to meet them.
public Vector3 End => transform.position + transform.rotation * new Vector3(0f, 0f, _len);
/// Where the run was laid from.
public Vector3 StartPoint => transform.position;
protected override Vector3 ExitAt(int route) => End;
public override void Ports(List into)
{
into.Add(new Port { at = StartPoint, dir = Tangent(0f, 0), input = true });
into.Add(new Port { at = End, dir = Tangent(Length(0), 0) });
}
Vector3 _from, _to;
int _seenVersion = -1;
float _nextLook;
///
/// How each end meets its neighbours, redone whenever something is built or taken down nearby: a belt running on gets
/// half of a rounded corner, a machine's port gets a bend out of it and a hood over the end, a free end keeps its drum.
///
protected override void Update()
{
base.Update();
if (_shape == null || BuildPiece.Version == _seenVersion || Time.time < _nextLook) return;
_seenVersion = BuildPiece.Version;
_nextLook = Time.time + 0.25f;
_shape.Fit(_from, _to, JointAt(End, true, this, Piece), JointAt(StartPoint, false, this, Piece));
}
/// What a belt end at meets (the ghost in the player's hands asks too, with no belt of its own).
public static BeltShape.Joint JointAt(Vector3 at, bool end, BeltRun self, BuildPiece skip)
{
foreach (var c in All)
{
if (!(c is BeltRun r) || r == self || r._shape == null) continue;
if (((end ? r.StartPoint : r.End) - at).sqrMagnitude < BeltNet.Joined * BeltNet.Joined)
return new BeltShape.Joint { kind = BeltShape.JointKind.Belt, dir = r.transform.forward, len = r._len };
}
// a splitter or merger is a belt too: the end bends round to its port, but keeps its drum instead of a hood
if (BeltNet.Nearest(at, end, BeltNet.Joined, skip, out var piece, out _, out var port))
return new BeltShape.Joint { kind = BeltShape.JointKind.Port, dir = port.dir, bare = piece.GetComponentInChildren() };
return default;
}
/// Stretches everything to the run. Every peer does this when the piece spawns.
public void Lay(Vector3 from, Vector3 to)
{
_len = Vector3.Distance(from, to);
_from = from;
_to = to;
_seenVersion = -1;
var root = Piece.transform;
if (_shape == null)
{
_shape = new BeltShape(root, root.gameObject.layer);
belts = new[] { _shape.Rubber };
}
_shape.Fit(from, to);
var trigger = GetComponent();
trigger.center = new Vector3(0f, 0.25f, _len * 0.5f);
trigger.size = new Vector3(0.92f, 0.5f, _len);
Bar("BeltBase", new Vector3(0f, -0.07f, _len * 0.5f), new Vector3(1f, 0.14f, _len));
Bar("RailL", new Vector3(-0.47f, 0.07f, _len * 0.5f), new Vector3(0.06f, 0.14f, _len));
Bar("RailR", new Vector3(0.47f, 0.07f, _len * 0.5f), new Vector3(0.06f, 0.14f, _len));
}
void Bar(string name, Vector3 at, Vector3 size)
{
var t = Piece.transform.Find(name);
if (!t) return;
t.localPosition = at;
t.GetComponent().size = size;
}
}
/// The look of a belt run, shared by the built thing and the ghost in the player's hands, and the path it runs along.
public class BeltShape
{
const float PostEvery = 6f, BracketEvery = 1.5f, BedTop = -0.02f, BedLow = -0.14f, DrumR = 0.1f, RailX = 0.47f;
/// How wide a bend sweeps round, measured to the middle of the belt.
const float Radius = 1.4f;
/// Degrees of arc per step: small enough that the rails read as one smooth curve.
const float ArcStep = 5f;
public readonly MeshRenderer Frame, Iron, Rubber;
readonly Mesh _frame = new Mesh { name = "BeltFrame" }, _iron = new Mesh { name = "BeltIron" }, _rubber = new Mesh { name = "BeltRubber" };
readonly List _v = new List(), _n = new List();
readonly List _uv = new List();
readonly List _t = new List();
/// The centre line in the run's own space (flat, +Z toward B), how far along it each point is, and its right-hand side at each point (longer than 1 where it turns, so the edges stay parallel).
readonly List _path = new List(), _side = new List();
/// At each point of the path: which way it runs (in 3D, so up and down slopes too), and the belt's own up,
/// square to that and to the planet's up. Two belts meeting at a corner work these out the same way at the same spot,
/// so their rails and bed meet edge to edge.
readonly List _tan = new List(), _up = new List();
readonly List _along = new List();
static readonly List s_head = new List(), s_tail = new List(), s_headT = new List(), s_tailT = new List();
/// Where the next parts go: a drum, a hood or a bracket is made square and put down along the path.
Matrix4x4 _xf = Matrix4x4.identity;
public BeltShape(Transform parent, int layer)
{
Frame = Part("Frame", parent, layer, _frame, BuildLook.Mat("M_Timber", new Color(0.55f, 0.4f, 0.25f)));
Iron = Part("Iron", parent, layer, _iron, BuildLook.Mat("M_Steel", new Color(0.55f, 0.57f, 0.6f)));
Rubber = Part("Rubber", parent, layer, _rubber, BuildLook.Mat("M_ConveyorBelt", new Color(0.16f, 0.16f, 0.17f)));
}
static MeshRenderer Part(string name, Transform parent, int layer, Mesh mesh, Material mat)
{
var go = new GameObject(name) { layer = layer };
go.transform.SetParent(parent, false);
go.AddComponent().sharedMesh = mesh;
var r = go.AddComponent();
r.sharedMaterial = mat;
return r;
}
/// The ghost is all one see-through material and casts no shadow.
public void Paint(Material m)
{
foreach (var r in new[] { Frame, Iron, Rubber })
{
r.sharedMaterial = m;
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
}
}
public void Destroy()
{
Object.Destroy(_frame);
Object.Destroy(_iron);
Object.Destroy(_rubber);
}
// ───────────────────────── the path ─────────────────────────
public float PathLength => _along.Count > 0 ? _along[_along.Count - 1] : 0f;
/// The point d metres along the path, in the run's space (x across, y along the run).
public Vector2 PathAt(float d)
{
int n = _path.Count;
if (n == 0) return new Vector2(0f, d);
if (d <= 0f) return Flat(_path[0]);
for (int i = 1; i < n; i++)
if (d <= _along[i]) return Flat(Vector3.Lerp(_path[i - 1], _path[i], Mathf.InverseLerp(_along[i - 1], _along[i], d)));
return Flat(_path[n - 1]);
}
/// How high the centre line is d metres along, in the run's space (it rounds over a change of slope).
public float HeightAt(float d)
{
int n = _path.Count;
if (n == 0 || d <= 0f) return n == 0 ? 0f : _path[0].y;
for (int i = 1; i < n; i++)
if (d <= _along[i]) return Mathf.Lerp(_path[i - 1].y, _path[i].y, Mathf.InverseLerp(_along[i - 1], _along[i], d));
return _path[n - 1].y;
}
/// How far along the path its nearest point to a local point is.
public float Project(Vector2 local)
{
if (_path.Count < 2) return 0f;
float best = float.MaxValue, d = 0f;
for (int i = 1; i < _path.Count; i++)
{
var a = Flat(_path[i - 1]);
var ab = Flat(_path[i]) - a;
float k = ab.sqrMagnitude > 1e-8f ? Mathf.Clamp01(Vector2.Dot(local - a, ab) / ab.sqrMagnitude) : 0f;
float e = (a + ab * k - local).sqrMagnitude;
if (e < best) { best = e; d = Mathf.Lerp(_along[i - 1], _along[i], k); }
}
return d;
}
static Vector2 Flat(Vector3 p) => new Vector2(p.x, p.z);
Vector3 At(float d) { var p = PathAt(d); return new Vector3(p.x, 0f, p.y); }
Vector3 Fwd(float d)
{
float L = PathLength;
var p = PathAt(Mathf.Clamp(d + 0.03f, 0f, L)) - PathAt(Mathf.Clamp(d - 0.03f, 0f, L));
return p.sqrMagnitude > 1e-8f ? new Vector3(p.x, 0f, p.y).normalized : Vector3.forward;
}
///
/// Lays out the centre line: a straight run, with half of a corner arc at an end that meets another belt (that belt draws
/// the other half, so the two halves meet in the middle of the arc), or a bend out of a port at an end that meets a machine.
///
void Route(float len, Vector3 a, Quaternion rot, Joint atEnd, Joint atStart)
{
var inv = Quaternion.Inverse(rot);
_path.Clear();
_tan.Clear();
_along.Clear();
s_head.Clear();
s_tail.Clear();
s_headT.Clear();
s_tailT.Clear();
var b = new Vector3(0f, 0f, len);
// a corner with the belt before or after: one arc between the two runs, in 3D, so a change of slope is rounded too
if (atStart.kind == JointKind.Belt) Corner(inv * atStart.dir, Vector3.forward, Mathf.Min(len, atStart.len), Vector3.zero, false, s_head, s_headT);
if (atEnd.kind == JointKind.Belt) Corner(Vector3.forward, inv * atEnd.dir, Mathf.Min(len, atEnd.len), b, true, s_tail, s_tailT);
bool portStart = atStart.kind == JointKind.Port && atStart.dir.sqrMagnitude > 1e-4f;
bool portEnd = atEnd.kind == JointKind.Port && atEnd.dir.sqrMagnitude > 1e-4f;
// a bend at both ends: each one aims for where the other one leaves off, and they settle in a couple of rounds
for (int pass = 0; pass < (portStart && portEnd ? 3 : 1); pass++)
{
if (portStart)
{
s_head.Clear();
s_headT.Clear();
if (!Bow(Vector3.zero, Level(inv * atStart.dir), s_tail.Count > 0 ? s_tail[0] : b, s_head)) s_head.Clear();
}
if (portEnd)
{
s_tail.Clear();
s_tailT.Clear();
if (Bow(b, -Level(inv * atEnd.dir), s_head.Count > 0 ? s_head[s_head.Count - 1] : Vector3.zero, s_tail)) s_tail.Reverse();
else s_tail.Clear();
}
}
if (s_head.Count == 0) s_head.Add(Vector3.zero);
if (s_tail.Count == 0) s_tail.Add(b);
for (int i = 0; i < s_head.Count; i++) Add(s_head[i], i < s_headT.Count ? s_headT[i] : Vector3.zero);
for (int i = 0; i < s_tail.Count; i++) Add(s_tail[i], i < s_tailT.Count ? s_tailT[i] : Vector3.zero);
Frames(a, rot, inv);
}
static Vector3 Level(Vector3 v) => new Vector3(v.x, 0f, v.z).normalized;
void Add(Vector3 p, Vector3 tangent)
{
int n = _path.Count;
if (n > 0 && (p - _path[n - 1]).sqrMagnitude < 1e-6f)
{
if (tangent.sqrMagnitude > 1e-6f) _tan[n - 1] = tangent;
return;
}
_along.Add(n == 0 ? 0f : _along[n - 1] + Vector3.Distance(p, _path[n - 1]));
_path.Add(p);
_tan.Add(tangent);
}
///
/// Half of the arc round a corner at , where a run heading meets one heading
/// (in 3D: a turn, a change of slope, or both). The arc lies in the plane of the two directions and
/// touches both runs; the end's half runs from where it leaves this run to its middle, the start's half from the middle
/// onto this run. Both belts work it out from the same directions, corner and shorter length, so the halves meet exactly.
///
static void Corner(Vector3 d1, Vector3 d2, float shortest, Vector3 j, bool atEnd, List into, List tangents)
{
d1.Normalize();
d2.Normalize();
float theta = Mathf.Min(Vector3.Angle(d1, d2), 150f);
if (theta < 2f) return;
float half = theta * 0.5f * Mathf.Deg2Rad, th = theta * Mathf.Deg2Rad;
float tanH = Mathf.Tan(half);
float cut = Mathf.Min(Radius * tanH, shortest * 0.5f);
float r = cut / tanH;
var inward = (d2 - d1 * Vector3.Dot(d1, d2)).normalized;
var c = j - d1 * cut + inward * r;
int steps = Mathf.Max(2, Mathf.CeilToInt(theta * 0.5f / ArcStep));
for (int i = 0; i <= steps; i++)
{
float k = (float)i / steps;
float phi = atEnd ? th * 0.5f * k : th * 0.5f * (1f + k);
into.Add(c - inward * r * Mathf.Cos(phi) + d1 * r * Mathf.Sin(phi));
tangents.Add((inward * Mathf.Sin(phi) + d1 * Mathf.Cos(phi)).normalized);
}
}
///
/// An arc that leaves heading and turns until it heads straight for
/// (false: no bend needed, or no room for one).
///
static bool Bow(Vector3 at, Vector3 heading, Vector3 target, List into)
{
var to = target - at;
to.y = 0f;
if (heading.sqrMagnitude < 1e-4f || to.sqrMagnitude < 0.25f) return false;
float turn = Vector3.SignedAngle(heading, to, Vector3.up);
if (Mathf.Abs(turn) < 3f || Mathf.Abs(turn) > 165f) return false;
float s = Mathf.Sign(turn);
float r = Mathf.Min(Radius, to.magnitude * 0.4f);
if (r < 0.6f) return false;
var c = at + Quaternion.AngleAxis(90f * s, Vector3.up) * heading * r;
var w = target - c;
w.y = 0f;
float dist = w.magnitude;
if (dist <= r * 1.05f) return false;
float alpha = Mathf.Acos(r / dist) * Mathf.Rad2Deg;
var spoke = at - c;
var end = Vector3.zero;
float fit = -2f;
foreach (float sign in new[] { -1f, 1f })
{
var rt = Quaternion.AngleAxis(alpha * sign, Vector3.up) * (w / dist) * r;
// which way the arc is heading where it leaves the circle
var h = Quaternion.AngleAxis(90f * s, Vector3.up) * rt.normalized;
float f = Vector3.Dot(h, (target - (c + rt)).normalized);
if (f > fit) { fit = f; end = rt; }
}
if (fit < 0.95f) return false;
float sweep = Vector3.SignedAngle(spoke, end, Vector3.up);
if (sweep * s < 0f) sweep += 360f * s;
if (Mathf.Abs(sweep) > 200f) return false;
int steps = Mathf.Max(2, Mathf.CeilToInt(Mathf.Abs(sweep) / ArcStep));
for (int i = 0; i <= steps; i++) into.Add(c + Quaternion.AngleAxis(sweep * i / steps, Vector3.up) * spoke);
return true;
}
///
/// The frame at each point of the path: its direction (worked out from the neighbours where the route didn't give one),
/// the right-hand side square to it and to the planet's up there, and the belt's own up square to both.
///
void Frames(Vector3 a, Quaternion rot, Quaternion inv)
{
_side.Clear();
_up.Clear();
int n = _path.Count;
for (int i = 0; i < n; i++)
{
var t = _tan[i];
if (t.sqrMagnitude < 1e-6f)
{
var f = n < 2 ? Vector3.forward : _path[Mathf.Min(n - 1, i + 1)] - _path[Mathf.Max(0, i - 1)];
t = f.sqrMagnitude > 1e-8f ? f.normalized : Vector3.forward;
_tan[i] = t;
}
var planetUp = inv * Planet.Up(a + rot * _path[i]);
var side = Vector3.Cross(planetUp, t);
side = side.sqrMagnitude > 1e-6f ? side.normalized : Vector3.right;
_side.Add(side);
_up.Add(Vector3.Cross(t, side).normalized);
}
}
// ───────────────────────── the meshes ─────────────────────────
void Begin()
{
_v.Clear(); _n.Clear(); _uv.Clear(); _t.Clear();
_xf = Matrix4x4.identity;
}
void Finish(Mesh m)
{
m.Clear();
m.indexFormat = _v.Count > 60000 ? UnityEngine.Rendering.IndexFormat.UInt32 : UnityEngine.Rendering.IndexFormat.UInt16;
m.SetVertices(_v);
m.SetNormals(_n);
m.SetUVs(0, _uv);
m.SetTriangles(_t, 0);
m.RecalculateBounds();
_xf = Matrix4x4.identity;
}
/// Square parts that follow go down d metres along the path, turned and tilted with it.
void Along(float d)
{
Frame3(d, out var at, out var fwd, out var up);
_xf = Matrix4x4.TRS(at, Quaternion.LookRotation(fwd, up), Vector3.one);
}
/// The point d metres along the path in 3D, with its direction and the belt's up there.
void Frame3(float d, out Vector3 at, out Vector3 fwd, out Vector3 up)
{
int n = _path.Count;
if (n == 0) { at = new Vector3(0f, 0f, d); fwd = Vector3.forward; up = Vector3.up; return; }
int i = 1;
while (i < n - 1 && _along[i] < d) i++;
float k = n < 2 ? 0f : Mathf.Clamp01(Mathf.InverseLerp(_along[i - 1], _along[i], d));
int a = n < 2 ? 0 : i - 1, b = n < 2 ? 0 : i;
at = Vector3.Lerp(_path[a], _path[b], k);
fwd = Vector3.Slerp(_tan[a], _tan[b], k).normalized;
up = Vector3.Slerp(_up[a], _up[b], k).normalized;
}
void Quad(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector3 n, Vector2 uv0, Vector2 uv1)
{
Face(a, b, c, d, n, n, n, n, uv0, new Vector2(uv1.x, uv0.y), uv1, new Vector2(uv0.x, uv1.y));
}
/// A four-cornered face given round its edge, facing whichever way its normals say.
void Face(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector3 na, Vector3 nb, Vector3 nc, Vector3 nd, Vector2 ua, Vector2 ub, Vector2 uc, Vector2 ud)
{
int i = _v.Count;
_v.Add(_xf.MultiplyPoint3x4(a)); _v.Add(_xf.MultiplyPoint3x4(b)); _v.Add(_xf.MultiplyPoint3x4(c)); _v.Add(_xf.MultiplyPoint3x4(d));
_n.Add(_xf.MultiplyVector(na).normalized); _n.Add(_xf.MultiplyVector(nb).normalized);
_n.Add(_xf.MultiplyVector(nc).normalized); _n.Add(_xf.MultiplyVector(nd).normalized);
_uv.Add(ua); _uv.Add(ub); _uv.Add(uc); _uv.Add(ud);
if (Vector3.Dot(Vector3.Cross(b - a, c - a), na + nb + nc + nd) < 0f)
{
_t.Add(i); _t.Add(i + 2); _t.Add(i + 1);
_t.Add(i); _t.Add(i + 3); _t.Add(i + 2);
}
else
{
_t.Add(i); _t.Add(i + 1); _t.Add(i + 2);
_t.Add(i); _t.Add(i + 2); _t.Add(i + 3);
}
}
/// A bar of square section swept along the whole path, from x0 to x1 across and y0 to y1 up, its ends closed.
bool _capStart = true, _capEnd = true;
void Sweep(float x0, float x1, float y0, float y1)
{
int n = _path.Count;
if (n < 2) return;
float w = (x1 - x0) * 0.8f, h = (y1 - y0) * 0.8f;
Vector3 P(int k, float x, float y) => _path[k] + _side[k] * x + _up[k] * y;
for (int i = 0; i + 1 < n; i++)
{
int j = i + 1;
float v0 = _along[i] * 0.8f, v1 = _along[j] * 0.8f;
var si = _side[i];
var sj = _side[j];
var ui = _up[i];
var uj = _up[j];
Face(P(i, x0, y1), P(i, x1, y1), P(j, x1, y1), P(j, x0, y1), ui, ui, uj, uj, new Vector2(0f, v0), new Vector2(w, v0), new Vector2(w, v1), new Vector2(0f, v1));
Face(P(i, x0, y0), P(i, x1, y0), P(j, x1, y0), P(j, x0, y0), -ui, -ui, -uj, -uj, new Vector2(0f, v0), new Vector2(w, v0), new Vector2(w, v1), new Vector2(0f, v1));
Face(P(i, x1, y0), P(i, x1, y1), P(j, x1, y1), P(j, x1, y0), si, si, sj, sj, new Vector2(0f, v0), new Vector2(h, v0), new Vector2(h, v1), new Vector2(0f, v1));
Face(P(i, x0, y0), P(i, x0, y1), P(j, x0, y1), P(j, x0, y0), -si, -si, -sj, -sj, new Vector2(0f, v0), new Vector2(h, v0), new Vector2(h, v1), new Vector2(0f, v1));
}
foreach (int k in new[] { 0, n - 1 })
{
if (k == 0 ? !_capStart : !_capEnd) continue;
var f = _tan[k] * (k == 0 ? -1f : 1f);
Quad(P(k, x0, y0), P(k, x1, y0), P(k, x1, y1), P(k, x0, y1), f, Vector2.zero, new Vector2(w, h));
}
}
/// The belt itself: one strip along the path, V in metres so the texture runs round the bends with it.
void Strip(float half)
{
for (int i = 0; i + 1 < _path.Count; i++)
{
int j = i + 1;
Face(_path[i] - _side[i] * half, _path[i] + _side[i] * half, _path[j] + _side[j] * half, _path[j] - _side[j] * half, _up[i], _up[i], _up[j], _up[j],
new Vector2(0f, _along[i]), new Vector2(1f, _along[i]), new Vector2(1f, _along[j]), new Vector2(0f, _along[j]));
}
}
void Box(Vector3 center, Quaternion rot, Vector3 size)
{
for (int axis = 0; axis < 3; axis++)
for (int sign = -1; sign <= 1; sign += 2)
{
var n = Vector3.zero; n[axis] = sign;
var u = Vector3.zero; u[(axis + 1) % 3] = 1f;
var v = Vector3.zero; v[(axis + 2) % 3] = 1f;
if (sign > 0) { var w = u; u = v; v = w; }
Vector3 P(float a, float b) => center + rot * Vector3.Scale((n + u * a + v * b) * 0.5f, size);
// the grain runs the long way and the texture keeps its scale
var tile = new Vector2(Vector3.Scale(u, size).magnitude, Vector3.Scale(v, size).magnitude) * 0.8f;
Quad(P(-1, -1), P(1, -1), P(1, 1), P(-1, 1), rot * n, Vector2.zero, tile);
}
}
/// An eight-sided roller across the belt.
void Drum(Vector3 center, float r, float width)
{
const int Sides = 8;
for (int k = 0; k < Sides; k++)
{
float a0 = k * Mathf.PI * 2f / Sides, a1 = (k + 1) * Mathf.PI * 2f / Sides, mid = (a0 + a1) * 0.5f;
Vector3 P(float ang, float x) => center + new Vector3(x, Mathf.Sin(ang) * r, Mathf.Cos(ang) * r);
Quad(P(a0, -width * 0.5f), P(a0, width * 0.5f), P(a1, width * 0.5f), P(a1, -width * 0.5f), new Vector3(0f, Mathf.Sin(mid), Mathf.Cos(mid)), Vector2.zero, Vector2.one);
}
}
public enum JointKind { Free, Belt, Port }
/// What an end of the run meets: nothing, another belt (which way it runs, how long it is), or a machine's port (which way things flow through it).
public struct Joint
{
public JointKind kind;
public Vector3 dir;
public float len;
/// A port on another belt piece: no hood over the end.
public bool bare;
public bool Hooded => kind == JointKind.Port && !bare;
public bool Drum => kind == JointKind.Free || (kind == JointKind.Port && bare);
}
/// Rebuilds the meshes for a run from A to B, with the parent standing at A along the run.
public void Fit(Vector3 a, Vector3 b) => Fit(a, b, default, default);
///
/// The same, knowing what each end meets. Bed, rails and belt are swept along one path, so a bend is one smooth piece:
/// no wedges, no rails crossing, the belt's arrows running round it. Where it ends at a machine, a hood comes down over
/// the end, as if the machine had drawn the belt in; a free end shows its drum.
///
public void Fit(Vector3 a, Vector3 b, Joint atEnd, Joint atStart)
{
float len = Vector3.Distance(a, b);
var rot = BuildRules.RunRotation(a, b);
Route(len, a, rot, atEnd, atStart);
float total = PathLength;
// the belt before this one already stands a post and a bracket at the middle of the corner
int first = atStart.kind == JointKind.Belt ? 1 : 0;
_capStart = atStart.kind != JointKind.Belt;
_capEnd = atEnd.kind != JointKind.Belt;
Begin();
Sweep(-0.45f, 0.45f, BedLow, BedTop);
Sweep(-RailX - 0.03f, -RailX + 0.03f, -0.05f, 0.15f);
Sweep(RailX - 0.03f, RailX + 0.03f, -0.05f, 0.15f);
int posts = Mathf.Max(1, Mathf.RoundToInt(total / PostEvery));
for (int i = first; i <= posts; i++)
{
Frame3(total * i / posts, out var on, out var fwd, out var up);
Post(a, rot, on + up * BedLow, fwd);
}
Finish(_frame);
Begin();
if (atStart.Drum) { Along(0f); Drum(new Vector3(0f, -0.09f, 0f), DrumR, 0.9f); }
if (atEnd.Drum) { Along(total); Drum(new Vector3(0f, -0.09f, 0f), DrumR, 0.9f); }
int brackets = Mathf.Max(1, Mathf.RoundToInt(total / BracketEvery));
for (int i = first; i <= brackets; i++)
{
Along(total * i / brackets);
foreach (float x in new[] { -0.51f, 0.51f })
Box(new Vector3(x, 0.05f, 0f), Quaternion.identity, new Vector3(0.02f, 0.24f, 0.09f));
}
if (atEnd.Hooded) { Along(total); Hood(0f, -1f); }
if (atStart.Hooded) { Along(0f); Hood(0f, 1f); }
Finish(_iron);
Begin();
Strip(0.44f);
Finish(_rubber);
}
/// Degrees the next run turns away from this one, seen from above: + to the right.
static float Turn(Vector3 localDir)
{
var flat = new Vector3(localDir.x, 0f, localDir.z);
if (flat.sqrMagnitude < 1e-4f) return 0f;
return Mathf.Clamp(Vector3.SignedAngle(Vector3.forward, flat, Vector3.up), -150f, 150f);
}
///
/// A hood over the end that meets a machine: an arch of iron hoops with a skin over them, open toward the belt, closed
/// against the machine. is +1 when the hood runs on from the start, -1 back from the end.
///
void Hood(float z, float way)
{
const int Arc = 7;
const float R = 0.5f, Long = 0.55f;
for (int hoop = 0; hoop <= 2; hoop++)
{
float hz = z + way * Long * hoop / 2f;
for (int k = 0; k < Arc; k++)
{
float a0 = Mathf.PI * k / Arc, a1 = Mathf.PI * (k + 1) / Arc;
var p0 = new Vector3(Mathf.Cos(a0) * R, Mathf.Sin(a0) * R * 0.7f, hz);
var p1 = new Vector3(Mathf.Cos(a1) * R, Mathf.Sin(a1) * R * 0.7f, hz);
var d = p1 - p0;
Box((p0 + p1) * 0.5f, Quaternion.LookRotation(Vector3.forward, Vector3.Cross(d, Vector3.forward)), new Vector3(d.magnitude + 0.01f, 0.04f, 0.05f));
}
}
// the skin between the first and last hoop
for (int k = 0; k < Arc; k++)
{
float a0 = Mathf.PI * k / Arc, a1 = Mathf.PI * (k + 1) / Arc;
Vector3 P(float a, float zz) => new Vector3(Mathf.Cos(a) * (R - 0.02f), Mathf.Sin(a) * (R - 0.02f) * 0.7f, zz);
var n = new Vector3(Mathf.Cos((a0 + a1) * 0.5f), Mathf.Sin((a0 + a1) * 0.5f), 0f);
float z0 = z, z1 = z + way * Long;
if (way > 0f) Quad(P(a0, z0), P(a1, z0), P(a1, z1), P(a0, z1), n, Vector2.zero, Vector2.one);
else Quad(P(a1, z0), P(a0, z0), P(a0, z1), P(a1, z1), n, Vector2.zero, Vector2.one);
}
}
/// Two legs spread apart straight down from the bed to whatever is underneath, a low block if there's hardly any room.
void Post(Vector3 a, Quaternion rot, Vector3 on, Vector3 fwd)
{
var top = a + rot * on;
var up = Planet.Up(top);
float drop = Planet.Altitude(top);
const int Under = (1 << Layers.Default) | (1 << Layers.Build);
if (Physics.Raycast(top - up * 0.2f, -up, out var hit, Mathf.Max(0.1f, drop), Under, QueryTriggerInteraction.Ignore)) drop = hit.distance + 0.2f;
if (drop < 0.2f) return;
var down = Quaternion.Inverse(rot) * -up;
// square across the belt where it stands, leaning with the ground
var stand = Quaternion.FromToRotation(Vector3.down, down) * Quaternion.LookRotation(fwd, Vector3.up);
var at = on;
float reach = drop;
if (reach < 0.5f)
{
Box(at + down * reach * 0.5f, stand, new Vector3(0.7f, reach, 0.14f));
return;
}
foreach (float side in new[] { -1f, 1f })
{
var from = at + stand * Vector3.right * side * 0.34f;
var to = at + down * reach + stand * Vector3.right * side * 0.5f;
Box((from + to) * 0.5f, Quaternion.FromToRotation(Vector3.up, from - to), new Vector3(0.11f, (from - to).magnitude, 0.11f));
Box(to, stand, new Vector3(0.26f, 0.05f, 0.36f));
}
Box(at + down * reach * 0.55f, stand, new Vector3(0.84f, 0.07f, 0.06f));
}
}
/// Materials for what's generated at run time.
public static class BuildLook
{
public static Material Mat(string name, Color fallback)
{
var m = AssetBank.I ? AssetBank.I.Mat(name) : null;
return m ? m : new Material(Shader.Find("Universal Render Pipeline/Lit")) { color = fallback };
}
}
}