using System; using System.Collections.Generic; using UnityEngine; namespace GrassCutter { /// /// Local tool use. You start with empty hands: take the nail scissors from the supply wall. Hold LMB and the blade /// sits where you aim, cutting a strip as wide as the tool as it moves; what it cuts lands straight in that tool's /// own container. Q ties a bundle of up to 1 kg, E at the depot hands in the whole container. Each tool keeps its own /// grass; the belt holds as many tools as you have slots. The hammer is driven by . /// public class PlayerTools : MonoBehaviour { PlayerAgent _p; public ToolId Current { get; private set; } = ToolId.None; public event Action ToolChanged; public event Action Used; // tool, pulse (true = a stroke) public bool IsCutting { get; private set; } /// Strokes so far: the sound falls on each whole number and the hands read the rest. public float Stroke => _strokeT; public bool IsUsing => IsCutting; /// Where the blade is while cutting. public Vector3 CutPoint { get; private set; } public bool OutOfRange { get; private set; } /// The grass the aim is on, in reach of the blade in hand. public bool BladeOn { get; private set; } public Vector3 BladeAt { get; private set; } /// Kilos per second going into the container. public float LastRate { get; private set; } /// The tools on the belt, in slot order. public List Belt => _belt; readonly List _belt = new List(); readonly float[] _bins = new float[GameDefs.ToolCount]; Vector3 _last; bool _hasLast; float _strokeT, _fullWarn, _packAt, _rate, _reportAt = 5f; int _ownedSeen; bool _changed; System.Action _saved; TeamState Ts => TeamState.Instance; public Vector3 Nozzle { get { var cam = CameraFx.Cam; if (!cam) return transform.position + transform.up; return cam.transform.position + cam.transform.forward * 0.75f + cam.transform.right * 0.2f - cam.transform.up * 0.2f; } } public Vector3 Aim => CameraFx.Cam ? CameraFx.Cam.transform.forward : transform.forward; void Awake() { _p = GetComponent(); } public bool Owns(ToolId t) => GameDefs.IsTool(t) && _p.Owns(t); // ───────────────────────── treat packs ───────────────────────── readonly int[] _packs = new int[2]; /// How many are left in the pack of this treat on the belt (0: none there). public int PackLeft(TreatId k) => _packs[(int)k]; /// Room for a pack of this treat: a free slot, or the one already on the belt not yet full. public bool PackRoom(TreatId k) => _belt.Contains(GameDefs.PackOf(k)) ? _packs[(int)k] + Treats.PackSize <= Treats.PackMost : _belt.Count < _p.BeltSlots.Value; /// A pack from a vending machine goes on the belt (onto the one there, or into a free slot). public bool AddPack(TreatId k, int n) { if (!PackRoom(k)) return false; var id = GameDefs.PackOf(k); if (!_belt.Contains(id)) _belt.Add(id); _packs[(int)k] = Mathf.Min(Treats.PackMost, _packs[(int)k] + n); _changed = true; BeltChanged?.Invoke(); return true; } /// The belt's contents changed without the hand changing (a pack topped up or used). public event Action BeltChanged; /// One from the pack in hand: the can or the cigar comes up, the boost starts, the pack runs down. void UsePack() { var k = GameDefs.PackTreat(Current); if (_packs[(int)k] <= 0 || TreatHand.Busy || !TreatHand.I) return; _packs[(int)k]--; _changed = true; // far from any machine: the others see the boost, not a machine's show _p.TreatRpc((byte)k, new Vector3(0f, -100000f, 0f), Nozzle); TreatHand.I.Play(k); if (_packs[(int)k] <= 0) { int i = _belt.IndexOf(Current); _belt.Remove(Current); var next = ToolId.None; foreach (var t in _belt) if (GameDefs.IsTool(t)) { next = t; break; } if (next == ToolId.None && _belt.Count > 0) next = _belt[Mathf.Clamp(i, 0, _belt.Count - 1)]; Current = ToolId.None; Select(next); } BeltChanged?.Invoke(); } /// Take a tool off the belt: it stays yours (the supply wall has it), the slot is free for something else. public void Unequip(ToolId t) { if (!_belt.Remove(t)) return; _changed = true; if (Current == t) { var next = ToolId.None; foreach (var b in _belt) if (GameDefs.IsTool(b)) { next = b; break; } if (next == ToolId.None && _belt.Count > 0) next = _belt[0]; Select(next); } BeltChanged?.Invoke(); } public float Bin(ToolId t) => GameDefs.IsBlade(t) ? _bins[(int)t] : 0f; public float CurrentCap => Ts && GameDefs.IsBlade(Current) ? Ts.ToolCap(Current) : 0f; void SetBin(ToolId t, float kg) { if (!GameDefs.IsBlade(t)) return; _bins[(int)t] = kg; _changed = true; if (t == Current) _p.Tank.Value = kg; } /// All the grass in all your blades' containers. public float Carried { get { float kg = 0f; for (int i = 0; i < _bins.Length; i++) if (GameDefs.IsBlade((ToolId)i)) kg += _bins[i]; return kg; } } /// Take this much grass out of your containers, the tool in hand first. False (and nothing taken) if there isn't enough. public bool Spend(float kg) { if (Carried < kg - 0.001f) return false; float take = Mathf.Min(kg, Bin(Current)); if (take > 0f) { SetBin(Current, Bin(Current) - take); kg -= take; } for (int i = 0; i < _bins.Length && kg > 0.0001f; i++) { var t = (ToolId)i; if (!GameDefs.IsBlade(t) || _bins[i] <= 0f) continue; take = Mathf.Min(kg, _bins[i]); SetBin(t, _bins[i] - take); kg -= take; } return true; } public void Select(ToolId t) { if (t == Current || (t != ToolId.None && !Owns(t) && !(GameDefs.IsPack(t) && _belt.Contains(t)))) return; Current = t; _changed = true; if (_p.IsOwner) { // a pack in hand shows as empty hands to the others: the can or cigar comes up when it is used _p.ToolNet.Value = (byte)(GameDefs.IsPack(t) ? ToolId.None : t); _p.Tank.Value = Bin(t); } StopCut(); Sfx.Play("ui_hover", 0.5f, 1.2f); ToolChanged?.Invoke(t); } /// Put an owned tool on the belt (over the one in hand when the belt is full) and take it. public void Equip(ToolId t) { if (!Owns(t)) return; if (!_belt.Contains(t)) { if (_belt.Count < _p.BeltSlots.Value) _belt.Add(t); else { int i = _belt.IndexOf(Current); _belt[i >= 0 ? i : _belt.Count - 1] = t; } } Select(t); } void Update() { if (!_p.IsOwner || !_p.IsSpawned) return; var ts = Ts; _saved?.Invoke(); WatchOwned(); HandleSwitching(); if (_changed && Time.time >= _reportAt) ReportNow(); if (GameDefs.IsPack(Current) && Ctl.UsePressed && !_p.Driving.Value && !_p.Grab.Holding && !Ctl.UIOpen) UsePack(); bool blocked = _p.Driving.Value || _p.Grab.Holding || Ctl.UIOpen || !GameDefs.IsBlade(Current) || TreatHand.Busy; if (blocked) { BladeOn = false; StopCut(); return; } BladeOn = FindBlade(out var at); if (BladeOn) BladeAt = at; OutOfRange = !BladeOn; if (Ctl.UseHeld) Cut(); else StopCut(); if (ts && Time.time >= _packAt) { float kg = Bin(Current); bool full = kg >= CurrentCap - 0.005f && kg > 0.005f; if (Ctl.PackHeld || (full && ts.Has(PerkId.AutoBaler))) Pack(kg, Ctl.PackHeld); } } /// Tell the host what the tools hold, for the save. public void ReportNow() { _changed = false; _reportAt = Time.time + 5f; var belt = new int[_belt.Count]; // a pack is kept as 1000 + 100 x its treat + how many are left in it for (int i = 0; i < belt.Length; i++) belt[i] = GameDefs.IsPack(_belt[i]) ? 1000 + 100 * (int)GameDefs.PackTreat(_belt[i]) + _packs[(int)GameDefs.PackTreat(_belt[i])] : (int)_belt[i]; _p.ReportToolsRpc(_bins, belt, (int)Current); } /// Back from a save: the belt as it was, the grass in every container, the same tool in hand. Waits for the /// server's word on what we own, which travels separately. public void Restore(int owned, float[] bins, int[] belt, int current) { _saved = () => { if ((_p.Owned.Value & owned) != owned) return; _saved = null; _ownedSeen = _p.Owned.Value; for (int i = 0; i < bins.Length && i < _bins.Length; i++) _bins[i] = bins[i]; _belt.Clear(); _packs[0] = _packs[1] = 0; foreach (int t in belt) { if (_belt.Count >= _p.BeltSlots.Value) break; if (t >= 1000) { int k = Mathf.Clamp((t - 1000) / 100, 0, 1), n = Mathf.Clamp((t - 1000) % 100, 0, Treats.PackMost); var id = GameDefs.PackOf((TreatId)k); if (n > 0 && !_belt.Contains(id)) { _belt.Add(id); _packs[k] = n; } } else if (Owns((ToolId)t) && !_belt.Contains((ToolId)t)) _belt.Add((ToolId)t); } var hand = _belt.Contains((ToolId)current) ? (ToolId)current : _belt.Count > 0 ? _belt[0] : ToolId.None; Current = ToolId.None; Select(hand); _p.Tank.Value = Bin(hand); ToolChanged?.Invoke(hand); }; } /// Newly bought tools go straight on the belt and into your hands. void WatchOwned() { int owned = _p.Owned.Value; if (owned == _ownedSeen) return; int fresh = owned & ~_ownedSeen; bool first = _ownedSeen == 0 && Current == ToolId.None; _ownedSeen = owned; if (first && Bits(fresh) > 1) { // back from a save: the best cutters fit on the belt, the hammer takes what's left if ((owned >> (int)ToolId.LawnMower & 1) != 0 && _belt.Count < _p.BeltSlots.Value) _belt.Add(ToolId.LawnMower); for (int t = (int)ToolId.WideScythe; t >= 0 && _belt.Count < _p.BeltSlots.Value; t--) if ((owned >> t & 1) != 0) _belt.Add((ToolId)t); if ((owned >> (int)ToolId.Hammer & 1) != 0 && _belt.Count < _p.BeltSlots.Value) _belt.Add(ToolId.Hammer); if (_belt.Count > 0) Select(_belt[0]); return; } for (int t = 0; t < GameDefs.ToolCount; t++) if ((fresh >> t & 1) != 0) Equip((ToolId)t); } static int Bits(int v) { int n = 0; while (v != 0) { v &= v - 1; n++; } return n; } void HandleSwitching() { int slot = Ctl.SlotPressed; if (slot >= 0 && slot < _belt.Count) Select(_belt[slot]); // behind the wheel the wheel zooms the chase camera instead float scroll = _p.Driving.Value ? 0f : Ctl.Scroll; if (Mathf.Abs(scroll) > 0.01f && _belt.Count > 1 && !(Current == ToolId.Hammer && PlayerBuild.Local && PlayerBuild.Local.Active)) { int i = Mathf.Max(0, _belt.IndexOf(Current)); i = (i + (scroll < 0 ? 1 : -1) + _belt.Count) % _belt.Count; Select(_belt[i]); } if (Ctl.BuildPressed && _belt.Contains(ToolId.Hammer)) { ToolId blade = ToolId.None; foreach (var t in _belt) if (GameDefs.IsBlade(t)) { blade = t; break; } Select(Current == ToolId.Hammer ? blade : ToolId.Hammer); } } // ───────────────────────── cutting ───────────────────────── /// Find the meadow along the aim, or right in front of us when looking flat over tall grass. bool FindBlade(out Vector3 hit) { var ts = Ts; var cam = CameraFx.Cam; hit = default; if (!ts || !cam) return false; if (GameDefs.IsMower(Current)) { // pushed, not swung: the strip under the deck, wherever you look if (!_p.Grounded || _p.IsSwimming) return false; var fwd = Vector3.ProjectOnPlane(transform.forward, transform.up).normalized; hit = Planet.Surface(transform.position + fwd * MowerAhead); return !ts.OnDeck(hit) && !ts.OnDeck(transform.position) && Planet.Altitude(transform.position) < GrassField.CurrentHeight + 0.6f; } float reach = ts.ToolReach; var aimRay = new Ray(cam.transform.position, cam.transform.forward); var up = transform.up; bool found = Meadow.Raycast(aimRay, reach + 1.2f, out hit); if (!found) { if (Planet.Altitude(cam.transform.position) < GrassField.CurrentHeight + 0.5f && Vector3.Dot(aimRay.direction, up) < 0.1f) { hit = Planet.Surface(aimRay.GetPoint(Mathf.Min(reach, 2.2f))); found = !ts.OnDeck(hit); } } // something solid in the way (deck, a machine)? if (found && Physics.Linecast(cam.transform.position, hit + up * 0.05f, (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Vehicle), QueryTriggerInteraction.Ignore)) found = false; return found && !ts.OnDeck(hit); } void Cut() { var ts = Ts; if (!ts || !CameraFx.Cam) return; float cap = ts.ToolCap(Current); bool found = BladeOn; var hit = BladeAt; float bin = Bin(Current); if (!found || bin >= cap - 0.001f) { if (found && Time.time > _fullWarn) { _fullWarn = Time.time + 2.5f; Sfx.Play("tank_full", 0.7f); CameraFx.Shake(0.05f); Hud.Toast(Loc.T("Container full! Q ties a bundle, E at the DEPOT hands it all in"), Hud.ToastKind.Warn); } if (!found && Ctl.UsePressed) { Sfx.Play("suck_stop", 0.4f, 1.4f); Hud.Toast(Loc.T("Aim at the grass — it's out of reach"), Hud.ToastKind.Info); } StopCut(); return; } if (!IsCutting) { IsCutting = true; _hasLast = false; // start partway round, so the first stroke has a wind-up _strokeT = 0.62f; CameraFx.FovKick(-0.5f); Used?.Invoke(Current, true); } CutPoint = hit; var from = _hasLast ? _last : hit; _last = hit; _hasLast = true; // a can of Grass Beer and you swing wider float width = ts.ToolWidth(Current) * Treats.MowMul; // the blade has depth, so even held still it eats the grass under it float area = MowMap.Cut(from, hit, width, width * 2f * ts.ToolDepthMul * Time.deltaTime); float add = Mathf.Min(area * GameDefs.GrassDensity, cap - bin); SetBin(Current, bin + add); _rate = Mathf.Lerp(_rate, add / Mathf.Max(0.001f, Time.deltaTime), Time.deltaTime * 6f); LastRate = _rate; // juice: the grass bends into the blade, clippings fly into the basket float power = Mathf.Clamp01(add / Mathf.Max(0.001f, Time.deltaTime) / 2f) + 0.25f; Meadow.Vortex(hit, 0.3f + power * 0.4f, width + 0.5f); if (add > 0f) { Fx.Stream(hit, Nozzle, power * 0.7f); if (UnityEngine.Random.value < Time.deltaTime * 8f) Fx.Splash(hit, 0.1f + power * 0.15f); CameraFx.Shake(0.002f); } float before = _strokeT; bool shears = Current <= ToolId.GardenShears; _strokeT += Time.deltaTime * StrokesPerSecond(Current); if (Mathf.Floor(_strokeT) != Mathf.Floor(before)) { Sfx.Play(shears ? "shears_snip_" + UnityEngine.Random.Range(1, 3) : "scythe_swing_" + UnityEngine.Random.Range(1, 4), shears ? 0.5f : 0.45f, UnityEngine.Random.Range(shears ? 0.92f : 0.8f, shears ? 1.1f : 0.95f)); Used?.Invoke(Current, true); } } /// How far ahead of the boots the mower's deck runs. public const float MowerAhead = 0.95f; AudioSource _motor; /// The mower's motor: idles while it's in your hands, opens up while it cuts. void LateUpdate() { if (!_p.IsOwner) return; bool mower = GameDefs.IsMower(Current) && !_p.Driving.Value; if (mower && !_motor) _motor = Sfx.Loop("mower_engine_loop", transform, 0f); if (_motor) _motor.volume = Mathf.MoveTowards(_motor.volume, (!mower ? 0f : IsCutting ? 0.45f : 0.12f) * Sfx.SfxVolume, Time.deltaTime * 1.5f); if (_motor) _motor.pitch = Mathf.Lerp(_motor.pitch, IsCutting ? 1.15f : 0.85f, Time.deltaTime * 3f); } /// The longer the blade, the slower it goes round. It sets the look and the sound, not how fast grass is cut. public static float StrokesPerSecond(ToolId t) => t == ToolId.LawnMower ? 0f : t == ToolId.NailScissors ? 3.2f : t == ToolId.GardenShears ? 2.4f : t == ToolId.Sickle ? 1.8f : t == ToolId.WideScythe ? 1f : 1.15f; /// The hammer came down on something. public void Struck() => Used?.Invoke(Current, true); void StopCut() { IsCutting = false; _hasLast = false; LastRate = _rate = 0f; } /// Dev cheat: a full container in the tool in hand. public void CheatFill() => SetBin(Current, CurrentCap); public void CheatEmpty() => SetBin(Current, 0f); // ───────────────────────── bundles & the depot ───────────────────────── /// Tie up to 1 kg from the current tool into a bundle and toss it out in front of you. void Pack(float kg, bool manual) { if (kg < 0.005f) { if (manual && Ctl.PackPressed) { Sfx.Play("error", 0.5f); Hud.Toast(Loc.T("Nothing to tie: cut some grass first"), Hud.ToastKind.Info); } return; } var ts = Ts; var cam = CameraFx.Cam; if (!ts || !cam) return; _packAt = Time.time + ts.BundleSeconds; float take = Mathf.Min(kg, GameDefs.BundleKg); SetBin(Current, kg - take); var fwd = cam.transform.forward; var at = manual ? cam.transform.position + fwd * 0.9f - transform.up * 0.35f : transform.position + transform.forward * 0.8f + transform.up * 0.5f; ts.BundleRpc(take, at, manual ? fwd * 2.5f + _p.Velocity * 0.5f : Vector3.zero); Sfx.Play("press_squash", 0.5f, 1.3f); Used?.Invoke(Current, true); } public void Feed(Binder b) { float kg = Bin(Current); if (!b || kg < 0.005f) return; SetBin(Current, 0f); b.TakeRpc(kg); Sfx.Play("compactor_crunch", 0.7f); Sfx.Play("scoop", 0.8f, 0.7f); Used?.Invoke(Current, true); } public void Deposit(Depot d) { var ts = Ts; float kg = Bin(Current); if (!ts || !d || kg < 0.005f) return; SetBin(Current, 0f); ts.DepositRpc(kg, (byte)CargoKind.Grass, d.Mouth); Fx.Splash(d.Mouth, 0.6f); Sfx.Play("throw_whoosh", 0.7f, 0.75f); Sfx.Play("scoop", 0.8f, 0.7f); CameraFx.Shake(0.02f); Used?.Invoke(Current, true); } } }