cu-trainer/Ultra Paradise Application/src/Health.cs
| 1 | using System; |
| 2 | using System.Collections.Generic; |
| 3 | using System.Globalization; |
| 4 | using System.Text; |
| 5 | using HarmonyLib; |
| 6 | using UnityEngine; |
| 7 | using UnityEngine.UI; |
| 8 | using Object = UnityEngine.Object; |
| 9 | |
| 10 | namespace UltraParadise |
| 11 | { |
| 12 | internal static class HealthMirror |
| 13 | { |
| 14 | public static int Mode; |
| 15 | private const int Layer = 31; |
| 16 | private const float FrameEvery = 0.1f; |
| 17 | private const float RebuildEvery = 30f; |
| 18 | |
| 19 | private static GameObject rig, holder, canvasGo, cloneGo; |
| 20 | private static Camera cam; |
| 21 | private static Canvas canvas; |
| 22 | private static RenderTexture rt; |
| 23 | private static Texture2D readTex; |
| 24 | private static WoundView clone, source; |
| 25 | private static Body sourceBody; |
| 26 | private static float nextFrame, nextVitals, rebuildAt, pendingDt, scale = 0.5f; |
| 27 | private static int width, height; |
| 28 | private static bool failed; |
| 29 | private static string lastState; |
| 30 | |
| 31 | public static void SetMode(int m) |
| 32 | { |
| 33 | Mode = Mathf.Clamp(m, 0, 1); |
| 34 | lastState = null; |
| 35 | nextVitals = 0f; |
| 36 | if (Mode < 2) { failed = false; Teardown(); } |
| 37 | } |
| 38 | |
| 39 | public static void Tick() |
| 40 | { |
| 41 | if (Mode == 0) return; |
| 42 | pendingDt += Time.unscaledDeltaTime; |
| 43 | Body b = PlayerCamera.main != null && WorldGeneration.world != null ? PlayerCamera.main.body : null; |
| 44 | if (Time.unscaledTime >= nextVitals) |
| 45 | { |
| 46 | nextVitals = Time.unscaledTime + 0.5f; |
| 47 | if (b != null) SendVitals(b); |
| 48 | else Link.Send("VITALS none"); |
| 49 | } |
| 50 | if (Mode < 2) return; |
| 51 | WoundView src = WoundView.view; |
| 52 | if (b == null || src == null || src.body == null || src == clone) |
| 53 | { |
| 54 | DropClone(); |
| 55 | State("norun"); |
| 56 | return; |
| 57 | } |
| 58 | if (failed || Time.unscaledTime < nextFrame || Link.FramePending) return; |
| 59 | nextFrame = Time.unscaledTime + FrameEvery; |
| 60 | try |
| 61 | { |
| 62 | if (clone == null || source != src || sourceBody != src.body || Time.unscaledTime >= rebuildAt) Build(src); |
| 63 | if (clone == null) return; |
| 64 | Render(); |
| 65 | State("ok"); |
| 66 | } |
| 67 | catch (Exception e) |
| 68 | { |
| 69 | failed = true; |
| 70 | Plugin.Log.LogWarning("Health mirror failed: " + e); |
| 71 | DropClone(); |
| 72 | State("error"); |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | private static void State(string s) |
| 77 | { |
| 78 | if (s == lastState) return; |
| 79 | lastState = s; |
| 80 | Link.Send("HSTATE " + s); |
| 81 | } |
| 82 | |
| 83 | public static void Click(float fx, float fy) |
| 84 | { |
| 85 | if (clone == null || source == null || cam == null || width == 0) return; |
| 86 | Vector2 p = new Vector2(fx * width, (1f - fy) * height); |
| 87 | Image[] limbs = clone.limbImages; |
| 88 | if (limbs == null || clone.body == null) return; |
| 89 | for (int i = 0; i < limbs.Length; i++) |
| 90 | { |
| 91 | if (limbs[i] == null || i >= clone.body.limbs.Length || clone.body.limbs[i].dismembered) continue; |
| 92 | if (RectTransformUtility.RectangleContainsScreenPoint(limbs[i].rectTransform, p, cam)) |
| 93 | { |
| 94 | source.limbLookingAt = i; |
| 95 | clone.limbLookingAt = i; |
| 96 | nextFrame = 0f; |
| 97 | return; |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | private static void EnsureRig() |
| 103 | { |
| 104 | if (rig != null) return; |
| 105 | rig = new GameObject("UltraParadiseHealthRig"); |
| 106 | rig.hideFlags = HideFlags.HideAndDontSave; |
| 107 | Object.DontDestroyOnLoad(rig); |
| 108 | rig.transform.position = new Vector3(60000f, 60000f, 0f); |
| 109 | |
| 110 | holder = new GameObject("Holder"); |
| 111 | holder.transform.SetParent(rig.transform, false); |
| 112 | holder.SetActive(false); |
| 113 | |
| 114 | GameObject camGo = new GameObject("Camera"); |
| 115 | camGo.transform.SetParent(rig.transform, false); |
| 116 | camGo.transform.localPosition = new Vector3(0f, 0f, -20f); |
| 117 | cam = camGo.AddComponent<Camera>(); |
| 118 | cam.enabled = false; |
| 119 | cam.orthographic = true; |
| 120 | cam.clearFlags = CameraClearFlags.SolidColor; |
| 121 | cam.backgroundColor = new Color(0f, 0f, 0f, 0f); |
| 122 | cam.cullingMask = 1 << Layer; |
| 123 | cam.nearClipPlane = 0.1f; |
| 124 | cam.farClipPlane = 100f; |
| 125 | |
| 126 | canvasGo = new GameObject("Canvas"); |
| 127 | canvasGo.layer = Layer; |
| 128 | canvasGo.transform.SetParent(rig.transform, false); |
| 129 | canvas = canvasGo.AddComponent<Canvas>(); |
| 130 | canvas.renderMode = RenderMode.ScreenSpaceCamera; |
| 131 | canvas.worldCamera = cam; |
| 132 | canvas.planeDistance = 10f; |
| 133 | } |
| 134 | |
| 135 | private static void Build(WoundView src) |
| 136 | { |
| 137 | EnsureRig(); |
| 138 | DropClone(); |
| 139 | source = src; |
| 140 | sourceBody = src.body; |
| 141 | rebuildAt = Time.unscaledTime + RebuildEvery; |
| 142 | |
| 143 | RectTransform srcRt = (RectTransform)src.transform; |
| 144 | Vector2 size = srcRt.rect.size; |
| 145 | GameObject go = Object.Instantiate(src.gameObject, holder.transform, false); |
| 146 | go.name = "HealthMirror"; |
| 147 | cloneGo = go; |
| 148 | try |
| 149 | { |
| 150 | foreach (MonoBehaviour mb in go.GetComponentsInChildren<MonoBehaviour>(true)) |
| 151 | { |
| 152 | if (mb == null) continue; |
| 153 | Type t = mb.GetType(); |
| 154 | if (!string.IsNullOrEmpty(t.Namespace)) continue; |
| 155 | if (mb is WoundView || mb is FilledImagePP || mb is ECGVisualizer) continue; |
| 156 | try { Object.DestroyImmediate(mb); } catch (Exception) { mb.enabled = false; } |
| 157 | } |
| 158 | foreach (AudioSource a in go.GetComponentsInChildren<AudioSource>(true)) a.enabled = false; |
| 159 | Transform tr = go.transform; |
| 160 | for (int i = tr.childCount - 1; i >= 0; i--) |
| 161 | if (tr.GetChild(i).name == "icon") Object.DestroyImmediate(tr.GetChild(i).gameObject); |
| 162 | foreach (Transform t2 in go.GetComponentsInChildren<Transform>(true)) t2.gameObject.layer = Layer; |
| 163 | |
| 164 | clone = go.GetComponent<WoundView>(); |
| 165 | clone.enabled = false; |
| 166 | clone.armorMode = false; |
| 167 | clone.body = src.body; |
| 168 | clone.limbLookingAt = src.limbLookingAt; |
| 169 | |
| 170 | RectTransform crt = (RectTransform)go.transform; |
| 171 | crt.anchorMin = new Vector2(0.5f, 0.5f); |
| 172 | crt.anchorMax = new Vector2(0.5f, 0.5f); |
| 173 | crt.sizeDelta = size; |
| 174 | crt.anchoredPosition = Vector2.zero; |
| 175 | crt.localRotation = Quaternion.identity; |
| 176 | crt.localScale = Vector3.one; |
| 177 | |
| 178 | go.SetActive(true); |
| 179 | go.transform.SetParent(canvasGo.transform, false); |
| 180 | } |
| 181 | finally |
| 182 | { |
| 183 | WoundView.view = src; |
| 184 | } |
| 185 | |
| 186 | scale = ArtScale(go); |
| 187 | canvas.scaleFactor = 1f; |
| 188 | SetTarget(256, 256); |
| 189 | Canvas.ForceUpdateCanvases(); |
| 190 | Rect bounds = Bounds(go); |
| 191 | if (bounds.width < 10f || bounds.height < 10f) bounds = new Rect(-size.x * 0.5f, -size.y * 0.5f, size.x, size.y); |
| 192 | ((RectTransform)go.transform).anchoredPosition -= bounds.center; |
| 193 | int w = Mathf.Clamp(Mathf.CeilToInt(bounds.width * scale) + 4, 32, 1400); |
| 194 | int h = Mathf.Clamp(Mathf.CeilToInt(bounds.height * scale) + 4, 32, 1800); |
| 195 | canvas.scaleFactor = scale; |
| 196 | SetTarget(w, h); |
| 197 | } |
| 198 | |
| 199 | private static float ArtScale(GameObject go) |
| 200 | { |
| 201 | Dictionary<int, int> votes = new Dictionary<int, int>(); |
| 202 | float root = Mathf.Max(0.0001f, Mathf.Abs(go.transform.lossyScale.x)); |
| 203 | foreach (Image img in go.GetComponentsInChildren<Image>(true)) |
| 204 | { |
| 205 | if (img.sprite == null || img.type != Image.Type.Simple) continue; |
| 206 | float sw = img.sprite.rect.width; |
| 207 | if (sw < 4f) continue; |
| 208 | float ratio = img.rectTransform.rect.width * Mathf.Abs(img.rectTransform.lossyScale.x) / root / sw; |
| 209 | int key = Mathf.RoundToInt(ratio * 2f); |
| 210 | if (key < 1 || key > 20) continue; |
| 211 | int n; |
| 212 | votes.TryGetValue(key, out n); |
| 213 | votes[key] = n + 1; |
| 214 | } |
| 215 | int best = 0, bestN = 0; |
| 216 | foreach (KeyValuePair<int, int> kv in votes) if (kv.Value > bestN) { best = kv.Key; bestN = kv.Value; } |
| 217 | if (best == 0) return 0.5f; |
| 218 | return Mathf.Clamp(2f / (best * 0.5f), 0.25f, 1f); |
| 219 | } |
| 220 | |
| 221 | private static Rect Bounds(GameObject go) |
| 222 | { |
| 223 | bool any = false; |
| 224 | float minX = 0, minY = 0, maxX = 0, maxY = 0; |
| 225 | Vector3[] c = new Vector3[4]; |
| 226 | Transform ct = canvasGo.transform; |
| 227 | foreach (Graphic g in go.GetComponentsInChildren<Graphic>(false)) |
| 228 | { |
| 229 | if (!g.enabled || g.color.a <= 0.01f) continue; |
| 230 | g.rectTransform.GetWorldCorners(c); |
| 231 | for (int i = 0; i < 4; i++) |
| 232 | { |
| 233 | Vector3 p = ct.InverseTransformPoint(c[i]); |
| 234 | if (!any) { minX = maxX = p.x; minY = maxY = p.y; any = true; } |
| 235 | else |
| 236 | { |
| 237 | minX = Mathf.Min(minX, p.x); maxX = Mathf.Max(maxX, p.x); |
| 238 | minY = Mathf.Min(minY, p.y); maxY = Mathf.Max(maxY, p.y); |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | return any ? Rect.MinMaxRect(minX, minY, maxX, maxY) : new Rect(0, 0, 0, 0); |
| 243 | } |
| 244 | |
| 245 | private static void SetTarget(int w, int h) |
| 246 | { |
| 247 | if (rt != null && rt.width == w && rt.height == h) return; |
| 248 | if (rt != null) { cam.targetTexture = null; rt.Release(); Object.Destroy(rt); } |
| 249 | if (readTex != null) Object.Destroy(readTex); |
| 250 | rt = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32); |
| 251 | rt.filterMode = FilterMode.Point; |
| 252 | rt.Create(); |
| 253 | cam.targetTexture = rt; |
| 254 | readTex = new Texture2D(w, h, TextureFormat.RGBA32, false); |
| 255 | readTex.filterMode = FilterMode.Point; |
| 256 | width = w; |
| 257 | height = h; |
| 258 | } |
| 259 | |
| 260 | private static void Render() |
| 261 | { |
| 262 | PlayerCamera pc = PlayerCamera.main; |
| 263 | Limb selected = pc != null ? pc.selectedLimb : null; |
| 264 | clone.body = source.body; |
| 265 | clone.limbLookingAt = source.limbLookingAt; |
| 266 | clone.timeOpen = 100f; |
| 267 | clone.checkTime += pendingDt; |
| 268 | pendingDt = 0f; |
| 269 | try { clone.UpdateView(); } |
| 270 | finally { if (pc != null) pc.selectedLimb = selected; } |
| 271 | |
| 272 | Canvas.ForceUpdateCanvases(); |
| 273 | cam.Render(); |
| 274 | RenderTexture prev = RenderTexture.active; |
| 275 | RenderTexture.active = rt; |
| 276 | readTex.ReadPixels(new Rect(0, 0, width, height), 0, 0, false); |
| 277 | readTex.Apply(false); |
| 278 | RenderTexture.active = prev; |
| 279 | byte[] png = ImageConversion.EncodeToPNG(readTex); |
| 280 | Link.PostFrame("HFRAME " + width + " " + height + " " + Convert.ToBase64String(png)); |
| 281 | } |
| 282 | |
| 283 | private static void SendVitals(Body b) |
| 284 | { |
| 285 | StringBuilder sb = new StringBuilder("VITALS "); |
| 286 | CultureInfo ci = CultureInfo.InvariantCulture; |
| 287 | int broken = 0, disloc = 0, shrap = 0, missing = 0; |
| 288 | float infect = 0f; |
| 289 | foreach (Limb l in b.limbs) |
| 290 | { |
| 291 | if (l == null) continue; |
| 292 | if (l.dismembered) { if (!l.prostheticInfo.hasProsthetic) missing++; continue; } |
| 293 | if (l.broken) broken++; |
| 294 | if (l.dislocated) disloc++; |
| 295 | if (l.hasShrapnel) shrap++; |
| 296 | infect = Mathf.Max(infect, l.infectionAmount); |
| 297 | } |
| 298 | sb.Append("alive=").Append(b.alive ? 1 : 0); |
| 299 | sb.Append("|crit=").Append(b.isCriticallyDying ? 1 : 0); |
| 300 | sb.Append("|arrest=").Append(b.inCardiacArrest ? 1 : 0); |
| 301 | sb.Append("|brain=").Append(b.brainHealth.ToString("0.#", ci)); |
| 302 | sb.Append("|blood=").Append(b.bloodVolume.ToString("0.#", ci)); |
| 303 | sb.Append("|bleed=").Append((b.bloodToLiters(b.totalBleedSpeed * b.bloodScale) * 60f).ToString("0.###", ci)); |
| 304 | sb.Append("|oxy=").Append(b.bloodOxygen.ToString("0.#", ci)); |
| 305 | sb.Append("|temp=").Append(b.temperature.ToString("0.#", ci)); |
| 306 | sb.Append("|consc=").Append(b.consciousness.ToString("0.#", ci)); |
| 307 | sb.Append("|pain=").Append(b.averagePain.ToString("0.#", ci)); |
| 308 | sb.Append("|hunger=").Append(b.hunger.ToString("0.#", ci)); |
| 309 | sb.Append("|thirst=").Append(b.thirst.ToString("0.#", ci)); |
| 310 | sb.Append("|energy=").Append(b.energy.ToString("0.#", ci)); |
| 311 | sb.Append("|sick=").Append(b.sicknessAmount.ToString("0.#", ci)); |
| 312 | sb.Append("|rad=").Append((b.radiationSickness * 0.3f).ToString("0.#", ci)); |
| 313 | sb.Append("|venom=").Append(b.venomCurrent.ToString("0.#", ci)); |
| 314 | sb.Append("|infect=").Append(infect.ToString("0.#", ci)); |
| 315 | sb.Append("|broken=").Append(broken).Append("|disloc=").Append(disloc).Append("|shrapnel=").Append(shrap).Append("|missing=").Append(missing); |
| 316 | sb.Append("|mood=").Append(b.totalHappiness.ToString("0.#", ci)); |
| 317 | sb.Append("|enc=").Append(b.overEncumberance > 0.01f ? 1 : 0); |
| 318 | sb.Append("|radline=").Append(RadiationLine.line != null && RadiationLine.line.active ? 1 : 0); |
| 319 | sb.Append("|hr=").Append(b.heartRate.ToString("0", ci)); |
| 320 | Link.Send(sb.ToString()); |
| 321 | } |
| 322 | |
| 323 | private static void DropClone() |
| 324 | { |
| 325 | if (cloneGo != null) |
| 326 | { |
| 327 | HashSet<Texture> keep = new HashSet<Texture>(); |
| 328 | if (source != null) |
| 329 | foreach (RawImage ri in source.GetComponentsInChildren<RawImage>(true)) |
| 330 | if (ri.texture != null) keep.Add(ri.texture); |
| 331 | foreach (ECGVisualizer e in cloneGo.GetComponentsInChildren<ECGVisualizer>(true)) |
| 332 | { |
| 333 | RawImage ri = e.GetComponent<RawImage>(); |
| 334 | if (ri != null && ri.texture != null && !keep.Contains(ri.texture) && string.IsNullOrEmpty(ri.texture.name)) Object.Destroy(ri.texture); |
| 335 | } |
| 336 | Object.Destroy(cloneGo); |
| 337 | } |
| 338 | cloneGo = null; |
| 339 | clone = null; |
| 340 | source = null; |
| 341 | sourceBody = null; |
| 342 | } |
| 343 | |
| 344 | private static void Teardown() |
| 345 | { |
| 346 | DropClone(); |
| 347 | if (rt != null) { if (cam != null) cam.targetTexture = null; rt.Release(); Object.Destroy(rt); rt = null; } |
| 348 | if (readTex != null) { Object.Destroy(readTex); readTex = null; } |
| 349 | if (rig != null) Object.Destroy(rig); |
| 350 | rig = null; |
| 351 | width = height = 0; |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | [HarmonyPatch(typeof(MoodleManager), "UpdateMoodles")] |
| 356 | internal static class MoodleUpdateHook |
| 357 | { |
| 358 | private static void Prefix(MoodleManager __instance) { if (__instance == MoodleManager.main) MoodleFeed.Begin(); } |
| 359 | private static void Postfix(MoodleManager __instance) { if (__instance == MoodleManager.main) MoodleFeed.End(); } |
| 360 | } |
| 361 | |
| 362 | [HarmonyPatch(typeof(MoodleManager), "AddMoodle")] |
| 363 | internal static class MoodleAddHook |
| 364 | { |
| 365 | private static void Postfix(MoodleManager __instance, int intensity, string icon, string name, string desc, bool critical, bool chippedOnly) |
| 366 | { |
| 367 | if (__instance == MoodleManager.main) MoodleFeed.Add(__instance, intensity, icon, name, desc, critical, chippedOnly); |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | internal static class MoodleFeed |
| 372 | { |
| 373 | private const char F = '\u001f'; |
| 374 | private const char R = '\u001e'; |
| 375 | private static readonly List<string> rows = new List<string>(); |
| 376 | private static readonly HashSet<int> sent = new HashSet<int>(); |
| 377 | private static readonly List<Sprite> pending = new List<Sprite>(); |
| 378 | private static bool collecting; |
| 379 | private static string last; |
| 380 | private static float lastAt; |
| 381 | |
| 382 | public static void Reset() |
| 383 | { |
| 384 | sent.Clear(); |
| 385 | pending.Clear(); |
| 386 | last = null; |
| 387 | } |
| 388 | |
| 389 | public static void Begin() |
| 390 | { |
| 391 | rows.Clear(); |
| 392 | collecting = true; |
| 393 | } |
| 394 | |
| 395 | public static void Add(MoodleManager m, int intensity, string icon, string name, string desc, bool critical, bool chippedOnly) |
| 396 | { |
| 397 | if (!collecting) return; |
| 398 | if (chippedOnly && WorldGeneration.unchipped) return; |
| 399 | if (rows.Count >= 60) return; |
| 400 | Sprite bg = m.backgroundIcons != null && intensity >= 0 && intensity < m.backgroundIcons.Length ? m.backgroundIcons[intensity] : null; |
| 401 | Sprite ic = null; |
| 402 | if (m.icons != null && icon != null) m.icons.TryGetValue(icon, out ic); |
| 403 | StringBuilder sb = new StringBuilder(); |
| 404 | sb.Append(Id(bg)).Append(F).Append(Id(ic)).Append(F).Append(critical ? '1' : '0').Append(F).Append(m.sideMoodles ? '1' : '0').Append(F); |
| 405 | sb.Append(Clean(name, 80)).Append(F).Append(Clean(desc, 400)); |
| 406 | rows.Add(sb.ToString()); |
| 407 | } |
| 408 | |
| 409 | public static void End() |
| 410 | { |
| 411 | collecting = false; |
| 412 | if (!Link.Connected || HealthMirror.Mode == 0) return; |
| 413 | string s = string.Join(R.ToString(), rows.ToArray()); |
| 414 | if (s == last && Time.unscaledTime - lastAt < 5f) return; |
| 415 | last = s; |
| 416 | lastAt = Time.unscaledTime; |
| 417 | Link.Send("MOODLES " + s); |
| 418 | } |
| 419 | |
| 420 | private static string Id(Sprite s) |
| 421 | { |
| 422 | if (s == null) return ""; |
| 423 | int id = s.GetInstanceID(); |
| 424 | if (!sent.Contains(id)) |
| 425 | { |
| 426 | sent.Add(id); |
| 427 | pending.Add(s); |
| 428 | } |
| 429 | return id.ToString(CultureInfo.InvariantCulture); |
| 430 | } |
| 431 | |
| 432 | private static string Clean(string s, int max) |
| 433 | { |
| 434 | if (string.IsNullOrEmpty(s)) return ""; |
| 435 | StringBuilder sb = new StringBuilder(); |
| 436 | bool tag = false; |
| 437 | foreach (char c in s) |
| 438 | { |
| 439 | if (c == '<') { tag = true; continue; } |
| 440 | if (c == '>' && tag) { tag = false; continue; } |
| 441 | if (tag) continue; |
| 442 | if (c == F || c == R || c == '\n' || c == '\r') { sb.Append(' '); continue; } |
| 443 | sb.Append(c); |
| 444 | if (sb.Length >= max) break; |
| 445 | } |
| 446 | return sb.ToString().Trim(); |
| 447 | } |
| 448 | |
| 449 | public static void Pump() |
| 450 | { |
| 451 | if (pending.Count == 0 || !Link.Connected) return; |
| 452 | int n = 0; |
| 453 | while (pending.Count > 0 && n < 4) |
| 454 | { |
| 455 | Sprite s = pending[0]; |
| 456 | pending.RemoveAt(0); |
| 457 | n++; |
| 458 | if (s == null) continue; |
| 459 | byte[] png = Png(s); |
| 460 | if (png != null) Link.Post("MICON " + s.GetInstanceID().ToString(CultureInfo.InvariantCulture) + " " + Convert.ToBase64String(png)); |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | private static byte[] Png(Sprite s) |
| 465 | { |
| 466 | Texture t = s.texture; |
| 467 | if (t == null) return null; |
| 468 | Rect r = s.textureRect; |
| 469 | int w = Mathf.RoundToInt(r.width), h = Mathf.RoundToInt(r.height); |
| 470 | if (w <= 0 || h <= 0 || w > 512 || h > 512) return null; |
| 471 | RenderTexture rt = RenderTexture.GetTemporary(w, h, 0, RenderTextureFormat.ARGB32); |
| 472 | RenderTexture prev = RenderTexture.active; |
| 473 | Texture2D tex = null; |
| 474 | try |
| 475 | { |
| 476 | rt.filterMode = FilterMode.Point; |
| 477 | Graphics.Blit(t, rt, new Vector2(r.width / t.width, r.height / t.height), new Vector2(r.x / t.width, r.y / t.height)); |
| 478 | RenderTexture.active = rt; |
| 479 | tex = new Texture2D(w, h, TextureFormat.RGBA32, false); |
| 480 | tex.ReadPixels(new Rect(0, 0, w, h), 0, 0); |
| 481 | tex.Apply(); |
| 482 | return tex.EncodeToPNG(); |
| 483 | } |
| 484 | catch (Exception) { return null; } |
| 485 | finally |
| 486 | { |
| 487 | RenderTexture.active = prev; |
| 488 | RenderTexture.ReleaseTemporary(rt); |
| 489 | if (tex != null) Object.Destroy(tex); |
| 490 | } |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | internal static class BarkFeed |
| 495 | { |
| 496 | private static PantSound lastPs; |
| 497 | private static string lastSet; |
| 498 | private static float nextCheck; |
| 499 | private static readonly List<AudioClip> waiting = new List<AudioClip>(); |
| 500 | |
| 501 | public static void Reset() |
| 502 | { |
| 503 | lastPs = null; |
| 504 | lastSet = null; |
| 505 | nextCheck = 0f; |
| 506 | waiting.Clear(); |
| 507 | } |
| 508 | |
| 509 | public static string Key(AudioClip c) |
| 510 | { |
| 511 | if (c == null || string.IsNullOrEmpty(c.name)) return null; |
| 512 | StringBuilder sb = new StringBuilder(); |
| 513 | foreach (char ch in c.name) |
| 514 | { |
| 515 | if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '-') sb.Append(ch); |
| 516 | if (sb.Length >= 40) break; |
| 517 | } |
| 518 | return sb.Length > 0 ? sb.ToString() : null; |
| 519 | } |
| 520 | |
| 521 | public static void Tick() |
| 522 | { |
| 523 | if (!Link.Connected) return; |
| 524 | Pump(); |
| 525 | if (Time.unscaledTime < nextCheck) return; |
| 526 | nextCheck = Time.unscaledTime + 1f; |
| 527 | Body b = PlayerCamera.main != null && WorldGeneration.world != null ? PlayerCamera.main.body : null; |
| 528 | if (b == null) return; |
| 529 | PantSound ps = b.GetComponent<PantSound>(); |
| 530 | if (ps == null || ps.barkSounds == null) return; |
| 531 | List<string> names = new List<string>(); |
| 532 | foreach (AudioClip c in ps.barkSounds) |
| 533 | { |
| 534 | string k = Key(c); |
| 535 | if (k != null && !names.Contains(k)) names.Add(k); |
| 536 | } |
| 537 | if (names.Count == 0) return; |
| 538 | string set = b.voicePitch.ToString("0.###", CultureInfo.InvariantCulture) + " " + string.Join(",", names.ToArray()); |
| 539 | lastPs = ps; |
| 540 | if (set == lastSet) return; |
| 541 | lastSet = set; |
| 542 | Link.Send("BARKSET " + set); |
| 543 | } |
| 544 | |
| 545 | public static void Request(string name) |
| 546 | { |
| 547 | if (lastPs == null || lastPs.barkSounds == null || waiting.Count > 8) return; |
| 548 | foreach (AudioClip c in lastPs.barkSounds) |
| 549 | { |
| 550 | if (c == null || Key(c) != name || waiting.Contains(c)) continue; |
| 551 | if (c.loadState != AudioDataLoadState.Loaded) c.LoadAudioData(); |
| 552 | waiting.Add(c); |
| 553 | return; |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | private static void Pump() |
| 558 | { |
| 559 | for (int i = waiting.Count - 1; i >= 0; i--) |
| 560 | { |
| 561 | AudioClip c = waiting[i]; |
| 562 | if (c == null || c.loadState == AudioDataLoadState.Failed) { waiting.RemoveAt(i); continue; } |
| 563 | if (c.loadState != AudioDataLoadState.Loaded) continue; |
| 564 | waiting.RemoveAt(i); |
| 565 | try |
| 566 | { |
| 567 | byte[] wav = Wav(c); |
| 568 | if (wav != null) Link.Post("SFX " + Key(c) + " " + Convert.ToBase64String(wav)); |
| 569 | } |
| 570 | catch (Exception e) { Plugin.Log.LogWarning("Couldn't read " + c.name + ": " + e.Message); } |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | private static byte[] Wav(AudioClip c) |
| 575 | { |
| 576 | int ch = c.channels, rate = c.frequency, samples = c.samples; |
| 577 | if (ch < 1 || ch > 2 || rate < 8000 || rate > 96000 || samples <= 0 || samples > rate * 8) return null; |
| 578 | float[] data = new float[samples * ch]; |
| 579 | if (!c.GetData(data, 0)) return null; |
| 580 | int bytes = data.Length * 2; |
| 581 | byte[] o = new byte[44 + bytes]; |
| 582 | Action<int, int> i32 = delegate (int at, int v) { o[at] = (byte)v; o[at + 1] = (byte)(v >> 8); o[at + 2] = (byte)(v >> 16); o[at + 3] = (byte)(v >> 24); }; |
| 583 | o[0] = (byte)'R'; o[1] = (byte)'I'; o[2] = (byte)'F'; o[3] = (byte)'F'; |
| 584 | i32(4, 36 + bytes); |
| 585 | o[8] = (byte)'W'; o[9] = (byte)'A'; o[10] = (byte)'V'; o[11] = (byte)'E'; |
| 586 | o[12] = (byte)'f'; o[13] = (byte)'m'; o[14] = (byte)'t'; o[15] = (byte)' '; |
| 587 | i32(16, 16); |
| 588 | o[20] = 1; o[21] = 0; |
| 589 | o[22] = (byte)ch; o[23] = 0; |
| 590 | i32(24, rate); |
| 591 | i32(28, rate * ch * 2); |
| 592 | o[32] = (byte)(ch * 2); o[33] = 0; |
| 593 | o[34] = 16; o[35] = 0; |
| 594 | o[36] = (byte)'d'; o[37] = (byte)'a'; o[38] = (byte)'t'; o[39] = (byte)'a'; |
| 595 | i32(40, bytes); |
| 596 | int p = 44; |
| 597 | for (int i = 0; i < data.Length; i++) |
| 598 | { |
| 599 | int v = (int)(Mathf.Clamp(data[i], -1f, 1f) * 32767f); |
| 600 | o[p++] = (byte)v; |
| 601 | o[p++] = (byte)(v >> 8); |
| 602 | } |
| 603 | return o; |
| 604 | } |
| 605 | } |
| 606 | } |