Decompiled source of DemonCompany v0.2.7

plugins/DemonCompany.Mod.dll

Decompiled an hour ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using DemonCompany.Shared;
using DemonCompany.Shared.Contracts;
using DemonCompany.Shared.Networking;
using Dissonance;
using Dissonance.Audio.Capture;
using DunGen;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using NAudio.Wave;
using Unity.Collections;
using Unity.Netcode;
using Unity.Netcode.Transports.UTP;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("DemonCompany.Mod")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.7.0")]
[assembly: AssemblyInformationalVersion("0.2.7+6bf6fcbcbe99d66c9e7d085230d3056454633faa")]
[assembly: AssemblyProduct("DemonCompany.Mod")]
[assembly: AssemblyTitle("DemonCompany.Mod")]
[assembly: AssemblyVersion("0.2.7.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DemonCompany.Mod
{
	internal sealed class Cabin : IDisposable
	{
		private readonly TextMesh _screen;

		private readonly Material _wall;

		private readonly Material _frame;

		private readonly StartOfRound _ship;

		private readonly Transform _standingNode;

		private readonly Vector3 _offset;

		private readonly Collider[] _overlaps = (Collider[])(object)new Collider[64];

		private readonly Vector3[] _roomCorners = (Vector3[])(object)new Vector3[8];

		private GameObject? _pane;

		private GameObject? _lowerWall;

		private GameObject? _upperRail;

		private GameObject? _windowSill;

		private GameObject? _leftPost;

		private GameObject? _rightPost;

		private float _halfWidth;

		private float _backDepth;

		public GameObject Root { get; }

		public Transform Tray { get; }

		public Vector3 PlayerPosition => _standingNode.position + Root.transform.forward * 0.35f + Root.transform.up * 0.03f;

		public Cabin(StartOfRound ship, Terminal terminal, string configuredOffset)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Expected O, but got Unknown
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Expected O, but got Unknown
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_0305: Unknown result type (might be due to invalid IL or missing references)
			//IL_0319: Unknown result type (might be due to invalid IL or missing references)
			//IL_0338: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: Expected O, but got Unknown
			//IL_036a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0389: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fe: Unknown result type (might be due to invalid IL or missing references)
			_ship = ship;
			_standingNode = ((Component)terminal).GetComponent<InteractTrigger>()?.playerPositionNode ?? throw new InvalidOperationException("Native terminal standing position is unavailable.");
			Root = new GameObject("DemonCompany.Cabin");
			Root.transform.SetParent(ship.elevatorTransform, false);
			string[] array = configuredOffset.Split(',');
			if (array.Length != 3)
			{
				throw new ArgumentException("CabinOffset requires x,y,z.");
			}
			_offset = new Vector3(float.Parse(array[0], CultureInfo.InvariantCulture), float.Parse(array[1], CultureInfo.InvariantCulture), float.Parse(array[2], CultureInfo.InvariantCulture));
			RefreshAnchor();
			Shader val = Shader.Find("HDRP/Lit") ?? Shader.Find("Standard") ?? throw new InvalidOperationException("No partition material shader available.");
			_wall = new Material(val);
			SetColor(_wall, new Color(0.12f, 0.13f, 0.15f));
			_frame = new Material(val);
			SetColor(_frame, new Color(0.12f, 0.55f, 0.6f));
			_pane = Block("Partition pane", new Vector3(0f, 1.9f, 0f), new Vector3(_halfWidth * 2f, 4f, 0.1f), _wall);
			_pane.GetComponent<Renderer>().enabled = false;
			_lowerWall = Block("Partition lower wall", new Vector3(0f, 0.42f, 0f), new Vector3(_halfWidth * 2f, 0.84f, 0.11f), _wall);
			_upperRail = Block("Partition upper rail", new Vector3(0f, 3.15f, 0f), new Vector3(_halfWidth * 2f, 0.06f, 0.13f), _frame);
			_leftPost = Block("Partition left post", new Vector3(0f - _halfWidth, 1.6f, 0f), new Vector3(0.07f, 3.2f, 0.13f), _frame);
			_rightPost = Block("Partition right post", new Vector3(_halfWidth, 1.6f, 0f), new Vector3(0.07f, 3.2f, 0.13f), _frame);
			_windowSill = Block("Partition window sill", new Vector3(0f, 0.86f, 0f), new Vector3(_halfWidth * 2f, 0.045f, 0.13f), _frame);
			Tray = Block("Offering receptacle", new Vector3(0f, 0.65f, 0.65f), new Vector3(1.4f, 0.12f, 0.8f), _wall).transform;
			GameObject val2 = new GameObject("DemonCompany.Screen");
			val2.transform.SetParent(Root.transform, false);
			val2.transform.localPosition = new Vector3(0f, 1.18f, 0.08f);
			val2.transform.localRotation = Quaternion.Euler(0f, 180f, 0f);
			_screen = val2.AddComponent<TextMesh>();
			_screen.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
			_screen.characterSize = 0.025f;
			_screen.fontSize = 48;
			_screen.anchor = (TextAnchor)4;
			_screen.alignment = (TextAlignment)1;
			_screen.color = new Color(0.4f, 1f, 0.65f);
			((Renderer)val2.GetComponent<MeshRenderer>()).sharedMaterial = _screen.font.material;
			_screen.text = "DEMONCOMPANY\nF6 : boutique\ndvd help : terminal";
		}

		internal void RefreshAnchor()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0302: Unknown result type (might be due to invalid IL or missing references)
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_0319: Unknown result type (might be due to invalid IL or missing references)
			//IL_031b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0322: Unknown result type (might be due to invalid IL or missing references)
			//IL_0327: Unknown result type (might be due to invalid IL or missing references)
			//IL_0329: Unknown result type (might be due to invalid IL or missing references)
			//IL_032e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_0339: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_034e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0353: Unknown result type (might be due to invalid IL or missing references)
			//IL_0358: Unknown result type (might be due to invalid IL or missing references)
			//IL_035d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0360: Unknown result type (might be due to invalid IL or missing references)
			//IL_0365: Unknown result type (might be due to invalid IL or missing references)
			//IL_0366: Unknown result type (might be due to invalid IL or missing references)
			//IL_036b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0381: Unknown result type (might be due to invalid IL or missing references)
			//IL_0384: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0260: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_040d: Unknown result type (might be due to invalid IL or missing references)
			//IL_040f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0472: Unknown result type (might be due to invalid IL or missing references)
			//IL_0483: Unknown result type (might be due to invalid IL or missing references)
			//IL_048d: Unknown result type (might be due to invalid IL or missing references)
			//IL_04cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0502: Unknown result type (might be due to invalid IL or missing references)
			Collider shipInnerRoomBounds = _ship.shipInnerRoomBounds;
			BoxCollider val = (BoxCollider)(object)(((shipInnerRoomBounds is BoxCollider) ? shipInnerRoomBounds : null) ?? throw new InvalidOperationException("Ship command area requires the native room box collider."));
			Vector3 up = _ship.elevatorTransform.up;
			Vector3 val2 = Vector3.ProjectOnPlane(((Component)val).transform.TransformVector(Vector3.right * val.size.x), up);
			Vector3 val3 = Vector3.ProjectOnPlane(((Component)val).transform.TransformVector(Vector3.forward * val.size.z), up);
			Vector3 val4 = ((((Vector3)(ref val2)).sqrMagnitude > ((Vector3)(ref val3)).sqrMagnitude) ? val2 : val3);
			Vector3 forward = ((Vector3)(ref val4)).normalized;
			if (Vector3.Dot(forward, _ship.shipDoorNode.position - _standingNode.position) < 0f)
			{
				forward = -forward;
			}
			val4 = Vector3.Cross(up, forward);
			Vector3 right = ((Vector3)(ref val4)).normalized;
			Vector3 val5 = val.size * 0.5f;
			int num = 0;
			for (int i = -1; i <= 1; i += 2)
			{
				for (int j = -1; j <= 1; j += 2)
				{
					for (int k = -1; k <= 1; k += 2)
					{
						_roomCorners[num++] = ((Component)val).transform.TransformPoint(val.center + Vector3.Scale(val5, new Vector3((float)i, (float)j, (float)k)));
					}
				}
			}
			float num2 = _roomCorners.Min((Vector3 point) => Vector3.Dot(point, right));
			float num3 = _roomCorners.Max((Vector3 point) => Vector3.Dot(point, right));
			float num4 = _roomCorners.Min((Vector3 point) => Vector3.Dot(point, forward));
			float num5 = Vector3.Dot(_standingNode.position, forward);
			MeshRenderer[] array = (MeshRenderer[])(object)new MeshRenderer[2]
			{
				_ship.mapScreen?.mesh,
				_ship.mapScreen?.mesh2
			};
			foreach (MeshRenderer val6 in array)
			{
				if (!((Object)(object)val6 == (Object)null))
				{
					Bounds bounds = ((Renderer)val6).bounds;
					float num7 = Math.Abs(forward.x) * ((Bounds)(ref bounds)).extents.x + Math.Abs(forward.y) * ((Bounds)(ref bounds)).extents.y + Math.Abs(forward.z) * ((Bounds)(ref bounds)).extents.z;
					num5 = Math.Max(num5, Vector3.Dot(((Bounds)(ref bounds)).center, forward) + num7);
				}
			}
			float num8 = num5 + 1.5f;
			Vector3 val7 = ((Component)val).transform.TransformPoint(val.center);
			Vector3 val8 = val7 + forward * (num8 - Vector3.Dot(val7, forward));
			val8 += up * Vector3.Dot(_standingNode.position - val8, up);
			val8 += _ship.elevatorTransform.TransformVector(_offset);
			Quaternion val9 = Quaternion.LookRotation(forward, up);
			float num9 = (num3 - num2) * 0.5f + 0.05f;
			_backDepth = Vector3.Dot(val8, forward) - num4;
			val4 = Root.transform.position - val8;
			bool flag = ((Vector3)(ref val4)).sqrMagnitude > 1E-06f || Quaternion.Angle(Root.transform.rotation, val9) > 0.01f || Math.Abs(num9 - _halfWidth) > 0.001f;
			_halfWidth = num9;
			if (!flag)
			{
				return;
			}
			Root.transform.SetPositionAndRotation(val8, val9);
			GameObject[] array2 = (GameObject[])(object)new GameObject[4] { _pane, _lowerWall, _upperRail, _windowSill };
			foreach (GameObject val10 in array2)
			{
				if ((Object)(object)val10 != (Object)null)
				{
					val10.transform.localScale = new Vector3(_halfWidth * 2f, val10.transform.localScale.y, val10.transform.localScale.z);
				}
			}
			if ((Object)(object)_leftPost != (Object)null)
			{
				_leftPost.transform.localPosition = new Vector3(0f - _halfWidth, 1.6f, 0f);
			}
			if ((Object)(object)_rightPost != (Object)null)
			{
				_rightPost.transform.localPosition = new Vector3(_halfWidth, 1.6f, 0f);
			}
			Physics.SyncTransforms();
		}

		private static void SetColor(Material material, Color color)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (material.HasProperty("_BaseColor"))
			{
				material.SetColor("_BaseColor", color);
			}
			if (material.HasProperty("_Color"))
			{
				material.SetColor("_Color", color);
			}
		}

		private GameObject Block(string name, Vector3 position, Vector3 scale, Material material)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = GameObject.CreatePrimitive((PrimitiveType)3);
			((Object)val).name = "DemonCompany." + name;
			val.transform.SetParent(Root.transform, false);
			val.transform.localPosition = position;
			val.transform.localScale = scale;
			val.GetComponent<Renderer>().sharedMaterial = material;
			return val;
		}

		internal bool IsOnDemonSide(Vector3 point)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return Root.transform.InverseTransformPoint(point).z <= 0.12f;
		}

		public bool Contains(Vector3 point)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = Root.transform.InverseTransformPoint(point);
			if (Math.Abs(val.x) <= _halfWidth + 0.2f && val.z >= 0f - _backDepth - 0.2f && val.z <= 0.12f && val.y >= -0.35f)
			{
				return val.y <= 2.3f;
			}
			return false;
		}

		public bool TryReturnPosition(PlayerControllerB player, bool inside, out Vector3 position)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = Root.transform.InverseTransformPoint(PlayerPosition);
			Vector3[] array = (Vector3[])(object)((!inside) ? new Vector3[4]
			{
				new Vector3(0f, 0.03f, 1.7f),
				new Vector3(0.9f, 0.03f, 1.7f),
				new Vector3(-0.9f, 0.03f, 1.7f),
				new Vector3(0f, 0.03f, 2.2f)
			} : new Vector3[8]
			{
				val,
				val + Vector3.forward * 0.4f,
				val + Vector3.right * 0.45f,
				val - Vector3.right * 0.45f,
				new Vector3(0f, 0.03f, -0.9f),
				new Vector3(0.7f, 0.03f, -0.9f),
				new Vector3(-0.7f, 0.03f, -0.9f),
				new Vector3(0f, 0.03f, -1.5f)
			});
			Vector3[] array2 = array;
			foreach (Vector3 val2 in array2)
			{
				Vector3 val3 = Root.transform.TransformPoint(val2);
				if (Contains(val3) == inside && CanStandAt(player, val3))
				{
					position = val3;
					return true;
				}
			}
			position = default(Vector3);
			return false;
		}

		internal bool CanStandAt(PlayerControllerB player, Vector3 position)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			RaycastHit val = default(RaycastHit);
			if (!Physics.Raycast(position + Root.transform.up * 0.2f, -Root.transform.up, ref val, 0.8f, _ship.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1) || Vector3.Dot(((RaycastHit)(ref val)).normal, Root.transform.up) < 0.7f)
			{
				return false;
			}
			Vector3 lossyScale = ((Component)player).transform.lossyScale;
			float num = player.thisController.radius * Math.Max(Math.Abs(lossyScale.x), Math.Abs(lossyScale.z));
			float num2 = Math.Max(player.thisController.height, 2.5f) * Math.Abs(lossyScale.y);
			Vector3 val2 = position + Root.transform.up * (1.28f * Math.Abs(lossyScale.y));
			float num3 = Math.Max(0f, num2 * 0.5f - num);
			int num4 = Physics.OverlapCapsuleNonAlloc(val2 - Root.transform.up * num3, val2 + Root.transform.up * num3, Math.Max(0.05f, num - 0.04f), _overlaps, _ship.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1);
			if (num4 == _overlaps.Length)
			{
				return false;
			}
			for (int i = 0; i < num4; i++)
			{
				if (!((Component)_overlaps[i]).transform.IsChildOf(((Component)player).transform) && (Object)(object)_overlaps[i] != (Object)(object)player.thisController)
				{
					return false;
				}
			}
			return true;
		}

		public bool InOfferingZone(Vector3 point)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			return Vector3.Distance(point, Tray.position + Vector3.up * 0.35f) <= 0.9f;
		}

		public void Display(string team, long credits, int round)
		{
			_screen.text = $"DEMON {team} | MANCHE {round}/3\n{credits} credits\nF6 / dvd shop";
		}

		public void Dispose()
		{
			Object.Destroy((Object)(object)Root);
			Object.Destroy((Object)(object)_wall);
			Object.Destroy((Object)(object)_frame);
		}
	}
	internal static class CabinPhysicsProbe
	{
		internal static IEnumerator Run(GameRuntime runtime)
		{
			PlayerControllerB player = GameNetworkManager.Instance.localPlayerController;
			Cabin cabin = runtime.DemonCabin;
			Terminal terminal = Object.FindObjectOfType<Terminal>();
			Transform node = ((Component)terminal).GetComponent<InteractTrigger>()?.playerPositionNode;
			StartOfRound instance = StartOfRound.Instance;
			ManualCameraRenderer val = instance.mapScreen ?? throw new InvalidOperationException("Native command monitors are unavailable.");
			MeshRenderer[] array = (MeshRenderer[])(object)new MeshRenderer[4]
			{
				instance.mapScreen?.mesh,
				instance.mapScreen?.mesh2,
				instance.securityCameraScreen?.mesh,
				instance.securityCameraScreen?.mesh2
			};
			Bounds bounds;
			foreach (MeshRenderer val2 in array)
			{
				if ((Object)(object)val2 != (Object)null)
				{
					ManualLogSource log = runtime.Log;
					string name = ((Object)val2).name;
					bounds = ((Renderer)val2).bounds;
					object arg = ((Bounds)(ref bounds)).center;
					bounds = ((Renderer)val2).bounds;
					log.LogInfo((object)$"PARTITION_SCREEN name={name} center={arg:F3} size={((Bounds)(ref bounds)).size:F3}");
				}
			}
			ManualLogSource log2 = runtime.Log;
			object[] obj = new object[6]
			{
				cabin.Root.transform.position,
				cabin.Root.transform.forward,
				instance.shipDoorNode.position,
				null,
				null,
				null
			};
			bounds = instance.shipInnerRoomBounds.bounds;
			obj[3] = ((Bounds)(ref bounds)).center;
			bounds = instance.shipInnerRoomBounds.bounds;
			obj[4] = ((Bounds)(ref bounds)).size;
			bounds = ((Renderer)val.mesh).bounds;
			obj[5] = ((Bounds)(ref bounds)).center;
			log2.LogInfo((object)string.Format("PARTITION_LAYOUT origin={0:F3} towardDoor={1:F3} door={2:F3} roomCenter={3:F3} roomSize={4:F3} monitor={5:F3}", obj));
			if (cabin.IsOnDemonSide(node.position))
			{
				bounds = ((Renderer)val.mesh).bounds;
				if (cabin.IsOnDemonSide(((Bounds)(ref bounds)).center) && !cabin.IsOnDemonSide(instance.shipDoorNode.position) && cabin.Root.GetComponentsInChildren<BoxCollider>().Count((BoxCollider c) => ((Object)c).name == "DemonCompany.Partition pane") == 1)
				{
					ManualLogSource log3 = runtime.Log;
					object[] obj2 = new object[8]
					{
						cabin.Root.transform.position,
						((Component)terminal).transform.position,
						null,
						null,
						null,
						null,
						null,
						null
					};
					obj2[2] = ((node != null) ? new Vector3?(node.position) : ((Vector3?)null));
					obj2[3] = ((Component)player).transform.position;
					obj2[4] = player.thisController.center;
					obj2[5] = player.thisController.height;
					obj2[6] = player.thisController.radius;
					obj2[7] = ((Component)player).transform.lossyScale;
					log3.LogInfo((object)string.Format("CABIN_PHYSICS_GEOMETRY root={0:F3} terminal={1:F3} nativePose={2:F3} player={3:F3} center={4:F3} height={5:F3} radius={6:F3} scale={7:F3}", obj2));
					int before = runtime.ConfinementCorrections;
					yield return (object)new WaitForSecondsRealtime(3f);
					runtime.Log.LogInfo((object)$"CABIN_PHYSICS_STANDING corrections={runtime.ConfinementCorrections - before} player={((Component)player).transform.position:F3} local={cabin.Root.transform.InverseTransformPoint(((Component)player).transform.position):F3} height={player.thisController.height:F3}");
					if (runtime.ConfinementCorrections - before > 1 || !cabin.Contains(((Component)player).transform.position) || !cabin.CanStandAt(player, ((Component)player).transform.position))
					{
						runtime.Log.LogError((object)"UNITY_LOCAL_PROTOTYPE_FAILED Standing demon is repeatedly teleported by confinement.");
						yield break;
					}
					player.Crouch(true);
					before = runtime.ConfinementCorrections;
					yield return (object)new WaitForSecondsRealtime(2f);
					player.Crouch(false);
					yield return (object)new WaitForSecondsRealtime(2f);
					if (runtime.ConfinementCorrections != before || player.isCrouching || player.thisController.height < 2.4f)
					{
						runtime.Log.LogError((object)"UNITY_LOCAL_PROTOTYPE_FAILED Crouch/stand cycle is blocked by the cabin.");
						yield break;
					}
					Vector3 start = ((Component)player).transform.position;
					bool moved = false;
					Vector3[] array2 = (Vector3[])(object)new Vector3[3]
					{
						cabin.Root.transform.forward,
						cabin.Root.transform.right,
						-cabin.Root.transform.right
					};
					foreach (Vector3 direction in array2)
					{
						player.TeleportPlayer(start, false, 0f, true, true);
						float until = Time.realtimeSinceStartup + 0.45f;
						while (Time.realtimeSinceStartup < until)
						{
							player.thisController.Move(direction * (1.5f * Time.unscaledDeltaTime));
							yield return null;
						}
						Vector3 val3 = Vector3.ProjectOnPlane(((Component)player).transform.position - start, Vector3.up);
						float magnitude = ((Vector3)(ref val3)).magnitude;
						runtime.Log.LogInfo((object)$"CABIN_PHYSICS_MOVEMENT distance={magnitude:F3} corrections={runtime.ConfinementCorrections - before}");
						if (magnitude >= 0.3f && cabin.Contains(((Component)player).transform.position))
						{
							moved = true;
							break;
						}
					}
					if (!moved || runtime.ConfinementCorrections != before)
					{
						runtime.Log.LogError((object)"UNITY_LOCAL_PROTOTYPE_FAILED Standing character cannot move freely inside the cabin.");
						yield break;
					}
					Vector3 val4 = cabin.Root.transform.TransformPoint(new Vector3(0f, 0.03f, -0.95f));
					if (!cabin.CanStandAt(player, val4))
					{
						runtime.Log.LogError((object)"UNITY_LOCAL_PROTOTYPE_FAILED Command-side approach to the partition is obstructed.");
						yield break;
					}
					player.TeleportPlayer(val4, false, 0f, true, true);
					bool[] array3 = new bool[2] { false, true };
					foreach (bool flag in array3)
					{
						player.Crouch(flag);
						yield return (object)new WaitForSecondsRealtime(1f);
						float until = Time.realtimeSinceStartup + 0.9f;
						while (Time.realtimeSinceStartup < until)
						{
							player.thisController.Move(cabin.Root.transform.forward * (2f * Time.unscaledDeltaTime));
							yield return null;
						}
						if (!cabin.IsOnDemonSide(((Component)player).transform.position) || runtime.ConfinementCorrections != before)
						{
							runtime.Log.LogError((object)"UNITY_LOCAL_PROTOTYPE_FAILED Standing or crouching character crossed the physical partition.");
							yield break;
						}
					}
					player.Crouch(false);
					player.TeleportPlayer(node.position, false, 0f, true, true);
					((Component)terminal).GetComponent<InteractTrigger>().Interact(((Component)player).transform);
					yield return (object)new WaitForSecondsRealtime(2f);
					bool enteredTerminal = player.inTerminalMenu && terminal.terminalInUse;
					terminal.QuitTerminal(true);
					yield return (object)new WaitForSecondsRealtime(1f);
					if (!enteredTerminal || player.inTerminalMenu || runtime.ConfinementCorrections != before || !cabin.Contains(((Component)player).transform.position))
					{
						runtime.Log.LogError((object)"UNITY_LOCAL_PROTOTYPE_FAILED Native terminal animation conflicts with cabin confinement.");
						yield break;
					}
					if (!cabin.TryReturnPosition(player, inside: false, out var position) || cabin.Contains(position))
					{
						runtime.Log.LogError((object)"UNITY_LOCAL_PROTOTYPE_FAILED Cabin has no unobstructed crew exit point.");
						yield break;
					}
					player.TeleportPlayer(position, false, 0f, true, true);
					before = runtime.ConfinementCorrections;
					yield return (object)new WaitForSecondsRealtime(2f);
					if (runtime.ConfinementCorrections != before + 1 || !cabin.Contains(((Component)player).transform.position) || !cabin.CanStandAt(player, ((Component)player).transform.position))
					{
						runtime.Log.LogError((object)"UNITY_LOCAL_PROTOTYPE_FAILED Escaped demon was not safely returned exactly once.");
						yield break;
					}
					before = runtime.ConfinementCorrections;
					yield return (object)new WaitForSecondsRealtime(2f);
					if (runtime.ConfinementCorrections != before)
					{
						runtime.Log.LogError((object)"UNITY_LOCAL_PROTOTYPE_FAILED Safe return caused repeated confinement teleports.");
						yield break;
					}
					GameObject val5 = GameObject.CreatePrimitive((PrimitiveType)3);
					val5.transform.SetPositionAndRotation(cabin.PlayerPosition + Vector3.up * 1.4f, cabin.Root.transform.rotation);
					val5.transform.localScale = new Vector3(1.2f, 2.8f, 1.2f);
					Physics.SyncTransforms();
					Vector3 position2;
					bool flag2 = !cabin.CanStandAt(player, cabin.PlayerPosition) && (!cabin.TryReturnPosition(player, inside: true, out position2) || cabin.CanStandAt(player, position2));
					Object.Destroy((Object)(object)val5);
					if (!flag2)
					{
						runtime.Log.LogError((object)"UNITY_LOCAL_PROTOTYPE_FAILED Obstructed return points were accepted.");
						yield break;
					}
					bool moveInput = player.disableMoveInput;
					bool lookInput = player.disableLookInput;
					bool interact = player.disableInteract;
					int menuFrames = runtime.MenuFrames;
					runtime.ToggleUi();
					yield return (object)new WaitForSecondsRealtime(1f);
					bool menuOpened = runtime.MenuOpen && player.disableMoveInput && player.disableLookInput && player.disableInteract;
					if (!Application.isBatchMode)
					{
						menuOpened &= runtime.MenuFrames > menuFrames;
						string directory = Path.Combine(Paths.ConfigPath, "DemonCompany", "ui-previews", "live-" + Guid.NewGuid().ToString("N"));
						Directory.CreateDirectory(directory);
						yield return (object)new WaitForEndOfFrame();
						ScreenCapture.CaptureScreenshot(Path.Combine(directory, "live-lobby.png"));
						yield return (object)new WaitForSecondsRealtime(0.4f);
					}
					runtime.ToggleUi();
					if (!menuOpened || runtime.MenuOpen || player.disableMoveInput != moveInput || player.disableLookInput != lookInput || player.disableInteract != interact)
					{
						runtime.Log.LogError((object)"UNITY_LOCAL_PROTOTYPE_FAILED Menu did not render or restore native player input correctly.");
						yield break;
					}
					runtime.Log.LogInfo((object)"UNITY_LIVE_MENU_OK opened=true closed=true playerInputRestored=true");
					runtime.Log.LogInfo((object)"UNITY_CABIN_PHYSICS_OK singlePartition=true monitorsAndTerminalInside=true entranceOutside=true standing=true crouch=true movement=true physicalBarrierStandingAndCrouched=true terminal=true crewExit=true escapeReturn=once obstructionRejected=true");
					yield break;
				}
			}
			runtime.Log.LogError((object)"UNITY_LOCAL_PROTOTYPE_FAILED Partition does not separate both workstations from the ship entrance.");
		}
	}
	internal sealed class DeadVoiceCapture : IMicrophoneSubscriber
	{
		private readonly object _gate = new object();

		private readonly ConcurrentQueue<byte[]> _frames = new ConcurrentQueue<byte[]>();

		private readonly short[] _samples = new short[320];

		private bool _enabled;

		private int _round;

		private int _life;

		private int _count;

		private int _sequence;

		private ulong _player;

		private double _phase;

		private double _sum;

		private int _sumCount;

		public void Configure(bool enabled, int round, ulong player, int life)
		{
			lock (_gate)
			{
				if (!enabled || round != _round || life != _life || player != _player)
				{
					_count = 0;
					_phase = 0.0;
					_sum = 0.0;
					_sumCount = 0;
					byte[] result;
					while (_frames.TryDequeue(out result))
					{
					}
				}
				_enabled = enabled;
				_round = round;
				_player = player;
				_life = life;
			}
		}

		public bool TryReceive(out byte[] data)
		{
			return _frames.TryDequeue(out data);
		}

		public void Reset()
		{
			lock (_gate)
			{
				_count = 0;
				_phase = 0.0;
				_sum = 0.0;
				_sumCount = 0;
				byte[] result;
				while (_frames.TryDequeue(out result))
				{
				}
			}
		}

		public void ReceiveMicrophoneData(ArraySegment<float> buffer, WaveFormat format)
		{
			lock (_gate)
			{
				if (!_enabled || buffer.Array == null || format.Channels < 1 || format.SampleRate < 16000)
				{
					return;
				}
				for (int i = 0; i < buffer.Count; i += format.Channels)
				{
					_sum += buffer.Array[buffer.Offset + i];
					_sumCount++;
					_phase += 16000.0;
					if (_phase < (double)format.SampleRate)
					{
						continue;
					}
					_phase -= format.SampleRate;
					double num = Math.Max(-1.0, Math.Min(1.0, _sum / (double)_sumCount));
					_sum = 0.0;
					_sumCount = 0;
					_samples[_count++] = (short)(num * 32767.0);
					if (_count == 320)
					{
						_count = 0;
						while (_frames.Count >= 4)
						{
							_frames.TryDequeue(out byte[] _);
						}
						_frames.Enqueue(VoicePacket.Create(_round, _player, _life, ++_sequence, _samples));
					}
				}
			}
		}
	}
	internal sealed class DeadVoicePlayback : IDisposable
	{
		private readonly GameObject _object;

		private readonly AudioClip _clip;

		private readonly AudioSource _source;

		private readonly DeadVoiceOutput _output;

		public DeadVoicePlayback()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			_object = new GameObject("DemonCompany.DeadVoice");
			_source = _object.AddComponent<AudioSource>();
			_source.spatialBlend = 0f;
			_source.loop = true;
			_source.playOnAwake = false;
			_output = _object.AddComponent<DeadVoiceOutput>();
			_output.OutputRate = AudioSettings.outputSampleRate;
			_clip = AudioClip.Create("Dead voice", 16000, 1, 16000, false);
			_source.clip = _clip;
			_source.Play();
		}

		public void Add(byte[] data, float volume)
		{
			_source.volume = volume;
			_output.Buffer.Add(data);
		}

		public void Dispose()
		{
			_source.Stop();
			Object.Destroy((Object)(object)_object);
			Object.Destroy((Object)(object)_clip);
		}
	}
	internal sealed class DeadVoiceOutput : MonoBehaviour
	{
		public VoicePlaybackBuffer Buffer { get; } = new VoicePlaybackBuffer();

		public int OutputRate { get; set; } = 48000;

		private void OnAudioFilterRead(float[] samples, int channels)
		{
			Buffer.Read(samples, channels, OutputRate);
		}
	}
	internal sealed class LocalEffect
	{
		public string Id { get; set; } = "";

		public ulong Target { get; set; }

		public ProductKind Kind { get; set; }
	}
	internal sealed class GameRuntime : MonoBehaviour
	{
		private LocalNetwork? _local;

		private NetworkManager? _manager;

		private Cabin? _cabin;

		private Terminal? _terminal;

		private readonly ConcurrentQueue<string> _networkLogs = new ConcurrentQueue<string>();

		private readonly Dictionary<string, Delivery> _deliveries = new Dictionary<string, Delivery>();

		private readonly Dictionary<ulong, ulong> _lastCarrier = new Dictionary<ulong, ulong>();

		private readonly Dictionary<ulong, float> _baseStamina = new Dictionary<ulong, float>();

		private readonly Dictionary<ulong, bool> _dead = new Dictionary<ulong, bool>();

		private readonly Dictionary<ulong, int> _life = new Dictionary<ulong, int>();

		private readonly Dictionary<ulong, LocalRequest> _deathProof = new Dictionary<ulong, LocalRequest>();

		private readonly Dictionary<ulong, float> _deathObserved = new Dictionary<ulong, float>();

		private readonly Dictionary<ulong, EnemyMarkerInfo> _markers = new Dictionary<ulong, EnemyMarkerInfo>();

		private readonly HashSet<string> _offered = new HashSet<string>();

		private readonly HashSet<string> _seenRequests = new HashSet<string>();

		private readonly HashSet<string> _appliedEffects = new HashSet<string>();

		private readonly List<LocalEffect> _effects = new List<LocalEffect>();

		private readonly Collider[] _offeringColliders = (Collider[])(object)new Collider[96];

		private float _nextTick;

		private string _rosterHash = "";

		private bool _rosterFrozen;

		private bool _landed;

		private int _round;

		private string _fingerprint = "";

		private bool _showUi;

		private DemonMenu? _menu;

		private MenuState? _menuState;

		private bool _hostConnected;

		private Task<TrustSession>? _trustJoin;

		private CancellationTokenSource? _trustStop;

		private TrustSession? _trustSession;

		private float _nextTrustJoin;

		private float _nextHello;

		private bool _cursorVisible;

		private CursorLockMode _cursorLock;

		private bool _savedLookDisabled;

		private bool _savedMoveDisabled;

		private bool _savedInteractDisabled;

		private int _departedRound;

		private float _departedAt;

		private double _departureDayTime;

		private int _retainedReferenceRound;

		private bool _referenceWasSpawning;

		private bool _deferredDeparture;

		private float _nextConfinementCorrection;

		private SoloPractice? _practice;

		private GUIStyle? _practiceHint;

		private string[]? _queuedPracticeCommand;

		private VoiceClient? _voiceRelay;

		private DeadVoiceCapture? _voiceCapture;

		private DissonanceComms? _voiceComms;

		private readonly Dictionary<ulong, DeadVoicePlayback> _voicePlayers = new Dictionary<ulong, DeadVoicePlayback>();

		private readonly Dictionary<ulong, (float Window, int Count)> _voiceRates = new Dictionary<ulong, (float, int)>();

		private int _voiceRound;

		private float _nextVoicePresence;

		public static GameRuntime? Instance { get; private set; }

		public ModOptions Options { get; private set; }

		public ManualLogSource Log { get; private set; }

		public TeamView? View { get; private set; }

		public ReliableHostClient? Coordinator { get; private set; }

		public SpawnService Spawns { get; private set; }

		public GenerationService Generation { get; private set; }

		public bool ModeEnabled
		{
			get
			{
				if (Options != null)
				{
					return Options.Enabled.Value;
				}
				return false;
			}
		}

		public bool IsHost
		{
			get
			{
				if ((Object)(object)NetworkManager.Singleton != (Object)null)
				{
					return NetworkManager.Singleton.IsServer;
				}
				return false;
			}
		}

		public bool AllowNativeLaunch { get; private set; }

		public bool PracticeEnabled { get; private set; }

		public string Team
		{
			get
			{
				TeamView? view = View;
				object obj = ((view != null) ? view.Team : null);
				if (obj == null)
				{
					TrustSession? trustSession = _trustSession;
					obj = ((trustSession != null) ? trustSession.Team : null) ?? Options.Team.Value;
				}
				return (string)obj;
			}
		}

		public bool IsMirror
		{
			get
			{
				if (ModeEnabled && Team == "B")
				{
					return IsHost;
				}
				return false;
			}
		}

		public bool Faulted { get; private set; }

		public string Notice { get; private set; } = "";

		internal OfferingCredits? TerminalOfferingCredits { get; private set; }

		public bool HoldingReference => ShouldRetainReference(_retainedReferenceRound);

		internal Cabin? DemonCabin => _cabin;

		internal int ConfinementCorrections { get; private set; }

		internal bool MenuOpen => _showUi;

		internal int MenuFrames => _menu?.DrawnFrames ?? 0;

		internal SoloPractice? PracticeSession => _practice;

		private bool DeadVoiceActive
		{
			get
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Invalid comparison between Unknown and I4
				if (Options.DeadVoice.Value && !PracticeEnabled && !Faulted)
				{
					TeamView? view = View;
					if (view != null && (int)view.Phase == 3 && _local != null && (Object)(object)_manager != (Object)null && (Object)(object)_manager == (Object)(object)NetworkManager.Singleton && _manager.IsListening)
					{
						return (Object)(object)StartOfRound.Instance != (Object)null;
					}
				}
				return false;
			}
		}

		public void Initialize(ModOptions options, ManualLogSource log)
		{
			Instance = this;
			Options = options;
			Log = log;
			PracticeEnabled = options.Enabled.Value && options.SoloPractice.Value;
			Spawns = new SpawnService(this);
			Generation = new GenerationService(this);
			if (ModeEnabled)
			{
				Log.LogInfo((object)"Competitive mode enabled; waiting for the local NGO session.");
			}
		}

		private void Update()
		{
			if (!ModeEnabled)
			{
				return;
			}
			UpdateDeadVoice();
			Keyboard current = Keyboard.current;
			if (current != null && ((ButtonControl)current.f6Key).wasPressedThisFrame)
			{
				ToggleUi();
			}
			if (PracticeEnabled && _practice != null && !_showUi)
			{
				GameNetworkManager instance = GameNetworkManager.Instance;
				if (instance == null || instance.localPlayerController?.inTerminalMenu != true)
				{
					Keyboard current2 = Keyboard.current;
					if (current2 != null && ((ButtonControl)current2.f7Key).wasPressedThisFrame)
					{
						PracticeCommand(new string[3] { "dvd", "test", "switch" });
					}
					Keyboard current3 = Keyboard.current;
					if (current3 != null && ((ButtonControl)current3.f8Key).wasPressedThisFrame)
					{
						PracticeCommand(new string[4] { "dvd", "test", "item", "100" });
					}
				}
			}
			if (Time.unscaledTime < _nextTick)
			{
				return;
			}
			_nextTick = Time.unscaledTime + 0.25f;
			try
			{
				Tick();
			}
			catch (Exception ex)
			{
				Log.LogError((object)ex);
				SetFault("Runtime error: " + ex.Message);
			}
		}

		private void Tick()
		{
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Expected O, but got Unknown
			//IL_0410: Unknown result type (might be due to invalid IL or missing references)
			//IL_0416: Invalid comparison between Unknown and I4
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Invalid comparison between Unknown and I4
			//IL_059e: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a4: Invalid comparison between Unknown and I4
			//IL_0615: Unknown result type (might be due to invalid IL or missing references)
			//IL_061a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0649: Expected O, but got Unknown
			string result;
			while (_networkLogs.TryDequeue(out result))
			{
				Log.LogInfo((object)result);
			}
			NetworkManager singleton = NetworkManager.Singleton;
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)singleton == (Object)null || !singleton.IsListening || singleton.CustomMessagingManager == null || (Object)(object)instance == (Object)null)
			{
				if (_local != null)
				{
					ResetSession();
				}
				return;
			}
			if (PracticeEnabled)
			{
				TickPractice(singleton, instance);
				return;
			}
			if ((Object)(object)_manager != (Object)(object)singleton || _local == null)
			{
				ResetSession();
				_manager = singleton;
				_local = new LocalNetwork(singleton, this);
				if (singleton.IsServer)
				{
					if (!Options.TrustMode.Value)
					{
						ConnectCoordinator(Options.MatchId.Value, Options.Team.Value);
					}
					_fingerprint = InstallationFingerprint(instance);
				}
			}
			if (IsHost && Coordinator == null && Options.TrustMode.Value && !Faulted && !ConnectTrustCoordinator())
			{
				return;
			}
			if (Faulted)
			{
				if (Coordinator != null)
				{
					ServerFrame result2;
					while (Coordinator.Frames.TryDequeue(out result2))
					{
					}
				}
				return;
			}
			if (!IsHost && Time.unscaledTime > _nextHello)
			{
				_nextHello = Time.unscaledTime + 2f;
				_local.Request(new LocalRequest
				{
					Action = "hello"
				});
			}
			if (IsHost)
			{
				ServerFrame result3;
				while (Coordinator != null && Coordinator.Frames.TryDequeue(out result3))
				{
					View = result3.View;
					if (!result3.Accepted)
					{
						Notice = "Commande refusee : " + result3.Error;
						TeamView? view = View;
						if (view != null && (int)view.Phase == 0)
						{
							_rosterFrozen = false;
						}
					}
					else if (result3.EventId.Length > 0)
					{
						Notice = "Commande acceptee.";
					}
					foreach (Delivery delivery in result3.Deliveries)
					{
						_deliveries[delivery.Id] = delivery;
					}
					HashSet<string> pending = result3.Deliveries.Select((Delivery d) => d.Id).ToHashSet();
					foreach (string item in _deliveries.Keys.Where((string id) => !pending.Contains(id)).ToList())
					{
						_deliveries.Remove(item);
					}
				}
				RegisterRoster(instance);
			}
			if (View == null)
			{
				return;
			}
			if (_retainedReferenceRound > 0 && !ShouldRetainReference(_retainedReferenceRound))
			{
				int retainedReferenceRound = _retainedReferenceRound;
				_retainedReferenceRound = 0;
				RoundManager.Instance.UnloadSceneObjectsEarly();
				Log.LogInfo((object)("REFERENCE_CLEANUP_OK round=" + retainedReferenceRound));
				if (_deferredDeparture)
				{
					_deferredDeparture = false;
					instance.ShipHasLeft();
				}
			}
			if (_round != View.Round)
			{
				_round = View.Round;
				_landed = false;
				_departedRound = 0;
				_offered.Clear();
				_lastCarrier.Clear();
				_dead.Clear();
				_life.Clear();
				_deathProof.Clear();
				_deathObserved.Clear();
				_effects.Clear();
				Generation.Reset();
			}
			if ((int)View.Phase == 5)
			{
				SetFault("Le coordinateur a bloque le match. Consultez les journaux des hotes.");
				return;
			}
			if ((Object)(object)_terminal == (Object)null)
			{
				_terminal = Object.FindObjectOfType<Terminal>();
			}
			if ((Object)(object)_terminal != (Object)null && _cabin == null)
			{
				_cabin = new Cabin(instance, _terminal, Options.CabinOffset.Value);
			}
			_cabin?.RefreshAnchor();
			ConfineDemon(instance);
			if (Faulted)
			{
				return;
			}
			ApplyStamina(instance);
			_cabin?.Display(View.Team, View.Credits, View.Round);
			if (!IsHost || Coordinator == null)
			{
				return;
			}
			ApplyOfferingCredits();
			PrepareRound(instance);
			foreach (Delivery item2 in _deliveries.Values.ToList())
			{
				if (item2.Round == View.Round && ApplyDelivery(item2))
				{
					_deliveries.Remove(item2.Id);
				}
			}
			Generation.Tick();
			if (HoldingReference && (Object)(object)RoundManager.Instance != (Object)null && _referenceWasSpawning)
			{
				RoundManager.Instance.isSpawningEnemies = true;
			}
			ObserveDeaths(instance);
			if ((int)View.Phase == 3 && !View.FinishedOwnRound)
			{
				CollectOfferings(instance);
				if (!instance.inShipPhase)
				{
					_landed = true;
				}
				if (_landed && Coordinator.PendingCount == 0 && ((_departedRound == View.Round && Time.unscaledTime - _departedAt >= 3f) || instance.inShipPhase))
				{
					Enqueue((CommandKind)14, new CommandBody
					{
						RoundTime = _departureDayTime
					}, "end-" + View.Round);
				}
			}
			LocalState localState = new LocalState
			{
				View = View,
				Notice = Notice,
				Connected = Coordinator.Connected,
				Enemies = (from e in Object.FindObjectsOfType<EnemyTag>().Where(delegate(EnemyTag e)
					{
						NetworkObject component = ((Component)e).GetComponent<NetworkObject>();
						return component != null && component.IsSpawned;
					})
					select new EnemyMarkerInfo
					{
						NetworkId = ((Component)e).GetComponent<NetworkObject>().NetworkObjectId,
						EnemyId = e.Event.Id,
						Origin = e.Event.Origin
					}).ToList(),
				Effects = _effects.ToList(),
				Lives = new Dictionary<ulong, int>(_life),
				Faulted = Faulted,
				TerminalCodes = (View.GenerationVerified ? Generation.TerminalCodes() : new Dictionary<ulong, string>())
			};
			_local.Publish(localState);
			ReceiveMarkers(localState.Enemies);
		}

		private void ConnectCoordinator(string matchId, string team, string? roomId = null)
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Expected O, but got Unknown
			if (team != "A" && team != "B")
			{
				throw new InvalidOperationException("Team must be A or B.");
			}
			string text = Path.Combine(Paths.ConfigPath, "DemonCompany", ManifestHash.Of(matchId + team) + ".json");
			Coordinator = new ReliableHostClient(new Uri(Options.Coordinator.Value.TrimEnd('/') + "/ws/" + team), (roomId == null) ? Options.Token.Value : "", matchId, text, (Action<string>)delegate(string item)
			{
				_networkLogs.Enqueue(item);
			}, roomId);
			Coordinator.Start();
			StartDeadVoiceRelay(matchId, team, roomId);
		}

		private bool ConnectTrustCoordinator()
		{
			if (_trustJoin == null)
			{
				if (Time.unscaledTime < _nextTrustJoin)
				{
					return false;
				}
				if (_trustStop == null)
				{
					_trustStop = new CancellationTokenSource();
				}
				_trustJoin = TrustDiscovery.JoinAsync(new Uri(Options.Coordinator.Value), Options.GetOrCreateRoomId(), _trustStop.Token);
				Notice = "Connexion au match en mode confiance...";
			}
			if (!_trustJoin.IsCompleted)
			{
				return false;
			}
			try
			{
				_trustSession = _trustJoin.GetAwaiter().GetResult();
			}
			catch (Exception ex)
			{
				Notice = "Connexion confiance : " + ex.Message;
				Log.LogWarning((object)Notice);
				_trustJoin = null;
				_nextTrustJoin = Time.unscaledTime + 3f;
				return false;
			}
			ConnectCoordinator(_trustSession.MatchId, _trustSession.Team, Options.RoomId.Value);
			Notice = "Room reliee automatiquement : equipe " + _trustSession.Team + ".";
			Log.LogInfo((object)("TRUST_ROOM_CONNECTED team=" + _trustSession.Team + " match=" + _trustSession.MatchId));
			return true;
		}

		private string InstallationFingerprint(StartOfRound ship)
		{
			IEnumerable<string> values = from info in Chainloader.PluginInfos.Values
				orderby info.Metadata.GUID
				select info.Metadata.GUID + ":" + info.Metadata.Version?.ToString() + ":" + HashFile(info.Location);
			string location = typeof(StartOfRound).Assembly.Location;
			return ManifestHash.Of(HashFile(location) + "\n" + HashFile(typeof(NetworkManager).Assembly.Location) + "\n" + HashFile(typeof(Wire).Assembly.Location) + "\n" + string.Join("\n", values) + string.Join("|", ship.levels.Select((SelectableLevel level) => level.levelID + ":" + level.PlanetName)));
		}

		private static string HashFile(string path)
		{
			using SHA256 sHA = SHA256.Create();
			using FileStream inputStream = File.OpenRead(path);
			return BitConverter.ToString(sHA.ComputeHash(inputStream)).Replace("-", "");
		}

		private void RegisterRoster(StartOfRound ship)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Expected O, but got Unknown
			if (Coordinator == null || _rosterFrozen || (View != null && (int)View.Phase != 0))
			{
				return;
			}
			List<PlayerInfo> list = ship.allPlayerScripts.Where((PlayerControllerB p) => (Object)(object)p != (Object)null && (p.isPlayerControlled || p.isPlayerDead)).Select((Func<PlayerControllerB, PlayerInfo>)((PlayerControllerB p) => new PlayerInfo
			{
				Id = p.playerClientId,
				Name = p.playerUsername
			})).ToList();
			PlayerControllerB demon = ship.allPlayerScripts.ElementAtOrDefault(Options.DemonSlot.Value);
			if (list.Count != 0 && !((Object)(object)demon == (Object)null) && !list.All((PlayerInfo p) => p.Id != demon.playerClientId))
			{
				CommandBody val = new CommandBody
				{
					Players = list,
					Demon = demon.playerClientId,
					Fingerprint = _fingerprint
				};
				string text = ManifestHash.Of(Wire.Encode((object)val));
				if (!(text == _rosterHash))
				{
					_rosterHash = text;
					Enqueue((CommandKind)0, val);
				}
			}
		}

		private void PrepareRound(StartOfRound ship)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Expected O, but got Unknown
			TeamView? view = View;
			if (view == null || (int)view.Phase != 2 || !ship.inShipPhase || ship.travellingToNewLevel)
			{
				return;
			}
			if (!ship.levels.Any((SelectableLevel level) => level.levelID == View.Moon && level.spawnEnemiesAndScrap))
			{
				throw new InvalidOperationException("Configured moon is not an explorable level: " + View.Moon);
			}
			if (ship.currentLevelID != View.Moon)
			{
				if (Coordinator.PendingCount == 0)
				{
					ship.ChangeLevelServerRpc(View.Moon, _terminal?.groupCredits ?? 0);
				}
			}
			else
			{
				Enqueue((CommandKind)3, new CommandBody(), "prepared-" + View.Round);
			}
		}

		public void ConfigureNativeRound(StartOfRound ship)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			if (View == null)
			{
				throw new InvalidOperationException("No coordinator round.");
			}
			ship.overrideRandomSeed = true;
			ship.overrideSeedNumber = View.Seed;
			ship.currentLevel.currentWeather = (LevelWeatherType)(-1);
			ship.currentLevel.moldSpreadIterations = 0;
			ship.daysPlayersSurvivedInARow = 0;
			if ((Object)(object)TimeOfDay.Instance != (Object)null)
			{
				TimeOfDay.Instance.daysUntilDeadline = 3;
				TimeOfDay.Instance.timeUntilDeadline = TimeOfDay.Instance.totalTime * 3f;
				TimeOfDay.Instance.profitQuota = 1000000;
			}
		}

		public void NativeShipLeaving()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			if (IsHost && !(Team != "A"))
			{
				TeamView? view = View;
				if (view != null && (int)view.Phase == 3)
				{
					_retainedReferenceRound = View.Round;
					_referenceWasSpawning = (Object)(object)RoundManager.Instance != (Object)null && RoundManager.Instance.isSpawningEnemies;
				}
			}
		}

		public bool ShouldRetainReference(int round)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Invalid comparison between Unknown and I4
			if (round > 0 && ModeEnabled && IsHost && Team == "A" && !Faulted)
			{
				TeamView? view = View;
				if (view != null && view.Round == round)
				{
					return (int)View.Phase == 3;
				}
			}
			return false;
		}

		public bool DeferReferenceDeparture()
		{
			if (!HoldingReference)
			{
				return false;
			}
			if (!_deferredDeparture)
			{
				_deferredDeparture = true;
				NativeShipDeparted();
				Log.LogInfo((object)("REFERENCE_SCENE_RETAINED round=" + View.Round));
			}
			return true;
		}

		public void NativeShipDeparted()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			if (IsHost)
			{
				TeamView? view = View;
				if (view != null && (int)view.Phase == 3)
				{
					_departedRound = View.Round;
					_departedAt = Time.unscaledTime;
					_departureDayTime = Math.Max(0f, TimeOfDay.Instance.currentDayTime);
					string text = Path.Combine(Paths.ConfigPath, "DemonCompany", "diagnostics", ManifestHash.Of(View.MatchId).Substring(0, 16));
					Directory.CreateDirectory(text);
					File.WriteAllText(Path.Combine(text, $"round-{View.Round}-end.json"), Wire.Encode((object)new
					{
						Round = View.Round,
						RoundTime = _departureDayTime
					}));
				}
			}
		}

		private bool ApplyDelivery(Delivery delivery)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Invalid comparison between Unknown and I4
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Invalid comparison between Unknown and I4
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Invalid comparison between Unknown and I4
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Expected I4, but got Unknown
			//IL_0296: Unknown result type (might be due to invalid IL or missing references)
			//IL_029c: Invalid comparison between Unknown and I4
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Expected O, but got Unknown
			if ((Coordinator == null && _practice == null) || View == null)
			{
				return false;
			}
			if (View.FinishedOwnRound && ((int)delivery.Kind == 2 || (int)delivery.Kind == 3 || (int)delivery.Kind == 5))
			{
				MarkDeliveryApplied(delivery.Id);
				Acknowledge(delivery);
				return true;
			}
			if (_practice?.WasApplied(delivery.Id) ?? Coordinator.WasApplied(delivery.Id))
			{
				Acknowledge(delivery);
				return true;
			}
			DeliveryKind kind = delivery.Kind;
			switch ((int)kind)
			{
			case 0:
			{
				StartOfRound instance = StartOfRound.Instance;
				if ((Object)(object)instance == (Object)null || !instance.inShipPhase || instance.travellingToNewLevel || instance.fullyLoadedPlayers.Count < instance.connectedPlayersAmount + 1)
				{
					return false;
				}
				AllowNativeLaunch = true;
				try
				{
					ConfigureNativeRound(instance);
					instance.StartGameServerRpc();
				}
				finally
				{
					AllowNativeLaunch = false;
				}
				break;
			}
			case 1:
			{
				GrabbableObject val = ((IEnumerable<GrabbableObject>)Object.FindObjectsOfType<GrabbableObject>()).FirstOrDefault((Func<GrabbableObject, bool>)((GrabbableObject item2) => ItemId(item2) == delivery.ItemId));
				if ((Object)(object)val == (Object)null)
				{
					Enqueue((CommandKind)((_practice?.WasConsumed(ConsumedKey(delivery.ItemId)) ?? Coordinator.WasConsumed(ConsumedKey(delivery.ItemId))) ? 8 : 9), new CommandBody
					{
						ReferenceId = delivery.ReferenceId
					}, "offer-result-" + delivery.Id);
					MarkDeliveryApplied(delivery.Id);
					return true;
				}
				if (val.isHeld || val.isHeldByEnemy || !((NetworkBehaviour)val).NetworkObject.IsSpawned)
				{
					return false;
				}
				((NetworkBehaviour)val).NetworkObject.Despawn(true);
				MarkDeliveryApplied(delivery.Id, ConsumedKey(delivery.ItemId));
				Acknowledge(delivery);
				return true;
			}
			case 2:
			case 5:
				if (!Spawns.Apply(delivery))
				{
					return false;
				}
				break;
			case 4:
				if (!Generation.Apply(delivery.Manifest))
				{
					return false;
				}
				break;
			case 3:
			{
				ProductDefinition product = delivery.Product;
				if (product != null && (int)product.Kind == 3)
				{
					TargetedRevival.Apply(delivery.Target, IsHost);
					LocalEffect item = new LocalEffect
					{
						Id = delivery.Id,
						Kind = (ProductKind)3,
						Target = delivery.Target
					};
					_effects.Add(item);
					_appliedEffects.Add(delivery.Id);
					_life[delivery.Target] = Life(delivery.Target) + 1;
					_dead[delivery.Target] = false;
				}
				break;
			}
			}
			MarkDeliveryApplied(delivery.Id);
			Acknowledge(delivery);
			return true;
		}

		private void Acknowledge(Delivery delivery)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Invalid comparison between Unknown and I4
			//IL_0046: Expected O, but got Unknown
			Enqueue((CommandKind)(((int)delivery.Kind == 1) ? 8 : 13), new CommandBody
			{
				ReferenceId = (((int)delivery.Kind == 1) ? delivery.ReferenceId : delivery.Id)
			}, "ack-" + delivery.Id);
		}

		public string Enqueue(CommandKind kind, CommandBody body, string? eventId = null)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			object obj = _practice?.Enqueue(kind, body, eventId);
			if (obj == null)
			{
				ReliableHostClient? coordinator = Coordinator;
				if (coordinator == null)
				{
					obj = null;
				}
				else
				{
					TeamView? view = View;
					obj = coordinator.Enqueue((view == null) ? 1 : view.Round, kind, body, eventId);
				}
				if (obj == null)
				{
					throw new InvalidOperationException("No host coordinator connection.");
				}
			}
			return (string)obj;
		}

		private void MarkDeliveryApplied(string id, string? consumed = null)
		{
			if (_practice != null)
			{
				_practice.MarkApplied(id, consumed);
			}
			else
			{
				Coordinator.MarkApplied(id, consumed);
			}
		}

		private string ConsumedKey(string id)
		{
			return View.Round + ":" + id;
		}

		public static string ItemId(GrabbableObject item)
		{
			return ((Component)item).GetComponent<ScrapTag>()?.LogicalId ?? ("extra-" + ((NetworkBehaviour)item).NetworkObjectId);
		}

		private void ApplyOfferingCredits()
		{
			if (!((Object)(object)_terminal == (Object)null) && View != null)
			{
				if (TerminalOfferingCredits == null)
				{
					OfferingCredits offeringCredits = (TerminalOfferingCredits = new OfferingCredits(View, GameNetworkManager.Instance.currentSaveFileName, PracticeEnabled));
				}
				TerminalOfferingCredits.Apply(_terminal, View.OfferingTotal);
			}
		}

		private void CollectOfferings(StartOfRound ship)
		{
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Expected O, but got Unknown
			if (_cabin == null || View == null)
			{
				return;
			}
			foreach (PlayerControllerB item in ship.allPlayerScripts.Where((PlayerControllerB p) => (Object)(object)p != (Object)null && p.isPlayerControlled))
			{
				foreach (GrabbableObject item2 in item.ItemSlots.Where((GrabbableObject i) => (Object)(object)i != (Object)null))
				{
					_lastCarrier[((NetworkBehaviour)item2).NetworkObjectId] = item.playerClientId;
					if ((Object)(object)((Component)item2).GetComponent<ScrapTag>() == (Object)null)
					{
						((Component)item2).gameObject.AddComponent<ScrapTag>().LogicalId = "extra-" + Guid.NewGuid().ToString("N");
					}
				}
			}
			int num = Physics.OverlapBoxNonAlloc(_cabin.Tray.position + Vector3.up * 0.45f, new Vector3(0.7f, 0.45f, 0.5f), _offeringColliders, _cabin.Tray.rotation, -1, (QueryTriggerInteraction)2);
			for (int num2 = 0; num2 < num; num2++)
			{
				GrabbableObject componentInParent = ((Component)_offeringColliders[num2]).GetComponentInParent<GrabbableObject>();
				if (!((Object)(object)componentInParent == (Object)null) && componentInParent.itemProperties.isScrap && componentInParent.scrapValue > 0 && !componentInParent.isHeld && !componentInParent.isHeldByEnemy && ((NetworkBehaviour)componentInParent).NetworkObject.IsSpawned && _lastCarrier.TryGetValue(((NetworkBehaviour)componentInParent).NetworkObjectId, out var value) && value != View.Demon)
				{
					string text = ItemId(componentInParent);
					if (_offered.Add(text))
					{
						Enqueue((CommandKind)7, new CommandBody
						{
							Actor = value,
							ItemId = text,
							Value = componentInParent.scrapValue
						}, "offer-" + View.Round + "-" + text);
					}
				}
			}
		}

		private void ConfineDemon(StartOfRound ship)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Invalid comparison between Unknown and I4
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			if (_cabin == null || View == null || (int)View.Phase == 4)
			{
				return;
			}
			PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
			if ((Object)(object)val == (Object)null || val.isPlayerDead || !val.isPlayerControlled)
			{
				return;
			}
			if (val.playerClientId != View.Demon)
			{
				if (_cabin.Contains(((Component)val).transform.position) && Time.unscaledTime >= _nextConfinementCorrection && _cabin.TryReturnPosition(val, inside: false, out var position))
				{
					val.TeleportPlayer(position, false, 0f, false, true);
					_nextConfinementCorrection = Time.unscaledTime + 1f;
				}
				return;
			}
			if (!_cabin.Contains(((Component)val).transform.position) && Time.unscaledTime >= _nextConfinementCorrection)
			{
				if (!_cabin.TryReturnPosition(val, inside: true, out var position2))
				{
					SetFault("Zone du demon obstruee : aucun point de retour ne permet de se tenir debout. Verifiez le placement du terminal et CabinOffset.");
					return;
				}
				ConfinementCorrections++;
				val.TeleportPlayer(position2, false, 0f, true, true);
				_nextConfinementCorrection = Time.unscaledTime + 1f;
			}
			val.isInHangarShipRoom = true;
			val.isInElevator = true;
			val.isInsideFactory = false;
		}

		private void ApplyStamina(StartOfRound ship)
		{
			if (View == null)
			{
				return;
			}
			foreach (PlayerControllerB player in ship.allPlayerScripts.Where((PlayerControllerB p) => (Object)(object)p != (Object)null))
			{
				if (!_baseStamina.ContainsKey(player.playerClientId))
				{
					_baseStamina.Add(player.playerClientId, player.sprintTime);
				}
				float val = View.Upgrades.Where((UpgradeState upgrade) => upgrade.Target == player.playerClientId && (!upgrade.Expires.HasValue || upgrade.Expires > DateTimeOffset.UtcNow)).Aggregate(1f, (float value, UpgradeState upgrade) => value * upgrade.Magnitude);
				player.sprintTime = _baseStamina[player.playerClientId] * Math.Min(val, 10f);
			}
		}

		public void HandleRequest(ulong sender, LocalRequest request)
		{
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Invalid comparison between Unknown and I4
			if (!IsHost || Coordinator == null || Faulted)
			{
				return;
			}
			PlayerControllerB val = ((IEnumerable<PlayerControllerB>)StartOfRound.Instance?.allPlayerScripts).FirstOrDefault((Func<PlayerControllerB, bool>)((PlayerControllerB p) => (Object)(object)p != (Object)null && p.actualClientId == sender && (p.isPlayerControlled || p.isPlayerDead)));
			if ((Object)(object)val == (Object)null || request.Id.Length > 128 || !_seenRequests.Add(sender + ":" + request.Id))
			{
				return;
			}
			if (_seenRequests.Count > 50000)
			{
				SetFault("Local request limit exceeded.");
				return;
			}
			try
			{
				CommandBody val2 = new CommandBody
				{
					Actor = val.playerClientId,
					Target = request.Target
				};
				switch (request.Action)
				{
				case "ready":
					if (View == null || val.playerClientId != View.Demon)
					{
						throw new InvalidOperationException("Seul le demon peut valider l'equipe.");
					}
					if (NetworkManager.Singleton.ConnectedClientsIds.Any((ulong id) => !_local.ModClients.Contains(id)))
					{
						throw new InvalidOperationException("Every connected player must have DemonCompany enabled.");
					}
					_rosterFrozen = true;
					Enqueue((CommandKind)1, val2);
					break;
				case "moon":
					val2.Moon = int.Parse(request.Argument, CultureInfo.InvariantCulture);
					Enqueue((CommandKind)2, val2);
					break;
				case "launch":
					Enqueue((CommandKind)4, val2);
					break;
				case "leave":
				{
					TeamView? view2 = View;
					if (view2 == null || (int)view2.Phase != 3 || View.FinishedOwnRound || val.playerClientId != View.Demon)
					{
						throw new InvalidOperationException("Seul le demon peut demander le depart pendant sa manche.");
					}
					(StartOfRound.Instance ?? throw new InvalidOperationException("Vaisseau indisponible.")).EndGameServerRpc((int)val.playerClientId);
					break;
				}
				case "buy":
					val2.ProductId = request.Argument;
					Enqueue((CommandKind)10, val2);
					break;
				case "death":
					if (val.isPlayerDead)
					{
						int round = request.Round;
						TeamView? view = View;
						if (round == ((view != null) ? new int?(view.Round) : ((int?)null)) && request.Life == Life(val.playerClientId))
						{
							_deathProof[val.playerClientId] = request;
						}
					}
					break;
				default:
					throw new InvalidOperationException("Unknown request.");
				}
			}
			catch (Exception ex)
			{
				Notice = "Commande refusee : " + ex.Message;
				Log.LogWarning((object)Notice);
			}
		}

		public string TerminalCommand(string command)
		{
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0297: Expected O, but got Unknown
			string[] array = command.Trim().Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			if (PracticeEnabled && array.Length > 1 && array[1].Equals("test", StringComparison.OrdinalIgnoreCase))
			{
				return PracticeCommand(array);
			}
			if (array.Length < 2 || array[1].Equals("help", StringComparison.OrdinalIgnoreCase))
			{
				return "DEMONCOMPANY\ndvd ready | dvd moon <id> | dvd launch | dvd leave\ndvd shop | dvd buy <produit> [joueur]\ndvd balance | dvd history\nF6 : interface. Les commandes natives restent disponibles.\n";
			}
			string text = array[1].ToLowerInvariant();
			switch (text)
			{
			case "shop":
				if (View != null)
				{
					return string.Join("\n", View.Shop.Select((ProductDefinition p) => $"{p.Id} : {p.Price} credits ({p.Name})")) + "\n";
				}
				return "Connexion en attente.\n";
			case "balance":
				if (View != null)
				{
					return $"Credits : {View.Credits}\nScore provisoire : {View.VisibleScore} (bonus reveles en fin de match)\n";
				}
				return "Connexion en attente.\n";
			case "history":
				if (View != null)
				{
					return string.Join("\n", View.Purchases.Select((PurchaseRecord p) => $"Manche {p.Round} : {p.ProductId} - {p.Price}")) + "\n";
				}
				return "Connexion en attente.\n";
			default:
			{
				if (PracticeEnabled)
				{
					return "TEST SOLO : F7 change de cote, F8 cree un objet de 100. dvd test help pour les commandes. Les achats du demon sont indisponibles.\n";
				}
				if (_local == null)
				{
					return "Connexion a l'hote indisponible.\n";
				}
				bool flag;
				switch (text)
				{
				case "ready":
				case "moon":
				case "launch":
				case "leave":
				case "buy":
					flag = true;
					break;
				default:
					flag = false;
					break;
				}
				if (!flag)
				{
					return "Commande dvd inconnue ; dvd help.\n";
				}
				if ((text == "moon" || text == "buy") && array.Length < 3)
				{
					return "Argument manquant ; dvd help.\n";
				}
				long num;
				if (array.Length <= 3 || !ulong.TryParse(array[3], out var result))
				{
					TeamView? view = View;
					ulong? obj;
					if (view == null)
					{
						obj = null;
					}
					else
					{
						PlayerInfo? obj2 = ((IEnumerable<PlayerInfo>)view.Players).FirstOrDefault((Func<PlayerInfo, bool>)((PlayerInfo p) => p.Id != View.Demon));
						obj = ((obj2 != null) ? new ulong?(obj2.Id) : ((ulong?)null));
					}
					num = (long)(obj ?? 1);
				}
				else
				{
					num = (long)result;
				}
				ulong target = (ulong)num;
				_local.Request(new LocalRequest
				{
					Action = text,
					Argument = ((array.Length > 2) ? array[2] : ""),
					Target = target
				});
				return "Requete envoyee. Consultez F6 pour le resultat et le solde.\n";
			}
			}
		}

		public void ReceiveLocalState(LocalState state)
		{
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Invalid comparison between Unknown and I4
			View = state.View;
			Notice = state.Notice;
			ReceiveMarkers(state.Enemies);
			_hostConnected = state.Connected;
			Generation.ApplyTerminalCodes(state.TerminalCodes);
			Faulted = state.Faulted;
			foreach (KeyValuePair<ulong, int> life in state.Lives)
			{
				_life[life.Key] = life.Value;
			}
			foreach (LocalEffect effect in state.Effects)
			{
				if (_appliedEffects.Add(effect.Id) && (int)effect.Kind == 3)
				{
					TargetedRevival.Apply(effect.Target, server: false);
				}
			}
		}

		private void ReceiveMarkers(List<EnemyMarkerInfo> markers)
		{
			_markers.Clear();
			foreach (EnemyMarkerInfo marker in markers)
			{
				_markers[marker.NetworkId] = marker;
			}
		}

		public void ReportLocalDeath(PlayerControllerB victim, EnemyAI? directEnemy)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Invalid comparison between Unknown and I4
			if (_local != null && View != null && ((NetworkBehaviour)victim).IsOwner && victim.isPlayerDead)
			{
				string text = "";
				if ((Object)(object)directEnemy != (Object)null && _markers.TryGetValue(((NetworkBehaviour)directEnemy).NetworkObjectId, out EnemyMarkerInfo value) && (int)value.Origin == 1)
				{
					text = value.EnemyId;
				}
				_local.Request(new LocalRequest
				{
					Action = "death",
					EnemyId = text,
					DirectEnemyKill = (text.Length > 0),
					Round = View.Round,
					Life = Life(victim.playerClientId)
				});
			}
		}

		private int Life(ulong player)
		{
			if (!_life.TryGetValue(player, out var value))
			{
				return 0;
			}
			return value;
		}

		private void ObserveDeaths(StartOfRound ship)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Expected O, but got Unknown
			TeamView? view = View;
			if (view == null || (int)view.Phase != 3 || View.FinishedOwnRound)
			{
				return;
			}
			foreach (PlayerControllerB player in ship.allPlayerScripts.Where((PlayerControllerB p) => (Object)(object)p != (Object)null && View.Players.Any((PlayerInfo info) => info.Id == p.playerClientId)))
			{
				ulong playerClientId = player.playerClientId;
				if (!player.isPlayerDead)
				{
					_dead[playerClientId] = false;
				}
				else
				{
					if (playerClientId == View.Demon || (_dead.TryGetValue(playerClientId, out var value) && value))
					{
						continue;
					}
					if (!_deathObserved.ContainsKey(playerClientId))
					{
						_deathObserved[playerClientId] = Time.unscaledTime;
					}
					if (_deathProof.ContainsKey(playerClientId) || !(Time.unscaledTime - _deathObserved[playerClientId] < 2f))
					{
						_deathProof.TryGetValue(playerClientId, out LocalRequest proof);
						EnemyTag enemyTag = ((proof == null) ? null : Object.FindObjectsOfType<EnemyTag>().FirstOrDefault((EnemyTag e) => e.Event.Id == proof.EnemyId && (int)e.Event.Origin == 1 && Vector3.Distance(((Component)e).transform.position, ((Component)player).transform.position) < 20f));
						CommandBody val = new CommandBody
						{
							Target = playerClientId,
							DeathId = $"{View.Round}:{playerClientId}:{Life(playerClientId)}",
							EnemyId = (((enemyTag != null) ? enemyTag.Event.Id : null) ?? "")
						};
						LocalRequest obj = proof;
						val.DirectEnemyKill = obj != null && obj.DirectEnemyKill && (Object)(object)enemyTag != (Object)null;
						Enqueue((CommandKind)11, val, $"death-{View.Round}-{playerClientId}-{Life(playerClientId)}");
						_dead[playerClientId] = true;
						_deathObserved.Remove(playerClientId);
						_deathProof.Remove(playerClientId);
					}
				}
			}
		}

		public void SetFault(string message)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Invalid comparison between Unknown and I4
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			if (Faulted)
			{
				return;
			}
			Faulted = true;
			Notice = "MATCH BLOQUE : " + message;
			Log.LogError((object)Notice);
			if (Coordinator != null)
			{
				TeamView? view = View;
				if (view == null || (int)view.Phase != 5)
				{
					try
					{
						CommandBody val = new CommandBody();
						TeamView? view2 = View;
						Enqueue((CommandKind)15, val, "fault-" + ((view2 == null) ? 1 : view2.Round));
					}
					catch (Exception ex)
					{
						Log.LogError((object)("Could not report match fault: " + ex));
					}
				}
			}
			if (IsHost)
			{
				_local?.Publish(new LocalState
				{
					View = View,
					Notice = Notice,
					Faulted = true
				});
			}
		}

		private void ResetSession()
		{
			StopDeadVoice();
			if (_showUi)
			{
				ToggleUi();
			}
			ReliableHostClient? coordinator = Coordinator;
			if (coordinator != null)
			{
				coordinator.Dispose();
			}
			Coordinator = null;
			_local?.Dispose();
			_local = null;
			_manager = null;
			_trustStop?.Cancel();
			_trustStop?.Dispose();
			_trustStop = null;
			if (_trustJoin != null)
			{
				_trustJoin.ContinueWith(delegate(Task<TrustSession> task)
				{
					_networkLogs.Enqueue("Trust discovery stopped: " + task.Exception?.GetBaseException().Message);
				}, TaskContinuationOptions.OnlyOnFaulted);
			}
			_trustJoin = null;
			_trustSession = null;
			_nextTrustJoin = 0f;
			_cabin?.Dispose();
			_cabin = null;
			_terminal = null;
			View = null;
			TerminalOfferingCredits = null;
			_practice = null;
			_queuedPracticeCommand = null;
			_deliveries.Clear();
			_rosterFrozen = false;
			_rosterHash = "";
			_landed = false;
			_round = 0;
			_baseStamina.Clear();
			_markers.Clear();
			_appliedEffects.Clear();
			_seenRequests.Clear();
			_retainedReferenceRound = (_departedRound = 0);
			_deferredDeparture = false;
			_nextConfinementCorrection = 0f;
			_hostConnected = false;
			_offered.Clear();
			_lastCarrier.Clear();
		}

		private void OnDestroy()
		{
			ResetSession();
			_menu?.Dispose();
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		internal void ToggleUi()
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
			if (!_showUi)
			{
				_cursorVisible = Cursor.visible;
				_cursorLock = Cursor.lockState;
				if ((Object)(object)val != (Object)null)
				{
					_savedLookDisabled = val.disableLookInput;
					_savedMoveDisabled = val.disableMoveInput;
					_savedInteractDisabled = val.disableInteract;
					val.disableLookInput = true;
					val.disableMoveInput = true;
					val.disableInteract = true;
				}
				_showUi = true;
				Cursor.visible = true;
				Cursor.lockState = (CursorLockMode)0;
			}
			else
			{
				_showUi = false;
				Cursor.visible = _cursorVisible;
				Cursor.lockState = _cursorLock;
				if ((Object)(object)val != (Object)null)
				{
					val.disableLookInput = _savedLookDisabled;
					val.disableMoveInput = _savedMoveDisabled;
					val.disableInteract = _savedInteractDisabled;
				}
			}
		}

		private void OnGUI()
		{
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Invalid comparison between Unknown and I4
			if (PracticeEnabled && ModeEnabled && !_showUi && _practice != null)
			{
				DrawPracticeHint();
			}
			if (!ModeEnabled || !_showUi)
			{
				return;
			}
			if (_menu == null)
			{
				_menu = new DemonMenu();
			}
			if (_menuState == null)
			{
				_menuState = new MenuState
				{
					IsDead = CrewDead,
					MoonName = MoonName,
					Send = delegate(string command)
					{
						TerminalCommand(command);
					},
					Close = ToggleUi
				};
			}
			_menuState.View = View;
			_menuState.IsDemon = View != null && GameNetworkManager.Instance?.localPlayerController?.playerClientId == View.Demon;
			_menuState.Practice = PracticeEnabled;
			MenuState? menuState = _menuState;
			int connected;
			if (!PracticeEnabled)
			{
				if (!IsHost)
				{
					connected = (_hostConnected ? 1 : 0);
				}
				else
				{
					ReliableHostClient? coordinator = Coordinator;
					connected = ((coordinator != null && coordinator.Connected) ? 1 : 0);
				}
			}
			else
			{
				connected = ((_practice != null) ? 1 : 0);
			}
			menuState.Connected = (byte)connected != 0;
			_menuState.Faulted = Faulted;
			_menuState.Notice = Notice;
			_menu.Draw(_menuState);
			if ((int)Event.current.type == 7)
			{
				Cursor.visible = true;
				Cursor.lockState = (CursorLockMode)0;
			}
		}

		private static bool? CrewDead(ulong id)
		{
			PlayerControllerB val = ((IEnumerable<PlayerControllerB>)StartOfRound.Instance?.allPlayerScripts).FirstOrDefault((Func<PlayerControllerB, bool>)((PlayerControllerB p) => (Object)(object)p != (Object)null && p.playerClientId == id && (p.isPlayerControlled || p.isPlayerDead)));
			if (!((Object)(object)val == (Object)null))
			{
				return val.isPlayerDead;
			}
			return null;
		}

		private static string MoonName(int id)
		{
			return ((IEnumerable<SelectableLevel>)StartOfRound.Instance?.levels).FirstOrDefault((Func<SelectableLevel, bool>)((SelectableLevel level) => level.levelID == id))?.PlanetName ?? ("Lune " + id);
		}

		private void TickPractice(NetworkManager manager, StartOfRound ship)
		{
			if (!manager.IsServer || manager.ConnectedClientsIds.Count != 1)
			{
				if (_practice != null)
				{
					ResetSession();
				}
				Notice = "Le test solo demande un lobby heberge avec un seul joueur.";
				return;
			}
			PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
			if ((Object)(object)val == (Object)null || !val.isPlayerControlled)
			{
				return;
			}
			if ((Object)(object)_manager != (Object)(object)manager || _practice == null)
			{
				ResetSession();
				_manager = manager;
				_practice = new SoloPractice(val.playerClientId, val.playerUsername);
				Notice = "TEST SOLO : F7 change de cote, F8 cree du butin. Aucun coordinateur.";
			}
			if ((Object)(object)_terminal == (Object)null)
			{
				_terminal = Object.FindObjectOfType<Terminal>();
			}
			if ((Object)(object)_terminal == (Object)null)
			{
				return;
			}
			GameNetworkManager.Instance.gameHasStarted = true;
			if (_cabin == null)
			{
				_cabin = new Cabin(ship, _terminal, Options.CabinOffset.Value);
			}
			_cabin.RefreshAnchor();
			View = _practice.View();
			if (_queuedPracticeCommand != null && !val.inTerminalMenu && !val.inSpecialInteractAnimation)
			{
				string[] queuedPracticeCommand = _queuedPracticeCommand;
				_queuedPracticeCommand = null;
				PracticeCommand(queuedPracticeCommand);
			}
			ConfineDemon(ship);
			if (Faulted)
			{
				return;
			}
			CollectOfferings(ship);
			foreach (Delivery item in _practice.Pending())
			{
				ApplyDelivery(item);
			}
			View = _practice.View();
			ApplyOfferingCredits();
			_cabin.Display("TEST SOLO", View.Credits, 1);
		}

		private string PracticeCommand(string[] parts)
		{
			try
			{
				if (_practice == null || _cabin == null)
				{
					throw new InvalidOperationException("Heberge d'abord un lobby solo.");
				}
				string text = ((parts.Length > 2) ? parts[2].ToLowerInvariant() : "help");
				bool flag;
				switch (text)
				{
				case "crew":
				case "demon":
				case "switch":
				case "item":
					flag = true;
					break;
				default:
					flag = false;
					break;
				}
				if (flag && GameNetworkManager.Instance.localPlayerController.inTerminalMenu)
				{
					_queuedPracticeCommand = parts;
					return "TEST SOLO : action prete. Quitte le terminal pour l'executer.\n";
				}
				switch (text)
				{
				case "crew":
				case "demon":
				case "switch":
					if (_showUi)
					{
						ToggleUi();
					}
					_practice.SwitchRole(text == "demon" || (text == "switch" && !_practice.IsDemon), _cabin);
					View = _practice.View();
					Notice = (_practice.IsDemon ? "TEST SOLO : cote demon. La cloison reste solide." : "TEST SOLO : cote Crewmate. Ramasse puis depose le butin sur le receptacle.");
					break;
				case "item":
				{
					if (_showUi)
					{
						ToggleUi();
					}
					int result;
					int value = ((parts.Length > 3 && int.TryParse(parts[3], out result)) ? result : 100);
					if (parts.Length > 3 && !int.TryParse(parts[3], out var _))
					{
						throw new ArgumentException("dvd test item <valeur de 1 a 10000>");
					}
					_practice.SpawnItem(value);
					Notice = "TEST SOLO : objet cree, valeur " + value + ". Ramasse-le puis pose-le sur le receptacle.";
					break;
				}
				case "help":
					return "TEST SOLO HORS LIGNE\ndvd test crew : cote Crewmate\ndvd test demon : cote demon\ndvd test item [valeur] : butin (100 par defaut)\nF7 : changer de cote | F8 : creer du butin\nDepose le butin sur le receptacle pour crediter le demon et le terminal.\nF6 affiche le solde du demon. Commande le materiel au terminal natif.\n";
				default:
					throw new ArgumentException("Commande inconnue : dvd test help.");
				}
				return Notice + "\n";
			}
			catch (Exception ex)
			{
				Notice = "Test solo : " + ex.Message;
				return Notice + "\n";
			}
		}

		private void DrawPracticeHint()
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0046: Expected O, but got Unknown
			if (_practiceHint == null)
			{
				_practiceHint = new GUIStyle(GUI.skin.box)
				{
					fontSize = 14,
					alignment = (TextAnchor)0,
					wordWrap = true,
					padding = new RectOffset(12, 12, 9, 9)
				};
			}
			int num = Math.Min(590, Screen.width - 24);
			Rect val = new Rect(12f, 12f, (float)num, 104f);
			string arg = (_practice.IsDemon ? "DÉMON" : "CREWMATE");
			TeamView? view = View;
			GUI.Box(val, $"TEST SOLO · {arg} · {((view != null) ? view.Credits : 0)} crédits\nF7 : changer de côté    F8 : butin 100    F6 : aide et solde\n{Notice}", _practiceHint);
		}

		private void StartDeadVoiceRelay(string matchId, string team, string? roomId)
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			if (Options.DeadVoice.Value)
			{
				Uri uri = new Uri(Options.Coordinator.Value.TrimEnd('/') + "/voice/" + team);
				Uri uri2 = new UriBuilder(uri)
				{
					Query = "matchId=" + Uri.EscapeDataString(matchId) + ((roomId == null) ? "" : ("&roomId=" + Uri.EscapeDataString(roomId)))
				}.Uri;
				_voiceRelay = new VoiceClient(uri2, (roomId == null) ? Options.Token.Value : "", (Action<string>)delegate(string entry)
				{
					_networkLogs.Enqueue(entry);
				});
			}
		}

		private void UpdateDeadVoice()
		{
			PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
			if (DeadVoiceActive && IsHost)
			{
				VoiceClient? voiceRelay = _voiceRelay;
				if (voiceRelay != null && voiceRelay.Connected && Time.unscaledTime >= _nextVoicePresence)
				{
					_nextVoicePresence = Time.unscaledTime + 0.5f;
					PlayerControllerB val2 = ((IEnumerable<PlayerControllerB>)StartOfRound.Instance.allPlayerScripts).FirstOrDefault((Func<PlayerControllerB, bool>)((PlayerControllerB p) => (Object)(object)p != (Object)null && p.playerClientId == View.Demon));
					if ((Object)(object)val2 != (Object)null)
					{
						_voiceRelay.Send(VoicePacket.Create(View.Round, val2.playerClientId, Life(val2.playerClientId), val2.isPlayerDead ? (-2147483647) : int.MinValue, new short[320]));
					}
				}
			}

plugins/DemonCompany.Shared.dll

Decompiled an hour ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.WebSockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DemonCompany.Shared.Contracts;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("DemonCompany.Shared")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.7.0")]
[assembly: AssemblyInformationalVersion("0.2.7+6bf6fcbcbe99d66c9e7d085230d3056454633faa")]
[assembly: AssemblyProduct("DemonCompany.Shared")]
[assembly: AssemblyTitle("DemonCompany.Shared")]
[assembly: AssemblyVersion("0.2.7.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DemonCompany.Shared
{
	public static class InstallationMigration
	{
		public static bool ImportLegacyProfile(string configDirectory)
		{
			string text = Path.Combine(configDirectory, "DemonVsDemon.Mod.cfg");
			string text2 = Path.Combine(configDirectory, "DemonCompany.Mod.cfg");
			bool flag = !File.Exists(text2) && File.Exists(text);
			if (flag)
			{
				File.Copy(text, text2);
			}
			string path = Path.Combine(configDirectory, "DemonVsDemon");
			string text3 = Path.Combine(configDirectory, "DemonCompany");
			if (Directory.Exists(path))
			{
				foreach (string item in Directory.EnumerateFiles(path, "*.json", SearchOption.TopDirectoryOnly))
				{
					string text4 = Path.Combine(text3, Path.GetFileName(item));
					if (!File.Exists(text4))
					{
						Directory.CreateDirectory(text3);
						File.Copy(item, text4);
					}
				}
			}
			return flag;
		}
	}
	public sealed class SelectionStep
	{
		public string Team { get; set; } = "A";

		public string Action { get; set; } = "ban";
	}
	public sealed class ProductDefinition
	{
		public string Id { get; set; } = "";

		public string Name { get; set; } = "";

		public ProductKind Kind { get; set; }

		public int Price { get; set; }

		public int CooldownSeconds { get; set; }

		public int LimitPerRound { get; set; } = 3;

		public int DurationSeconds { get; set; }

		public float Magnitude { get; set; } = 1f;

		public string EnemyType { get; set; } = "";

		public bool Outside { get; set; }
	}
	public sealed class MatchOptions
	{
		public const string TeleporterUpgradeId = "teleporter";

		public int PointsPerKill { get; set; } = 100;

		public int DeathPenalty { get; set; } = 50;

		public int PlayersPerTeam { get; set; } = 2;

		public bool AllowSoloDevelopment { get; set; }

		public int MaximumOfferingValue { get; set; } = 10000;

		public int MaximumNaturalSpawnsPerRound { get; set; } = 2000;

		public int MaximumPurchasesPerRound { get; set; } = 30;

		public List<int> Moons { get; set; } = new List<int> { 0, 1, 2, 4, 7, 9 };

		public List<SelectionStep> Selection { get; set; } = new List<SelectionStep>
		{
			new SelectionStep
			{
				Team = "A",
				Action = "ban"
			},
			new SelectionStep
			{
				Team = "B",
				Action = "ban"
			},
			new SelectionStep
			{
				Team = "A",
				Action = "pick"
			}
		};

		public List<ProductDefinition> Products { get; set; } = new List<ProductDefinition>
		{
			new ProductDefinition
			{
				Id = "crawler",
				Name = "Thumper (interieur)",
				Kind = ProductKind.Monster,
				Price = 120,
				CooldownSeconds = 30,
				EnemyType = "Crawler"
			},
			new ProductDefinition
			{
				Id = "dog",
				Name = "Eyeless dog (exterieur)",
				Kind = ProductKind.Monster,
				Price = 180,
				CooldownSeconds = 45,
				EnemyType = "MouthDog",
				Outside = true
			},
			new ProductDefinition
			{
				Id = "stamina",
				Name = "Stamina permanente",
				Kind = ProductKind.PermanentStamina,
				Price = 80,
				CooldownSeconds = 10,
				Magnitude = 1.2f,
				LimitPerRound = 2
			},
			new ProductDefinition
			{
				Id = "boost",
				Name = "Stamina temporaire",
				Kind = ProductKind.TemporaryStamina,
				Price = 40,
				DurationSeconds = 60,
				CooldownSeconds = 60,
				Magnitude = 1.5f
			},
			new ProductDefinition
			{
				Id = "revive",
				Name = "Reanimation",
				Kind = ProductKind.Revive,
				Price = 200,
				CooldownSeconds = 60,
				LimitPerRound = 2
			},
			DefaultTeleporterUpgrade()
		};

		private static ProductDefinition DefaultTeleporterUpgrade()
		{
			return new ProductDefinition
			{
				Id = "teleporter",
				Name = "Teleporter avec inventaire",
				Kind = ProductKind.TeleporterRetention,
				Price = 300,
				LimitPerRound = 1
			};
		}

		[OnDeserialized]
		private void RestoreDefaultTeleporterUpgrade(StreamingContext context)
		{
			if (!Products.Any((ProductDefinition p) => p.Kind == ProductKind.TeleporterRetention || p.Id == "teleporter"))
			{
				Products.Add(DefaultTeleporterUpgrade());
			}
		}

		public void Validate()
		{
			int playersPerTeam = PlayersPerTeam;
			if ((playersPerTeam < 2 || playersPerTeam > 4) ? true : false)
			{
				throw new ArgumentException("PlayersPerTeam must be between two and four (one demon and the remaining crewmates).");
			}
			if (PointsPerKill < 0 || DeathPenalty < 0 || MaximumOfferingValue <= 0 || MaximumNaturalSpawnsPerRound <= 0 || MaximumPurchasesPerRound <= 0)
			{
				throw new ArgumentException("Score coefficients and limits must be valid nonnegative values.");
			}
			if (Moons.Any((int id) => id < 0) || Moons.Distinct().Count() != Moons.Count || Selection.Count == 0 || Selection.Last().Action != "pick" || Selection.Count((SelectionStep step) => step.Action == "pick") != 1 || Selection.Any((SelectionStep step) => (step.Team != "A" && step.Team != "B") || (step.Action != "ban" && step.Action != "pick")) || Moons.Count < Selection.Count + 2)
			{
				throw new ArgumentException("Selection requires enough unique moons for three rounds and a final single pick.");
			}
			if (Products.Select((ProductDefinition product) => product.Id).Distinct().Count() != Products.Count || Products.Any((ProductDefinition p) => string.IsNullOrWhiteSpace(p.Id) || p.Price < 0 || p.CooldownSeconds < 0 || p.DurationSeconds < 0 || p.LimitPerRound <= 0 || float.IsNaN(p.Magnitude) || float.IsInfinity(p.Magnitude) || p.Magnitude < 1f || (p.Kind == ProductKind.Monster && string.IsNullOrWhiteSpace(p.EnemyType)) || (p.Kind == ProductKind.TemporaryStamina && p.DurationSeconds == 0)))
			{
				throw new ArgumentException("Invalid shop configuration.");
			}
		}
	}
	public sealed class RuleViolation : Exception
	{
		public RuleViolation(string message)
			: base(message)
		{
		}
	}
	public sealed class MatchEngine
	{
		public MatchState State { get; private set; }

		public MatchEngine(string matchId, MatchOptions options)
		{
			options.Validate();
			if (string.IsNullOrWhiteSpace(matchId))
			{
				throw new ArgumentException("Match ID is required.");
			}
			State = new MatchState
			{
				MatchId = matchId,
				Options = Wire.Clone(options),
				Teams = new Dictionary<string, TeamState>
				{
					["A"] = new TeamState
					{
						Id = "A"
					},
					["B"] = new TeamState
					{
						Id = "B"
					}
				}
			};
		}

		public MatchEngine(MatchState state)
		{
			if (state.SchemaVersion != 1 || state.Teams.Count != 2 || !state.Teams.ContainsKey("A") || !state.Teams.ContainsKey("B"))
			{
				throw new ArgumentException("Unsupported or invalid persisted match.");
			}
			state.Options.Validate();
			State = Wire.Clone(state);
		}

		public Receipt Apply(string teamId, ClientMessage message, DateTimeOffset now)
		{
			Require(State.Teams.ContainsKey(teamId), "Unknown team.");
			Require(ProtocolInfo.IsSupported(message.Protocol), "Protocol mismatch.");
			Require(message.MatchId == State.MatchId, "Match mismatch.");
			int length = message.EventId.Length;
			int condition;
			if (length > 0 && length <= 128)
			{
				length = message.InstanceId.Length;
				condition = ((length > 0 && length <= 128) ? 1 : 0);
			}
			else
			{
				condition = 0;
			}
			Require((byte)condition != 0, "Invalid event or instance identifier.");
			TeamState teamState = State.Teams[teamId];
			Require(teamState.InstanceId.Length == 0 || teamState.InstanceId == message.InstanceId, "Instance identity changed; restore the original host journal.");
			string text = ManifestHash.Of(Wire.Encode(message));
			string key = teamId + ":" + message.EventId;
			if (State.Receipts.TryGetValue(key, out Receipt value))
			{
				Require(value.Fingerprint == text, "Event ID reused with a different payload.");
				return value;
			}
			Require(message.Sequence == teamState.LastSequence + 1, "Sequence gap or replay with a different event ID.");
			Require(State.Receipts.Count < 100000, "Event journal limit reached.");
			MatchState state = Wire.Clone(State);
			Receipt receipt = new Receipt
			{
				Fingerprint = text,
				Sequence = message.Sequence,
				Accepted = true
			};
			try
			{
				Execute(teamId, message, now);
				State.History.Add(new LedgerEvent
				{
					Id = message.EventId,
					Team = teamId,
					Round = message.Round,
					Kind = message.Kind,
					At = now,
					Detail = ((message.Kind == CommandKind.Purchase) ? message.Body.ProductId : message.Body.ReferenceId)
				});
			}
			catch (RuleViolation ruleViolation)
			{
				State = state;
				receipt.Accepted = false;
				receipt.Error = ruleViolation.Message;
			}
			catch
			{
				State = state;
				throw;
			}
			State.Teams[teamId].InstanceId = message.InstanceId;
			State.Teams[teamId].LastSequence = message.Sequence;
			State.Receipts.Add(key, receipt);
			return receipt;
		}

		private void Execute(string id, ClientMessage message, DateTimeOffset now)
		{
			TeamState teamState = State.Teams[id];
			CommandBody body = message.Body;
			if (message.Kind == CommandKind.Fault)
			{
				State.Phase = MatchPhase.Faulted;
				return;
			}
			if (message.Kind == CommandKind.Roster)
			{
				Require(State.Phase == MatchPhase.Lobby, "Roster is locked after readiness.");
				int count = body.Players.Count;
				Require(count > 0 && count <= 4 && body.Players.Select((PlayerInfo p) => p.Id).Distinct().Count() == body.Players.Count && body.Players.All((PlayerInfo p) => p.Name.Length <= 80), "Invalid roster.");
				Require(body.Players.Any((PlayerInfo p) => p.Id == body.Demon), "Demon must belong to the roster.");
				Require(!string.IsNullOrWhiteSpace(body.Fingerprint) && body.Fingerprint.Length <= 128, "Missing installation fingerprint.");
				teamState.Players = Wire.Clone(body.Players);
				teamState.Demon = body.Demon;
				teamState.Fingerprint = body.Fingerprint;
				teamState.Ready = false;
				return;
			}
			Require(teamState.Players.Count > 0, "Register the roster first.");
			if (message.Kind == CommandKind.Ready)
			{
				Require(State.Phase == MatchPhase.Lobby && body.Actor == teamState.Demon, "Only the demon can ready a lobby.");
				Require(State.Options.AllowSoloDevelopment || teamState.Players.Count == State.Options.PlayersPerTeam, $"Exactly {State.Options.PlayersPerTeam} players per team are required (one demon, the others crewmates).");
				TeamState teamState2 = State.Teams[Other(id)];
				Require(teamState2.Fingerprint.Length == 0 || teamState2.Fingerprint == teamState.Fingerprint, "The two game/mod installations differ.");
				teamState.Ready = true;
				if (State.Teams.Values.All((TeamState t) => t.Ready))
				{
					State.Phase = MatchPhase.Selection;
				}
				return;
			}
			Require(message.Round == State.Round, "Stale round.");
			if (message.Kind == CommandKind.SelectMoon)
			{
				Require(State.Phase == MatchPhase.Selection && body.Actor == teamState.Demon, "Moon selection is not allowed.");
				SelectionStep selectionStep = State.Options.Selection[State.SelectionIndex];
				Require(selectionStep.Team == id, "It is not your selection turn.");
				Require(AvailableMoons().Contains(body.Moon), "Moon is banned, played or unavailable.");
				if (selectionStep.Action == "ban")
				{
					State.BannedMoons.Add(body.Moon);
				}
				else
				{
					State.PlayedMoons.Add(body.Moon);
					string text = ManifestHash.Of(State.MatchId + ":" + State.Round);
					State.Rounds.Add(new RoundState
					{
						Number = State.Round,
						Moon = body.Moon,
						Seed = (int)(Convert.ToUInt32(text.Substring(0, 8), 16) % 99999999 + 1)
					});
					State.Phase = MatchPhase.Loading;
				}
				State.SelectionIndex++;
				return;
			}
			RoundState roundState = CurrentRound();
			switch (message.Kind)
			{
			case CommandKind.HostPrepared:
				Require(State.Phase == MatchPhase.Loading && !roundState.Launched, "Round is not awaiting preparation.");
				teamState.Prepared = true;
				break;
			case CommandKind.RequestLaunch:
				Require(body.Actor == teamState.Demon && State.Phase == MatchPhase.Loading && !roundState.Launched, "Launch is not allowed.");
				Require(State.Teams.Values.All((TeamState t) => t.Prepared), "Both hosts must finish preparing.");
				roundState.Launched = true;
				{
					foreach (string key2 in State.Teams.Keys)
					{
						AddDelivery(key2, DeliveryKind.Launch, message.EventId);
					}
					break;
				}
			case CommandKind.Generation:
			{
				Require(id == "A" && State.Phase == MatchPhase.Loading && roundState.Launched && roundState.Manifest == null, "Only the reference can publish generation once.");
				GenerationManifest manifest = body.Manifest;
				Require(manifest != null, "Generation manifest missing.");
				ValidateManifest(manifest, roundState);
				roundState.Manifest = Wire.Clone(manifest);
				teamState.VerifiedGeneration = true;
				AddDelivery("B", DeliveryKind.Generation, message.EventId).Manifest = Wire.Clone(manifest);
				break;
			}
			case CommandKind.GenerationAccepted:
				Require(id == "B" && State.Phase == MatchPhase.Loading && roundState.Manifest != null, "Generation verification is not expected.");
				Require(body.Checksum == roundState.Manifest.Checksum, "Generation checksum mismatch; round remains blocked.");
				teamState.VerifiedGeneration = true;
				State.Phase = MatchPhase.Playing;
				break;
			case CommandKind.OfferPrepare:
			{
				RequirePlayable(teamState);
				Require(body.Actor != teamState.Demon && teamState.Players.Any((PlayerInfo p) => p.Id == body.Actor), "Only a crewmate can offer scrap.");
				int count = body.ItemId.Length;
				Require(count > 0 && count <= 180 && body.Value > 0 && body.Value <= State.Options.MaximumOfferingValue, "Invalid offering.");
				string key = OfferingKey(id, body.ItemId);
				Require(!State.Offerings.ContainsKey(key), "This item is already reserved or consumed.");
				State.Offerings.Add(key, new OfferingState
				{
					Id = message.EventId,
					Team = id,
					Round = State.Round,
					ItemId = body.ItemId,
					Value = body.Value
				});
				Delivery delivery2 = AddDelivery(id, DeliveryKind.ConsumeOffering, message.EventId);
				delivery2.ItemId = body.ItemId;
				break;
			}
			case CommandKind.OfferConsumed:
			case CommandKind.OfferCancelled:
			{
				OfferingState offeringState = State.Offerings.Values.SingleOrDefault((OfferingState o) => o.Id == body.ReferenceId && o.Team == id && o.Round == State.Round);
				Require(offeringState != null && !offeringState.Cancelled, "Unknown or cancelled offering reservation.");
				checked
				{
					if (!offeringState.Consumed)
					{
						if (message.Kind == CommandKind.OfferCancelled)
						{
							offeringState.Cancelled = true;
						}
						else
						{
							offeringState.Consumed = true;
							teamState.Credits += offeringState.Value;
							roundState.Scores[id].Offerings = roundState.Scores[id].Offerings + offeringState.Value;
						}
						State.Deliveries.RemoveAll((Delivery d) => d.Team == id && d.Kind == DeliveryKind.ConsumeOffering && d.ReferenceId == body.ReferenceId);
					}
					break;
				}
			}
			case CommandKind.Purchase:
			{
				RequirePlayable(teamState);
				Require(body.Actor == teamState.Demon, "Only the demon can buy.");
				ProductDefinition product = State.Options.Products.SingleOrDefault((ProductDefinition p) => p.Id == body.ProductId);
				Require(product != null, "Unknown product.");
				bool flag = product.Kind == ProductKind.TeleporterRetention;
				Require(!flag || !teamState.TeleporterRetention, "Teleporter upgrade already owned.");
				Require(teamState.Credits >= product.Price, "Insufficient credits.");
				Require(teamState.Purchases.Count((PurchaseRecord p) => p.Round == State.Round) < State.Options.MaximumPurchasesPerRound, "Round purchase limit reached.");
				Require(teamState.Purchases.Count((PurchaseRecord p) => p.Round == State.Round && p.ProductId == product.Id) < product.LimitPerRound, "Product round limit reached.");
				PurchaseRecord purchaseRecord = teamState.Purchases.LastOrDefault((PurchaseRecord p) => p.ProductId == product.Id);
				Require(purchaseRecord == null || (now - purchaseRecord.At).TotalSeconds >= (double)product.CooldownSeconds, "Product cooldown active.");
				if (!flag && product.Kind != ProductKind.Monster)
				{
					Require(body.Target != teamState.Demon && teamState.Players.Any((PlayerInfo p) => p.Id == body.Target), "Choose an allied crewmate.");
					Require((product.Kind == ProductKind.Revive) ? teamState.DeadPlayers.Contains(body.Target) : (!teamState.DeadPlayers.Contains(body.Target)), "Target is not in the required life state.");
				}
				teamState.Credits -= product.Price;
				teamState.Purchases.Add(new PurchaseRecord
				{
					Id = message.EventId,
					ProductId = product.Id,
					Price = product.Price,
					Round = State.Round,
					Target = (flag ? 0 : body.Target),
					At = now
				});
				if (flag)
				{
					teamState.TeleporterRetention = true;
					break;
				}
				string text2 = ((product.Kind == ProductKind.Monster) ? Other(id) : id);
				Delivery delivery = AddDelivery(text2, (product.Kind == ProductKind.Monster) ? DeliveryKind.SpawnEnemy : DeliveryKind.ApplyUpgrade, message.EventId);
				delivery.Product = Wire.Clone(product);
				delivery.Target = body.Target;
				if (product.Kind == ProductKind.Monster)
				{
					SpawnEvent spawnEvent = (delivery.Spawn = new SpawnEvent
					{
						Id = message.EventId,
						Origin = SpawnOrigin.Demon,
						ResponsibleTeam = id,
						EnemyType = product.EnemyType,
						Outside = product.Outside
					});
					roundState.Enemies.Add(spawnEvent.Id, Wire.Clone(spawnEvent));
				}
				else if (product.Kind != ProductKind.Revive)
				{
					teamState.Upgrades.Add(new UpgradeState
					{
						PurchaseId = message.EventId,
						Kind = product.Kind,
						Target = body.Target,
						Magnitude = product.Magnitude,
						Round = State.Round,
						Expires = ((product.Kind == ProductKind.TemporaryStamina) ? new DateTimeOffset?(now.AddSeconds(product.DurationSeconds)) : ((DateTimeOffset?)null))
					});
				}
				if (product.Kind == ProductKind.Monster && State.Teams[text2].FinishedRound)
				{
					State.Deliveries.Remove(delivery);
				}
				break;
			}
			case CommandKind.Death:
			{
				Require(State.Phase == MatchPhase.Playing && !teamState.FinishedRound, "Death outside an active round.");
				Require(body.Target != teamState.Demon && teamState.Players.Any((PlayerInfo p) => p.Id == body.Target), "Victim must be an allied crewmate.");
				int count = body.DeathId.Length;
				Require(count > 0 && count <= 180, "Missing life/death identifier.");
				Require(!teamState.Deaths.Contains(body.DeathId) && !teamState.DeadPlayers.Contains(body.Target), "Death already counted.");
				teamState.Deaths.Add(body.DeathId);
				teamState.DeadPlayers.Add(body.Target);
				roundState.Scores[id].Deaths++;
				if (body.DirectEnemyKill && roundState.Enemies.TryGetValue(body.EnemyId, out SpawnEvent value) && value.Origin == SpawnOrigin.Demon && value.ResponsibleTeam == Other(id))
				{
					roundState.Scores[value.ResponsibleTeam].Kills++;
				}
				break;
			}
			case CommandKind.NaturalSpawn:
				Require(id == "A" && roundState.Launched && (State.Phase == MatchPhase.Loading || State.Phase == MatchPhase.Playing), "Only the reference can publish natural spawns.");
				Require(body.Spawn != null && body.Spawn.Origin == SpawnOrigin.Natural && body.Spawn.ResponsibleTeam.Length == 0, "Invalid natural origin.");
				ValidateSpawn(body.Spawn);
				Require(roundState.Enemies.Values.Count((SpawnEvent e) => e.Origin == SpawnOrigin.Natural) < State.Options.MaximumNaturalSpawnsPerRound, "Natural spawn limit reached.");
				Require(!roundState.Enemies.ContainsKey(body.Spawn.Id), "Spawn already registered.");
				roundState.Enemies.Add(body.Spawn.Id, Wire.Clone(body.Spawn));
				if (!State.Teams["B"].FinishedRound)
				{
					AddDelivery("B", DeliveryKind.NaturalSpawn, message.EventId).Spawn = Wire.Clone(body.Spawn);
				}
				break;
			case CommandKind.DeliveryApplied:
			{
				Delivery delivery3 = State.Deliveries.SingleOrDefault((Delivery d) => d.Id == body.ReferenceId && d.Team == id);
				if (delivery3 == null)
				{
					break;
				}
				Require(delivery3.Kind != DeliveryKind.ConsumeOffering, "Offering requires a consumption receipt.");
				if (delivery3.Kind == DeliveryKind.ApplyUpgrade)
				{
					ProductDefinition? product2 = delivery3.Product;
					if (product2 != null && product2.Kind == ProductKind.Revive)
					{
						teamState.DeadPlayers.Remove(delivery3.Target);
					}
				}
				State.Deliveries.Remove(delivery3);
				break;
			}
			case CommandKind.RoundFinished:
				Require(State.Phase == MatchPhase.Playing, "Round is not active.");
				Require(!State.Offerings.Values.Any((OfferingState o) => o.Team == id && o.Round == State.Round && !o.Consumed && !o.Cancelled), "Wait for pending offering receipts before ending the round.");
				Require(!double.IsNaN(body.RoundTime) && !double.IsInfinity(body.RoundTime) && body.RoundTime >= 0.0, "Invalid round end time.");
				roundState.EndTimes[id] = body.RoundTime;
				teamState.FinishedRound = true;
				State.Deliveries.RemoveAll((Delivery d) => d.Team == id && d.Kind != DeliveryKind.ConsumeOffering);
				if (State.Teams.Values.All((TeamState t) => t.FinishedRound))
				{
					AdvanceRound();
				}
				break;
			default:
				throw new RuleViolation("Unsupported command.");
			}
		}

		public TeamView View(string id, DateTimeOffset now)
		{
			TeamState teamState = State.Teams[id];
			RoundState roundState = State.Rounds.LastOrDefault();
			SelectionStep selectionStep = ((State.Phase == MatchPhase.Selection) ? State.Options.Selection[State.SelectionIndex] : null);
			long num = State.Rounds.Sum((RoundState r) => r.Scores[id].Offerings);
			return new TeamView
			{
				MatchId = State.MatchId,
				Team = id,
				Phase = State.Phase,
				Round = State.Round,
				FinishedOwnRound = teamState.FinishedRound,
				GenerationVerified = State.Teams.Values.All((TeamState t) => t.VerifiedGeneration),
				CanLaunch = (State.Phase == MatchPhase.Loading && roundState != null && !roundState.Launched && State.Teams.Values.All((TeamState t) => t.Prepared)),
				Moon = ((State.Phase == MatchPhase.Selection) ? (-1) : (roundState?.Moon ?? (-1))),
				Seed = (roundState?.Seed ?? 0),
				Demon = teamState.Demon,
				Players = Wire.Clone(teamState.Players),
				Credits = teamState.Credits,
				TeleporterRetention = teamState.TeleporterRetention,
				OfferingTotal = num,
				VisibleScore = num - State.Rounds.Sum((RoundState r) => (long)State.Options.DeathPenalty * (long)r.Scores[id].Deaths),
				SelectionTeam = (selectionStep?.Team ?? ""),
				SelectionAction = (selectionStep?.Action ?? ""),
				AvailableMoons = AvailableMoons(),
				Shop = Wire.Clone(State.Options.Products),
				Purchases = Wire.Clone(teamState.Purchases),
				Upgrades = Wire.Clone(teamState.Upgrades.Where((UpgradeState u) => !u.Expires.HasValue || u.Expires > now).ToList()),
				Results = ((State.Phase != MatchPhase.Finished) ? null : (from teamId in State.Teams.Keys
					select new TeamResult
					{
						Team = teamId,
						Score = State.Rounds.Sum((RoundState r) => r.Scores[teamId].Total(State.Options)),
						Rounds = State.Rounds.Select((RoundState r) => Wire.Clone(r.Scores[teamId])).ToList()
					} into result
					orderby result.Score descending
					select result).ToList())
			};
		}

		public List<Delivery> Pending(string id)
		{
			return Wire.Clone(State.Deliveries.Where((Delivery d) => d.Team == id && d.Round == State.Round).ToList());
		}

		private void AdvanceRound()
		{
			State.Deliveries.Clear();
			if (State.Round == 3)
			{
				State.Phase = MatchPhase.Finished;
				return;
			}
			State.Round++;
			State.SelectionIndex = 0;
			State.BannedMoons.Clear();
			foreach (TeamState value in State.Teams.Values)
			{
				bool flag = (value.VerifiedGeneration = false);
				bool prepared = (value.FinishedRound = flag);
				value.Prepared = prepared;
				value.DeadPlayers.Clear();
				value.Upgrades.RemoveAll((UpgradeState upgrade) => upgrade.Kind != ProductKind.PermanentStamina);
			}
			State.Phase = MatchPhase.Selection;
		}

		private void RequirePlayable(TeamState team)
		{
			Require(State.Phase == MatchPhase.Playing && !team.FinishedRound, "Your round is not active.");
		}

		private RoundState CurrentRound()
		{
			return State.Rounds.LastOrDefault((RoundState r) => r.Number == State.Round) ?? throw new RuleViolation("No moon selected.");
		}

		private List<int> AvailableMoons()
		{
			return State.Options.Moons.Except(State.PlayedMoons).Except(State.BannedMoons).ToList();
		}

		private static string OfferingKey(string team, string item)
		{
			return team + ":" + item;
		}

		private Delivery AddDelivery(string team, DeliveryKind kind, string reference)
		{
			Delivery delivery = new Delivery
			{
				Team = team,
				Kind = kind,
				Round = State.Round,
				ReferenceId = reference
			};
			State.Deliveries.Add(delivery);
			return delivery;
		}

		private void ValidateManifest(GenerationManifest manifest, RoundState round)
		{
			Require(manifest.Moon == round.Moon && manifest.Seed == round.Seed && manifest.Dungeon >= 0 && manifest.GeometryChecksum.Length == 64, "Manifest generation parameters differ.");
			Require(manifest.Scrap.Count <= 2000 && manifest.Scrap.All(delegate(ScrapEntry i)
			{
				int length = i.Id.Length;
				return length > 0 && length <= 128 && i.ItemType >= 0 && i.Value >= 0 && i.Value <= State.Options.MaximumOfferingValue && Finite(i.Position) && Finite(i.Rotation) && ValidOrientation(i.Orientation);
			}) && manifest.Scrap.Select((ScrapEntry i) => i.Id).Distinct().Count() == manifest.Scrap.Count, "Invalid scrap manifest.");
			Require(manifest.Hazards.Count <= 1000 && manifest.Hazards.All((HazardEntry h) => h.Prefab >= 0 && h.TerminalCode.Length <= 32 && Finite(h.Position) && Finite(h.Rotation) && ValidOrientation(h.Orientation)), "Invalid hazard manifest.");
			Require(manifest.Checksum == ManifestHash.Compute(manifest), "Manifest checksum is invalid.");
		}

		private static void ValidateSpawn(SpawnEvent spawn)
		{
			int length = spawn.Id.Length;
			int condition;
			if (length > 0 && length <= 128)
			{
				length = spawn.EnemyType.Length;
				if (length > 0 && length <= 128 && Finite(spawn.Position) && !double.IsNaN(spawn.RoundTime) && !double.IsInfinity(spawn.RoundTime) && spawn.RoundTime >= 0.0 && !float.IsNaN(spawn.RotationY))
				{
					condition = ((!float.IsInfinity(spawn.RotationY)) ? 1 : 0);
					goto IL_0086;
				}
			}
			condition = 0;
			goto IL_0086;
			IL_0086:
			Require((byte)condition != 0, "Invalid spawn parameters.");
		}

		private static bool Finite(Vec3 vector)
		{
			return new float[3] { vector.X, vector.Y, vector.Z }.All((float v) => !float.IsNaN(v) && !float.IsInfinity(v) && Math.Abs(v) < 100000f);
		}

		private static bool ValidOrientation(Rotation4? value)
		{
			if (value != null)
			{
				if (new float[4] { value.X, value.Y, value.Z, value.W }.All((float v) => !float.IsNaN(v) && !float.IsInfinity(v) && Math.Abs(v) <= 1.001f))
				{
					return Math.Abs(value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W - 1f) < 0.001f;
				}
				return false;
			}
			return true;
		}

		private static string Other(string id)
		{
			if (!(id == "A"))
			{
				return "A";
			}
			return "B";
		}

		private static void Require(bool condition, string message)
		{
			if (!condition)
			{
				throw new RuleViolation(message);
			}
		}
	}
	public static class ManifestHash
	{
		public static string Of(string value)
		{
			using SHA256 sHA = SHA256.Create();
			return string.Concat(from b in sHA.ComputeHash(Encoding.UTF8.GetBytes(value))
				select b.ToString("x2", CultureInfo.InvariantCulture));
		}

		public static string Compute(GenerationManifest manifest)
		{
			StringBuilder stringBuilder = new StringBuilder().Append(manifest.Moon).Append('|').Append(manifest.Seed)
				.Append('|')
				.Append(manifest.Dungeon)
				.Append('|')
				.Append(manifest.GeometryChecksum);
			foreach (ScrapEntry item in manifest.Scrap.OrderBy<ScrapEntry, string>((ScrapEntry item) => item.Id, StringComparer.Ordinal))
			{
				stringBuilder.Append('\n').Append(item.Id).Append('|')
					.Append(item.ItemType)
					.Append('|')
					.Append(item.Value);
				float[] array = new float[3]
				{
					item.Position.X,
					item.Position.Y,
					item.Position.Z
				};
				foreach (float num2 in array)
				{
					stringBuilder.Append('|').Append(Quantize(num2));
				}
				AppendRotation(stringBuilder, item.Rotation, item.Orientation);
			}
			foreach (HazardEntry hazard in manifest.Hazards)
			{
				stringBuilder.Append("\nhazard|").Append(hazard.Prefab).Append('|')
					.Append(hazard.TerminalCode);
				float[] array2 = new float[3]
				{
					hazard.Position.X,
					hazard.Position.Y,
					hazard.Position.Z
				};
				foreach (float num4 in array2)
				{
					stringBuilder.Append('|').Append(Quantize(num4));
				}
				AppendRotation(stringBuilder, hazard.Rotation, hazard.Orientation);
			}
			return Of(stringBuilder.ToString());
		}

		private static void AppendRotation(StringBuilder text, Vec3 euler, Rotation4? orientation)
		{
			if (orientation == null)
			{
				float[] array = new float[3] { euler.X, euler.Y, euler.Z };
				foreach (float num in array)
				{
					text.Append('|').Append(Quantize(Math.Round(((double)num % 360.0 + 360.0) % 360.0, 3) % 360.0));
				}
				return;
			}
			double[] array2 = new double[4] { orientation.W, orientation.Z, orientation.Y, orientation.X };
			double num2 = Math.Sqrt(array2.Sum((double value) => value * value));
			int num3 = ((!(array2.FirstOrDefault((double value) => Math.Abs(value) > 1E-06) < 0.0)) ? 1 : (-1));
			text.Append("|q");
			double[] array3 = array2;
			foreach (double num5 in array3)
			{
				double num6 = Math.Round(num5 / num2 * (double)num3, 4);
				text.Append('|').Append(((num6 == 0.0) ? 0.0 : num6).ToString("F4", CultureInfo.InvariantCulture));
			}
		}

		private static string Quantize(double value)
		{
			double num = Math.Round(value, 3, MidpointRounding.ToEven);
			return ((num == 0.0) ? 0.0 : num).ToString("F3", CultureInfo.InvariantCulture);
		}
	}
	public sealed class MatchState
	{
		public int SchemaVersion { get; set; } = 1;

		public string MatchId { get; set; } = "";

		public MatchOptions Options { get; set; } = new MatchOptions();

		public MatchPhase Phase { get; set; }

		public int Round { get; set; } = 1;

		public int SelectionIndex { get; set; }

		public List<int> BannedMoons { get; set; } = new List<int>();

		public List<int> PlayedMoons { get; set; } = new List<int>();

		public List<RoundState> Rounds { get; set; } = new List<RoundState>();

		public Dictionary<string, TeamState> Teams { get; set; } = new Dictionary<string, TeamState>();

		public List<Delivery> Deliveries { get; set; } = new List<Delivery>();

		public Dictionary<string, Receipt> Receipts { get; set; } = new Dictionary<string, Receipt>();

		public Dictionary<string, OfferingState> Offerings { get; set; } = new Dictionary<string, OfferingState>();

		public List<LedgerEvent> History { get; set; } = new List<LedgerEvent>();
	}
	public sealed class TeamState
	{
		public string Id { get; set; } = "";

		public string RoomId { get; set; } = "";

		public string InstanceId { get; set; } = "";

		public string Fingerprint { get; set; } = "";

		public List<PlayerInfo> Players { get; set; } = new List<PlayerInfo>();

		public ulong Demon { get; set; }

		public bool Ready { get; set; }

		public bool Prepared { get; set; }

		public bool FinishedRound { get; set; }

		public bool VerifiedGeneration { get; set; }

		public long Credits { get; set; }

		public bool TeleporterRetention { get; set; }

		public long LastSequence { get; set; }

		public HashSet<ulong> DeadPlayers { get; set; } = new HashSet<ulong>();

		public HashSet<string> Deaths { get; set; } = new HashSet<string>();

		public List<PurchaseRecord> Purchases { get; set; } = new List<PurchaseRecord>();

		public List<UpgradeState> Upgrades { get; set; } = new List<UpgradeState>();
	}
	public sealed class RoundState
	{
		public int Number { get; set; }

		public int Moon { get; set; }

		public int Seed { get; set; }

		public GenerationManifest? Manifest { get; set; }

		public Dictionary<string, RoundScore> Scores { get; set; } = new Dictionary<string, RoundScore>
		{
			["A"] = new RoundScore(),
			["B"] = new RoundScore()
		};

		public Dictionary<string, SpawnEvent> Enemies { get; set; } = new Dictionary<string, SpawnEvent>();

		public bool Launched { get; set; }

		public Dictionary<string, double> EndTimes { get; set; } = new Dictionary<string, double>();
	}
	public sealed class RoundScore
	{
		public long Offerings { get; set; }

		public int Kills { get; set; }

		public int Deaths { get; set; }

		public long Total(MatchOptions options)
		{
			checked
			{
				return Offerings + unchecked((long)options.PointsPerKill) * unchecked((long)Kills) - unchecked((long)options.DeathPenalty) * unchecked((long)Deaths);
			}
		}
	}
	public sealed class OfferingState
	{
		public string Id { get; set; } = "";

		public string Team { get; set; } = "";

		public string ItemId { get; set; } = "";

		public int Round { get; set; }

		public int Value { get; set; }

		public bool Consumed { get; set; }

		public bool Cancelled { get; set; }
	}
	public sealed class PurchaseRecord
	{
		public string Id { get; set; } = "";

		public string ProductId { get; set; } = "";

		public int Price { get; set; }

		public int Round { get; set; }

		public ulong Target { get; set; }

		public DateTimeOffset At { get; set; }
	}
	public sealed class UpgradeState
	{
		public string PurchaseId { get; set; } = "";

		public ProductKind Kind { get; set; }

		public ulong Target { get; set; }

		public float Magnitude { get; set; }

		public int Round { get; set; }

		public DateTimeOffset? Expires { get; set; }
	}
	public sealed class Receipt
	{
		public string Fingerprint { get; set; } = "";

		public long Sequence { get; set; }

		public bool Accepted { get; set; }

		public string Error { get; set; } = "";
	}
	public sealed class LedgerEvent
	{
		public string Id { get; set; } = "";

		public string Team { get; set; } = "";

		public int Round { get; set; }

		public CommandKind Kind { get; set; }

		public DateTimeOffset At { get; set; }

		public string Detail { get; set; } = "";
	}
	public sealed class TeamResult
	{
		public string Team { get; set; } = "";

		public long Score { get; set; }

		public List<RoundScore> Rounds { get; set; } = new List<RoundScore>();
	}
	public static class ProtocolInfo
	{
		public const int CurrentVersion = 1;

		public static bool IsSupported(int version)
		{
			return version == 1;
		}
	}
}
namespace DemonCompany.Shared.Networking
{
	public sealed class HostJournal
	{
		public string MatchId { get; set; } = "";

		public string InstanceId { get; set; } = Guid.NewGuid().ToString("N");

		public long NextSequence { get; set; } = 1L;

		public long LastAck { get; set; }

		public List<ClientMessage> Outbox { get; set; } = new List<ClientMessage>();

		public HashSet<string> IssuedEvents { get; set; } = new HashSet<string>();

		public HashSet<string> AppliedDeliveries { get; set; } = new HashSet<string>();

		public HashSet<string> ConsumedItems { get; set; } = new HashSet<string>();
	}
	public sealed class ReliableHostClient : IDisposable
	{
		private readonly object _gate = new object();

		private readonly string _path;

		private readonly Uri _address;

		private readonly string _token;

		private readonly Action<string> _log;

		private readonly CancellationTokenSource _stop = new CancellationTokenSource();

		private readonly HostJournal _journal;

		private Task? _worker;

		public ConcurrentQueue<ServerFrame> Frames { get; } = new ConcurrentQueue<ServerFrame>();

		public bool Connected { get; private set; }

		public string LastError { get; private set; } = "";

		public int PendingCount
		{
			get
			{
				lock (_gate)
				{
					return _journal.Outbox.Count;
				}
			}
		}

		public ReliableHostClient(Uri address, string token, string matchId, string journalPath, Action<string> log, string? roomId = null)
		{
			if (address.Scheme != "ws" && address.Scheme != "wss")
			{
				throw new ArgumentException("A ws:// or wss:// coordinator URL is required.");
			}
			if (matchId.Length == 0 || (roomId == null && token.Length < 32))
			{
				throw new ArgumentException("Configure the match ID and team token.");
			}
			if (roomId != null && !Guid.TryParseExact(roomId, "N", out var _))
			{
				throw new ArgumentException("Invalid room identity.");
			}
			_address = ((roomId == null) ? address : new UriBuilder(address)
			{
				Query = "roomId=" + roomId
			}.Uri);
			_token = token;
			_path = Path.GetFullPath(journalPath);
			_log = log;
			_journal = (File.Exists(_path) ? Wire.Decode<HostJournal>(File.ReadAllText(_path)) : new HostJournal
			{
				MatchId = matchId
			});
			if (_journal.MatchId != matchId)
			{
				throw new InvalidDataException("Host journal belongs to another match.");
			}
			Save();
		}

		public void Start()
		{
			if (_worker == null)
			{
				_worker = Task.Run((Func<Task?>)RunAsync);
			}
		}

		public string Enqueue(int round, CommandKind kind, CommandBody body, string? eventId = null)
		{
			lock (_gate)
			{
				if (eventId == null)
				{
					eventId = Guid.NewGuid().ToString("N");
				}
				if (_journal.IssuedEvents.Contains(eventId))
				{
					return eventId;
				}
				if (_journal.Outbox.Count >= 5000 || _journal.IssuedEvents.Count >= 100000)
				{
					throw new InvalidOperationException("Host journal limit reached; resolve the connection before continuing.");
				}
				ClientMessage item = new ClientMessage
				{
					MatchId = _journal.MatchId,
					InstanceId = _journal.InstanceId,
					EventId = eventId,
					Sequence = _journal.NextSequence++,
					Round = round,
					Kind = kind,
					Body = Wire.Clone(body)
				};
				_journal.Outbox.Add(item);
				_journal.IssuedEvents.Add(eventId);
				Save();
				return eventId;
			}
		}

		public bool WasApplied(string id)
		{
			lock (_gate)
			{
				return _journal.AppliedDeliveries.Contains(id);
			}
		}

		public bool WasConsumed(string id)
		{
			lock (_gate)
			{
				return _journal.ConsumedItems.Contains(id);
			}
		}

		public void MarkApplied(string id, string? consumedItem = null)
		{
			lock (_gate)
			{
				_journal.AppliedDeliveries.Add(id);
				if (consumedItem != null)
				{
					_journal.ConsumedItems.Add(consumedItem);
				}
				Save();
			}
		}

		private void Save()
		{
			Directory.CreateDirectory(Path.GetDirectoryName(_path));
			string text = _path + ".tmp";
			byte[] bytes = Encoding.UTF8.GetBytes(Wire.Encode(_journal));
			using (FileStream fileStream = new FileStream(text, FileMode.Create, FileAccess.Write, FileShare.None))
			{
				fileStream.Write(bytes, 0, bytes.Length);
				fileStream.Flush(flushToDisk: true);
			}
			int num = 0;
			while (true)
			{
				try
				{
					if (File.Exists(_path))
					{
						File.Replace(text, _path, null);
					}
					else
					{
						File.Move(text, _path);
					}
					break;
				}
				catch (IOException) when (num < 4 && File.Exists(text))
				{
					Thread.Sleep(20 << num);
				}
				num++;
			}
		}

		private async Task RunAsync()
		{
			int delay = 1;
			while (!_stop.IsCancellationRequested)
			{
				try
				{
					using ClientWebSocket socket = new ClientWebSocket();
					if (_token.Length > 0)
					{
						socket.Options.SetRequestHeader("Authorization", "Bearer " + _token);
					}
					socket.Options.KeepAliveInterval = TimeSpan.FromSeconds(5.0);
					using CancellationTokenSource connect = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken[1] { _stop.Token });
					connect.CancelAfter(TimeSpan.FromSeconds(10.0));
					await socket.ConnectAsync(_address, connect.Token).ConfigureAwait(continueOnCapturedContext: false);
					Connected = true;
					delay = 1;
					LastError = "";
					_log("Coordinator connected.");
					await SessionAsync(socket, _stop.Token).ConfigureAwait(continueOnCapturedContext: false);
				}
				catch (OperationCanceledException) when (_stop.IsCancellationRequested)
				{
					break;
				}
				catch (Exception ex2)
				{
					LastError = ex2.Message;
					_log("Coordinator connection interrupted: " + ex2.GetType().Name + ": " + ex2.Message);
				}
				finally
				{
					Connected = false;
				}
				try
				{
					await Task.Delay(TimeSpan.FromSeconds(delay), _stop.Token).ConfigureAwait(continueOnCapturedContext: false);
				}
				catch (OperationCanceledException) when (_stop.IsCancellationRequested)
				{
					break;
				}
				delay = Math.Min(delay * 2, 10);
			}
		}

		private async Task SessionAsync(ClientWebSocket socket, CancellationToken token)
		{
			using CancellationTokenSource session = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken[1] { token });
			Task<string?> receive = WebSocketWire.ReceiveAsync(socket, session.Token);
			DateTimeOffset lastReceive = DateTimeOffset.UtcNow;
			DateTimeOffset lastSend = DateTimeOffset.MinValue;
			bool ready = false;
			long lastSentSequence = -1L;
			try
			{
				while (!token.IsCancellationRequested && socket.State == WebSocketState.Open)
				{
					if ((DateTimeOffset.UtcNow - lastReceive).TotalSeconds > 15.0)
					{
						throw new TimeoutException("Coordinator heartbeat expired.");
					}
					if (receive.IsCompleted)
					{
						string text = await receive.ConfigureAwait(continueOnCapturedContext: false);
						if (text == null)
						{
							return;
						}
						ServerFrame frame = Wire.Decode<ServerFrame>(text);
						if (!ProtocolInfo.IsSupported(frame.Protocol))
						{
							throw new InvalidDataException("Coordinator protocol mismatch.");
						}
						lock (_gate)
						{
							if (frame.AckSequence < _journal.LastAck || frame.AckSequence >= _journal.NextSequence)
							{
								throw new InvalidDataException("Coordinator and host journal sequences diverged; automatic replay is blocked.");
							}
							if (!frame.Accepted)
							{
								_log("Command " + frame.EventId + " rejected: " + frame.Error);
							}
							if (frame.AckSequence > _journal.LastAck)
							{
								_journal.LastAck = frame.AckSequence;
								_journal.Outbox.RemoveAll((ClientMessage message) => message.Sequence <= frame.AckSequence);
								Save();
							}
						}
						if (Frames.Count >= 512)
						{
							throw new InvalidDataException("Unity main thread is not consuming coordinator frames.");
						}
						Frames.Enqueue(frame);
						lastReceive = DateTimeOffset.UtcNow;
						ready = true;
						receive = WebSocketWire.ReceiveAsync(socket, session.Token);
					}
					if (ready)
					{
						ClientMessage next;
						lock (_gate)
						{
							next = _journal.Outbox.FirstOrDefault();
						}
						if ((next != null && (next.Sequence != lastSentSequence || (DateTimeOffset.UtcNow - lastSend).TotalSeconds > 3.0)) || (DateTimeOffset.UtcNow - lastSend).TotalSeconds > 5.0)
						{
							await WebSocketWire.SendAsync(socket, (next == null) ? "ping" : Wire.Encode(next), token).ConfigureAwait(continueOnCapturedContext: false);
							lastSentSequence = next?.Sequence ?? (-1);
							lastSend = DateTimeOffset.UtcNow;
						}
						next = null;
					}
					await Task.WhenAny(new Task[2]
					{
						receive,
						Task.Delay(100, token)
					}).ConfigureAwait(continueOnCapturedContext: false);
				}
			}
			finally
			{
				session.Cancel();
				socket.Abort();
				try
				{
					await receive.ConfigureAwait(continueOnCapturedContext: false);
				}
				catch (Exception ex) when (((ex is OperationCanceledException || ex is WebSocketException || ex is IOException) ? 1 : 0) != 0)
				{
					_log("Coordinator receive stopped: " + ex.GetType().Name);
				}
			}
		}

		public void Dispose()
		{
			_stop.Cancel();
			if (_worker != null)
			{
				_worker.ContinueWith(delegate(Task task)
				{
					_log("Host worker failed: " + task.Exception);
				}, TaskContinuationOptions.OnlyOnFaulted);
			}
		}
	}
	public static class TrustDiscovery
	{
		public static async Task<TrustSession> JoinAsync(Uri coordinator, string roomId, CancellationToken token)
		{
			if (coordinator.Scheme != "ws" && coordinator.Scheme != "wss")
			{
				throw new ArgumentException("A ws:// or wss:// coordinator URL is required.");
			}
			if (!Guid.TryParseExact(roomId, "N", out var _))
			{
				throw new ArgumentException("Invalid room identity.");
			}
			UriBuilder uriBuilder = new UriBuilder(coordinator)
			{
				Scheme = ((coordinator.Scheme == "wss") ? "https" : "http")
			};
			uriBuilder.Path = uriBuilder.Path.TrimEnd('/') + "/trust/rooms/" + roomId;
			using HttpClient http = new HttpClient
			{
				Timeout = TimeSpan.FromSeconds(10.0)
			};
			using HttpResponseMessage response = await http.PostAsync(uriBuilder.Uri, new StringContent(""), token).ConfigureAwait(continueOnCapturedContext: false);
			string text = await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false);
			if (!response.IsSuccessStatusCode)
			{
				throw new InvalidOperationException($"Trust connection refused ({(int)response.StatusCode}): {text}");
			}
			TrustSession trustSession = Wire.Decode<TrustSession>(text);
			if (!ProtocolInfo.IsSupported(trustSession.Protocol) || string.IsNullOrWhiteSpace(trustSession.MatchId) || (trustSession.Team != "A" && trustSession.Team != "B"))
			{
				throw new InvalidDataException("Invalid trust coordinator response.");
			}
			return trustSession;
		}
	}
	public sealed class VoiceClient : IDisposable
	{
		private readonly Uri _address;

		private readonly string _token;

		private readonly Action<string> _log;

		private readonly CancellationTokenSource _stop = new CancellationTokenSource();

		private readonly ConcurrentQueue<(long Time, byte[] Data)> _outgoing = new ConcurrentQueue<(long, byte[])>();

		private readonly ConcurrentQueue<(long Time, byte[] Data)> _incoming = new ConcurrentQueue<(long, byte[])>();

		private volatile bool _connected;

		public bool Connected => _connected;

		public VoiceClient(Uri address, string token, Action<string> log)
		{
			_address = address;
			_token = token;
			_log = log;
			Task.Run((Func<Task?>)RunAsync);
		}

		private static bool Fresh(long time)
		{
			return (double)(Stopwatch.GetTimestamp() - time) / (double)Stopwatch.Frequency < 0.25;
		}

		public void Send(byte[] data)
		{
			if (_connected && VoicePacket.Valid(data))
			{
				while (_outgoing.Count >= 8)
				{
					_outgoing.TryDequeue(out (long, byte[]) _);
				}
				_outgoing.Enqueue((Stopwatch.GetTimestamp(), data));
			}
		}

		public bool TryReceive(out byte[] data)
		{
			(long, byte[]) result;
			while (_incoming.TryDequeue(out result))
			{
				if (Fresh(result.Item1))
				{
					data = result.Item2;
					return true;
				}
			}
			data = Array.Empty<byte>();
			return false;
		}

		private async Task RunAsync()
		{
			while (!_stop.IsCancellationRequested)
			{
				(long, byte[]) result;
				try
				{
					using ClientWebSocket socket = new ClientWebSocket();
					if (_token.Length > 0)
					{
						socket.Options.SetRequestHeader("Authorization", "Bearer " + _token);
					}
					socket.Options.KeepAliveInterval = TimeSpan.FromSeconds(5.0);
					using CancellationTokenSource session = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken[1] { _stop.Token });
					session.CancelAfter(TimeSpan.FromSeconds(10.0));
					await socket.ConnectAsync(_address, session.Token).ConfigureAwait(continueOnCapturedContext: false);
					session.CancelAfter(-1);
					while (_outgoing.TryDequeue(out result))
					{
					}
					_connected = true;
					_log("Dead voice relay connected.");
					Task receive = ReceiveAsync(socket, session.Token);
					try
					{
						while (!receive.IsCompleted && !session.IsCancellationRequested)
						{
							if (!_outgoing.TryDequeue(out (long, byte[]) result2) || !Fresh(result2.Item1))
							{
								await Task.Delay(5, session.Token).ConfigureAwait(continueOnCapturedContext: false);
								continue;
							}
							using CancellationTokenSource send = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken[1] { session.Token });
							send.CancelAfter(TimeSpan.FromSeconds(2.0));
							await socket.SendAsync(new ArraySegment<byte>(result2.Item2), WebSocketMessageType.Binary, endOfMessage: true, send.Token).ConfigureAwait(continueOnCapturedContext: false);
						}
						await receive.ConfigureAwait(continueOnCapturedContext: false);
					}
					finally
					{
						session.Cancel();
						socket.Abort();
						try
						{
							await receive.ConfigureAwait(continueOnCapturedContext: false);
						}
						catch (Exception)
						{
						}
					}
				}
				catch (OperationCanceledException) when (_stop.IsCancellationRequested)
				{
					break;
				}
				catch (Exception ex3)
				{
					_log("Dead voice relay unavailable: " + ex3.Message);
				}
				finally
				{
					_connected = false;
					while (_outgoing.TryDequeue(out result))
					{
					}
					while (_incoming.TryDequeue(out result))
					{
					}
				}
				try
				{
					await Task.Delay(2000, _stop.Token).ConfigureAwait(continueOnCapturedContext: false);
				}
				catch (OperationCanceledException)
				{
					break;
				}
			}
		}

		private async Task ReceiveAsync(WebSocket socket, CancellationToken token)
		{
			while (!token.IsCancellationRequested)
			{
				byte[] array = await VoicePacket.ReceiveAsync(socket, token).ConfigureAwait(continueOnCapturedContext: false);
				if (array == null)
				{
					break;
				}
				while (_incoming.Count >= 16)
				{
					_incoming.TryDequeue(out (long, byte[]) _);
				}
				_incoming.Enqueue((Stopwatch.GetTimestamp(), array));
			}
		}

		public void Dispose()
		{
			_connected = false;
			_stop.Cancel();
		}
	}
	public static class VoicePacket
	{
		public const int SampleRate = 16000;

		public const int Samples = 320;

		public const int HeaderSize = 24;

		public const int Size = 664;

		public static byte[] Create(int round, ulong player, int life, int sequence, short[] samples)
		{
			if (samples.Length != 320)
			{
				throw new ArgumentException("Invalid audio frame.");
			}
			byte[] array = new byte[664];
			Buffer.BlockCopy(BitConverter.GetBytes(827736900), 0, array, 0, 4);
			Buffer.BlockCopy(BitConverter.GetBytes(round), 0, array, 4, 4);
			Buffer.BlockCopy(BitConverter.GetBytes(player), 0, array, 8, 8);
			Buffer.BlockCopy(BitConverter.GetBytes(life), 0, array, 16, 4);
			Buffer.BlockCopy(BitConverter.GetBytes(sequence), 0, array, 20, 4);
			Buffer.BlockCopy(samples, 0, array, 24, 640);
			return array;
		}

		public static bool Valid(byte[] bytes)
		{
			if (bytes.Length == 664)
			{
				return BitConverter.ToInt32(bytes, 0) == 827736900;
			}
			return false;
		}

		public static int Round(byte[] bytes)
		{
			return BitConverter.ToInt32(bytes, 4);
		}

		public static ulong Player(byte[] bytes)
		{
			return BitConverter.ToUInt64(bytes, 8);
		}

		public static int Life(byte[] bytes)
		{
			return BitConverter.ToInt32(bytes, 16);
		}

		public static int Sequence(byte[] bytes)
		{
			return BitConverter.ToInt32(bytes, 20);
		}

		public static async Task<byte[]?> ReceiveAsync(WebSocket socket, CancellationToken token)
		{
			byte[] bytes = new byte[664];
			int offset = 0;
			WebSocketReceiveResult webSocketReceiveResult;
			do
			{
				if (offset == 664)
				{
					throw new InvalidDataException("Oversize voice frame.");
				}
				webSocketReceiveResult = await socket.ReceiveAsync(new ArraySegment<byte>(bytes, offset, 664 - offset), token).ConfigureAwait(continueOnCapturedContext: false);
				if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close)
				{
					return null;
				}
				if (webSocketReceiveResult.MessageType != WebSocketMessageType.Binary)
				{
					throw new InvalidDataException("Binary voice frame required.");
				}
				offset += webSocketReceiveResult.Count;
			}
			while (!webSocketReceiveResult.EndOfMessage);
			if (offset != 664 || !Valid(bytes))
			{
				throw new InvalidDataException("Invalid voice frame.");
			}
			return bytes;
		}
	}
	public sealed class VoicePlaybackBuffer
	{
		private readonly object _gate = new object();

		private readonly float[] _buffer = new float[1600];

		private int _read;

		private int _write;

		private int _count;

		private int _life = -1;

		private int _sequence;

		private bool _primed;

		private double _phase;

		private float _current;

		public void Add(byte[] data)
		{
			if (!VoicePacket.Valid(data))
			{
				return;
			}
			lock (_gate)
			{
				int num = VoicePacket.Life(data);
				if (num < _life || (num == _life && VoicePacket.Sequence(data) <= _sequence))
				{
					return;
				}
				if (num != _life)
				{
					_read = (_write = (_count = 0));
					_primed = false;
					_phase = 0.0;
					_current = 0f;
				}
				_life = num;
				_sequence = VoicePacket.Sequence(data);
				for (int i = 24; i < data.Length; i += 2)
				{
					if (_count == _buffer.Length)
					{
						_read = (_read + 1) % _buffer.Length;
						_count--;
					}
					_buffer[_write] = (float)BitConverter.ToInt16(data, i) / 32768f;
					_write = (_write + 1) % _buffer.Length;
					_count++;
				}
			}
		}

		public void Read(float[] samples, int channels, int outputRate)
		{
			if (channels < 1 || outputRate < 16000)
			{
				Array.Clear(samples, 0, samples.Length);
				return;
			}
			lock (_gate)
			{
				if (!_primed && _count >= 640)
				{
					_primed = true;
					_phase = outputRate;
				}
				for (int i = 0; i < samples.Length; i += channels)
				{
					if (_primed)
					{
						if (_phase >= (double)outputRate)
						{
							_phase -= outputRate;
							if (_count > 0)
							{
								_current = _buffer[_read];
								_read = (_read + 1) % _buffer.Length;
								_count--;
							}
							else
							{
								_primed = false;
								_current = 0f;
							}
						}
						_phase += 16000.0;
					}
					else
					{
						_current = 0f;
					}
					for (int j = 0; j < channels && i + j < samples.Length; j++)
					{
						samples[i + j] = _current;
					}
				}
			}
		}
	}
	public static class WebSocketWire
	{
		public static async Task SendAsync(WebSocket socket, string text, CancellationToken token)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(text);
			if (bytes.Length > 1048576)
			{
				throw new InvalidDataException("Message exceeds protocol limit.");
			}
			await socket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, endOfMessage: true, token).ConfigureAwait(continueOnCapturedContext: false);
		}

		public static async Task<string?> ReceiveAsync(WebSocket socket, CancellationToken token)
		{
			byte[] buffer = new byte[8192];
			using MemoryStream stream = new MemoryStream();
			WebSocketReceiveResult webSocketReceiveResult;
			do
			{
				webSocketReceiveResult = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), token).ConfigureAwait(continueOnCapturedContext: false);
				if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close)
				{
					return null;
				}
				if (webSocketReceiveResult.MessageType != WebSocketMessageType.Text)
				{
					throw new InvalidDataException("Text messages required.");
				}
				if (stream.Length + webSocketReceiveResult.Count > 1048576)
				{
					throw new InvalidDataException("Message exceeds protocol limit.");
				}
				stream.Write(buffer, 0, webSocketReceiveResult.Count);
			}
			while (!webSocketReceiveResult.EndOfMessage);
			return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(stream.ToArray());
		}
	}
}
namespace DemonCompany.Shared.Contracts
{
	public static class Wire
	{
		public const int MaximumBytes = 1048576;

		private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
		{
			TypeNameHandling = (TypeNameHandling)0,
			ObjectCreationHandling = (ObjectCreationHandling)2,
			MaxDepth = 32,
			Converters = { (JsonConverter)new StringEnumConverter() },
			FloatParseHandling = (FloatParseHandling)0
		};

		public static string Encode(object value)
		{
			return JsonConvert.SerializeObject(value, Settings);
		}

		public static T Decode<T>(string json)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			T val = JsonConvert.DeserializeObject<T>(json, Settings);
			if (val == null)
			{
				throw new JsonSerializationException("Missing message body.");
			}
			return val;
		}

		public static T Clone<T>(T value)
		{
			return Decode<T>(Encode(value));
		}
	}
	public enum CommandKind
	{
		Roster,
		Ready,
		SelectMoon,
		HostPrepared,
		RequestLaunch,
		Generation,
		GenerationAccepted,
		OfferPrepare,
		OfferConsumed,
		OfferCancelled,
		Purchase,
		Death,
		NaturalSpawn,
		DeliveryApplied,
		RoundFinished,
		Fault
	}
	public enum DeliveryKind
	{
		Launch,
		ConsumeOffering,
		SpawnEnemy,
		ApplyUpgrade,
		Generation,
		NaturalSpawn
	}
	public enum ProductKind
	{
		Monster,
		PermanentStamina,
		TemporaryStamina,
		Revive,
		TeleporterRetention
	}
	public enum MatchPhase
	{
		Lobby,
		Selection,
		Loading,
		Playing,
		Finished,
		Faulted
	}
	public enum SpawnOrigin
	{
		Natural,
		Demon
	}
	public sealed class ClientMessage
	{
		public int Protocol { get; set; } = 1;

		public string MatchId { get; set; } = "";

		public string InstanceId { get; set; } = "";

		public long Sequence { get; set; }

		public string EventId { get; set; } = Guid.NewGuid().ToString("N");

		public int Round { get; set; }

		public CommandKind Kind { get; set; }

		public CommandBody Body { get; set; } = new CommandBody();
	}
	public sealed class CommandBody
	{
		public ulong Actor { get; set; }

		public ulong Target { get; set; }

		public List<PlayerInfo> Players { get; set; } = new List<PlayerInfo>();

		public ulong Demon { get; set; }

		public string Fingerprint { get; set; } = "";

		public int Moon { get; set; }

		public string ItemId { get; set; } = "";

		public int Value { get; set; }

		public string ProductId { get; set; } = "";

		public string ReferenceId { get; set; } = "";

		public string DeathId { get; set; } = "";

		public string EnemyId { get; set; } = "";

		public bool DirectEnemyKill { get; set; }

		public string Checksum { get; set; } = "";

		public double RoundTime { get; set; }

		public GenerationManifest? Manifest { get; set; }

		public SpawnEvent? Spawn { get; set; }
	}
	public sealed class ServerFrame
	{
		public int Protocol { get; set; } = 1;

		public long AckSequence { get; set; }

		public string EventId { get; set; } = "";

		public bool Accepted { get; set; } = true;

		public string Error { get; set; } = "";

		public TeamView? View { get; set; }

		public List<Delivery> Deliveries { get; set; } = new List<Delivery>();
	}
	public sealed class TrustSession
	{
		public int Protocol { get; set; } = 1;

		public string MatchId { get; set; } = "";

		public string Team { get; set; } = "";
	}
	public sealed class PlayerInfo
	{
		public ulong Id { get; set; }

		public string Name { get; set; } = "";
	}
	public sealed class Delivery
	{
		public string Id { get; set; } = Guid.NewGuid().ToString("N");

		public int Round { get; set; }

		public string Team { get; set; } = "";

		public DeliveryKind Kind { get; set; }

		public string ReferenceId { get; set; } = "";

		public string ItemId { get; set; } = "";

		public ulong Target { get; set; }

		public ProductDefinition? Product { get; set; }

		public SpawnEvent? Spawn { get; set; }

		public GenerationManifest? Manifest { get; set; }
	}
	public sealed class Vec3
	{
		public float X { get; set; }

		public float Y { get; set; }

		public float Z { get; set; }
	}
	public sealed class Rotation4
	{
		public float X { get; set; }

		public float Y { get; set; }

		public float Z { get; set; }

		public float W { get; set; } = 1f;
	}
	public sealed class ScrapEntry
	{
		public string Id { get; set; } = "";

		public int ItemType { get; set; }

		public int Value { get; set; }

		public Vec3 Position { get; set; } = new Vec3();

		public Vec3 Rotation { get; set; } = new Vec3();

		public Rotation4? Orientation { get; set; }
	}
	public sealed class HazardEntry
	{
		public int Prefab { get; set; }

		public Vec3 Position { get; set; } = new Vec3();

		public Vec3 Rotation { get; set; } = new Vec3();

		public Rotation4? Orientation { get; set; }

		public string TerminalCode { get; set; } = "";
	}
	public sealed class GenerationManifest
	{
		public int Moon { get; set; }

		public int Seed { get; set; }

		public int Dungeon { get; set; }

		public string GeometryChecksum { get; set; } = "";

		public List<string> GeometryEntries { get; set; } = new List<string>();

		public string Checksum { get; set; } = "";

		public List<ScrapEntry> Scrap { get; set; } = new List<ScrapEntry>();

		public List<HazardEntry> Hazards { get; set; } = new List<HazardEntry>();
	}
	public sealed class SpawnEvent
	{
		public string Id { get; set; } = "";

		public SpawnOrigin Origin { get; set; }

		public string ResponsibleTeam { get; set; } = "";

		public string EnemyType { get; set; } = "";

		public Vec3 Position { get; set; } = new Vec3();

		public float RotationY { get; set; }

		public double RoundTime { get; set; }

		public bool Outside { get; set; }
	}
	public sealed class TeamView
	{
		public string MatchId { get; set; } = "";

		public string Team { get; set; } = "";

		public MatchPhase Phase { get; set; }

		public int Round { get; set; }

		public bool FinishedOwnRound { get; set; }

		public bool GenerationVerified { get; set; }

		public bool CanLaunch { get; set; }

		public int Moon { get; set; } = -1;

		public int Seed { get; set; }

		public ulong Demon { get; set; }

		public List<PlayerInfo> Players { get; set; } = new List<PlayerInfo>();

		public long Credits { get; set; }

		public long OfferingTotal { get; set; }

		public bool TeleporterRetention { get; set; }

		public long VisibleScore { get; set; }

		public string SelectionTeam { get; set; } = "";

		public string SelectionAction { get; set; } = "";

		public List<int> AvailableMoons { get; set; } = new List<int>();

		public List<ProductDefinition> Shop { get; set; } = new List<ProductDefinition>();

		public List<PurchaseRecord> Purchases { get; set; } = new List<PurchaseRecord>();

		public List<UpgradeState> Upgrades { get; set; } = new List<UpgradeState>();

		public List<TeamResult>? Results { get; set; }
	}
	public sealed class LocalRequest
	{
		public string Id { get; set; } = Guid.NewGuid().ToString("N");

		public string Action { get; set; } = "";

		public string Argument { get; set; } = "";

		public ulong Target { get; set; }

		public string EnemyId { get; set; } = "";

		public bool DirectEnemyKill { get; set; }

		public int Round { get; set; }

		public int Life { get; set; }
	}
}