Files
grass-cutters/Assets/Scripts/World/WeatherFx.cs
NiemandKG 36e4bb2a10 Round 6 fixes: held tools, headlamp glare, ladder openings, level horizon, roof hulls, rain hits, idle motion, belt packs, meadow variety
- Held tools sit lower and further right; the hammer faces forward and strikes about the camera's right
- Headlamp leaves held items, treats and vending machines alone (rendering layer NoLamp); other lights keep lighting them
- Hay grounded on the floor in world space (it floated)
- Deck fence opens at each ladder, rail colliders split around it; ladders moved to 2 m off the edge middle, clear of the intakes; climbing goes over a rail only if one is in the way
- Crew stand to the soil's up (Planet.Level): flat round the base, the ball's up past it, so the horizon stays level on a small planet
- Convex roof hulls for the crew cabin, garage, pitched roof and windmill tower; cabin box lowered to the eaves
- Rain and acid rain hits differ by surface: soil, grass, wood, metal
- Idle motion: dishes pan, sways sway, sensors turn, eyes blink, windmill turns in the breeze, reels and parked rotors tick over
- Belt: take tools off at the supply wall; hold E at a vending machine for a pack of 3 on the belt, LMB has one
- New meadow pieces: boulders, slab stones, crystals, mushrooms, stump, bulb plants
- -demofix checks for all of the above; loc rows in all 11 tables

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 22:52:05 +06:00

685 lines
36 KiB
C#

using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// What the weather looks and sounds like where the camera is. The host decides the weather (<see cref="TeamState"/>); this
/// eases into it and draws it: rain and acid rain around the camera, the sky clouding over, the fog closing in, a gale in
/// the grass, lightning and thunder, shooting stars, the twister and the saucer. The twister's and the saucer's paths are
/// worked out from server time, so every machine sees them in the same place and cuts the same grass.
/// </summary>
public class WeatherFx : MonoBehaviour
{
/// <summary>Eased weather, 0..1: rain falling (acid or not), how much of it is acid, wind, storm.</summary>
public static float Rain, Acid, Wind, Storm;
/// <summary>How much the weather thickens the air (0 clear), and the fog's colour then.</summary>
public static float Murk;
public static Color FogTint = new Color(0.55f, 0.6f, 0.66f);
/// <summary>What's left of the sunlight; a lightning flash, 0..1.</summary>
public static float SunMul = 1f, Flash;
public static float FogMul => Mathf.Lerp(1f, 0.25f, Murk);
static readonly int CoverId = Shader.PropertyToID("_GcCoverAdd"), StormId = Shader.PropertyToID("_GcStorm"), FlashId = Shader.PropertyToID("_GcFlash"),
AcidId = Shader.PropertyToID("_GcAcid"), GustId = Shader.PropertyToID("_GcGust");
/// <summary>The share of sunshine the solar panels get in each weather (the host's own figure, not eased).</summary>
public static float SolarOf(WeatherKind k)
{
switch (k)
{
case WeatherKind.Clouds: return 0.75f;
case WeatherKind.Rain: return 0.55f;
case WeatherKind.AcidRain: return 0.5f;
case WeatherKind.Wind: return 0.9f;
case WeatherKind.Storm: return 0.35f;
default: return 1f;
}
}
float _cover;
ParticleSystem _drops, _splash, _funnel, _debris, _meteor, _beam;
AudioSource _rainLoop, _windLoop, _twisterLoop, _ufoHum, _ufoBeam;
Transform _twister, _ufo;
Light _ufoLight;
Renderer[] _ufoLights;
Material _ufoGlow;
float _rainDue, _splashDue, _windDue, _funnelDue, _beamDue, _nextFlash = 8f, _thunderAt = -1f, _thunderVol, _nextMeteor, _flingAt;
Vector3 _lastTwister;
bool _twisterWas;
double _circleOf;
int _circleDone;
Vector3 _ufoAt;
void Start()
{
var fx = Fx.I;
var bank = AssetBank.I;
var soft = bank.Mat("FX_Soft");
var spark = bank.Mat("FX_Sparkle") ?? soft;
_drops = fx.Make("rain", soft, 0.9f, 0.03f, 0f, false);
var dr = _drops.GetComponent<ParticleSystemRenderer>();
dr.renderMode = ParticleSystemRenderMode.Stretch;
dr.velocityScale = 0.05f;
dr.lengthScale = 1f;
_splash = fx.Make("rain_splash", soft, 0.25f, 0.12f, 0f, false);
Fx.SetSizeCurve(_splash, 0.3f, 1.2f);
Fx.SetFade(_splash, 0.6f);
_funnel = fx.Make("twister", soft, 2.6f, 1.2f, 0f, true);
Fx.SetSizeCurve(_funnel, 0.5f, 2.2f);
Fx.SetFade(_funnel, 0.55f);
var fm = _funnel.main; fm.simulationSpace = ParticleSystemSimulationSpace.Local; fm.maxParticles = 1500;
var orbit = _funnel.velocityOverLifetime;
orbit.enabled = true;
orbit.space = ParticleSystemSimulationSpace.Local;
orbit.x = orbit.y = orbit.z = new ParticleSystem.MinMaxCurve(0f);
orbit.orbitalX = orbit.orbitalZ = new ParticleSystem.MinMaxCurve(0f);
orbit.orbitalY = new ParticleSystem.MinMaxCurve(5.5f);
orbit.radial = new ParticleSystem.MinMaxCurve(1.7f);
_twister = _funnel.transform;
_twister.SetParent(transform, false);
_debris = fx.Make("twister_debris", bank.Mat("FX_Leaf") ?? soft, 2.2f, 0.12f, 0f, true);
var dm = _debris.main; dm.simulationSpace = ParticleSystemSimulationSpace.Local;
var dorbit = _debris.velocityOverLifetime;
dorbit.enabled = true;
dorbit.space = ParticleSystemSimulationSpace.Local;
dorbit.x = dorbit.y = dorbit.z = new ParticleSystem.MinMaxCurve(0f);
dorbit.orbitalX = dorbit.orbitalZ = new ParticleSystem.MinMaxCurve(0f);
dorbit.orbitalY = new ParticleSystem.MinMaxCurve(7f);
dorbit.radial = new ParticleSystem.MinMaxCurve(1.6f);
_debris.transform.SetParent(_twister, false);
_meteor = fx.Make("meteors", spark, 0.9f, 0.6f, 0f, false);
var mr = _meteor.GetComponent<ParticleSystemRenderer>();
mr.renderMode = ParticleSystemRenderMode.Stretch;
mr.velocityScale = 0.18f;
mr.lengthScale = 2f;
Fx.SetFade(_meteor, 1f);
_beam = fx.Make("ufo_beam", soft, 0.9f, 1.4f, 0f, false);
Fx.SetSizeCurve(_beam, 0.6f, 1.4f);
Fx.SetFade(_beam, 0.5f);
}
void OnDestroy()
{
foreach (var ps in new[] { _drops, _splash, _meteor, _beam })
if (ps) Destroy(ps.gameObject);
}
void OnDisable()
{
Rain = Acid = Wind = Storm = Murk = Flash = 0f;
SunMul = 1f;
}
void Update()
{
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (!cam) return;
var ts = TeamState.Instance;
var kind = ts && ts.IsSpawned ? ts.WeatherNow : WeatherKind.Clear;
float dt = Time.deltaTime;
Ease(kind, dt);
var eye = cam.transform.position;
var up = Planet.Up(eye);
var windDir = Vector3.ProjectOnPlane(new Vector3(0.87f, 0.11f, 0.48f), up).normalized;
Shader.SetGlobalFloat(CoverId, _cover);
// rain greys the sky too, a storm most of all
Shader.SetGlobalFloat(StormId, Mathf.Clamp01(Storm + Rain * 0.45f));
Shader.SetGlobalFloat(AcidId, Acid * Mathf.Clamp01(Rain * 1.6f));
Shader.SetGlobalFloat(GustId, Wind * 2.2f + Storm * 0.8f);
TickRain(eye, up, windDir, dt);
TickWind(eye, up, windDir, dt);
TickLightning(eye, dt);
TickMeteors(eye, up, kind, dt);
TickTwister(ts, eye);
TickUfo(ts, eye);
}
void Ease(WeatherKind k, float dt)
{
float rain = 0f, acid = Acid, wind = 0f, storm = 0f, cover = -0.15f, murk = 0f, sun = SolarOf(k);
switch (k)
{
case WeatherKind.Clouds: cover = 0.35f; murk = 0.12f; break;
case WeatherKind.Rain: rain = 0.75f; acid = 0f; cover = 0.5f; murk = 0.45f; break;
case WeatherKind.AcidRain: rain = 0.7f; acid = 1f; cover = 0.5f; murk = 0.5f; break;
case WeatherKind.Wind: wind = 1f; cover = 0.1f; murk = 0.15f; break;
case WeatherKind.Storm: rain = 1f; acid = 0f; wind = 0.7f; storm = 1f; cover = 0.65f; murk = 0.75f; break;
case WeatherKind.Meteors: cover = -0.35f; break;
}
float step = dt / 9f;
Rain = Mathf.MoveTowards(Rain, rain, step);
// the acid share only flips while nothing is falling, so a shower never changes colour in mid-air
if (Rain < 0.02f || rain > 0f) Acid = Mathf.MoveTowards(Acid, acid, step * 3f);
Wind = Mathf.MoveTowards(Wind, wind, step);
Storm = Mathf.MoveTowards(Storm, storm, step);
_cover = Mathf.MoveTowards(_cover, cover, step);
Murk = Mathf.MoveTowards(Murk, murk, step);
SunMul = Mathf.MoveTowards(SunMul, Mathf.Lerp(1f, sun, 0.8f), step);
FogTint = Color.Lerp(new Color(0.55f, 0.6f, 0.66f), new Color(0.66f, 0.74f, 0.3f), Acid);
}
// ───────────────────────── rain ─────────────────────────
void TickRain(Vector3 eye, Vector3 up, Vector3 windDir, float dt)
{
float r = Rain;
if (r > 0.01f)
{
var tint = Color.Lerp(new Color(0.82f, 0.88f, 1f, 0.7f), new Color(0.78f, 1f, 0.3f, 0.8f), Acid);
var fall = -up * 24f + windDir * (Wind * 7f + 1.5f);
_rainDue += dt * 2600f * r;
int n = Mathf.Min((int)_rainDue, 200);
_rainDue -= (int)_rainDue;
var ground = Planet.Surface(eye);
float lift = Mathf.Max(14f, Vector3.Dot(eye - ground, up) + 10f);
for (int i = 0; i < n; i++)
{
var o = Random.insideUnitCircle * 24f;
var at = ground + Planet.Frame * new Vector3(o.x, 0f, o.y) + up * (lift + Random.Range(0f, 6f)) - windDir * 4f;
Fx.Emit(_drops, at, fall * Random.Range(0.9f, 1.1f), Random.Range(0.045f, 0.07f), tint, (lift + 3f) / 24f);
}
_splashDue += dt * 110f * r;
for (; _splashDue >= 1f; _splashDue -= 1f)
{
// where a drop lands: on whatever stands there (deck, roof, machine), else on the soil
var o = Random.insideUnitCircle * 12f;
var at = Planet.Surface(eye + Planet.Frame * new Vector3(o.x, 0f, o.y));
if (Vector3.Dot(eye - at, up) > 25f) break;
var on = Fx.Surface.Ground;
if (Physics.Raycast(at + up * 30f, -up, out var hit, 31f, HitMask, QueryTriggerInteraction.Ignore) && Vector3.Dot(hit.point - at, up) > -0.05f)
{
at = hit.point;
on = SurfaceOf(hit.collider);
}
else if (MowMap.Yield(at) > 0.3f) on = Fx.Surface.Grass;
Fx.Emit(_splash, at + up * 0.05f, up * 0.4f, Random.Range(0.08f, 0.16f), new Color(tint.r, tint.g, tint.b, 0.5f));
Fx.RainHit(at, up, on, tint, Acid);
}
}
Volume(ref _rainLoop, "rain_loop", r * (0.55f + Storm * 0.25f));
}
const int HitMask = (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Vehicle) | (1 << Layers.Prop);
static readonly Dictionary<Collider, Fx.Surface> s_surface = new Dictionary<Collider, Fx.Surface>();
/// <summary>What a collider is made of, as far as rain can tell: machines and vehicles are metal, the deck and what is
/// built of planks is wood, anything else by its material's name.</summary>
static Fx.Surface SurfaceOf(Collider c)
{
if (s_surface.TryGetValue(c, out var k)) return k;
k = Fx.Surface.Ground;
if (c.gameObject.layer == Layers.Vehicle || c.GetComponentInParent<Vehicle>()) k = Fx.Surface.Metal;
else if (c.GetComponentInParent<DeckTileView>()) k = Fx.Surface.Wood;
else if (c.GetComponentInParent<BuildPiece>() is BuildPiece bp)
{
switch (bp.piece)
{
case PieceId.Wall: case PieceId.WindowWall: case PieceId.DoorWall: case PieceId.Railing: case PieceId.Fence:
case PieceId.Floor: case PieceId.FlatRoof: case PieceId.Roof: case PieceId.Stairs: case PieceId.Steps:
case PieceId.Pillar: case PieceId.Planter: case PieceId.Bench: case PieceId.Crates: case PieceId.Square: case PieceId.Hex:
k = Fx.Surface.Wood; break;
default: k = Fx.Surface.Metal; break;
}
}
else
{
var r = c.GetComponent<Renderer>();
if (!r) r = c.GetComponentInParent<Renderer>();
if (!r && c.transform.parent) r = c.transform.parent.GetComponentInChildren<Renderer>();
var n = r && r.sharedMaterial ? r.sharedMaterial.name.ToLowerInvariant() : c.name.ToLowerInvariant();
if (n.Contains("metal") || n.Contains("iron") || n.Contains("steel") || n.Contains("hull") || n.Contains("tin") || n.Contains("chrome") || n.Contains("paint")) k = Fx.Surface.Metal;
else if (n.Contains("wood") || n.Contains("plank") || n.Contains("timber") || n.Contains("log") || n.Contains("bark") || n.Contains("tree") || n.Contains("hay") || n.Contains("deck")) k = Fx.Surface.Wood;
}
if (s_surface.Count > 4000) s_surface.Clear();
s_surface[c] = k;
return k;
}
void TickWind(Vector3 eye, Vector3 up, Vector3 windDir, float dt)
{
float w = Mathf.Max(Wind, Storm * 0.6f);
Volume(ref _windLoop, "wind_loop", w * 0.5f);
if (w < 0.05f) return;
// clippings and dust streaming past low over the meadow
_windDue += dt * 30f * w;
for (; _windDue >= 1f; _windDue -= 1f)
{
var at = Planet.Surface(eye - windDir * 12f + Random.insideUnitSphere * 14f) + up * Random.Range(0.2f, 2.5f);
Fx.Emit(_splash, at, windDir * Random.Range(8f, 14f) * w + up * Random.Range(-0.3f, 0.6f), Random.Range(0.12f, 0.3f), new Color(0.85f, 0.85f, 0.75f, 0.25f), 1.2f);
}
}
// ───────────────────────── storm ─────────────────────────
void TickLightning(Vector3 eye, float dt)
{
Flash = Mathf.MoveTowards(Flash, 0f, dt * 3.5f);
// a flicker: the flash dips and comes back once before it goes
float shown = Flash * (Flash > 0.55f && Flash < 0.75f ? 0.35f : 1f);
Shader.SetGlobalFloat(FlashId, shown);
if (_thunderAt > 0f && Time.time >= _thunderAt)
{
_thunderAt = -1f;
Sfx.Play("thunder", _thunderVol, Random.Range(0.85f, 1.1f));
if (_thunderVol > 0.7f) CameraFx.Shake(0.15f);
}
if (Storm < 0.6f) { _nextFlash = Time.time + Random.Range(4f, 10f); return; }
if (Time.time < _nextFlash) return;
_nextFlash = Time.time + Random.Range(5f, 16f);
float near = Random.value;
Flash = Mathf.Lerp(0.5f, 1f, near);
_thunderAt = Time.time + Mathf.Lerp(3f, 0.3f, near);
_thunderVol = Mathf.Lerp(0.45f, 1f, near);
}
void TickMeteors(Vector3 eye, Vector3 up, WeatherKind kind, float dt)
{
if (kind != WeatherKind.Meteors || DayNight.Dark < 0.4f || Time.time < _nextMeteor) return;
_nextMeteor = Time.time + Random.Range(0.1f, 0.7f);
var side = Vector3.ProjectOnPlane(Random.onUnitSphere, up).normalized;
var at = eye + (up * Random.Range(0.45f, 1f) + side).normalized * 320f;
var dir = (Vector3.ProjectOnPlane(Random.onUnitSphere, up).normalized - up * 0.35f).normalized;
var c = Color.Lerp(new Color(1.6f, 1.5f, 1.2f), new Color(0.9f, 1.4f, 1.8f), Random.value);
Fx.Emit(_meteor, at, dir * Random.Range(120f, 200f), Random.Range(2.2f, 3.6f), c * 1.6f, Random.Range(0.6f, 1.1f));
if (Random.value < 0.08f) Sfx.Play("meteor_whoosh", 0.25f, Random.Range(0.8f, 1.2f), 0.1f, 2f);
}
// ───────────────────────── twister ─────────────────────────
void TickTwister(TeamState ts, Vector3 eye)
{
bool on = ts && ts.IsSpawned && ts.TwisterOn;
if (!on)
{
if (_twisterWas) { _twisterWas = false; Volume(ref _twisterLoop, "twister_loop", 0f); }
return;
}
double now = ts.Now;
var at = ts.TwisterPos(now);
var up = Planet.Up(at);
float age = (float)(now - ts.TwisterAt.Value);
// it spins up and dies away again
float life = Mathf.Clamp01(age / 4f) * Mathf.Clamp01((TeamState.TwisterLife - age) / 6f);
_twister.position = at;
_twister.rotation = Quaternion.FromToRotation(Vector3.up, up);
if (!_twisterWas) { _twisterWas = true; _lastTwister = at; }
_funnelDue += Time.deltaTime * 420f * life;
for (; _funnelDue >= 1f; _funnelDue -= 1f)
{
float h = Random.Range(0f, 1f);
float a = Random.Range(0f, Mathf.PI * 2f);
float r = Mathf.Lerp(0.6f, 2.2f, h) * Random.Range(0.8f, 1.2f);
var local = new Vector3(Mathf.Cos(a) * r, h * 3f, Mathf.Sin(a) * r);
var col = Color.Lerp(new Color(0.5f, 0.52f, 0.44f, 0.75f), new Color(0.72f, 0.74f, 0.7f, 0.55f), h);
Fx.Emit(_funnel, local, Vector3.up * Random.Range(5f, 7f), Random.Range(1.3f, 2.4f), col);
if (Random.value < 0.35f)
Fx.Emit(_debris, new Vector3(Mathf.Cos(a), 0.2f, Mathf.Sin(a)) * 1.2f, Vector3.up * Random.Range(3f, 9f), Random.Range(0.06f, 0.14f), Fx.Clip());
}
Meadow.Vortex(at, life, TeamState.TwisterRadius * 1.6f);
// the grass in its path is torn out: gone, and nobody is paid for it
if (life > 0.3f && (at - _lastTwister).sqrMagnitude > 0.25f)
{
MowMap.Cut(_lastTwister, at, TeamState.TwisterRadius * 1.1f);
_lastTwister = at;
}
else if (life <= 0.3f) _lastTwister = at;
if (!_twisterLoop) { Volume(ref _twisterLoop, "twister_loop", 0f); if (_twisterLoop) { _twisterLoop.transform.SetParent(_twister, false); _twisterLoop.spatialBlend = 0.95f; _twisterLoop.maxDistance = 110f; _twisterLoop.minDistance = 6f; } }
if (_twisterLoop) _twisterLoop.volume = life * 0.9f * Sfx.SfxVolume;
var me = PlayerAgent.Local;
if (me && !me.Vehicle && Time.time >= _flingAt)
{
var off = Vector3.ProjectOnPlane(me.transform.position - at, up);
if (off.magnitude < TeamState.TwisterRadius + 0.8f && life > 0.5f)
{
_flingAt = Time.time + 3f;
var swirl = Vector3.Cross(up, off.normalized);
me.Fling(up * 13f + swirl * 9f + off.normalized * 6f);
Sfx.Play("throw_whoosh", 0.9f, 0.7f);
Assistant.Say("asst_thrown"); Hud.Toast(Loc.T("Whoa! The twister threw you."), Hud.ToastKind.Warn);
}
}
else if (me && me.Vehicle && Vector3.Distance(me.transform.position, at) < TeamState.TwisterRadius + 3f) CameraFx.Shake(0.05f);
}
// ───────────────────────── the saucer ─────────────────────────
// the saucer: the model's parts, its glow, its beam
Transform _ufoRing, _beamCone;
Quaternion _ringRest;
Material _bulbMat, _domeMat, _emitMat, _beamMat;
Vector3 _ufoVel, _ufoLast;
float _ufoYaw, _ringSpin;
bool _ufoLanded, _ufoGone;
const float Hover = 21f;
void TickUfo(TeamState ts, Vector3 eye)
{
bool on = ts && ts.IsSpawned && ts.UfoOn;
if (!on)
{
if (_ufo && _ufo.gameObject.activeSelf)
{
_ufo.gameObject.SetActive(false);
Volume(ref _ufoHum, "ufo_hum_loop", 0f);
Volume(ref _ufoBeam, "ufo_beam_loop", 0f);
}
return;
}
if (!_ufo) BuildSaucer();
if (!_ufo.gameObject.activeSelf) { _ufo.gameObject.SetActive(true); _ufoLanded = _ufoGone = false; _ufoVel = Vector3.zero; }
double now = ts.Now;
float t = (float)(now - ts.UfoAt.Value);
var spot = ts.UfoSpot.Value;
var up = Planet.Up(spot);
int seed = (int)(ts.UfoAt.Value * 997d) ^ 0x5F3759;
if (_circleOf != ts.UfoAt.Value)
{
_circleOf = ts.UfoAt.Value; _circleDone = 0; _ufoAt = spot;
_ufoLanded = _ufoGone = false;
Sfx.PlayAt("meteor_whoosh", spot + up * 120f, 0.8f, 0.55f, 0.05f);
}
float dt = Mathf.Max(1e-4f, Time.deltaTime);
Vector3 pos;
float beam = 0f, stretch = 0f;
const float A = TeamState.UfoArrive, D = TeamState.UfoDraw;
var side = Vector3.Cross(up, Vector3.forward).normalized;
var fwd = Vector3.Cross(side, up);
if (t < A)
{
// swoops in on a curve, brakes hard and bobs to a stop over the field
float k = Mathf.Clamp01(t / A);
float e = 1f - Mathf.Pow(1f - k, 3.2f);
var p0 = spot + up * 260f + side * 340f + fwd * 160f;
var p1 = spot + up * 70f + side * 60f - fwd * 30f;
var p2 = spot + up * Hover;
pos = (1 - e) * (1 - e) * p0 + 2f * (1 - e) * e * p1 + e * e * p2;
// the last moment: a little overshoot down and back
if (k > 0.82f) pos += up * Mathf.Sin((k - 0.82f) / 0.18f * Mathf.PI) * -1.6f;
}
else if (t < A + D)
{
if (!_ufoLanded)
{
_ufoLanded = true;
var g = Planet.Surface(spot);
Fx.Slam(g, Planet.Up(g), 9f);
Fx.Dust(g, 1.2f, 30);
}
float f = (t - A) / D;
TeamState.CropCircle(spot, seed, f, ref _circleDone);
// glides over the line it is drawing, on a soft spring rather than a lerp
var target = TeamState.CircleAt(spot, seed, f);
_ufoAt = Vector3.SmoothDamp(_ufoAt, target, ref _ufoVel, 0.55f, 40f, dt);
pos = _ufoAt + Planet.Up(_ufoAt) * (Hover + Mathf.Sin(t * 1.7f) * 0.7f + Mathf.Sin(t * 0.63f) * 0.4f);
beam = Mathf.Clamp01((t - A) * 1.5f) * Mathf.Clamp01((A + D - t) * 1.5f);
}
else
{
TeamState.CropCircle(spot, seed, 1f, ref _circleDone);
float k = (t - A - D) / TeamState.UfoLeave;
var hold = _ufoAt + Planet.Up(_ufoAt) * Hover;
if (k < 0.18f)
{
// crouches before the jump
pos = hold - Planet.Up(_ufoAt) * Mathf.Sin(k / 0.18f * Mathf.PI * 0.5f) * 2.2f;
}
else
{
if (!_ufoGone)
{
_ufoGone = true;
Sfx.PlayAt("meteor_whoosh", hold, 1f, 1.35f, 0.05f);
Fx.Sparkles(hold - Planet.Up(_ufoAt) * 2f, 40, new Color(0.5f, 1f, 0.85f));
}
float j = (k - 0.18f) / 0.82f;
pos = hold - Planet.Up(_ufoAt) * 2.2f + Planet.Up(_ufoAt) * (j * j * j * 900f) + side * j * j * 80f;
stretch = Mathf.Clamp01(j * 3f) * Mathf.Clamp01((1f - j) * 4f + 0.4f);
}
}
// banks into where it's going, turns slowly, wobbles
var vel = (pos - _ufoLast) / dt;
_ufoLast = pos;
var pu = Planet.Up(pos);
var flatVel = Vector3.ProjectOnPlane(vel, pu);
float bank = Mathf.Clamp(flatVel.magnitude * 0.35f, 0f, 22f);
var bankAxis = flatVel.sqrMagnitude > 1e-3f ? Vector3.Cross(pu, flatVel.normalized) : side;
_ufoYaw += dt * (25f + beam * 45f);
var level = Quaternion.FromToRotation(Vector3.up, pu);
var wobble = Quaternion.Euler(Mathf.Sin(t * 0.9f) * 3f, 0f, Mathf.Cos(t * 1.1f) * 3f);
_ufo.SetPositionAndRotation(pos, Quaternion.AngleAxis(bank, bankAxis) * level * wobble * Quaternion.AngleAxis(_ufoYaw, Vector3.up));
_ufo.localScale = new Vector3(1f - stretch * 0.35f, 1f + stretch * 1.6f, 1f - stretch * 0.35f);
// the rim spins up while it works; the bulbs breathe and flash in turn; the belly glows with the beam
_ringSpin += dt * (90f + beam * 260f);
if (_ufoRing)
{
// round the saucer's own up, whatever the import did to the ring's axes
var axis = _ufoRing.parent ? _ufoRing.parent.InverseTransformDirection(_ufo.up).normalized : Vector3.up;
_ufoRing.localRotation = Quaternion.AngleAxis(_ringSpin, axis) * _ringRest;
}
float pulse = 0.6f + 0.4f * Mathf.Sin(t * 6f);
if (_bulbMat) _bulbMat.SetColor("_EmissionColor", Color.Lerp(new Color(1f, 0.6f, 0.2f), new Color(0.4f, 1f, 0.8f), 0.5f + 0.5f * Mathf.Sin(t * 1.3f)) * (2.5f + pulse * 4f));
if (_domeMat) _domeMat.SetColor("_EmissionColor", new Color(0.2f, 0.9f, 0.7f) * (0.8f + pulse * 0.8f));
if (_emitMat) _emitMat.SetColor("_EmissionColor", new Color(0.4f, 1f, 0.55f) * (0.6f + beam * 7f));
if (_ufoLights != null)
for (int i = 0; i < _ufoLights.Length; i++)
{
float lit = Mathf.Repeat(t * 3f - i / (float)_ufoLights.Length, 1f) < 0.3f ? 1f : 0.25f;
_ufoLights[i].transform.localScale = Vector3.one * (0.35f + lit * 0.25f);
}
_ufoLight.intensity = beam * 80f;
// the beam: a cone of light down to the meadow, and the grass swirling up inside it
float drop = Mathf.Max(1f, Vector3.Dot(pos - Planet.Surface(pos), pu) - 1.2f);
if (_beamCone)
{
_beamCone.gameObject.SetActive(beam > 0.01f);
_beamCone.localScale = new Vector3(1f, drop / Mathf.Max(0.2f, _ufo.localScale.y), 1f);
if (_beamMat) _beamMat.SetFloat("_Power", beam);
}
if (beam > 0.05f)
{
var down = -pu;
_beamDue += dt * 260f * beam;
for (; _beamDue >= 1f; _beamDue -= 1f)
{
float along = Random.value;
var at = pos + down * (1.2f + along * drop) + Random.insideUnitSphere * Mathf.Lerp(1.5f, 5f, along);
Fx.Emit(_beam, at, -down * Random.Range(2f, 5f), Random.Range(1.4f, 2.8f), new Color(0.6f, 1.6f, 1.4f, 0.35f));
}
if (Random.value < dt * 30f * beam)
{
var g = Planet.Surface(pos + Random.insideUnitSphere.Flat() * 4f);
Fx.Droplets(g + Planet.Up(g) * 0.2f, Planet.Up(g) * 2f, 4);
}
}
Volume(ref _ufoHum, "ufo_hum_loop", 0f);
if (_ufoHum && _ufoHum.transform.parent != _ufo) { _ufoHum.transform.SetParent(_ufo, false); _ufoHum.spatialBlend = 0.95f; _ufoHum.maxDistance = 220f; _ufoHum.minDistance = 10f; }
if (_ufoHum) { _ufoHum.volume = 0.85f * Sfx.SfxVolume; _ufoHum.pitch = 0.9f + Mathf.Clamp01(vel.magnitude / 60f) * 0.5f + beam * 0.1f; }
Volume(ref _ufoBeam, "ufo_beam_loop", 0f);
if (_ufoBeam && _ufoBeam.transform.parent != _ufo) { _ufoBeam.transform.SetParent(_ufo, false); _ufoBeam.spatialBlend = 0.95f; _ufoBeam.maxDistance = 120f; _ufoBeam.minDistance = 8f; }
if (_ufoBeam) _ufoBeam.volume = beam * 0.75f * Sfx.SfxVolume;
}
/// <summary>The saucer from its model: the rim (it spins), the bulbs, the glass dome and the belly emitter glow.</summary>
void BuildSaucer()
{
var model = AssetBank.I.Model("SM_Ufo");
if (!model) { BuildPrimitiveSaucer(); return; }
_ufo = new GameObject("Saucer").transform;
_ufo.SetParent(transform, false);
var go = Instantiate(model, _ufo);
go.transform.localPosition = Vector3.zero;
foreach (var c in go.GetComponentsInChildren<Collider>(true)) Destroy(c);
var lit = Shader.Find("Universal Render Pipeline/Lit");
_bulbMat = new Material(lit) { color = new Color(1f, 0.8f, 0.45f) };
_bulbMat.EnableKeyword("_EMISSION");
_domeMat = new Material(lit) { color = new Color(0.32f, 0.92f, 0.82f) };
_domeMat.SetFloat("_Smoothness", 0.95f);
_domeMat.EnableKeyword("_EMISSION");
_emitMat = new Material(lit) { color = new Color(0.45f, 1f, 0.55f) };
_emitMat.EnableKeyword("_EMISSION");
foreach (var tr in go.GetComponentsInChildren<Transform>(true))
{
var r = tr.GetComponent<Renderer>();
switch (tr.name)
{
case "Ring": _ufoRing = tr; _ringRest = tr.localRotation; break;
case "Bulbs": if (r) r.sharedMaterial = _bulbMat; break;
case "Dome": if (r) r.sharedMaterial = _domeMat; break;
case "Emitter": if (r) r.sharedMaterial = _emitMat; break;
}
if (r) r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;
}
_ufoLights = new Renderer[0];
// the cone: 2.4 m across at the ship, 7 m on the ground, one metre tall (stretched to the drop)
var cone = new GameObject("BeamCone");
cone.transform.SetParent(_ufo, false);
cone.transform.localPosition = new Vector3(0f, -1.3f, 0f);
cone.AddComponent<MeshFilter>().sharedMesh = Cone(1.2f, 3.5f, 40);
var mr = cone.AddComponent<MeshRenderer>();
var bm = AssetBank.I.Mat("M_UfoBeam");
_beamMat = bm ? new Material(bm) : null;
if (_beamMat) _beamMat.SetColor("_BaseColor", new Color(0.45f, 1f, 0.8f, 0.32f));
mr.sharedMaterial = _beamMat;
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
mr.receiveShadows = false;
_beamCone = cone.transform;
cone.SetActive(false);
_ufoLight = new GameObject("Beam").AddComponent<Light>();
_ufoLight.transform.SetParent(_ufo, false);
_ufoLight.transform.localPosition = new Vector3(0f, -1.6f, 0f);
_ufoLight.transform.localRotation = Quaternion.Euler(90f, 0f, 0f);
_ufoLight.type = LightType.Spot;
_ufoLight.spotAngle = 32f;
_ufoLight.range = 60f;
_ufoLight.color = new Color(0.5f, 1f, 0.85f);
_ufoLight.shadows = LightShadows.None;
}
/// <summary>An open cone hanging down from y 0 (radius top) to y -1 (radius bottom); uv.y is 0 at the ground.</summary>
static Mesh Cone(float top, float bottom, int n)
{
var v = new Vector3[(n + 1) * 2];
var nm = new Vector3[v.Length];
var uv = new Vector2[v.Length];
var tri = new int[n * 6];
for (int i = 0; i <= n; i++)
{
float a = i * Mathf.PI * 2f / n;
var d = new Vector3(Mathf.Cos(a), 0f, Mathf.Sin(a));
v[i * 2] = d * top;
v[i * 2 + 1] = d * bottom + Vector3.down;
var slope = new Vector3(d.x, (bottom - top), d.z).normalized;
nm[i * 2] = nm[i * 2 + 1] = slope;
uv[i * 2] = new Vector2(i / (float)n, 1f);
uv[i * 2 + 1] = new Vector2(i / (float)n, 0f);
}
for (int i = 0; i < n; i++)
{
int k = i * 6, a0 = i * 2;
tri[k] = a0; tri[k + 1] = a0 + 2; tri[k + 2] = a0 + 1;
tri[k + 3] = a0 + 1; tri[k + 4] = a0 + 2; tri[k + 5] = a0 + 3;
}
var m = new Mesh { name = "BeamCone", vertices = v, normals = nm, uv = uv, triangles = tri };
m.bounds = new Bounds(new Vector3(0f, -0.5f, 0f), new Vector3(bottom * 2f, 1f, bottom * 2f));
return m;
}
void BuildPrimitiveSaucer()
{
_ufo = new GameObject("Saucer").transform;
_ufo.SetParent(transform, false);
var shader = Shader.Find("Universal Render Pipeline/Lit");
var hull = new Material(shader) { color = new Color(0.62f, 0.66f, 0.7f) };
hull.SetFloat("_Metallic", 0.85f);
hull.SetFloat("_Smoothness", 0.75f);
var glass = new Material(shader) { color = new Color(0.3f, 0.95f, 0.8f) };
glass.SetFloat("_Smoothness", 0.95f);
glass.EnableKeyword("_EMISSION");
glass.SetColor("_EmissionColor", new Color(0.2f, 0.9f, 0.7f) * 1.5f);
_ufoGlow = new Material(shader) { color = new Color(1f, 0.85f, 0.3f) };
_ufoGlow.EnableKeyword("_EMISSION");
_ufoGlow.SetColor("_EmissionColor", new Color(1f, 0.8f, 0.25f) * 4f);
Part(PrimitiveType.Sphere, new Vector3(0f, 0f, 0f), new Vector3(10f, 1.3f, 10f), hull);
Part(PrimitiveType.Cylinder, new Vector3(0f, -0.15f, 0f), new Vector3(10.6f, 0.12f, 10.6f), hull);
Part(PrimitiveType.Sphere, new Vector3(0f, 0.7f, 0f), new Vector3(4.2f, 2.6f, 4.2f), glass);
Part(PrimitiveType.Cylinder, new Vector3(0f, -0.65f, 0f), new Vector3(3f, 0.25f, 3f), glass);
const int n = 14;
_ufoLights = new Renderer[n];
for (int i = 0; i < n; i++)
{
float a = i * Mathf.PI * 2f / n;
_ufoLights[i] = Part(PrimitiveType.Sphere, new Vector3(Mathf.Cos(a) * 5.05f, -0.15f, Mathf.Sin(a) * 5.05f), Vector3.one * 0.45f, _ufoGlow);
}
_ufoLight = new GameObject("Beam").AddComponent<Light>();
_ufoLight.transform.SetParent(_ufo, false);
_ufoLight.transform.localPosition = new Vector3(0f, -0.8f, 0f);
_ufoLight.transform.localRotation = Quaternion.Euler(90f, 0f, 0f);
_ufoLight.type = LightType.Spot;
_ufoLight.spotAngle = 38f;
_ufoLight.range = 40f;
_ufoLight.color = new Color(0.5f, 1f, 0.85f);
_ufoLight.shadows = LightShadows.None;
}
Renderer Part(PrimitiveType type, Vector3 at, Vector3 size, Material mat)
{
var go = GameObject.CreatePrimitive(type);
Destroy(go.GetComponent<Collider>());
go.transform.SetParent(_ufo, false);
go.transform.localPosition = at;
go.transform.localScale = size;
var r = go.GetComponent<Renderer>();
r.sharedMaterial = mat;
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;
return r;
}
// ───────────────────────── sound ─────────────────────────
static bool s_missing(string clip) => !AssetBank.I || !AssetBank.I.Clip(clip);
/// <summary>A flat (not placed) weather loop at a volume: started the first time it's wanted, left playing silent after.</summary>
void Volume(ref AudioSource s, string clip, float vol)
{
if (!s)
{
if (vol <= 0.001f && clip != "twister_loop" && clip != "ufo_hum_loop" && clip != "ufo_beam_loop") return;
if (s_missing(clip)) return;
s = Sfx.Loop(clip, transform, 0f);
if (!s) return;
s.spatialBlend = 0f;
}
s.volume = vol * Sfx.SfxVolume;
}
/// <summary>Acid rain scorching a patch: a hiss and a puff of yellow-green steam.</summary>
public static void Sizzle(Vector3 at)
{
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (cam && (cam.transform.position - at).sqrMagnitude > 60f * 60f) return;
Sfx.PlayAt("acid_sizzle", at, 0.45f, 1f, 0.15f, 0.25f);
Fx.Steam(at, 0.6f);
}
}
}