diff --git a/Assets/Scripts/Core/DemoBot.Auto.cs b/Assets/Scripts/Core/DemoBot.Auto.cs index 293088a..285269a 100644 --- a/Assets/Scripts/Core/DemoBot.Auto.cs +++ b/Assets/Scripts/Core/DemoBot.Auto.cs @@ -10,6 +10,13 @@ namespace GrassCutter /// and unload, then come back to mow), and a grass train laying its track to the next station and starting to run. /// Time goes six times as fast. Logs both every ten seconds and takes pictures of them. /// + static bool FindDock(out Vector3 at) + { + var dz = GameObject.Find("DockZone"); + at = dz ? dz.transform.position : default; + return dz; + } + IEnumerator AutoDemo() { TeamState.DeleteSave(); @@ -44,12 +51,65 @@ namespace GrassCutter var train = piece ? piece.GetComponent() : null; Log($"train built: {(train ? "ok" : "MISSING")}"); + // something in the way to the yard: the autopilot should go straight through it + if (FindDock(out var dock)) + { + var mid = Planet.Surface(Vector3.Lerp(tractor.transform.position, dock, 0.5f)); + var block = Spawner.Instance.SpawnPiece(PieceId.Press, mid, Face(mid, dock - mid), mid, true); + Log($"obstacle: {(block ? "press" : "MISSING")} {Vector3.Distance(mid, tractor.transform.position):0} m on the way to the yard"); + } + + // a building on the steepest slope round here, sat on it the way the build tool now sets it down + Vector3 steep = default; + float worst = -1f; + for (int a = 0; a < 48; a++) + for (float r = 60f; r <= 300f; r += 15f) + { + var q = Soil17(Mathf.Cos(a * 7.5f * Mathf.Deg2Rad) * r, Mathf.Sin(a * 7.5f * Mathf.Deg2Rad) * r); + var u = Planet.Up(q); + var e = Vector3.ProjectOnPlane(Vector3.right, u).normalized; + var n2 = Vector3.Cross(u, e); + var nrm = Vector3.Cross(Planet.Surface(q + n2 * 2f) - Planet.Surface(q - n2 * 2f), Planet.Surface(q + e * 2f) - Planet.Surface(q - e * 2f)); + float slope = Vector3.Angle(nrm.normalized * Mathf.Sign(Vector3.Dot(nrm, u)), u); + if (slope > worst && !Ts.OnDeck(q) && !(Ground.Instance && Ground.Instance.RockAt(q)) && !Physics.CheckSphere(q + u * 3f, 9f, 1 << Layers.Default, QueryTriggerInteraction.Ignore)) { worst = slope; steep = q; } + } + var dryerDef = GameDefs.Piece(PieceId.Dryer); + var dAt = steep; + var dRot = Face(steep, Vector3.forward); + PlayerBuild.Lean(dryerDef, ref dAt, ref dRot); + var dryer = Spawner.Instance.SpawnPiece(PieceId.Dryer, dAt, dRot, dAt, true); + Log($"slope {worst:0} deg: dryer leans {Vector3.Angle(dRot * Vector3.up, Planet.Up(steep)):0} deg, sunk {Vector3.Dot(dAt - steep, Planet.Up(steep)):0.00} m"); + if (dryer) + { + var du = Planet.Up(dAt); + var side = Vector3.Cross(du, dRot * Vector3.forward).normalized; + yield return Look("auto00_slope_dryer", dAt + du * 3f + side * 13f, dAt + du * 1.5f, 1f); + yield return Look("auto00_slope_dryer2", dAt + du * 4f - (dRot * Vector3.forward) * 13f, dAt + du * 1.5f, 0.4f); + } + Time.timeScale = 6f; var start = tractor.transform.position; + bool flipped = false; double money = Ts.Money.Value; for (int k = 1; k <= 18; k++) { - yield return new WaitForSecondsRealtime(10f); + float until = Time.realtimeSinceStartup + 10f; + while (Time.realtimeSinceStartup < until) + { + yield return null; + var tp0 = tractor.transform.position; + float tilt = Vector3.Angle(tractor.transform.up, Planet.Up(tp0)); + if (tilt > 40f && !flipped) + { + flipped = true; + Log($" TIPPED {tilt:0} deg: {tractor.Job}, alt {Planet.Altitude(tp0):0.00} m, {Vector3.Distance(tp0, Planet.FromBase(0f, 0f) * Planet.Radius):0} m from base, speed {tractor.Body.linearVelocity.magnitude:0.0}, on deck {Ts.OnDeck(tp0)}, exclude {tractor.Body.excludeLayers.value}"); + Time.timeScale = 1f; + var u0 = Planet.Up(tp0); + yield return Look($"auto_tipped", tp0 + u0 * 8f + Vector3.ProjectOnPlane(Vector3.forward, u0).normalized * -10f, tp0, 0.1f); + Time.timeScale = 6f; + } + if (tilt < 20f) flipped = false; + } Log($"t+{k * 60} game s: earned {Ts.Money.Value - money:0}, closed {Ts.Closed.Value}"); Log($" tractor: {tractor.Job}, {GameDefs.Kilos(tractor.Tank.Value)} of {GameDefs.Kilos(tractor.Capacity)}, {Vector3.Distance(start, tractor.transform.position):0} m from start, speed {tractor.Body.linearVelocity.magnitude:0.0}, tilt {Vector3.Angle(tractor.transform.up, Planet.Up(tractor.transform.position)):0} deg"); if (train) Log($" train: {train.Prompt}"); diff --git a/Assets/Scripts/Gameplay/Train.cs b/Assets/Scripts/Gameplay/Train.cs index 8b32d83..1fb31e1 100644 --- a/Assets/Scripts/Gameplay/Train.cs +++ b/Assets/Scripts/Gameplay/Train.cs @@ -25,7 +25,9 @@ namespace GrassCutter const float Strip = 3.4f, Arm = 3f; /// How far out the side cutters reach at Mk I, either side of the track. const float Reach = 18f; - const float WaitAtEnd = 6f, Hold = 6000f, Gap = 5.2f, Gauge = 1.5f; + const float WaitAtEnd = 6f, Hold = 6000f, Gap = 5.2f, Gauge = 1.62f; + /// The top of the rails above the track line: the models' wheels stand on their origin. + const float RailTop = 0.27f; /// The station it is laying track to (255: not chosen yet). public readonly NetworkVariable Target = new NetworkVariable(255); @@ -47,7 +49,7 @@ namespace GrassCutter float Mul => (Piece ? Piece.TierMul : 1f) * (Ts ? Ts.BotSpeedMul : 1f); float MaxOut => Reach * (Piece ? Piece.TierMul : 1f); /// Where the train stands at home: far enough along for every wagon to be on the rails. - float HomeAt => Mathf.Min(_length, (wagons != null ? wagons.Length : 0) * Gap + 1f); + float HomeAt => Mathf.Min(_length, (wagons != null ? wagons.Length : 0) * Gap + 2.5f); float Inner => Strip * 0.5f + (Runs.Value - 1) * Arm; bool Laying => Laid.Value < _length - 0.01f; bool RouteDone => !Laying && Runs.Value > 0 && Inner >= MaxOut; @@ -72,6 +74,10 @@ namespace GrassCutter var mf = t.GetComponent(); float rad = mf && mf.sharedMesh ? Mathf.Max(0.1f, mf.sharedMesh.bounds.extents.y) : 0.4f; _wheels.Add((t, t.localRotation, rad)); + // how far the axles reach fore and aft: the model sits on the rails at its end axles + var lp = Vector3.Scale(root.InverseTransformPoint(t.position), root.localScale); + float z = Mathf.Abs((root.localRotation * lp).z); + _axles[root] = Mathf.Max(_axles.TryGetValue(root, out var had) ? had : 0f, z); } else if (t.name == "Reel") { _reel = t; _reelRest = t.localRotation; } } @@ -151,6 +157,14 @@ namespace GrassCutter _length = _cum[_cum.Count - 1]; } + /// The point this far along the track, carried on straight past either end. + Vector3 PosOn(float d) + { + if (d < 0f) return Pos(0f) - Ahead(0f) * -d; + if (d > _length) return Pos(_length) + Ahead(_length) * (d - _length); + return Pos(d); + } + /// The point this far along the track. Vector3 Pos(float d) { @@ -276,15 +290,27 @@ namespace GrassCutter /// How each model stands in its own frame (an FBX with one root object brings its axis turn on that root). readonly Dictionary _rest = new Dictionary(); + readonly Dictionary _axles = new Dictionary(); + + /// + /// Stands a model on the rails: its front and back axles both on the track, so it leans up and down the slopes + /// with the rails instead of standing level and hanging off one end. + /// void Place(Transform t, float d, bool onRails) { if (!t) return; if (!_rest.TryGetValue(t, out var rest)) _rest[t] = rest = t.localRotation; - var p = Pos(d); - var up = Planet.Up(p); - var f = Vector3.ProjectOnPlane(Ahead(d), up); - if (f.sqrMagnitude < 1e-6f) f = Vector3.ProjectOnPlane(transform.forward, up); - t.SetPositionAndRotation(p + up * (onRails ? 0.22f : 0f), Quaternion.LookRotation(f.normalized, up) * rest); + float half = _axles.TryGetValue(t, out var ax) && ax > 0.2f ? ax : 1.5f; + var back = PosOn(d - half); + var front = PosOn(d + half); + var f = front - back; + if (f.sqrMagnitude < 1e-4f) f = Ahead(d); + f.Normalize(); + var mid = (back + front) * 0.5f; + var up = Vector3.ProjectOnPlane(Planet.Up(mid), f); + if (up.sqrMagnitude < 1e-6f) up = Planet.Up(mid); + up.Normalize(); + t.SetPositionAndRotation(mid + up * (onRails ? RailTop : 0f), Quaternion.LookRotation(f, up) * rest); } // ───────────────────────── the track ───────────────────────── diff --git a/Assets/Scripts/Gameplay/Vehicle.Auto.cs b/Assets/Scripts/Gameplay/Vehicle.Auto.cs index 36f116f..ec0deb3 100644 --- a/Assets/Scripts/Gameplay/Vehicle.Auto.cs +++ b/Assets/Scripts/Gameplay/Vehicle.Auto.cs @@ -29,13 +29,56 @@ namespace GrassCutter /// Strokes as pairs of points on the ground: start, end, start, end... readonly List _strokes = new List(); int _next, _field; - float _stuck, _back, _backSteer, _lastSteer; + float _stuck, _lastSteer; int _stuckTimes; /// The closest it has come to where it's going, and when: circling round a point inside its turn, it gives up on it. float _bestDist, _bestAt; int _goalKey = -1; Vector3 _unloadAt; + /// An autopilot touches nothing: it rides on the soil and on the base deck, through everything else. + const int GhostMask = ~0; + bool _ghost; + static readonly RaycastHit[] s_deckHits = new RaycastHit[8]; + + /// How high this wheel stands over the base deck's slab under it, if there is one (it keeps to the deck, not to what's on it). + static float DeckClearance(Vector3 wp, Vector3 up, float reach) + { + int n = Physics.RaycastNonAlloc(wp + up * 1.2f, -up, s_deckHits, reach, 1 << Layers.Default, QueryTriggerInteraction.Ignore); + float best = float.MaxValue; + for (int i = 0; i < n; i++) + if (s_deckHits[i].collider is BoxCollider && s_deckHits[i].collider.GetComponent()) + best = Mathf.Min(best, s_deckHits[i].distance - 1.2f); + return best; + } + + void Ghost(bool on) + { + if (_ghost == on) return; + _ghost = on; + Body.excludeLayers = on ? (LayerMask)GhostMask : (LayerMask)0; + } + + /// The last way out: picks the machine up and sets it down a few metres on, facing where it's going. + void Hop(Vector3 goal, float metres) + { + var p = transform.position; + var up = Planet.Up(p); + var to = Vector3.ProjectOnPlane(goal - p, up); + float d = to.magnitude; + if (d < 0.5f) return; + var dir = to / d; + var at = Planet.Surface(p + dir * Mathf.Min(metres, d)); + var nu = Planet.Up(at); + // onto the base deck, not under it + if (Ts && Ts.OnDeck(at)) { float c = DeckClearance(at + nu * 4f, nu, 8f); if (c < 50f) at += nu * (4f - c); } + Body.position = at + nu * 0.6f; + Body.rotation = Quaternion.LookRotation(Vector3.ProjectOnPlane(dir, nu).normalized, nu); + Body.linearVelocity = Vector3.zero; + Body.angularVelocity = Vector3.zero; + _hasCut = false; + } + static readonly List s_fields = new List(); static readonly Collider[] s_block = new Collider[4]; @@ -256,10 +299,11 @@ namespace GrassCutter else if (dist < _bestDist - 1f) { _bestDist = dist; _bestAt = Time.time; } else if (Time.time - _bestAt > 7f) { - // round and round a point it can't turn into: on to the next one (or the next stroke) + // round and round a point it can't turn into: on to the next one (or the next stroke); + // on the way to unload it gets there anyway, a hop at a time _goalKey = -1; if (job == AutoJob.Mowing) _next++; - else if (++_stuckTimes >= 5) Auto.Value = (byte)AutoJob.Done; + else Hop(goal, Mathf.Min(dist, 8f)); return new Vector2(_lastSteer, 0.4f); } @@ -267,13 +311,6 @@ namespace GrassCutter float ang = Vector3.SignedAngle(fwd, to, up); float speed = Vector3.ProjectOnPlane(Body.linearVelocity, up).magnitude; - // backing out of something it ran into - if (_back > 0f) - { - _back -= dt; - return new Vector2(_backSteer, -1f); - } - float steer = Mathf.Clamp(ang / 30f, -1f, 1f); // mowing it keeps to a pace it can turn at; on the way somewhere far it goes faster float cap = job == AutoJob.Mowing ? 0.7f : dist > 20f ? 1f : 0.6f; @@ -283,21 +320,14 @@ namespace GrassCutter if (Mathf.Abs(ang) > 50f && dist < 10f) thr = Mathf.Min(thr, 0.22f); _lastSteer = steer; + // it drives through what's in its way; still not moving (wedged on a slope, sunk in something), it hops on if (speed < 0.5f && thr > 0.2f) { _stuck += dt; - if (_stuck > 2.2f) + if (_stuck > 2f) { _stuck = 0f; - _back = 1.5f; - _backSteer = ang > 0f ? -1f : 1f; - if (++_stuckTimes >= 4) - { - // can't get there: the next stroke, or another way home - _stuckTimes = 0; - if (job == AutoJob.Mowing) _next += (_next % 2 == 0) ? 2 : 1; - else Auto.Value = (byte)AutoJob.Done; - } + Hop(goal, 4f); } } else _stuck = 0f; diff --git a/Assets/Scripts/Gameplay/Vehicle.cs b/Assets/Scripts/Gameplay/Vehicle.cs index 32731de..f8e2684 100644 --- a/Assets/Scripts/Gameplay/Vehicle.cs +++ b/Assets/Scripts/Gameplay/Vehicle.cs @@ -278,7 +278,7 @@ namespace GrassCutter void FixedUpdate() { - if (!IsSpawned || !IsOwner || Body.isKinematic) return; + if (!IsSpawned || !IsOwner || Body.isKinematic) { if (_ghost) Ghost(false); return; } bool driving = LocalDriving; var input = driving ? Ctl.Move : Vector2.zero; // the host drives a machine on autopilot @@ -295,6 +295,8 @@ namespace GrassCutter var up = Planet.Up(transform.position); Body.AddForce(-up * GameDefs.LowGravity, ForceMode.Acceleration); + // on autopilot nothing stops it: it drives through buildings, rocks, props, people and machines, on the soil + Ghost(auto); // raycast springs at four corners (soil, deck, ramp) int wet = 0; @@ -306,7 +308,8 @@ namespace GrassCutter var local = new Vector3(Probes[i].x * width, 0f, Probes[i].y * length); var wp = transform.TransformPoint(local); float clearance = Planet.Altitude(wp); - if (Physics.Raycast(wp + up * 1.2f, -up, out var sh, 1.2f + ride + 1.5f, groundMask, QueryTriggerInteraction.Ignore)) + if (auto) clearance = Mathf.Min(clearance, DeckClearance(wp, up, 1.2f + ride + 1.5f)); + else if (Physics.Raycast(wp + up * 1.2f, -up, out var sh, 1.2f + ride + 1.5f, groundMask, QueryTriggerInteraction.Ignore)) clearance = Mathf.Min(clearance, sh.distance - 1.2f); float depth = ride - clearance; if (depth > 0f) diff --git a/Assets/Scripts/Player/PlayerBuild.cs b/Assets/Scripts/Player/PlayerBuild.cs index 3f99825..565ef60 100644 --- a/Assets/Scripts/Player/PlayerBuild.cs +++ b/Assets/Scripts/Player/PlayerBuild.cs @@ -271,8 +271,44 @@ namespace GrassCutter return; } at = _point; - if (GameDefs.IsFoundation(id)) at += _up * Raise; rot = Quaternion.LookRotation(Quaternion.AngleAxis(_yaw, _up) * Heading(_up), _up); + // a foundation stays level (it is a floor to build on); everything else sits on the slope it stands on + if (GameDefs.IsFoundation(id)) at += _up * Raise; + else if (!_on) Lean(GameDefs.Piece(id), ref at, ref rot); + } + + /// The most a piece leans with the ground under it. + const float MaxLean = 22f; + + /// + /// Tilts a piece standing on the soil to the ground under its footprint (the plane through its four corners), + /// then lowers it until no corner hangs in the air. + /// + internal static void Lean(PieceDef d, ref Vector3 at, ref Quaternion rot) + { + if (d == null || Planet.Altitude(at) > 0.3f) return; + var up = Planet.Up(at); + float hx = Mathf.Max(0.5f, d.sizeX * 0.5f), hz = Mathf.Max(0.5f, d.sizeZ * 0.5f); + var r = rot * Vector3.right * hx; + var f = rot * Vector3.forward * hz; + var fr = Planet.Surface(at + r + f); + var fl = Planet.Surface(at - r + f); + var bl = Planet.Surface(at - r - f); + var br = Planet.Surface(at + r - f); + var n = Vector3.Cross(fr + fl - bl - br, fr + br - fl - bl); + if (n.sqrMagnitude < 1e-6f) return; + n.Normalize(); + if (Vector3.Dot(n, up) < 0f) n = -n; + n = Vector3.RotateTowards(up, n, MaxLean * Mathf.Deg2Rad, 0f).normalized; + var mid = (fr + fl + bl + br) * 0.25f; + var c = Planet.Surface(at); + var p = mid + Vector3.ProjectOnPlane(c - mid, n); + // sink to the lowest of the corners and the middle, a little more than that so no gap shows + float drop = 0f; + foreach (var s in new[] { fr, fl, bl, br, c }) drop = Mathf.Min(drop, Vector3.Dot(s - p, n)); + at = p + n * (Mathf.Max(drop, -0.6f) - 0.04f); + var fwd = Vector3.ProjectOnPlane(rot * Vector3.forward, n); + if (fwd.sqrMagnitude > 1e-6f) rot = Quaternion.LookRotation(fwd.normalized, n); } // ───────────────────────── pieces ─────────────────────────