using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering.Universal;
namespace GrassCutter
{
///
/// Where the people on the video calls are filmed: far under the planet, out of every other camera's sight, each in a
/// booth of their own with a camera rendering into a texture that the phone (or the HUD) shows. The booth has the
/// mission-control picture behind its sitter and its own lamps, in a shader that takes no light from the planet's sun.
///
public class Studio : MonoBehaviour
{
/// The layer nothing else draws.
public const int Layer = 31;
static readonly Vector3 Origin = new Vector3(0f, -9000f, 0f);
static Studio _i;
readonly Dictionary _booths = new Dictionary();
float _nextMask;
static Studio I
{
get
{
if (!_i && Application.isPlaying) _i = new GameObject("[Studio]").AddComponent();
return _i;
}
}
/// The booth for this model (SM_Dir_Boss, SM_Dir_Assistant), made the first time it's asked for.
/// Height on the sitter the picture is centred on, metres.
/// How much of them, side to side, the picture takes in, metres.
public static Booth Get(string model, int w, int h, float centreY, float width)
{
var i = I;
if (!i) return null;
var key = $"{model}:{w}x{h}";
if (i._booths.TryGetValue(key, out var b) && b != null && b.Root) return b;
b = Booth.Make(model, w, h, centreY, width, Origin + Vector3.right * 40f * i._booths.Count, i.transform);
i._booths[key] = b;
return b;
}
void LateUpdate()
{
// a -batchmode player (the dev bots) renders no camera by itself: the booths that are on are filmed by hand
if (Application.isBatchMode)
foreach (var b in _booths.Values)
if (b != null && b.Cam && b.Cam.enabled) b.Cam.Render();
// nothing else ever looks into the booths
if (Time.unscaledTime < _nextMask) return;
_nextMask = Time.unscaledTime + 1f;
foreach (var c in Camera.allCameras)
{
bool ours = false;
foreach (var b in _booths.Values) if (b != null && b.Cam == c) ours = true;
if (!ours) c.cullingMask &= ~(1 << Layer);
}
}
}
public class Booth
{
public Transform Root;
public Camera Cam;
public RenderTexture Rt;
public Puppet Puppet;
readonly List _skin = new List();
public static Booth Make(string model, int w, int h, float centreY, float width, Vector3 at, Transform parent)
{
var b = new Booth();
var root = new GameObject("[Booth " + model + "]").transform;
root.SetParent(parent, false);
root.position = at;
b.Root = root;
var studio = AssetBank.I.Mat("M_Studio");
var src = AssetBank.I.Model(model);
if (!src || !studio)
{
Debug.LogWarning($"[Studio] missing {(src ? "M_Studio" : model)}");
return b;
}
var sitter = Object.Instantiate(src, root);
// the model keeps its own turn (the importer faces it along +Z of its parent): the booth's forward is its front
sitter.transform.localPosition = Vector3.zero;
foreach (var r in sitter.GetComponentsInChildren(true))
{
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
r.receiveShadows = false;
if (r is SkinnedMeshRenderer smr) smr.updateWhenOffscreen = true;
var mats = r.sharedMaterials;
for (int k = 0; k < mats.Length; k++)
{
var m = new Material(studio);
var o = mats[k];
string name = o ? o.name.Replace(" (Instance)", "") : "";
var bank = AssetBank.I.Mat(name);
Texture tex = o && o.HasProperty("_BaseMap") ? o.GetTexture("_BaseMap") : null;
if (!tex && bank && bank.HasProperty("_BaseMap")) tex = bank.GetTexture("_BaseMap");
if (tex) m.SetTexture("_BaseMap", tex);
if (name.Contains("MouthVoid"))
{
m.SetColor("_BaseColor", new Color(0.03f, 0.015f, 0.02f));
m.SetFloat("_Cull", 0f);
}
else b._skin.Add(m);
mats[k] = m;
}
r.sharedMaterials = mats;
}
// the picture: centred on centreY, `width` across
float aspect = w / (float)h;
const float fov = 20f;
float viewH = width / aspect;
float dist = viewH * 0.5f / Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad);
var camGo = new GameObject("Camera");
camGo.transform.SetParent(root, false);
camGo.transform.localPosition = new Vector3(0f, centreY, dist);
camGo.transform.localRotation = Quaternion.LookRotation(Vector3.back, Vector3.up);
var cam = camGo.AddComponent();
cam.fieldOfView = fov;
cam.nearClipPlane = 0.2f;
cam.farClipPlane = dist + 8f;
cam.cullingMask = 1 << Studio.Layer;
cam.clearFlags = CameraClearFlags.SolidColor;
cam.backgroundColor = new Color(0.1f, 0.16f, 0.3f);
cam.depth = -50;
var data = camGo.AddComponent();
data.renderShadows = false;
data.renderPostProcessing = false;
b.Rt = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32) { antiAliasing = 4, name = "Booth " + model };
b.Rt.Create();
cam.targetTexture = b.Rt;
cam.enabled = false;
b.Cam = cam;
// mission control behind them
var bg = AssetBank.I.Tex("T_Dir_Bg");
var wall = GameObject.CreatePrimitive(PrimitiveType.Quad);
Object.Destroy(wall.GetComponent());
wall.name = "Backdrop";
wall.transform.SetParent(root, false);
const float back = 2.2f;
float wallH = 2f * (dist + back) * Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad) * 1.04f;
float imgAspect = bg ? bg.width / (float)bg.height : 1f;
float qh = Mathf.Max(wallH, wallH * aspect / imgAspect), qw = qh * imgAspect;
wall.transform.localPosition = new Vector3(0f, centreY, -back);
wall.transform.localRotation = Quaternion.LookRotation(Vector3.back, Vector3.up);
wall.transform.localScale = new Vector3(qw, qh, 1f);
var wm = new Material(studio);
wm.SetFloat("_Lit", 0f);
if (bg) wm.SetTexture("_BaseMap", bg);
wm.SetColor("_BaseColor", new Color(0.82f, 0.86f, 0.95f));
wall.GetComponent().sharedMaterial = wm;
foreach (var t in root.GetComponentsInChildren(true)) t.gameObject.layer = Studio.Layer;
b.Puppet = new Puppet(sitter.transform, root);
return b;
}
/// Films while it's shown.
public void Show(bool on)
{
if (Cam) Cam.enabled = on;
}
/// Red in the face, 0..1.
public void Flush(float k)
{
foreach (var m in _skin) m.SetColor("_Flush", new Color(0f, 0f, 0f, k));
}
/// A point of the booth on the picture, in pixels of a w by h picture (y down).
public Vector2 OnPicture(Vector3 world, float w, float h)
{
if (!Cam) return Vector2.zero;
var v = Cam.WorldToViewportPoint(world);
return new Vector2(v.x * w, (1f - v.y) * h);
}
}
///
/// Works a sitter like a South Park cut-out: the top of the head (bone Top, cut at the mouth by gc_director.py) tips up off
/// one side of the head and then the other, a syllable each, about the hinges Hinge_L and Hinge_R; the arms swing at
/// the shoulders, the head nods and shakes, the body breathes; eyes and lids, where the model has them, look and blink
/// (CrewFace). Every turn is about the sitter's own axes, found from the bind pose.
///
public class Puppet
{
readonly Transform _root, _top, _head, _body, _frame;
readonly Transform[] _arm = new Transform[2], _fore = new Transform[2];
readonly Vector3 _rootPos, _topPos;
readonly Quaternion _topRot, _headRot, _bodyRot;
readonly Quaternion[] _armRot = new Quaternion[2], _foreRot = new Quaternion[2];
readonly Vector3[] _hinge = new Vector3[2];
readonly float[] _hingeSign = new float[2], _armSign = new float[2], _foreSign = new float[2];
readonly Vector3 _topFwd, _headRight, _headFwd, _headUp, _bodyRight;
readonly Vector3[] _armFwd = new Vector3[2], _foreFwd = new Vector3[2], _armRight = new Vector3[2], _foreRight = new Vector3[2];
readonly float[] _swingSign = new float[2], _liftSign = new float[2];
// the pose as it is, easing toward where it's going: arms out, swung forward, forearms raised; the head
readonly float[] _out = new float[2], _swing = new float[2], _lift = new float[2], _beat = new float[2];
float _nod, _tilt, _yaw, _nextBeat;
readonly float _nodSign = 1f, _leanSign = 1f;
readonly CrewFace _face;
readonly Dictionary _anchors = new Dictionary();
int _side = 1;
bool _syllable;
float _shake, _lastT;
public Transform Top => _top;
/// Faces the way the sitter does: forward is their front, right their right.
public Puppet(Transform sitter, Transform frame)
{
_root = sitter;
_rootPos = sitter.localPosition;
Transform hl = null, hr = null;
foreach (var t in sitter.GetComponentsInChildren(true))
{
switch (t.name)
{
case "Top": _top = t; break;
case "Head": _head = t; break;
case "Body": _body = t; break;
case "Arm_L": _arm[0] = t; break;
case "Arm_R": _arm[1] = t; break;
case "Fore_L": _fore[0] = t; break;
case "Fore_R": _fore[1] = t; break;
case "Hinge_L": hl = t; break;
case "Hinge_R": hr = t; break;
}
if (t.name.StartsWith("Anchor_")) _anchors[t.name.Substring(7)] = t;
}
var fwd = frame.forward;
var up = frame.up;
var right = frame.right;
if (_top && _top.parent)
{
_topPos = _top.localPosition;
_topRot = _top.localRotation;
var p = _top.parent;
_topFwd = p.InverseTransformDirection(fwd).normalized;
var upP = p.InverseTransformDirection(up);
var hs = new[] { hl, hr };
for (int i = 0; i < 2; i++)
_hinge[i] = hs[i] ? p.InverseTransformPoint(hs[i].position) : _topPos;
// which way round lifts the far side: try a little turn about each hinge and see the other one go up
for (int i = 0; i < 2; i++)
{
var other = _hinge[1 - i];
var moved = _hinge[i] + Quaternion.AngleAxis(5f, _topFwd) * (other - _hinge[i]);
_hingeSign[i] = Vector3.Dot(moved - other, upP) >= 0f ? 1f : -1f;
}
}
if (_head && _head.parent)
{
_headRot = _head.localRotation;
var p = _head.parent;
_headRight = p.InverseTransformDirection(right).normalized;
_headFwd = p.InverseTransformDirection(fwd).normalized;
_headUp = p.InverseTransformDirection(up).normalized;
if (_top) _nodSign = SignFor(_head, _headRight, _top, fwd);
}
if (_body && _body.parent)
{
_bodyRot = _body.localRotation;
_bodyRight = _body.parent.InverseTransformDirection(right).normalized;
if (_head) _leanSign = SignFor(_body, _bodyRight, _head, fwd);
}
for (int i = 0; i < 2; i++)
{
var a = _arm[i];
if (!a || !a.parent) continue;
_armRot[i] = a.localRotation;
_armFwd[i] = a.parent.InverseTransformDirection(fwd).normalized;
var probe = _fore[i] ? _fore[i] : a;
var hand = _fore[i] && _fore[i].childCount > 0 ? _fore[i].GetChild(0) : probe;
float lateral = Mathf.Sign(Vector3.Dot(probe.position - frame.position, right));
_armSign[i] = SignFor(a, _armFwd[i], probe, right * lateral);
_armRight[i] = a.parent.InverseTransformDirection(right).normalized;
_swingSign[i] = SignFor(a, _armRight[i], probe, fwd);
if (_fore[i] && _fore[i].parent)
{
_foreRot[i] = _fore[i].localRotation;
_foreFwd[i] = _fore[i].parent.InverseTransformDirection(fwd).normalized;
_foreSign[i] = SignFor(_fore[i], _foreFwd[i], hand, right * lateral);
_foreRight[i] = _fore[i].parent.InverseTransformDirection(right).normalized;
_liftSign[i] = SignFor(_fore[i], _foreRight[i], hand, fwd);
}
}
_face = CrewFace.Find(sitter, frame);
_frame = frame;
}
/// The sign of a turn of t about axis (in t's parent space) that moves probe along want.
static float SignFor(Transform t, Vector3 axis, Transform probe, Vector3 want)
{
var rest = t.localRotation;
var p0 = probe.position;
t.localRotation = Quaternion.AngleAxis(6f, axis) * rest;
var p1 = probe.position;
t.localRotation = rest;
return Vector3.Dot(p1 - p0, want) >= 0f ? 1f : -1f;
}
/// Where an effect goes: Forehead, Temple, Eye_L, Eye_R, Ear_L, Ear_R (falls back to the top of the head).
public Vector3 Anchor(string name)
{
if (_anchors.TryGetValue(name, out var t) && t) return t.position;
return _top ? _top.position + _frame.up * 0.15f : _frame.position + _frame.up * 1.1f;
}
/// How far the mouth is open, 0..1.
/// How much of each Mood shows, indexed by Mood.
public void Tick(float t, float open, float[] mood)
{
float dt = Mathf.Clamp(t - _lastT, 0f, 0.1f);
if (t < _lastT) dt = 0f;
_lastT = t;
float angry = mood[(int)Mood.Angry], stern = mood[(int)Mood.Stern], happy = mood[(int)Mood.Happy];
float sad = mood[(int)Mood.Sad], scared = mood[(int)Mood.Scared], whisper = mood[(int)Mood.Whisper];
// the jaw: each syllable the top tips up off one side, the next off the other
if (open > 0.28f) _syllable = true;
else if (open < 0.07f && _syllable) { _syllable = false; _side = 1 - _side; }
_shake = Mathf.Lerp(_shake, Mathf.Max(open > 0.5f ? (open - 0.5f) * (1f + angry * 2f) : 0f, scared * 0.5f), dt * 10f);
if (_top)
{
int i = _side;
float ang = open * (11f + angry * 4f) * _hingeSign[i];
var q = Quaternion.AngleAxis(ang, _topFwd);
_top.localRotation = q * _topRot;
_top.localPosition = _hinge[i] + q * (_topPos - _hinge[i]);
}
// everything eases toward its pose, so nothing jerks
float ease = 1f - Mathf.Exp(-dt * 9f);
// the head: nods a little with the words, hangs when he's sad, cocks when stern, shudders when he shouts
if (_head)
{
_nod = Mathf.Lerp(_nod, Mathf.Sin(t * 2.3f) * 1.2f + open * 2.5f + sad * 8f - happy * 3f - scared * 2f, ease);
_tilt = Mathf.Lerp(_tilt, Mathf.Sin(t * 0.7f) * 1.2f + stern * 3f, ease);
_yaw = Mathf.Lerp(_yaw, Mathf.Sin(t * 0.45f) * 2f, ease);
float shudder = Mathf.Sin(t * 31f) * _shake * 1.6f;
_head.localRotation = Quaternion.AngleAxis(_yaw + shudder, _headUp) * Quaternion.AngleAxis(_tilt, _headFwd) * Quaternion.AngleAxis(_nod * _nodSign, _headRight) * _headRot;
}
// the body: breathing, bouncing when pleased, leaning in to whisper
if (_body) _body.localRotation = Quaternion.AngleAxis((whisper * 7f + Mathf.Sin(t * 1.6f) * 0.6f) * _leanSign, _bodyRight) * _bodyRot;
float hop = Mathf.Abs(Mathf.Sin(t * 7f)) * happy * 0.02f + Mathf.Sin(t * 1.6f) * 0.003f;
_root.position = _frame.TransformPoint(_rootPos) + _frame.up * hop;
// the arms talk the way people's do: a forearm comes up in front with a word now and then, one hand and then the
// other; both come up and shake when he shouts, higher when he's thrilled, they tremble in a fright and hang when
// he's sad. They hardly go out to the side, where the coat's shoulders would stretch.
if (t >= _nextBeat)
{
_nextBeat = t + Random.Range(0.7f, 1.6f);
int hand = Random.value < 0.5f ? 0 : 1;
_beat[hand] = open > 0.15f || Random.value < 0.3f ? Random.Range(0.5f, 1f) : 0f;
_beat[1 - hand] *= 0.4f;
}
for (int i = 0; i < 2; i++)
{
if (!_arm[i]) continue;
_beat[i] = Mathf.MoveTowards(_beat[i], 0f, dt * 0.35f);
float shake = Mathf.Sin(t * 13f + i * 1.7f);
float o = 1.5f + angry * 5f + happy * 12f + scared * 6f - sad * 1.5f;
float sw = _beat[i] * 6f + angry * (8f + shake * 3f * Mathf.Max(open, 0.3f)) + happy * 6f + scared * 4f;
float lf = _beat[i] * 32f + angry * (30f + shake * 6f) + happy * 45f + scared * (18f + Mathf.Sin(t * 37f + i) * 3f) - sad * 4f;
_out[i] = Mathf.Lerp(_out[i], o, ease);
_swing[i] = Mathf.Lerp(_swing[i], sw, ease);
_lift[i] = Mathf.Lerp(_lift[i], Mathf.Max(0f, lf), ease);
_arm[i].localRotation = Quaternion.AngleAxis(_out[i] * _armSign[i], _armFwd[i]) * Quaternion.AngleAxis(_swing[i] * _swingSign[i], _armRight[i]) * _armRot[i];
if (_fore[i]) _fore[i].localRotation = Quaternion.AngleAxis(_lift[i] * _liftSign[i], _foreRight[i]) * _foreRot[i];
}
_face?.Tick(dt, sad * -8f, angry > 0.3f || stern > 0.4f, scared > 0.3f || happy > 0.5f, false);
}
}
}