using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using DiceKingdoms.Game;
using DiceKingdoms.Network;
using DiceModders.ModCore;
using DiceModders.UiKit;
using DiceModders.UiKit.Custom;
using DiceModders.UiKit.Native;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.UI;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("DiceModders")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Revive for Dice Kingdoms: when a human player loses his castle, the others vote whether he gets a spin of the wheel of revival. A lobby rule.")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("DiceModders.Revive")]
[assembly: AssemblyTitle("DiceModders.Revive")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
[module: UnverifiableCode]
[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 DiceModders.Revive
{
internal static class Clock
{
private static readonly List<(float at, Action work)> Jobs = new List<(float, Action)>();
private static Action _tick;
private static float _nextTick;
private static GameObject _go;
private static float _nextDue = float.MaxValue;
internal static void At(float seconds, Action work)
{
float num = Time.unscaledTime + seconds;
Jobs.Add((num, work));
if (num < _nextDue)
{
_nextDue = num;
}
Wake();
}
internal static void EverySecond(Action tick)
{
_tick = tick;
_nextTick = 0f;
if (tick != null)
{
Wake();
}
}
internal static void Clear()
{
Jobs.Clear();
_nextDue = float.MaxValue;
_tick = null;
if ((Object)(object)_go != (Object)null)
{
_go.SetActive(false);
}
}
private static void Wake()
{
//IL_001e: Unknown result type (might be due to invalid IL or missing references)
//IL_0023: Unknown result type (might be due to invalid IL or missing references)
//IL_0030: Expected O, but got Unknown
if ((Object)(object)_go == (Object)null)
{
if (!ClassInjector.IsTypeRegisteredInIl2Cpp<ReviveClock>())
{
ClassInjector.RegisterTypeInIl2Cpp<ReviveClock>();
}
_go = new GameObject("DiceModders Revive Clock")
{
hideFlags = (HideFlags)61
};
Object.DontDestroyOnLoad((Object)(object)_go);
_go.AddComponent<ReviveClock>();
}
_go.SetActive(true);
}
internal static void Update()
{
float unscaledTime = Time.unscaledTime;
if (Jobs.Count > 0 && unscaledTime >= _nextDue)
{
List<Action> list = new List<Action>();
_nextDue = float.MaxValue;
for (int num = Jobs.Count - 1; num >= 0; num--)
{
if (Jobs[num].at <= unscaledTime)
{
list.Insert(0, Jobs[num].work);
Jobs.RemoveAt(num);
}
else if (Jobs[num].at < _nextDue)
{
_nextDue = Jobs[num].at;
}
}
foreach (Action item in list)
{
try
{
item();
}
catch (Exception ex)
{
Plugin.Once("clock", "revive (later): " + ex);
}
}
}
if (_tick != null && unscaledTime >= _nextTick)
{
_nextTick = unscaledTime + 1f;
try
{
_tick();
}
catch (Exception ex2)
{
Plugin.Once("tick", "revive (countdown): " + ex2);
}
}
if (Jobs.Count == 0 && _tick == null && (Object)(object)_go != (Object)null)
{
_go.SetActive(false);
}
}
}
internal sealed class ReviveClock : MonoBehaviour
{
public ReviveClock(IntPtr ptr)
: base(ptr)
{
}
private void Update()
{
Clock.Update();
}
}
internal enum Outcome
{
Out,
Full,
NoCulture,
Fresh
}
internal static class Faces
{
internal const int Count = 20;
private static Outcome[] _faces;
private static string _for;
internal static Outcome[] All
{
get
{
string text = $"{Rules.FullPercent}|{Rules.NoCulturePercent}|{Rules.FreshPercent}";
if (_faces != null && text == _for)
{
return _faces;
}
_for = text;
return _faces = Build(Rules.FullPercent / 5, Rules.NoCulturePercent / 5, Rules.FreshPercent / 5);
}
}
private static Outcome[] Build(int full, int noCulture, int fresh)
{
int[] array = new int[3]
{
Math.Max(0, full),
Math.Max(0, noCulture),
Math.Max(0, fresh)
};
while (array[0] + array[1] + array[2] > 20)
{
int num = 2;
int[] array2 = new int[2] { 1, 0 };
foreach (int num2 in array2)
{
if (array[num2] > array[num])
{
num = num2;
}
}
array[num]--;
}
int count = 20 - array[0] - array[1] - array[2];
List<(double pos, int order, Outcome what)> items = new List<(double, int, Outcome)>();
Spread(array[0], 0.0, 0, Outcome.Full);
Spread(array[1], 10.6, 1, Outcome.NoCulture);
Spread(array[2], 5.3, 2, Outcome.Fresh);
Spread(count, 0.5, 3, Outcome.Out);
items.Sort(((double pos, int order, Outcome what) a, (double pos, int order, Outcome what) b) => (a.pos == b.pos) ? a.order.CompareTo(b.order) : a.pos.CompareTo(b.pos));
Outcome[] array3 = new Outcome[20];
for (int num3 = 0; num3 < 20; num3++)
{
array3[num3] = items[num3].what;
}
return array3;
void Spread(int num4, double offset, int order, Outcome what)
{
for (int j = 0; j < num4; j++)
{
items.Add(((((double)j + 0.5) * 20.0 / (double)num4 + offset) % 20.0, order, what));
}
}
}
internal static int Percent(Outcome kind)
{
int num = 0;
Outcome[] all = All;
for (int i = 0; i < all.Length; i++)
{
if (all[i] == kind)
{
num++;
}
}
return num * 100 / 20;
}
}
internal static class Host
{
private sealed class Vote
{
public int Seq;
public ulong Dead;
public List<ulong> Voters = new List<ulong>();
public readonly Dictionary<ulong, bool> Ballots = new Dictionary<ulong, bool>();
public bool Open = true;
}
private const float SpinSeconds = 8f;
private static readonly Queue<ulong> Waiting = new Queue<ulong>();
private static readonly HashSet<ulong> Down = new HashSet<ulong>();
private static readonly Dictionary<ulong, int> Losses = new Dictionary<ulong, int>();
private static readonly Dictionary<ulong, Outcome> Comeback = new Dictionary<ulong, Outcome>();
private static readonly Random Rng = new Random();
private static Vote _vote;
private static bool _busy;
private static int _seq;
private static bool _startTaken;
internal static bool IsHost
{
get
{
MatchPlayer local = Players.Local;
if (local == null)
{
return false;
}
return local.IsHost;
}
}
private static bool DevSolo => false;
internal static void Install(ConfigFile config)
{
Match.Started += Reset;
Match.Ended += Reset;
Match.GameOver += Stop;
Match.PhaseEntered += OnPhase;
PlayerValues.Changed += OnValues;
Lobby.Changed += Recheck;
}
private static void Reset()
{
Waiting.Clear();
Down.Clear();
Losses.Clear();
Comeback.Clear();
_vote = null;
_busy = false;
_seq = Rng.Next(1, 1000000) * 100;
_startTaken = false;
Snapshots.Clear();
Clock.Clear();
if (IsHost && Lobby.InLobby)
{
PlayerValues.Set("revive.state", new VoteState().Write());
}
}
private static void Stop()
{
Waiting.Clear();
Comeback.Clear();
if (_vote != null)
{
_vote.Open = false;
}
Clock.Clear();
}
private static bool Revivable(MatchPlayer p)
{
if (p != null)
{
if (p.IsAI)
{
return DevSolo;
}
return true;
}
return false;
}
private static void OnPhase(MatchPhase phase)
{
//IL_0017: Unknown result type (might be due to invalid IL or missing references)
//IL_0019: Invalid comparison between Unknown and I4
//IL_0025: Unknown result type (might be due to invalid IL or missing references)
//IL_0027: Invalid comparison between Unknown and I4
if (!Rules.On || !IsHost || !Match.Running)
{
return;
}
try
{
if ((int)phase == 2)
{
PutBack();
}
FindLosses();
bool flag = (int)phase == 2 && !_startTaken;
foreach (MatchPlayer item in Players.All)
{
if (Revivable(item) && !item.IsDefeated)
{
Island island = item.Island;
if (Snapshots.HasCastle((island != null) ? island.grid : null))
{
Snapshots.Take(item, flag);
}
}
}
if (flag)
{
_startTaken = true;
}
if (!_busy)
{
Next();
}
}
catch (Exception ex)
{
Plugin.Once("phase", "revive (phase): " + ex);
}
}
private static void FindLosses()
{
//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
//IL_00ac: Expected O, but got Unknown
bool flag = default(bool);
foreach (MatchPlayer item in Players.All)
{
if (!Revivable(item) || !item.IsDefeated || Down.Contains(item.Id))
{
continue;
}
Island island = item.Island;
if (!Snapshots.HasCastle((island != null) ? island.grid : null))
{
Down.Add(item.Id);
int value;
int num = ((!Losses.TryGetValue(item.Id, out value)) ? 1 : (value + 1));
Losses[item.Id] = num;
ManualLogSource l = Plugin.L;
BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(32, 3, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("turn ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(Match.Turn);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(item.Name);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" lost the castle (");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(". time)");
}
l.LogInfo(val);
if (num > Rules.Times)
{
Post("log.noMore", item);
}
else
{
Waiting.Enqueue(item.Id);
}
}
}
}
private static void PutBack()
{
//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
//IL_00ca: Expected O, but got Unknown
bool flag2 = default(bool);
foreach (var (num2, outcome2) in Comeback.ToList())
{
Comeback.Remove(num2);
MatchPlayer val = Players.Find(num2);
if (val == null || !val.IsDefeated)
{
continue;
}
bool flag;
string why;
try
{
flag = Snapshots.Restore(val, outcome2, out why);
}
catch (Exception ex)
{
flag = false;
why = ex.Message;
Plugin.L.LogError((object)("revive: " + ex));
}
if (flag)
{
Down.Remove(num2);
Post("log.back", val);
continue;
}
ManualLogSource l = Plugin.L;
BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(32, 2, ref flag2);
if (flag2)
{
((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("revive: ");
((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(val.Name);
((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" could not be put back: ");
((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(why);
}
l.LogWarning(val2);
Post("log.backFailed", val);
}
}
private static void Next()
{
while (Waiting.Count > 0)
{
MatchPlayer p = Players.Find(Waiting.Dequeue());
if (p == null || !p.IsDefeated)
{
continue;
}
if (Sides() < 2)
{
Plugin.L.LogInfo((object)("revive: the match is decided, no vote for " + p.Name));
continue;
}
List<ulong> list = (from v in Players.All
where !v.IsAI && !v.IsDefeated && v.IsConnected && v.Id != p.Id
select v.Id).ToList();
if (list.Count == 0 && DevSolo && Players.Local != null)
{
list.Add(Players.Local.Id);
}
if (list.Count == 0)
{
Post("log.noVoters", p);
continue;
}
Begin(p, list);
break;
}
}
private static int Sides()
{
List<MatchPlayer> list = Players.All.Where((MatchPlayer p) => !p.IsDefeated).ToList();
if (!Match.Settings.Teams)
{
return list.Count;
}
return list.Select((MatchPlayer p) => p.Team).Distinct().Count();
}
private static void Begin(MatchPlayer p, List<ulong> voters)
{
//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
//IL_00c6: Expected O, but got Unknown
_busy = true;
_vote = new Vote
{
Seq = ++_seq,
Dead = p.Id,
Voters = voters
};
int seconds = Rules.Seconds;
int seq = _vote.Seq;
Clock.At((float)seconds + 1f, delegate
{
Timeout(seq);
});
Publish(new VoteState
{
Seq = _vote.Seq,
Stage = Stage.Vote,
Dead = p.Id,
Seconds = seconds,
Voters = voters
});
Post("log.vote", p);
ManualLogSource l = Plugin.L;
bool flag = default(bool);
BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(35, 4, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("revive: vote ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_vote.Seq);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" about ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(p.Name);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(voters.Count);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" voter(s), ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(seconds);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" s");
}
l.LogInfo(val);
foreach (ulong voter in voters)
{
bool? flag2 = Votes.BallotOf(voter);
if (flag2.HasValue)
{
Receive(voter, seq, flag2.Value);
}
}
}
private static void OnValues(ulong steamId)
{
if (Rules.On && IsHost && _vote != null && _vote.Open && _vote.Voters.Contains(steamId))
{
bool? flag = Votes.BallotOf(steamId);
if (flag.HasValue)
{
Receive(steamId, _vote.Seq, flag.Value);
}
}
}
internal static void Receive(ulong voter, int seq, bool yes)
{
Vote vote = _vote;
if (vote != null && vote.Open && vote.Seq == seq && vote.Voters.Contains(voter) && !vote.Ballots.ContainsKey(voter))
{
vote.Ballots[voter] = yes;
Decide(vote);
}
}
private static void Decide(Vote v)
{
if (v == null || !v.Open)
{
return;
}
int num = v.Voters.Count(delegate(ulong id)
{
if (!v.Ballots.ContainsKey(id))
{
MatchPlayer obj = Players.Find(id);
if (obj == null)
{
return false;
}
return obj.IsConnected;
}
return true;
});
int num2 = v.Ballots.Values.Count((bool b) => b);
int num3 = v.Ballots.Count - num2;
if (num == 0)
{
Fail(num2, num3);
}
else if (num2 * 2 > num)
{
Pass(num2, num3);
}
else if (num3 * 2 >= num)
{
Fail(num2, num3);
}
}
private static void Recheck()
{
if (!Rules.On || !IsHost || _vote == null || !_vote.Open)
{
return;
}
try
{
Decide(_vote);
}
catch (Exception ex)
{
Plugin.Once("recheck", "revive (vote after a player left): " + ex);
}
}
private static void Timeout(int seq)
{
Vote vote = _vote;
if (vote != null && vote.Open && vote.Seq == seq)
{
int num = vote.Ballots.Values.Count((bool b) => b);
Fail(num, vote.Ballots.Count - num);
}
}
private static void Pass(int yes, int no)
{
//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
//IL_00c1: Expected O, but got Unknown
Vote vote = _vote;
vote.Open = false;
int num = Rng.Next(20);
Outcome outcome = Faces.All[num];
Publish(new VoteState
{
Seq = vote.Seq,
Stage = Stage.Spin,
Dead = vote.Dead,
Face = num,
Voters = vote.Voters,
Yes = yes,
No = no
});
MatchPlayer p = Players.Find(vote.Dead);
Post("log.passed", p, yes, vote.Voters.Count);
ManualLogSource l = Plugin.L;
bool flag = default(bool);
BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(41, 5, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("revive: vote ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(vote.Seq);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" passed (");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(yes);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" yes, ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(no);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" no); face ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Outcome>(outcome);
}
l.LogInfo(val);
if (outcome != Outcome.Out)
{
Comeback[vote.Dead] = outcome;
}
ulong dead = vote.Dead;
Clock.At(8f, delegate
{
Post("log.result." + outcome.ToString().ToLowerInvariant(), Players.Find(dead));
Done();
});
}
private static void Fail(int yes, int no)
{
//IL_0087: Unknown result type (might be due to invalid IL or missing references)
//IL_008d: Expected O, but got Unknown
Vote vote = _vote;
vote.Open = false;
Publish(new VoteState
{
Seq = vote.Seq,
Stage = Stage.Fail,
Dead = vote.Dead,
Voters = vote.Voters,
Yes = yes,
No = no
});
Post("log.failed", Players.Find(vote.Dead), yes, no);
ManualLogSource l = Plugin.L;
bool flag = default(bool);
BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(32, 3, ref flag);
if (flag)
{
((BepInExLogInterpolatedStringHandler)val).AppendLiteral("revive: vote ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(vote.Seq);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" failed (");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(yes);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" yes, ");
((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(no);
((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" no)");
}
l.LogInfo(val);
Clock.At(3f, Done);
}
private static void Done()
{
_busy = false;
_vote = null;
if (Match.Running && Rules.On)
{
Next();
}
}
private static void Publish(VoteState s)
{
if (Lobby.InLobby)
{
PlayerValues.Set("revive.state", s.Write());
}
Votes.Apply(s);
}
private static void Post(string key, MatchPlayer p, params object[] numbers)
{
//IL_0032: Unknown result type (might be due to invalid IL or missing references)
//IL_0038: Expected O, but got Unknown
try
{
object[] array = new object[numbers.Length + 1];
array[0] = "\u0001";
Array.Copy(numbers, 0, array, 1, numbers.Length);
string[] array2 = Tx.T(key, array).Split("\u0001");
GameText val = new GameText();
for (int i = 0; i < array2.Length; i++)
{
if (i > 0)
{
if (p != null)
{
val.Player(p);
}
else
{
val.Text("?");
}
}
val.Text(array2[i]);
}
Messages.Post(val);
}
catch (Exception ex)
{
Plugin.Once("post", "revive (log line): " + ex.Message);
}
}
}
[BepInPlugin("org.dicemodders.dicekingdoms.revive", "DiceKingdoms Revive", "1.0.1")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInProcess("Dice-Kingdoms.exe")]
public sealed class Plugin : BasePlugin
{
public const string Guid = "org.dicemodders.dicekingdoms.revive";
public const string Name = "DiceKingdoms Revive";
public const string Version = "1.0.1";
internal static ManualLogSource L;
internal static bool On;
private static readonly HashSet<string> Logged = new HashSet<string>();
public override void Load()
{
Tx.Load();
L = ((BasePlugin)this).Log;
Rules.Install();
Votes.Install();
Host.Install(((BasePlugin)this).Config);
ReviveWindow.Install(UiKit.CreateScope("org.dicemodders.dicekingdoms.revive"));
Mods.Switch(((BasePlugin)this).Config, true, false, "Turns the Revive rule of this mod on or off.").WhenOn((Action)delegate
{
On = true;
ReviveWindow.Refresh();
}, (Action)delegate
{
On = false;
ReviveWindow.Refresh();
});
}
internal static void Once(string key, string message)
{
if (Logged.Add(key))
{
ManualLogSource l = L;
if (l != null)
{
l.LogError((object)message);
}
}
}
}
internal static class ReviveWindow
{
private static UiScope _ui;
private static TopBarButtonHandle _button;
private static UiWindow _window;
private static UiImage _wheel;
private static UiImage _pointer;
private static UiText _who;
private static UiText _result;
private static UiText _question;
private static UiText _status;
private static UiContainer _buttons;
private static Texture2D _wheelTexture;
private static Texture2D _pointerTexture;
private static Outcome[] _texturedFaces;
private static ulong _iconsFor;
private static float _angle;
private static int _turnedSeq = -1;
private static int _shownSeq = -1;
internal static void Install(UiScope ui)
{
_ui = ui;
UiScope ui2 = _ui;
if (ui2 != null)
{
ui2.WhenReady((Action<UiScope>)delegate(UiScope s)
{
_button = s.Native.TopBar.AddIconButton("culture", Tx.T("window.tooltip"), (Action)Toggle, 23);
Refresh();
});
}
Texts.LanguageChanged += delegate
{
TopBarButtonHandle button = _button;
if (button != null)
{
button.SetTooltip(Tx.T("window.tooltip"));
}
if (_window != null)
{
_window.Close();
Open();
}
};
Match.Started += delegate
{
_angle = 0f;
_turnedSeq = -1;
_shownSeq = -1;
Refresh();
};
Match.Ended += delegate
{
UiWindow window = _window;
if (window != null)
{
window.Close();
}
Refresh();
};
Votes.Changed += OnState;
Votes.BallotsChanged += Redraw;
}
internal static void Refresh()
{
bool flag = Rules.On && Match.Running;
VoteState current = Votes.Current;
TopBarButtonHandle button = _button;
if (button != null)
{
button.SetVisible(flag && current != null && current.Stage != Stage.None);
}
if (!flag)
{
UiWindow window = _window;
if (window != null)
{
window.Close();
}
}
}
private static void Toggle()
{
if (_window != null)
{
_window.Close();
}
else
{
Open();
}
}
private static void OnState()
{
Refresh();
VoteState current = Votes.Current;
if (current == null || current.Stage == Stage.None || !Rules.On || !Match.Running)
{
UiWindow window = _window;
if (window != null)
{
window.Close();
}
return;
}
Open();
if (current.Stage == Stage.Spin && _turnedSeq != current.Seq)
{
Spin(current);
}
Redraw();
}
private static void Open()
{
VoteState s = Votes.Current;
if (!Rules.On || s == null || s.Stage == Stage.None)
{
return;
}
if (_window == null)
{
Outcome[] all = Faces.All;
if ((Object)(object)_wheelTexture == (Object)null || _texturedFaces != all)
{
if ((Object)(object)_wheelTexture != (Object)null)
{
Object.Destroy((Object)(object)_wheelTexture);
}
_wheelTexture = WheelArt.Disc(384, all);
_texturedFaces = all;
}
if ((Object)(object)_pointerTexture == (Object)null)
{
_pointerTexture = WheelArt.Pointer(48, 28);
}
UiScope ui = _ui;
_window = ((ui != null) ? ui.Custom.Window((Action<UiWindow>)delegate(UiWindow w)
{
//IL_011b: Unknown result type (might be due to invalid IL or missing references)
//IL_0128: Unknown result type (might be due to invalid IL or missing references)
//IL_0135: Unknown result type (might be due to invalid IL or missing references)
//IL_0142: Unknown result type (might be due to invalid IL or missing references)
//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
w.Title(Tx.T("window.title")).Size(450f, 780f).Position(60f, 80f)
.Draggable(true)
.Closable(true);
w.OnClose((Action)delegate
{
_window = null;
_wheel = (_pointer = null);
_who = (_result = (_question = (_status = null)));
_buttons = null;
_iconsFor = 0uL;
Clock.EverySecond(null);
});
_who = w.Body.Paragraph("");
_pointer = Height(w.Body.Image((Texture)(object)_pointerTexture), 26f);
GameObject val = PictureOf(_pointer);
if ((Object)(object)val != (Object)null)
{
val.GetComponent<RectTransform>().pivot = new Vector2(0.5f, 1f);
}
_wheel = Height(w.Body.Image((Texture)(object)_wheelTexture), 250f);
_result = w.Body.Paragraph("");
w.Body.Separator(1f);
w.Body.Paragraph(Tx.T("window.odds", Hex(WheelArt.Full), Hex(WheelArt.NoCulture), Hex(WheelArt.Fresh), Hex(WheelArt.Out), Faces.Percent(Outcome.Full), Faces.Percent(Outcome.NoCulture), Faces.Percent(Outcome.Fresh), Faces.Percent(Outcome.Out)));
w.Body.Separator(1f);
_question = w.Body.Paragraph("");
_buttons = w.Body.Row((Action<UiContainer>)delegate(UiContainer r)
{
r.Button(Tx.T("window.yes"), (Action)delegate
{
Votes.Cast(yes: true);
});
r.Button(Tx.T("window.no"), (Action)delegate
{
Votes.Cast(yes: false);
});
});
_status = w.Body.Paragraph("");
}) : null);
if (s.Stage == Stage.Spin && _turnedSeq == s.Seq && !ReviveSpin.Running)
{
_angle = FaceAngle(s.Face);
}
Turn(_angle);
}
if (_iconsFor != s.Dead)
{
_iconsFor = s.Dead;
WheelArt.AddIcons(Picture(), Faces.All, (Outcome o) => IconOf(o, Players.Find(s.Dead)), 19f);
}
Clock.EverySecond((s.Stage == Stage.Vote) ? new Action(Redraw) : null);
Redraw();
}
private static UiImage Height(UiImage image, float height)
{
object obj;
if (image == null)
{
obj = null;
}
else
{
RectTransform root = ((UiElement)image).Root;
obj = ((root != null) ? ((Component)root).GetComponent<LayoutElement>() : null);
}
LayoutElement val = (LayoutElement)obj;
if ((Object)(object)val != (Object)null)
{
val.preferredHeight = height;
}
return image;
}
private static string Hex(Color c)
{
//IL_0000: Unknown result type (might be due to invalid IL or missing references)
return ColorUtility.ToHtmlStringRGB(c);
}
private static string NameOf(ulong id)
{
//IL_0021: Unknown result type (might be due to invalid IL or missing references)
MatchPlayer val = Players.Find(id);
if (val == null)
{
return "?";
}
return "<color=#" + Hex(val.Color) + ">" + val.Name + "</color>";
}
private static Sprite IconOf(Outcome o, MatchPlayer dead)
{
return (Sprite)(o switch
{
Outcome.Full => Theme("culture"),
Outcome.NoCulture => BuildingIcon(dead, castle: true) ?? Theme("hammer"),
Outcome.Fresh => BuildingIcon(dead, castle: false) ?? Theme("food"),
_ => Theme("disaster"),
});
}
private static Sprite Theme(string name)
{
UiScope ui = _ui;
if (ui == null)
{
return null;
}
return ui.Custom.Theme.Icon(name);
}
private static Sprite BuildingIcon(MatchPlayer p, bool castle)
{
try
{
Island val = ((p != null) ? p.Island : null);
object obj;
if (val == null)
{
obj = null;
}
else
{
IslandGrid grid = val.grid;
obj = ((grid != null) ? grid.buildingTypes : null);
}
BuildingTypes val2 = (BuildingTypes)obj;
if ((Object)(object)val2 == (Object)null)
{
return null;
}
BuildingType val3 = (BuildingType)(castle ? ((object)val2.castle) : ((object)val2.cottage));
PlayerSkins skins = val.Skins;
BuildingVisual val4 = ((skins != null) ? skins.GetBuildingVisualPrefab(val3) : null);
return ((Object)(object)val4 != (Object)null) ? val4.Icon(p.Game.Color) : null;
}
catch
{
return null;
}
}
private static float FaceAngle(int face)
{
float num = 18f;
if (face >= 0)
{
return (float)face * num + num / 2f;
}
return 0f;
}
private static void Spin(VoteState s)
{
_turnedSeq = s.Seq;
_shownSeq = -1;
GameObject val = Picture();
if ((Object)(object)val == (Object)null || s.Face < 0 || Votes.Age > 6f)
{
_angle = FaceAngle(s.Face);
Turn(_angle);
_shownSeq = s.Seq;
return;
}
float step = 18f;
float num = _angle % 360f;
int num2 = (int)(3 + (uint)Environment.TickCount % 3u);
float to = num - ((float)num2 * 360f + Mod(num - FaceAngle(s.Face), 360f));
int seq = s.Seq;
ReviveSpin.Start(val, PictureOf(_pointer), step, num, to, 7f, delegate(float a)
{
_angle = a;
}, delegate
{
_shownSeq = seq;
Redraw();
});
}
private static float Mod(float a, float m)
{
a %= m;
if (!(a < 0f))
{
return a;
}
return a + m;
}
private static GameObject Picture()
{
return PictureOf(_wheel);
}
private static GameObject PictureOf(UiImage image)
{
if (!((Object)(object)((image != null) ? ((UiElement)image).Root : null) != (Object)null) || ((Transform)((UiElement)image).Root).childCount <= 0)
{
return null;
}
return ((Component)((Transform)((UiElement)image).Root).GetChild(0)).gameObject;
}
private static void Turn(float angle)
{
//IL_0020: Unknown result type (might be due to invalid IL or missing references)
GameObject val = Picture();
if ((Object)(object)val != (Object)null)
{
val.transform.localRotation = Quaternion.Euler(0f, 0f, angle);
}
}
private static void Redraw()
{
if (_window == null)
{
return;
}
VoteState current = Votes.Current;
if (current == null)
{
return;
}
string text = NameOf(current.Dead);
bool flag = current.Dead == Votes.LocalId;
bool flag2 = current.Stage == Stage.Vote;
bool canVote = Votes.CanVote;
if (_who != null)
{
_who.Value = (flag ? Tx.T("window.youLost") : Tx.T("window.lost", text));
}
UiContainer buttons = _buttons;
if ((Object)(object)((buttons != null) ? ((UiElement)buttons).Root : null) != (Object)null)
{
((Component)((UiElement)_buttons).Root).gameObject.SetActive(canVote);
}
if (_question != null)
{
bool? myBallot = Votes.MyBallot;
_question.Value = ((!flag2) ? "" : (canVote ? Tx.T("window.question", text) : ((myBallot == true) ? Tx.T("window.votedYes") : ((myBallot == false) ? Tx.T("window.votedNo") : (flag ? Tx.T("window.you") : Tx.T("window.watch"))))));
}
if (_status != null)
{
if (flag2)
{
var (num, num2) = Votes.Count();
_status.Value = Tx.T("window.left", Votes.SecondsLeft) + "\n" + Tx.T("window.tally", num, num2, current.Voters.Count);
}
else if (current.Stage == Stage.Fail)
{
_status.Value = Tx.T("window.failed", current.Yes, current.No, text);
}
else if (current.Stage == Stage.Spin)
{
_status.Value = Tx.T("window.passed", current.Yes, current.Voters.Count);
}
else
{
_status.Value = "";
}
}
if (_result != null)
{
if (current.Stage == Stage.Spin && _shownSeq == current.Seq && current.Face >= 0)
{
_result.Value = Tx.T("result." + Faces.All[current.Face].ToString().ToLowerInvariant(), text);
}
else if (current.Stage == Stage.Spin && ReviveSpin.Running)
{
_result.Value = Tx.T("window.turning");
}
else
{
_result.Value = "";
}
}
if (!flag2)
{
Clock.EverySecond(null);
}
}
}
internal sealed class ReviveSpin : MonoBehaviour
{
private float _from;
private float _to;
private float _time;
private float _duration;
private float _step;
private float _kick;
private int _line;
private Transform _pointer;
private Action<float> _onAngle;
private Action _onDone;
internal static bool Running;
public ReviveSpin(IntPtr ptr)
: base(ptr)
{
}
internal static void Start(GameObject target, GameObject pointer, float step, float from, float to, float seconds, Action<float> onAngle, Action onDone)
{
if (!ClassInjector.IsTypeRegisteredInIl2Cpp<ReviveSpin>())
{
ClassInjector.RegisterTypeInIl2Cpp<ReviveSpin>();
}
ReviveSpin reviveSpin = target.GetComponent<ReviveSpin>() ?? target.AddComponent<ReviveSpin>();
reviveSpin._from = from;
reviveSpin._to = to;
reviveSpin._time = 0f;
reviveSpin._duration = Mathf.Max(0.1f, seconds);
reviveSpin._step = Mathf.Max(1f, step);
reviveSpin._line = Line(from, reviveSpin._step);
reviveSpin._kick = 0f;
reviveSpin._pointer = (((Object)(object)pointer != (Object)null) ? pointer.transform : null);
reviveSpin._onAngle = onAngle;
reviveSpin._onDone = onDone;
((Behaviour)reviveSpin).enabled = true;
Running = true;
}
private static int Line(float angle, float step)
{
return Mathf.FloorToInt(angle / step);
}
public void Update()
{
//IL_0063: 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)
float unscaledDeltaTime = Time.unscaledDeltaTime;
_time += unscaledDeltaTime;
float num = Mathf.Clamp01(_time / _duration);
float num2 = 1f - Mathf.Pow(1f - num, 4f);
float num3 = Mathf.Lerp(_from, _to, num2);
((Component)this).transform.localRotation = Quaternion.Euler(0f, 0f, num3);
_onAngle?.Invoke(num3);
int num4 = Line(num3, _step);
if (num4 != _line)
{
_line = num4;
_kick = 1f;
}
else
{
_kick = Mathf.Max(0f, _kick - unscaledDeltaTime * 7f);
}
if ((Object)(object)_pointer != (Object)null)
{
_pointer.localRotation = Quaternion.Euler(0f, 0f, 26f * Mathf.SmoothStep(0f, 1f, _kick));
}
if (!(num < 1f))
{
Finish();
}
}
public void OnDestroy()
{
Finish();
}
private void Finish()
{
//IL_0024: Unknown result type (might be due to invalid IL or missing references)
if (!Running && _onDone == null)
{
return;
}
if ((Object)(object)_pointer != (Object)null)
{
_pointer.localRotation = Quaternion.identity;
}
((Behaviour)this).enabled = false;
Running = false;
Action onDone = _onDone;
_onDone = null;
try
{
onDone?.Invoke();
}
catch (Exception ex)
{
Plugin.L.LogWarning((object)("wheel: " + ex.Message));
}
}
}
internal static class Rules
{
private static LobbyRule<bool> _on;
private static LobbyRule<int> _times;
private static LobbyRule<int> _full;
private static LobbyRule<int> _noCulture;
private static LobbyRule<int> _fresh;
private static LobbyRule<int> _seconds;
private static bool _fixing;
internal static bool On
{
get
{
if (Plugin.On && _on != null)
{
return _on.Value;
}
return false;
}
}
internal static int Times => _times?.Value ?? 1;
internal static int FullPercent => _full?.Value ?? 15;
internal static int NoCulturePercent => _noCulture?.Value ?? 15;
internal static int FreshPercent => _fresh?.Value ?? 20;
internal static int Seconds => _seconds?.Value ?? 60;
internal static void Install()
{
_on = Rules.Toggle("revive.on", "Revive", false, "When a human player loses the castle, the other living human players vote whether that player gets one spin of the wheel of revival (a majority is needed).", (Func<bool>)null, true);
Func<bool> func = () => _on != null && _on.Live;
_times = Rules.Number("revive.times", "Revivals per player", 1, 1, 5, 1, "How many times one player can lose the castle and get a vote in one match.", func, true);
_full = Rules.Number("revive.full", "Back fully (%)", 15, 0, 100, 5, "Chance that the island, resources and technologies come back exactly as before the castle fell, culture included. The three chances together are at most 100 %; the rest of the wheel: the player stays out.", func, true);
_noCulture = Rules.Number("revive.noCulture", "Without culture (%)", 15, 0, 100, 5, "Chance of coming back the same way, but without the stored culture.", func, true);
_fresh = Rules.Number("revive.fresh", "Fresh start (%)", 20, 0, 100, 5, "Chance of the island as at the start of the match with the starting buildings; food, wood, stone and military full, 10 hammers, 15 culture, no gold; technologies are lost.", func, true);
_seconds = Rules.Number("revive.seconds", "Voting time (s)", 60, 20, 120, 10, "How long the other players have to vote.", func, true);
LobbyRule<int>[] array = new LobbyRule<int>[3] { _full, _noCulture, _fresh };
foreach (LobbyRule<int> val in array)
{
LobbyRule<int> r = val;
r.Changed += delegate
{
KeepSum(r);
};
}
Lobby.Changed += delegate
{
KeepSum(null);
};
LobbyGroup val2 = Groups.Get("revive", "Revive", 500);
_on.InGroup(val2);
_times.InGroup(val2);
_full.InGroup(val2);
_noCulture.InGroup(val2);
_fresh.InGroup(val2);
_seconds.InGroup(val2);
}
private static void KeepSum(LobbyRule<int> changed)
{
if (_fixing || _full == null || _noCulture == null || _fresh == null || !_full.Editable)
{
return;
}
int num = _full.Live + _noCulture.Live + _fresh.Live - 100;
if (num <= 0)
{
return;
}
_fixing = true;
try
{
LobbyRule<int>[] array = ((changed == null) ? new LobbyRule<int>[3] { _fresh, _noCulture, _full } : new LobbyRule<int>[1] { changed });
foreach (LobbyRule<int> val in array)
{
int num2 = Math.Min(num, val.Live);
if (num2 > 0 && val.TrySet(val.Live - num2))
{
num -= num2;
}
if (num <= 0)
{
break;
}
}
}
catch (Exception ex)
{
Plugin.Once("sum", "revive (chances): " + ex.Message);
}
finally
{
_fixing = false;
}
}
}
internal static class Snapshots
{
private sealed class Terrain
{
public byte[] Ground;
public byte[] Nature;
}
private static readonly Dictionary<ulong, Terrain> Latest = new Dictionary<ulong, Terrain>();
private static readonly Dictionary<ulong, Terrain> Start = new Dictionary<ulong, Terrain>();
private static readonly int Header = 4 * IntPtr.Size;
internal static void Clear()
{
Latest.Clear();
Start.Clear();
}
internal static void Take(MatchPlayer p, bool alsoStart)
{
object obj;
if (p == null)
{
obj = null;
}
else
{
Island island = p.Island;
obj = ((island != null) ? island.grid : null);
}
IslandGrid val = (IslandGrid)obj;
if ((Object)(object)val == (Object)null)
{
return;
}
try
{
if (!Latest.TryGetValue(p.Id, out var value))
{
value = (Latest[p.Id] = new Terrain());
}
Read(val, value);
if (alsoStart && !Start.ContainsKey(p.Id))
{
Terrain terrain2 = new Terrain();
if (Read(val, terrain2))
{
Start[p.Id] = terrain2;
}
}
}
catch (Exception ex)
{
Plugin.Once("terrain", "revive (terrain copy): " + ex.Message);
}
}
private static bool Read(IslandGrid grid, Terrain t)
{
Il2CppArrayBase<GroundTile> val = grid.groundLayer?.contents;
Il2CppArrayBase<Nullable<NatureTile>> val2 = grid.natureLayer?.contents;
if (val == null || val2 == null)
{
return false;
}
t.Ground = ReadArray(((Il2CppObjectBase)val).Pointer, t.Ground);
t.Nature = ReadArray(((Il2CppObjectBase)val2).Pointer, t.Nature);
return true;
}
private static byte[] ReadArray(IntPtr array, byte[] buffer)
{
int num = (int)IL2CPP.il2cpp_array_get_byte_length(array);
if (buffer == null || buffer.Length != num)
{
buffer = new byte[num];
}
Marshal.Copy(array + Header, buffer, 0, num);
return buffer;
}
private static IntPtr ArrayLike(IntPtr live, byte[] bytes)
{
if (live == IntPtr.Zero || bytes == null)
{
return IntPtr.Zero;
}
IntPtr intPtr = IL2CPP.il2cpp_object_get_class(live);
uint num = IL2CPP.il2cpp_array_length(live);
IntPtr intPtr2 = IL2CPP.il2cpp_array_new_specific(intPtr, (ulong)num);
if (intPtr2 == IntPtr.Zero || IL2CPP.il2cpp_array_get_byte_length(intPtr2) != (uint)bytes.Length)
{
return IntPtr.Zero;
}
Marshal.Copy(bytes, 0, intPtr2 + Header, bytes.Length);
return intPtr2;
}
private static int IndexOf(GameState gs, Player player)
{
List<Player> val = ((gs != null) ? gs.Players : null);
if (val == null || (Object)(object)player == (Object)null)
{
return -1;
}
for (int i = 0; i < val.Count; i++)
{
if ((Object)(object)val[i] != (Object)null && ((Il2CppObjectBase)val[i]).Pointer == ((Il2CppObjectBase)player).Pointer)
{
return i;
}
}
return -1;
}
private static bool HasCapacity(SyncData s)
{
//IL_0001: Unknown result type (might be due to invalid IL or missing references)
//IL_0006: Unknown result type (might be due to invalid IL or missing references)
//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_0012: Unknown result type (might be due to invalid IL or missing references)
//IL_0019: 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_0035: Unknown result type (might be due to invalid IL or missing references)
ResourceAmount capacity = s.storage.capacity;
return capacity.food + capacity.wood + capacity.stone + capacity.gold + capacity.hammer + capacity.culture + capacity.military > 0;
}
private static bool Find(SnapshotStore store, int player, bool last, out Key key)
{
//IL_0001: Unknown result type (might be due to invalid IL or missing references)
//IL_005c: Unknown result type (might be due to invalid IL or missing references)
//IL_0066: Unknown result type (might be due to invalid IL or missing references)
//IL_0070: 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_0081: Unknown result type (might be due to invalid IL or missing references)
key = default(Key);
Dictionary<Key, SyncData> statisticsStore = store.statisticsStore;
Dictionary<Key, SyncData> gridStore = store.gridStore;
if (statisticsStore == null || gridStore == null)
{
return false;
}
int maxTurn = store.maxTurn;
int maxPhase = store.maxPhase;
Key val = default(Key);
for (int i = 0; i <= maxTurn; i++)
{
int num = (last ? (maxTurn - i) : i);
for (int j = 0; j <= maxPhase; j++)
{
int num2 = (last ? (maxPhase - j) : j);
((Key)(ref val))..ctor(player, num, num2);
if (statisticsStore.ContainsKey(val) && gridStore.ContainsKey(val) && HasCapacity(statisticsStore[val]))
{
key = val;
return true;
}
}
}
return false;
}
internal static bool Restore(MatchPlayer p, Outcome outcome, out string why)
{
//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
//IL_00b7: 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: 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_00eb: Unknown result type (might be due to invalid IL or missing references)
//IL_00fa: Expected O, but got Unknown
//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
//IL_01df: Unknown result type (might be due to invalid IL or missing references)
//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
//IL_026d: Unknown result type (might be due to invalid IL or missing references)
//IL_026f: Unknown result type (might be due to invalid IL or missing references)
//IL_0271: Unknown result type (might be due to invalid IL or missing references)
//IL_0207: Unknown result type (might be due to invalid IL or missing references)
//IL_020f: 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_022b: Unknown result type (might be due to invalid IL or missing references)
//IL_0239: Unknown result type (might be due to invalid IL or missing references)
//IL_0267: Unknown result type (might be due to invalid IL or missing references)
//IL_0269: Unknown result type (might be due to invalid IL or missing references)
why = "";
Island val = ((p != null) ? p.Island : null);
IslandGrid val2 = ((val != null) ? val.grid : null);
Statistics val3 = ((val != null) ? val.statistics : null);
GameState val4 = ((val != null) ? val.GameState : null);
SnapshotStore val5 = ((val4 != null) ? val4.snapshotStore : null);
if ((Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null || (Object)(object)val5 == (Object)null)
{
why = "no island";
return false;
}
bool flag = outcome == Outcome.Fresh;
int num = IndexOf(val4, p.Game);
if (num < 0 || !Find(val5, num, !flag, out var key))
{
why = "the game kept no state of this island with a castle";
return false;
}
SyncData val6 = val5.gridStore[key];
SyncData val7 = new SyncData
{
buildings = val6.buildings,
remains = val6.remains,
innerCliffs = val6.innerCliffs,
groundTiles = val6.groundTiles,
natureTiles = val6.natureTiles
};
Terrain value;
Terrain terrain = ((flag ? Start : Latest).TryGetValue(p.Id, out value) ? value : null);
if (terrain != null)
{
IntPtr intPtr = ArrayLike(((Il2CppObjectBase)val2.groundLayer.contents).Pointer, terrain.Ground);
IntPtr intPtr2 = ArrayLike(((Il2CppObjectBase)val2.natureLayer.contents).Pointer, terrain.Nature);
if (intPtr != IntPtr.Zero && intPtr2 != IntPtr.Zero)
{
val7.groundTiles = new Il2CppStructArray<GroundTile>(intPtr);
val7.natureTiles = new Il2CppReferenceArray<Nullable<NatureTile>>(intPtr2);
}
else
{
Plugin.L.LogWarning((object)"revive: the terrain copy does not fit the island; the terrain stays as it is now");
}
}
else
{
Plugin.L.LogWarning((object)("revive: no terrain copy of " + p.Name + "; the terrain stays as it is now"));
}
SyncData val8 = val5.statisticsStore[key];
ResourceStorage storage = val8.storage;
ResourceAmount val9 = storage.stored;
ResourceAmount capacity = storage.capacity;
if (outcome == Outcome.NoCulture)
{
val9.culture = 0;
}
else if (flag)
{
val9 = new ResourceAmount
{
food = capacity.food,
wood = capacity.wood,
stone = capacity.stone,
military = capacity.military,
gold = 0,
hammer = 10,
culture = 15,
disaster = 0
};
}
val8.storage = new ResourceStorage(val9, capacity);
Il2CppStructArray<byte> val10 = null;
try
{
val10 = val2.ExportIsland();
}
catch (Exception ex)
{
Plugin.L.LogWarning((object)("revive: could not copy the island before putting it back: " + ex.Message));
}
try
{
((IslandSyncedBehaviour<SyncData>)(object)val2).ApplySync(val7);
}
catch (Exception ex2)
{
why = "the game refused the island: " + (ex2.Message ?? "").Split('\n')[0].Trim();
if (val10 != null)
{
try
{
val2.ImportIsland(val10);
Plugin.L.LogInfo((object)"revive: the island was put back as it was");
}
catch (Exception ex3)
{
Plugin.L.LogError((object)("revive: putting the island back as it was failed too: " + ex3.Message));
}
}
try
{
val.Sync();
}
catch (Exception ex4)
{
Plugin.L.LogWarning((object)("revive: sync after the failure: " + ex4.Message));
}
return false;
}
((IslandSyncedBehaviour<SyncData>)(object)val3).ApplySync(val8);
val.Recompute();
p.Game.IsDefeated = false;
val.Sync();
Plugin.L.LogInfo((object)($"revive: {p.Name} is back ({outcome}) from the game's state of turn {((Key)(ref key)).Turn}, phase {((Key)(ref key)).Phase}" + ((terrain == null) ? " (current terrain)" : "")));
return true;
}
internal static bool HasCastle(IslandGrid grid)
{
//IL_002e: Unknown result type (might be due to invalid IL or missing references)
//IL_0034: Invalid comparison between Unknown and I4
if ((Object)(object)grid == (Object)null)
{
return false;
}
Enumerator<Id, Building> enumerator = grid.Buildings.GetEnumerator();
while (enumerator.MoveNext())
{
Building current = enumerator.Current;
if (current.type != null && (int)current.type.name == 2)
{
return true;
}
}
return false;
}
}
internal static class Tx
{
internal static TextSet Set;
internal static void Load()
{
Set = Texts.Load("texts.json", (string)null);
}
internal static string T(string key)
{
TextSet set = Set;
return ((set != null) ? set.Get(key) : null) ?? key;
}
internal static string T(string key, params object[] values)
{
TextSet set = Set;
return ((set != null) ? set.Get(key, values) : null) ?? key;
}
}
internal enum Stage
{
None,
Vote,
Spin,
Fail
}
internal sealed class VoteState
{
public int Seq;
public Stage Stage;
public ulong Dead;
public int Face = -1;
public int Seconds;
public List<ulong> Voters = new List<ulong>();
public int Yes;
public int No;
public string Write()
{
string[] obj = new string[8]
{
Seq.ToString(CultureInfo.InvariantCulture),
null,
null,
null,
null,
null,
null,
null
};
int stage = (int)Stage;
obj[1] = stage.ToString(CultureInfo.InvariantCulture);
obj[2] = Dead.ToString(CultureInfo.InvariantCulture);
obj[3] = Face.ToString(CultureInfo.InvariantCulture);
obj[4] = Seconds.ToString(CultureInfo.InvariantCulture);
obj[5] = string.Join(",", Voters);
obj[6] = Yes.ToString(CultureInfo.InvariantCulture);
obj[7] = No.ToString(CultureInfo.InvariantCulture);
return string.Join("|", obj);
}
public static VoteState Read(string raw)
{
if (string.IsNullOrEmpty(raw))
{
return null;
}
string[] array = raw.Split('|');
if (array.Length < 8)
{
return null;
}
VoteState voteState = new VoteState();
if (!int.TryParse(array[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out voteState.Seq))
{
return null;
}
if (!int.TryParse(array[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || result < 0 || result > 3)
{
return null;
}
voteState.Stage = (Stage)result;
ulong.TryParse(array[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out voteState.Dead);
int.TryParse(array[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out voteState.Face);
int.TryParse(array[4], NumberStyles.Integer, CultureInfo.InvariantCulture, out voteState.Seconds);
string[] array2 = array[5].Split(',', StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < array2.Length; i++)
{
if (ulong.TryParse(array2[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2))
{
voteState.Voters.Add(result2);
}
}
int.TryParse(array[6], NumberStyles.Integer, CultureInfo.InvariantCulture, out voteState.Yes);
int.TryParse(array[7], NumberStyles.Integer, CultureInfo.InvariantCulture, out voteState.No);
if (voteState.Face >= 20)
{
voteState.Face = -1;
}
return voteState;
}
}
internal static class Votes
{
internal const string StateKey = "revive.state";
internal const string BallotKey = "revive.ballot";
private static float _receivedAt;
private static readonly Dictionary<int, bool> Mine = new Dictionary<int, bool>();
internal static VoteState Current { get; private set; }
internal static ulong LocalId
{
get
{
MatchPlayer local = Players.Local;
if (local == null)
{
return 0uL;
}
return local.Id;
}
}
private static ulong HostId
{
get
{
MatchPlayer host = Players.Host;
if (host == null)
{
return 0uL;
}
return host.Id;
}
}
internal static int SecondsLeft
{
get
{
if (Current != null)
{
return Math.Max(0, (int)Math.Ceiling((float)Current.Seconds - (Time.unscaledTime - _receivedAt)));
}
return 0;
}
}
internal static float Age => Time.unscaledTime - _receivedAt;
internal static bool CanVote
{
get
{
VoteState current = Current;
if (current != null && current.Stage == Stage.Vote && current.Voters.Contains(LocalId) && !Mine.ContainsKey(current.Seq))
{
return SecondsLeft > 0;
}
return false;
}
}
internal static bool? MyBallot
{
get
{
if (Current == null || !Mine.TryGetValue(Current.Seq, out var value))
{
return null;
}
return value;
}
}
internal static event Action Changed;
internal static event Action BallotsChanged;
internal static void Install()
{
Match.Started += Clear;
Match.Ended += Clear;
Match.GameOver += Clear;
Match.Rejoined += ReadHost;
PlayerValues.Changed += OnValues;
}
private static void Clear()
{
Current = null;
Mine.Clear();
if (Lobby.InLobby)
{
PlayerValues.Set("revive.ballot", "");
}
Raise(Votes.Changed);
}
private static void Raise(Action handler)
{
try
{
handler?.Invoke();
}
catch (Exception ex)
{
Plugin.Once("votes:event", "revive (window): " + ex);
}
}
private static void OnValues(ulong steamId)
{
if (Rules.On && Match.Running)
{
if (steamId == HostId && !Host.IsHost)
{
ReadHost();
}
if (Current != null && Current.Stage == Stage.Vote)
{
Raise(Votes.BallotsChanged);
}
}
}
private static void ReadHost()
{
if (Rules.On && !Host.IsHost)
{
VoteState voteState = VoteState.Read(PlayerValues.Get(HostId, "revive.state"));
if (voteState != null)
{
Apply(voteState);
}
}
}
internal static void Apply(VoteState s)
{
if (s != null && (Current == null || Current.Seq != s.Seq || Current.Stage != s.Stage))
{
Current = s;
_receivedAt = Time.unscaledTime;
Raise(Votes.Changed);
}
}
internal static bool? BallotOf(ulong id)
{
VoteState current = Current;
if (current == null)
{
return null;
}
if (id == LocalId && Mine.TryGetValue(current.Seq, out var value))
{
return value;
}
string text = PlayerValues.Get(id, "revive.ballot");
if (string.IsNullOrEmpty(text))
{
return null;
}
string[] array = text.Split('|');
if (array.Length < 2 || !int.TryParse(array[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || result != current.Seq)
{
return null;
}
if (!(array[1] == "y"))
{
if (!(array[1] == "n"))
{
return null;
}
return false;
}
return true;
}
internal static (int yes, int no) Count()
{
int num = 0;
int num2 = 0;
if (Current == null)
{
return (yes: 0, no: 0);
}
foreach (ulong voter in Current.Voters)
{
bool? flag = BallotOf(voter);
if (flag == true)
{
num++;
}
else if (flag == false)
{
num2++;
}
}
return (yes: num, no: num2);
}
internal static void Cast(bool yes)
{
if (CanVote)
{
int seq = Current.Seq;
Mine[seq] = yes;
PlayerValues.Set("revive.ballot", seq.ToString(CultureInfo.InvariantCulture) + "|" + (yes ? "y" : "n"));
if (Host.IsHost)
{
Host.Receive(LocalId, seq, yes);
}
Raise(Votes.BallotsChanged);
}
}
}
internal static class WheelArt
{
internal static readonly Color Full = new Color(0.93f, 0.74f, 0.28f);
internal static readonly Color NoCulture = new Color(0.47f, 0.7f, 0.38f);
internal static readonly Color Fresh = new Color(0.42f, 0.62f, 0.86f);
internal static readonly Color Out = new Color(0.56f, 0.5f, 0.47f);
private static readonly Color Out2 = new Color(0.47f, 0.41f, 0.38f);
private static readonly Color Wood = new Color(0.36f, 0.24f, 0.15f);
private static readonly Color WoodDark = new Color(0.25f, 0.16f, 0.1f);
private static readonly Color Gold = new Color(0.96f, 0.8f, 0.38f);
private static readonly Color GoldDark = new Color(0.72f, 0.53f, 0.2f);
private static readonly Color Clear = new Color(0f, 0f, 0f, 0f);
internal static Color Of(Outcome o, int face)
{
//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_001e: Unknown result type (might be due to invalid IL or missing references)
//IL_0023: 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)
//IL_0040: Unknown result type (might be due to invalid IL or missing references)
//IL_003a: Unknown result type (might be due to invalid IL or missing references)
//IL_0033: Unknown result type (might be due to invalid IL or missing references)
//IL_003f: Unknown result type (might be due to invalid IL or missing references)
return (Color)(o switch
{
Outcome.Full => Full,
Outcome.NoCulture => NoCulture,
Outcome.Fresh => Fresh,
_ => (face % 2 == 0) ? Out : Out2,
});
}
internal static Texture2D Disc(int size, Outcome[] faces)
{
//IL_0004: Unknown result type (might be due to invalid IL or missing references)
//IL_0009: Unknown result type (might be due to invalid IL or missing references)
//IL_0010: Unknown result type (might be due to invalid IL or missing references)
//IL_001c: Expected O, but got Unknown
//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
//IL_00ba: 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_00db: Unknown result type (might be due to invalid IL or missing references)
//IL_00f9: 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_02c9: Unknown result type (might be due to invalid IL or missing references)
//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
//IL_01b1: 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_0160: Unknown result type (might be due to invalid IL or missing references)
//IL_0170: Unknown result type (might be due to invalid IL or missing references)
//IL_0175: Unknown result type (might be due to invalid IL or missing references)
//IL_0243: Unknown result type (might be due to invalid IL or missing references)
//IL_0248: Unknown result type (might be due to invalid IL or missing references)
//IL_0268: Unknown result type (might be due to invalid IL or missing references)
//IL_0277: Unknown result type (might be due to invalid IL or missing references)
//IL_0286: Unknown result type (might be due to invalid IL or missing references)
//IL_02a8: 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_02ba: 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_01f0: Unknown result type (might be due to invalid IL or missing references)
//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
//IL_0201: Unknown result type (might be due to invalid IL or missing references)
Texture2D val = Keep(new Texture2D(size, size, (TextureFormat)4, false)
{
filterMode = (FilterMode)1,
wrapMode = (TextureWrapMode)1
});
Color[] array = (Color[])(object)new Color[size * size];
float num = (float)(size - 1) / 2f;
float num2 = (float)size / 2f - 1.5f;
float num3 = num2 * 0.86f;
float num4 = num2 * 0.16f;
int num5 = faces.Length;
float num6 = 360f / (float)num5;
Color val2 = default(Color);
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
float num7 = (float)j - num;
float num8 = (float)i - num;
float num9 = Mathf.Sqrt(num7 * num7 + num8 * num8);
float num10 = Mathf.Atan2(num7, num8) * 57.29578f;
if (num10 < 0f)
{
num10 += 360f;
}
if (num9 > num2)
{
val2 = Clear;
}
else if (num9 > num3)
{
float num11 = (num9 - num3) / (num2 - num3);
val2 = Color.Lerp(WoodDark, Wood, 1f - Mathf.Abs(num11 - 0.5f) * 2f);
float num12 = ((num10 / num6 + 0.5f) % 1f - 0.5f) * num6 * ((float)Math.PI / 180f) * ((num3 + num2) / 2f);
float num13 = num9 - (num3 + num2) / 2f;
float num14 = Mathf.Sqrt(num12 * num12 + num13 * num13);
float num15 = (num2 - num3) * 0.28f;
if (num14 < num15)
{
val2 = Color.Lerp(Gold, GoldDark, num14 / num15 * 0.8f);
}
if (num9 > num2 - 1.2f)
{
val2.a = Mathf.Clamp01(num2 - num9 + 0.2f);
}
}
else if (num9 > num3 - 2.2f)
{
val2 = GoldDark;
}
else if (num9 < num4)
{
float num16 = num9 / num4;
val2 = ((num9 < num4 * 0.45f) ? Color.Lerp(Gold, GoldDark, num16) : Color.Lerp(GoldDark, WoodDark, (num16 - 0.45f) * 1.4f));
}
else
{
int num17 = Mathf.Min(num5 - 1, (int)(num10 / num6));
float num18 = Mathf.Min(num10 - (float)num17 * num6, (float)(num17 + 1) * num6 - num10) * ((float)Math.PI / 180f) * num9;
Color val3 = Of(faces[num17], num17);
float num19 = Mathf.Lerp(0.82f, 1.06f, (num9 - num4) / (num3 - num4));
((Color)(ref val2))..ctor(Mathf.Clamp01(val3.r * num19), Mathf.Clamp01(val3.g * num19), Mathf.Clamp01(val3.b * num19), 1f);
if (num18 < 1.3f)
{
val2 = Color.Lerp(GoldDark, Gold, num18 / 1.3f);
}
}
array[i * size + j] = val2;
}
}
val.SetPixels(Il2CppStructArray<Color>.op_Implicit(array));
val.Apply();
return val;
}
private static Texture2D Keep(Texture2D tex)
{
((Object)tex).hideFlags = (HideFlags)32;
return tex;
}
internal static Texture2D Pointer(int width, int height)
{
//IL_0004: Unknown result type (might be due to invalid IL or missing references)
//IL_0009: Unknown result type (might be due to invalid IL or missing references)
//IL_0010: Unknown result type (might be due to invalid IL or missing references)
//IL_001c: Expected O, but got Unknown
//IL_0093: Unknown result type (might be due to invalid IL or missing references)
//IL_0098: Unknown result type (might be due to invalid IL or missing references)
//IL_008c: Unknown result type (might be due to invalid IL or missing references)
//IL_0076: Unknown result type (might be due to invalid IL or missing references)
//IL_007b: Unknown result type (might be due to invalid IL or missing references)
//IL_0085: Unknown result type (might be due to invalid IL or missing references)
Texture2D val = Keep(new Texture2D(width, height, (TextureFormat)4, false)
{
filterMode = (FilterMode)1,
wrapMode = (TextureWrapMode)1
});
Color[] array = (Color[])(object)new Color[width * height];
float num = (float)(width - 1) / 2f;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
float num2 = (float)i / (float)(height - 1) * ((float)width * 0.24f) - Mathf.Abs((float)j - num);
array[i * width + j] = ((num2 < 0f) ? Clear : ((num2 < 2f || i > height - 3) ? WoodDark : Color.Lerp(GoldDark, Gold, (float)i / (float)height)));
}
}
val.SetPixels(Il2CppStructArray<Color>.op_Implicit(array));
val.Apply();
return val;
}
internal static void AddIcons(GameObject picture, Outcome[] faces, Func<Outcome, Sprite> icon, float iconSize)
{
//IL_008f: Unknown result type (might be due to invalid IL or missing references)
//IL_0094: Unknown result type (might be due to invalid IL or missing references)
//IL_00a6: 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_00e2: 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_00f7: Unknown result type (might be due to invalid IL or missing references)
//IL_010e: Unknown result type (might be due to invalid IL or missing references)
if ((Object)(object)picture == (Object)null)
{
return;
}
for (int num = picture.transform.childCount - 1; num >= 0; num--)
{
Object.Destroy((Object)(object)((Component)picture.transform.GetChild(num)).gameObject);
}
int num2 = faces.Length;
Vector2 val3 = default(Vector2);
for (int i = 0; i < num2; i++)
{
Sprite val;
try
{
val = icon(faces[i]);
}
catch
{
val = null;
}
if (!((Object)(object)val == (Object)null))
{
float num3 = ((float)i + 0.5f) * 360f / (float)num2;
float num4 = num3 * ((float)Math.PI / 180f);
GameObject val2 = new GameObject("Revive face " + i);
val2.transform.SetParent(picture.transform, false);
RectTransform obj2 = val2.AddComponent<RectTransform>();
((Vector2)(ref val3))..ctor(0.5f + 0.31f * Mathf.Sin(num4), 0.5f + 0.31f * Mathf.Cos(num4));
obj2.anchorMin = val3;
obj2.anchorMax = val3;
obj2.sizeDelta = new Vector2(iconSize, iconSize);
obj2.anchoredPosition = Vector2.zero;
((Transform)obj2).localRotation = Quaternion.Euler(0f, 0f, 0f - num3);
Image obj3 = val2.AddComponent<Image>();
obj3.sprite = val;
obj3.preserveAspect = true;
((Graphic)obj3).raycastTarget = false;
}
}
}
}
}