Decompiled source of WhisperOfTheWorld v0.9.0

WhisperOfTheWorld/WhisperOfTheWorld.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Splatform;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using WhisperOfTheWorld.Content;
using WhisperOfTheWorld.Content.Models;
using WhisperOfTheWorld.Core;
using WhisperOfTheWorld.Core.Commands;
using WhisperOfTheWorld.Core.Config;
using WhisperOfTheWorld.Domain;
using WhisperOfTheWorld.Domain.Events;
using WhisperOfTheWorld.GameAdapter;
using WhisperOfTheWorld.Generation;
using WhisperOfTheWorld.Network;
using WhisperOfTheWorld.Persistence;
using WhisperOfTheWorld.Presentation;
using WhisperOfTheWorld.Quests;
using WhisperOfTheWorld.WorldAwareness;

[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("WhisperOfTheWorld")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.9.0.0")]
[assembly: AssemblyInformationalVersion("0.9.0")]
[assembly: AssemblyProduct("WhisperOfTheWorld")]
[assembly: AssemblyTitle("WhisperOfTheWorld")]
[assembly: AssemblyVersion("0.9.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 WhisperOfTheWorld.WorldAwareness
{
	public static class ProgressionModel
	{
		public static int ComputeTier(IEnumerable<BossInfo> bosses, ICollection<string> globalKeys, out List<string> defeatedKeys)
		{
			defeatedKeys = new List<string>();
			if (bosses == null || globalKeys == null)
			{
				return 0;
			}
			HashSet<string> hashSet = new HashSet<string>(globalKeys, StringComparer.OrdinalIgnoreCase);
			int num = 0;
			foreach (BossInfo boss in bosses)
			{
				if (hashSet.Contains(boss.GlobalKey))
				{
					if (!defeatedKeys.Contains<string>(boss.GlobalKey, StringComparer.OrdinalIgnoreCase))
					{
						defeatedKeys.Add(boss.GlobalKey);
					}
					if (boss.Order > 0)
					{
						num = Math.Max(num, boss.Order);
					}
				}
			}
			return num;
		}

		public static List<string> AddedKeys(IEnumerable<string> before, IEnumerable<string> after)
		{
			HashSet<string> previous = new HashSet<string>(before ?? Enumerable.Empty<string>(), StringComparer.OrdinalIgnoreCase);
			return (after ?? Enumerable.Empty<string>()).Where((string k) => !previous.Contains(k)).OrderBy<string, string>((string k) => k, StringComparer.Ordinal).ToList();
		}
	}
	internal sealed class WorldAwarenessService
	{
		private readonly WowConfig config;

		private readonly EventBus bus;

		private readonly ValheimGameCatalog catalog;

		private long sequence;

		private long currentWorldUid;

		private float nextSnapshotAt;

		private float nextBiomeAt;

		private bool refreshRequested;

		private string refreshReason;

		private string lastLocalBiome;

		private string lastLocalSector;

		private List<string> lastGlobalKeys;

		private int lastTier;

		public WorldContextSnapshot Current { get; private set; }

		public WorldAwarenessService(WowConfig config, EventBus bus, ValheimGameCatalog catalog)
		{
			this.config = config;
			this.bus = bus;
			this.catalog = catalog;
		}

		public void RequestRefresh(string reason)
		{
			refreshRequested = true;
			refreshReason = reason;
		}

		public void Reset()
		{
			Current = null;
			currentWorldUid = 0L;
			lastLocalBiome = null;
			lastLocalSector = null;
			lastGlobalKeys = null;
			lastTier = 0;
			refreshRequested = false;
		}

		public void Tick(float now)
		{
			if (!GameState.InWorld)
			{
				if (currentWorldUid != 0L)
				{
					Reset();
				}
				return;
			}
			long worldUID = ZNet.instance.GetWorldUID();
			if (worldUID != currentWorldUid)
			{
				Reset();
				currentWorldUid = worldUID;
				RequestRefresh("world loaded");
			}
			if (now >= nextBiomeAt)
			{
				nextBiomeAt = now + config.BiomeCheckIntervalSeconds.Value;
				SampleLocalBiome();
			}
			if (refreshRequested || now >= nextSnapshotAt)
			{
				string reason = (refreshRequested ? refreshReason : "interval");
				refreshRequested = false;
				nextSnapshotAt = now + (float)config.WorldSnapshotIntervalSeconds.Value;
				Rebuild(reason);
			}
		}

		private void SampleLocalBiome()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return;
			}
			string biome = ((object)localPlayer.GetCurrentBiome()/*cast due to .constrained prefix*/).ToString();
			string sector = WorldReader.SafeSectorName(localPlayer.GetCurrentBiomeData());
			if (biome == lastLocalBiome && sector == lastLocalSector)
			{
				return;
			}
			string previous = lastLocalBiome;
			lastLocalBiome = biome;
			lastLocalSector = sector;
			if (!(biome == ((object)(Biome)0/*cast due to .constrained prefix*/).ToString()))
			{
				Log.Debug(() => "Local biome: " + (previous ?? "-") + " -> " + biome + " (" + sector + ")");
				bus.Publish(new LocalBiomeChangedEvent(localPlayer.GetPlayerID(), previous, biome, sector));
				RequestRefresh("local biome changed");
			}
		}

		private void Rebuild(string reason)
		{
			try
			{
				IReadOnlyList<BossInfo> readOnlyList2;
				if (!catalog.IsReady)
				{
					IReadOnlyList<BossInfo> readOnlyList = Array.Empty<BossInfo>();
					readOnlyList2 = readOnlyList;
				}
				else
				{
					readOnlyList2 = catalog.Bosses;
				}
				IReadOnlyList<BossInfo> bosses = readOnlyList2;
				WorldContextSnapshot snapshot = WorldReader.Capture(++sequence, bosses);
				Current = snapshot;
				if (snapshot.IsAuthority)
				{
					if (lastGlobalKeys != null)
					{
						List<string> list = (from k in ProgressionModel.AddedKeys(lastGlobalKeys, snapshot.GlobalKeys)
							where k.IndexOf(' ') < 0
							select k).ToList();
						if (list.Count > 0)
						{
							Log.Info(string.Format("World progression: +{0} (tier {1} -> {2}).", string.Join(", ", list), lastTier, snapshot.ProgressionTier));
							bus.Publish(new WorldProgressionChangedEvent(list, lastTier, snapshot.ProgressionTier));
						}
					}
					lastGlobalKeys = new List<string>(snapshot.GlobalKeys);
					lastTier = snapshot.ProgressionTier;
				}
				Log.Debug(() => $"Snapshot #{snapshot.Sequence} ({reason}): day {snapshot.Day}, tier {snapshot.ProgressionTier}, players {snapshot.Players.Count}.");
				bus.Publish(new WorldSnapshotUpdatedEvent(snapshot, reason));
			}
			catch (Exception ex)
			{
				Log.Error("World snapshot failed", ex);
			}
		}
	}
	public sealed class BossInfo
	{
		public string Prefab { get; }

		public string NameToken { get; }

		public string GlobalKey { get; }

		public int Order { get; }

		public BossInfo(string prefab, string nameToken, string globalKey, int order)
		{
			Prefab = prefab;
			NameToken = nameToken;
			GlobalKey = globalKey;
			Order = order;
		}
	}
	public sealed class PlayerContext
	{
		public long PlayerId { get; set; }

		public long PeerUid { get; set; }

		public string Name { get; set; }

		public bool IsLocal { get; set; }

		public string Biome { get; set; }

		public string Sector { get; set; }

		public float X { get; set; }

		public float Z { get; set; }

		public bool InInterior { get; set; }

		public bool? IsDead { get; set; }

		public bool? IsSensedByEnemies { get; set; }

		public string Environment { get; set; }
	}
	public sealed class WorldContextSnapshot
	{
		public long Sequence { get; }

		public DateTime CapturedUtc { get; }

		public long WorldUid { get; }

		public string WorldName { get; }

		public bool IsAuthority { get; }

		public int Day { get; }

		public bool IsNight { get; }

		public int ProgressionTier { get; }

		public IReadOnlyList<string> DefeatedBossKeys { get; }

		public IReadOnlyCollection<string> GlobalKeys { get; }

		public IReadOnlyList<PlayerContext> Players { get; }

		public PlayerContext LocalPlayer => Players.FirstOrDefault((PlayerContext p) => p.IsLocal);

		public WorldContextSnapshot(long sequence, DateTime capturedUtc, long worldUid, string worldName, bool isAuthority, int day, bool isNight, int progressionTier, IReadOnlyList<string> defeatedBossKeys, IReadOnlyCollection<string> globalKeys, IReadOnlyList<PlayerContext> players)
		{
			Sequence = sequence;
			CapturedUtc = capturedUtc;
			WorldUid = worldUid;
			WorldName = worldName;
			IsAuthority = isAuthority;
			Day = day;
			IsNight = isNight;
			ProgressionTier = progressionTier;
			DefeatedBossKeys = defeatedBossKeys ?? Array.Empty<string>();
			GlobalKeys = (IReadOnlyCollection<string>)(((object)globalKeys) ?? ((object)Array.Empty<string>()));
			Players = players ?? Array.Empty<PlayerContext>();
		}

		public bool HasGlobalKey(string key)
		{
			return GlobalKeys.Contains<string>(key, StringComparer.OrdinalIgnoreCase);
		}

		public PlayerContext FindPlayer(long playerId)
		{
			return Players.FirstOrDefault((PlayerContext p) => p.PlayerId == playerId);
		}
	}
}
namespace WhisperOfTheWorld.Quests
{
	internal sealed class AuthorityService : IQuestEngineSink
	{
		private sealed class Binding
		{
			public long PlayerId;

			public string Name;
		}

		private const float OfferCheckRealSeconds = 10f;

		private const float SaveDebounceRealSeconds = 30f;

		private readonly WowConfig config;

		private readonly ContentRegistry content;

		private readonly ValheimGameCatalog catalog;

		private readonly QuestNetwork network;

		private readonly WorldAwarenessService world;

		private readonly string dataDirectory;

		private readonly Dictionary<long, Binding> bindings = new Dictionary<long, Binding>();

		private readonly HashSet<long> changedPlayers = new HashSet<long>();

		private readonly List<IDisposable> subscriptions = new List<IDisposable>();

		private QuestEngine engine;

		private QuestRepository repository;

		private long runningWorldUid;

		private float nextOfferCheck;

		private float nextSave;

		private readonly Dictionary<long, string> lastOfferReason = new Dictionary<long, string>();

		private readonly Dictionary<string, float> recentBossDeaths = new Dictionary<string, float>();

		private const float BossDeathDedupeSeconds = 30f;

		public bool IsRunning => engine != null;

		public QuestEngine Engine => engine;

		public string SavePath => repository?.FilePath;

		public AuthorityService(WowConfig config, ContentRegistry content, ValheimGameCatalog catalog, QuestNetwork network, WorldAwarenessService world, EventBus bus, string dataDirectory)
		{
			this.config = config;
			this.content = content;
			this.catalog = catalog;
			this.network = network;
			this.world = world;
			this.dataDirectory = dataDirectory;
			network.ServerReceived += OnMessage;
			subscriptions.Add(bus.Subscribe<WorldProgressionChangedEvent>(OnProgression));
			ZNet.WorldSaveStarted = (Action)Delegate.Combine(ZNet.WorldSaveStarted, new Action(OnWorldSave));
		}

		public void Dispose()
		{
			Stop();
			network.ServerReceived -= OnMessage;
			ZNet.WorldSaveStarted = (Action)Delegate.Remove(ZNet.WorldSaveStarted, new Action(OnWorldSave));
			foreach (IDisposable subscription in subscriptions)
			{
				subscription.Dispose();
			}
		}

		public void Tick(float now)
		{
			bool flag = GameState.InWorld && GameState.IsAuthority;
			long num = (flag ? ZNet.instance.GetWorldUID() : 0);
			if (IsRunning && (!flag || num != runningWorldUid))
			{
				Stop();
			}
			if (flag)
			{
				if (!IsRunning)
				{
					Start(num);
				}
				if (now >= nextOfferCheck)
				{
					nextOfferCheck = now + 10f;
					double num2 = WorldReader.WorldTimeSeconds();
					engine.TickExpiry(num2);
					TickSurvive(num2);
					GenerateOffers(num2);
				}
				FlushViews();
				if (engine.Dirty && now >= nextSave)
				{
					nextSave = now + 30f;
					Persist("debounce");
				}
			}
		}

		private void Start(long worldUid)
		{
			runningWorldUid = worldUid;
			repository = QuestRepository.ForCurrentWorld(dataDirectory);
			QuestWorldSave save = repository.Load(worldUid, ZNet.instance.GetWorldName());
			engine = new QuestEngine(content, catalog, new EngineSettings
			{
				Enabled = () => config.Enabled.Value,
				CategoryEnabled = config.IsCategoryEnabled,
				MaxActive = config.MaxActive,
				OfferIntervalSeconds = () => (double)config.OfferIntervalMinutes.Value * 60.0,
				MainOfferDelaySeconds = () => config.MainQuestDelaySeconds.Value,
				MainOfferAnywhere = () => config.MainQuestAnywhere.Value,
				OfferTtlSeconds = () => (double)config.OfferTtlDays.Value * WorldReader.SecondsPerDay(),
				IgnoreCooldownSeconds = () => (double)config.IgnoreCooldownDays.Value * WorldReader.SecondsPerDay(),
				AbandonCooldownSeconds = () => (double)config.AbandonCooldownDays.Value * WorldReader.SecondsPerDay(),
				SecondsPerDay = WorldReader.SecondsPerDay,
				ActivityInfluence = () => config.OfferActivityInfluence.Value,
				ActivityHalfLifeSeconds = () => (double)config.ActivityMemoryDays.Value * WorldReader.SecondsPerDay(),
				SiteOpportunitiesEnabled = () => config.EnableSiteOpportunities.Value,
				SiteDeclineCooldownSeconds = () => (double)config.SiteDeclineCooldownDays.Value * WorldReader.SecondsPerDay(),
				SiteMinGapSeconds = () => config.SiteMinGapSeconds.Value,
				BiomeRequiredKey = config.RequiredKeyForBiome,
				PerCharacterProgression = () => config.PerCharacterProgression.Value,
				IsBossToken = (string token) => catalog.Bosses.Any((BossInfo boss) => string.Equals(boss.NameToken, token, StringComparison.Ordinal)),
				FindSite = FindNearestSite,
				CreatureExists = CreatureExists,
				ContractMaxDistance = () => config.ContractMaxDistance.Value,
				EchoPlacesEnabled = () => config.EnablePlaceEchoes.Value,
				EchoPlaceCooldownSeconds = () => (double)config.PlaceEchoCooldownDays.Value * WorldReader.SecondsPerDay(),
				EchoFallsEnabled = () => config.EnableFallEchoes.Value,
				EchoFallDelaySeconds = () => (double)config.FallEchoDelayMinutes.Value * 60.0,
				RumorsEnabled = () => config.EnableRumors.Value,
				RumorIntervalSeconds = () => (double)config.RumorIntervalDays.Value * WorldReader.SecondsPerDay(),
				RumorTtlSeconds = () => (double)config.RumorLifetimeDays.Value * WorldReader.SecondsPerDay(),
				RumorMaxDistance = () => config.RumorMaxDistance.Value,
				SiteRepeatSeconds = () => (double)config.SiteRepeatDays.Value * WorldReader.SecondsPerDay(),
				SiteRepopulatedShare = () => config.SiteRefillShare.Value,
				ItemRewardMultiplier = () => config.ItemRewardMultiplier.Value,
				MaxRewardAmount = () => config.MaxRewardAmount.Value,
				SkillRewardsEnabled = () => config.EnableSkillRewards.Value,
				SkillRewardMultiplier = () => config.SkillRewardMultiplier.Value,
				MaxSkillLevelsPerReward = () => config.MaxSkillLevelsPerReward.Value,
				AdaptiveSkillRewards = () => config.AdaptiveSkillRewards.Value,
				BossCreditByParticipation = () => config.BossCredit.Value == BossCreditMode.Participation,
				CountPreviousBossDefeats = () => config.CountPreviousBossDefeats.Value,
				BossKillRewardsEnabled = () => config.EnableBossKillRewards.Value,
				BossFirstKillLevels = config.FirstKillLevelsFor,
				BossSecondKillFraction = () => config.BossSecondKillFraction.Value,
				BossLaterKillFraction = () => config.BossLaterKillFraction.Value,
				BossSecondSkillShare = () => config.BossSecondSkillShare.Value,
				BossKillMaxLevels = () => config.BossKillMaxLevels.Value,
				BossKillFallbackSkill = () => ValheimGameCatalog.SkillNames.FirstOrDefault((string s) => string.Equals(s, (config.BossKillFallbackSkill.Value ?? string.Empty).Trim(), StringComparison.OrdinalIgnoreCase)) ?? "Clubs"
			}, this);
			engine.Logger = delegate(string message)
			{
				Log.Info("Quest engine: " + message);
			};
			engine.Load(save);
			bindings.Clear();
			changedPlayers.Clear();
			Log.Info($"Quest authority started for world uid {worldUid}. Save: {repository.FilePath}");
		}

		private void Stop()
		{
			if (IsRunning)
			{
				Persist("stop");
				Log.Info("Quest authority stopped.");
				engine = null;
				repository = null;
				bindings.Clear();
				changedPlayers.Clear();
				runningWorldUid = 0L;
			}
		}

		private void OnWorldSave()
		{
			if (IsRunning)
			{
				Persist("world save");
			}
		}

		public void Persist(string reason)
		{
			if (IsRunning && repository.Save(engine.Save))
			{
				engine.Dirty = false;
				Log.Debug(() => "Quest save written (" + reason + ").");
			}
		}

		private void GenerateOffers(double worldNow)
		{
			WorldContextSnapshot current = world.Current;
			foreach (KeyValuePair<long, Binding> item in bindings.ToList())
			{
				PlayerContext playerContext = ContextFor(item.Key, item.Value);
				if (playerContext != null)
				{
					string message;
					bool flag = engine.TryOffer(playerContext, current, worldNow, force: false, null, out message);
					lastOfferReason.TryGetValue(playerContext.PlayerId, out var value);
					if (flag || value != message)
					{
						lastOfferReason[playerContext.PlayerId] = (flag ? null : message);
						Log.Info(flag ? ("Offer for " + playerContext.Name + ": " + message) : ("No offer for " + playerContext.Name + " yet: " + message));
					}
				}
			}
		}

		private void TickSurvive(double worldNow)
		{
			if ((Object)(object)EnvMan.instance == (Object)null)
			{
				return;
			}
			bool isNight = EnvMan.IsNight();
			foreach (KeyValuePair<long, Binding> item in bindings.ToList())
			{
				PlayerContext playerContext = ContextFor(item.Key, item.Value);
				if (playerContext != null)
				{
					engine.TickSurvive(playerContext, world.Current, isNight, worldNow);
				}
			}
		}

		public SiteRecord OfferSiteForLocal(SiteSighting sighting, out string reason)
		{
			reason = null;
			long num = LocalPlayerId(out reason);
			if (num == 0L)
			{
				return null;
			}
			SiteRecord siteRecord = engine.OfferSite(num, sighting, WorldReader.WorldTimeSeconds(), out reason, world.Current);
			if (siteRecord != null)
			{
				Log.Info($"Place opportunity '{siteRecord.OpportunityId}' offered: {sighting}.");
			}
			return siteRecord;
		}

		public string CheckSiteForLocal(SiteSighting sighting, out OpportunityDefinition definition)
		{
			definition = null;
			string reason;
			long num = LocalPlayerId(out reason);
			if (num != 0L)
			{
				return engine.CheckSite(num, sighting, WorldReader.WorldTimeSeconds(), out definition, world.Current);
			}
			return reason;
		}

		public void WithdrawSiteForLocal(string key)
		{
			string reason;
			long num = LocalPlayerId(out reason);
			if (num == 0L)
			{
				return;
			}
			string error = engine.WithdrawSite(num, key, WorldReader.WorldTimeSeconds());
			if (error == null)
			{
				Log.Info("Place " + key + " offer withdrawn: the player walked away.");
				Persist("place withdrawn");
			}
			else
			{
				Log.Debug(() => "Place withdraw " + key + ": " + error);
			}
			FlushViews();
		}

		public void AnswerSiteForLocal(string key, bool accept)
		{
			string reason;
			long num = LocalPlayerId(out reason);
			if (num == 0L)
			{
				Log.Warning("Place answer ignored: " + reason);
				return;
			}
			string text = engine.AnswerSite(num, key, accept, WorldReader.WorldTimeSeconds());
			if (text != null)
			{
				Log.Warning("Place answer for " + key + " ignored: " + text);
			}
			else
			{
				Log.Info("Place " + key + " " + (accept ? "accepted" : "declined (not now)") + ".");
				Persist("place answered");
			}
			FlushViews();
		}

		private long LocalPlayerId(out string reason)
		{
			reason = null;
			if (!IsRunning)
			{
				reason = "authority not running";
				return 0L;
			}
			Player player = Player.m_localPlayer;
			if ((Object)(object)player == (Object)null)
			{
				reason = "no local player";
				return 0L;
			}
			KeyValuePair<long, Binding> keyValuePair = bindings.FirstOrDefault((KeyValuePair<long, Binding> b) => b.Value.PlayerId == player.GetPlayerID());
			if (keyValuePair.Value == null)
			{
				reason = "local player not registered yet";
				return 0L;
			}
			return keyValuePair.Value.PlayerId;
		}

		public string DescribeOffersForLocal()
		{
			if (!IsRunning)
			{
				return "authority not running";
			}
			Player player = Player.m_localPlayer;
			if ((Object)(object)player == (Object)null)
			{
				return "no local player";
			}
			KeyValuePair<long, Binding> keyValuePair = bindings.FirstOrDefault((KeyValuePair<long, Binding> b) => b.Value.PlayerId == player.GetPlayerID());
			if (keyValuePair.Value == null)
			{
				return "local player not registered yet (wait a few seconds after spawning)";
			}
			world.RequestRefresh("offer debug");
			return engine.DescribeOffers(ContextFor(keyValuePair.Key, keyValuePair.Value), world.Current, WorldReader.WorldTimeSeconds());
		}

		public string ForceOfferToLocal(string templateId)
		{
			if (!IsRunning)
			{
				return "authority not running";
			}
			Player player = Player.m_localPlayer;
			if ((Object)(object)player == (Object)null)
			{
				return "no local player";
			}
			KeyValuePair<long, Binding> keyValuePair = bindings.FirstOrDefault((KeyValuePair<long, Binding> b) => b.Value.PlayerId == player.GetPlayerID());
			if (keyValuePair.Value == null)
			{
				return "local player not registered yet (wait a few seconds after spawning)";
			}
			world.RequestRefresh("forced offer");
			string message;
			bool num = engine.TryOffer(ContextFor(keyValuePair.Key, keyValuePair.Value), world.Current, WorldReader.WorldTimeSeconds(), force: true, templateId, out message);
			FlushViews();
			return (num ? "OK: " : "No offer: ") + message;
		}

		public string ForgetForLocal(string templateId)
		{
			if (!IsRunning)
			{
				return "authority not running";
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null)
			{
				return "no local player";
			}
			if (string.IsNullOrEmpty(templateId))
			{
				return "usage: wow_forget <templateId>";
			}
			bool num = engine.ForgetTemplate(localPlayer.GetPlayerID(), templateId);
			if (num)
			{
				Persist("forget");
			}
			if (!num)
			{
				return "Nothing to forget for '" + templateId + "'.";
			}
			return "Forgot completion/cooldown of '" + templateId + "'. It can be offered again (try wow_offer " + templateId + ").";
		}

		private PlayerContext ContextFor(long sender, Binding binding)
		{
			if (sender == long.MinValue)
			{
				PlayerContext playerContext = WorldReader.CaptureLocalPlayer();
				if (playerContext != null)
				{
					playerContext.PlayerId = binding.PlayerId;
				}
				return playerContext;
			}
			ZNetPeer peer = ZNet.instance.GetPeer(sender);
			if (peer == null)
			{
				bindings.Remove(sender);
				return null;
			}
			return WorldReader.CapturePeer(peer, binding.PlayerId, binding.Name);
		}

		private void OnMessage(long sender, Envelope env)
		{
			if (IsRunning)
			{
				switch (env.Type)
				{
				case MessageType.Hello:
					HandleHello(sender, env.Read<HelloMessage>());
					break;
				case MessageType.Intent:
					HandleIntent(sender, env.Read<IntentMessage>());
					break;
				case MessageType.Claim:
					HandleClaim(sender, env.Read<ClaimMessage>());
					break;
				case MessageType.RewardAck:
					HandleRewardAck(sender, env.Read<RewardAckMessage>());
					break;
				case MessageType.BossDeath:
					HandleBossDeath(sender, env.Read<BossDeathMessage>());
					break;
				case MessageType.Memory:
					HandleMemory(sender, env.Read<MemoryReportMessage>());
					break;
				default:
					Log.Warning($"Unexpected {env.Type} from {sender}.");
					break;
				}
			}
		}

		private void HandleHello(long sender, HelloMessage hello)
		{
			if (hello == null || hello.PlayerId == 0L)
			{
				return;
			}
			if (sender != long.MinValue)
			{
				ZNetPeer peer = ZNet.instance.GetPeer(sender);
				if (peer == null)
				{
					return;
				}
				if (peer.m_playerID != 0L && peer.m_playerID != hello.PlayerId)
				{
					Log.Warning($"Peer {sender} claimed player {hello.PlayerId} but the game reports {peer.m_playerID}; rejected.");
					return;
				}
			}
			foreach (long item in (from b in bindings
				where b.Value.PlayerId == hello.PlayerId && b.Key != sender
				select b.Key).ToList())
			{
				bindings.Remove(item);
			}
			string text = (string.IsNullOrEmpty(hello.Name) ? hello.PlayerId.ToString() : hello.Name);
			bindings[sender] = new Binding
			{
				PlayerId = hello.PlayerId,
				Name = text
			};
			engine.GetOrCreatePlayer(hello.PlayerId, text);
			Log.Info(string.Format("Player bound: {0} ({1}) via {2}.", text, hello.PlayerId, (sender == long.MinValue) ? "local" : sender.ToString()));
			if (!string.IsNullOrEmpty(hello.ContentFingerprint) && hello.ContentFingerprint != content.Fingerprint)
			{
				Log.Warning(text + " has different content packs (" + hello.ContentFingerprint + ") than the server (" + content.Fingerprint + "). Server content is used.");
			}
			SendView(sender, hello.PlayerId);
			foreach (LedgerEntry item2 in engine.PendingRewards(hello.PlayerId).ToList())
			{
				Deliver(sender, item2);
			}
		}

		private void HandleIntent(long sender, IntentMessage intent)
		{
			if (intent == null || !bindings.TryGetValue(sender, out var b))
			{
				return;
			}
			string error = engine.ApplyIntent(b.PlayerId, intent, world.Current, ContextFor(sender, b), WorldReader.WorldTimeSeconds());
			if (error != null)
			{
				Log.Debug(() => $"Intent {intent.Action} {intent.InstanceId} from {b.Name} refused: {error}");
			}
			changedPlayers.Add(b.PlayerId);
		}

		private void HandleClaim(long sender, ClaimMessage claim)
		{
			if (claim == null || !bindings.TryGetValue(sender, out var b))
			{
				return;
			}
			PlayerContext ctx = ContextFor(sender, b);
			if (sender != long.MinValue && ctx?.Biome != null)
			{
				if (claim.Kind == ClaimKind.Explore && !string.Equals(claim.Target, ctx.Biome, StringComparison.OrdinalIgnoreCase))
				{
					Log.Debug(() => "Explore claim " + claim.Target + " from " + b.Name + " rejected: server sees " + ctx.Biome + ".");
					return;
				}
				claim.Biome = ctx.Biome;
			}
			string error = engine.ApplyClaim(b.PlayerId, claim, world.Current, ctx, WorldReader.WorldTimeSeconds());
			Log.Debug(() => string.Format("Claim {0} {1} x{2} from {3}: {4}", claim.Kind, claim.Target, claim.Amount, b.Name, error ?? "applied"));
		}

		private SiteSighting FindNearestSite(string opportunityId, float x, float z, Func<SiteSighting, bool> accept)
		{
			//IL_0032: 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_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: 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_0099: 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_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: 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_010f: 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_0121: Unknown result type (might be due to invalid IL or missing references)
			ZoneSystem instance = ZoneSystem.instance;
			if ((Object)(object)instance == (Object)null || string.IsNullOrEmpty(opportunityId))
			{
				return null;
			}
			List<SiteSighting> list = new List<SiteSighting>();
			foreach (LocationInstance location in instance.GetLocationList())
			{
				string text = location.m_location?.m_prefabName;
				if (!string.IsNullOrEmpty(text))
				{
					OpportunityDefinition opportunityDefinition = content.MatchOpportunity(SiteKind.Location, text) ?? content.MatchOpportunity(SiteKind.DungeonEntrance, text);
					if (opportunityDefinition != null && !(opportunityDefinition.Id != opportunityId))
					{
						Vector3 position = location.m_position;
						float num = position.x - x;
						float num2 = position.z - z;
						list.Add(new SiteSighting
						{
							Kind = SiteKind.Location,
							Prefab = text,
							X = position.x,
							Z = position.z,
							Distance = (float)Math.Sqrt(num * num + num2 * num2),
							Biome = ((WorldGenerator.instance != null) ? ((object)WorldGenerator.instance.GetBiome(position.x, position.z, 0.02f, false)/*cast due to .constrained prefix*/).ToString() : null)
						});
					}
				}
			}
			return list.OrderBy((SiteSighting s) => s.Distance).FirstOrDefault(accept);
		}

		private static bool CreatureExists(string zdoid)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			int num = zdoid?.IndexOf(':') ?? (-1);
			if (num <= 0 || ZDOMan.instance == null)
			{
				return false;
			}
			if (!long.TryParse(zdoid.Substring(0, num), out var result) || !uint.TryParse(zdoid.Substring(num + 1), out var result2))
			{
				return false;
			}
			return ZDOMan.instance.GetZDO(new ZDOID(result, result2)) != null;
		}

		private void HandleMemory(long sender, MemoryReportMessage report)
		{
			if (report != null && bindings.TryGetValue(sender, out var b))
			{
				int applied = engine.ApplyMemory(b.PlayerId, report, WorldReader.WorldTimeSeconds());
				Log.Debug(() => $"Memory report from {b.Name}: {applied}/{report.Tallies?.Count ?? 0} tallies applied.");
			}
		}

		public string DescribeMemoryForLocal()
		{
			if (engine == null)
			{
				return "the quest authority is not running here (only the host/server keeps the memory)";
			}
			long playerId = (((Object)(object)Player.m_localPlayer != (Object)null) ? Player.m_localPlayer.GetPlayerID() : 0);
			return engine.DescribeMemory(playerId, WorldReader.WorldTimeSeconds(), WorldReader.SecondsPerDay());
		}

		private unsafe void HandleBossDeath(long sender, BossDeathMessage msg)
		{
			if (msg == null || string.IsNullOrEmpty(msg.Token))
			{
				return;
			}
			BossInfo bossInfo = catalog.Bosses.FirstOrDefault((BossInfo b) => string.Equals(b.NameToken, msg.Token, StringComparison.Ordinal));
			if (bossInfo == null)
			{
				Log.Warning($"Ignored boss death report for '{msg.Token}' from {sender}: not a known boss.");
				return;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (recentBossDeaths.TryGetValue(bossInfo.NameToken, out var value) && realtimeSinceStartup - value < 30f)
			{
				return;
			}
			recentBossDeaths[bossInfo.NameToken] = realtimeSinceStartup;
			string text = ((msg.KillerPlayerId != 0L && ValheimGameCatalog.CombatSkills.Any((SkillType s) => ((object)(*(SkillType*)(&s))/*cast due to .constrained prefix*/).ToString() == msg.KillerSkill)) ? msg.KillerSkill : null);
			float value2 = config.BossParticipationRadius.Value;
			HashSet<long> hashSet = new HashSet<long>();
			HashSet<long> hashSet2 = new HashSet<long>();
			List<string> list = new List<string>();
			foreach (KeyValuePair<long, Binding> item in bindings.ToList())
			{
				PlayerContext playerContext = ContextFor(item.Key, item.Value);
				if (playerContext != null)
				{
					hashSet2.Add(item.Value.PlayerId);
					float num = playerContext.X - msg.X;
					float num2 = playerContext.Z - msg.Z;
					float num3 = (float)Math.Sqrt(num * num + num2 * num2);
					bool flag = msg.KillerPlayerId != 0L && item.Value.PlayerId == msg.KillerPlayerId;
					bool flag2 = num3 <= value2 || flag;
					if (flag2)
					{
						hashSet.Add(item.Value.PlayerId);
					}
					list.Add(string.Format("{0} {1:0}m{2}", item.Value.Name, num3, flag ? (" (killing blow, " + (text ?? msg.KillerSkill) + ")") : (flag2 ? " (in)" : string.Empty)));
				}
			}
			world.RequestRefresh("boss died");
			string arg = engine.OnBossDefeated(bossInfo.GlobalKey, bossInfo.NameToken, bossInfo.Order, hashSet, hashSet2, world.Current, WorldReader.WorldTimeSeconds(), msg.KillerPlayerId, text);
			Log.Info(string.Format("Boss death: {0} Radius {1:0}m: {2}.", arg, value2, string.Join(", ", list)));
		}

		private void HandleRewardAck(long sender, RewardAckMessage ack)
		{
			if (ack != null && bindings.TryGetValue(sender, out var value))
			{
				engine.MarkDelivered(value.PlayerId, ack.LedgerKey);
				Persist("reward delivered");
			}
		}

		private void OnProgression(WorldProgressionChangedEvent evt)
		{
			if (IsRunning && world.Current != null)
			{
				engine.OnWorldKeys(world.Current, WorldReader.WorldTimeSeconds());
			}
		}

		public void PlayerChanged(long playerId)
		{
			changedPlayers.Add(playerId);
		}

		public void Notice(long playerId, string text, bool center, bool progress = false)
		{
			foreach (long item in SendersFor(playerId))
			{
				network.SendToClient(item, MessageType.Notice, new NoticeMessage
				{
					Text = text,
					Center = center,
					Progress = progress
				});
			}
		}

		public void RewardIssued(LedgerEntry entry)
		{
			Persist("reward issued");
			foreach (long item in SendersFor(entry.PlayerId))
			{
				Deliver(item, entry);
			}
		}

		private void Deliver(long sender, LedgerEntry entry)
		{
			network.SendToClient(sender, MessageType.RewardGrant, new RewardGrantMessage
			{
				LedgerKey = entry.Key,
				Type = entry.Type,
				Skill = entry.Skill,
				FallbackSkill = entry.FallbackSkill,
				ExcludeSkill = entry.ExcludeSkill,
				Levels = entry.Levels,
				Prefab = entry.Prefab,
				Amount = entry.Amount,
				Quality = entry.Quality
			});
		}

		private IEnumerable<long> SendersFor(long playerId)
		{
			return (from b in bindings
				where b.Value.PlayerId == playerId
				select b.Key).ToList();
		}

		private void FlushViews()
		{
			if (changedPlayers.Count == 0)
			{
				return;
			}
			List<long> list = changedPlayers.ToList();
			changedPlayers.Clear();
			foreach (long item in list)
			{
				foreach (long item2 in SendersFor(item))
				{
					SendView(item2, item);
				}
			}
		}

		private void SendView(long sender, long playerId)
		{
			network.SendToClient(sender, MessageType.View, engine.BuildView(playerId, WorldReader.WorldTimeSeconds()));
		}
	}
	public sealed class PlayerMemory
	{
		public const int MaxChronicle = 200;

		public const int MaxFalls = 10;

		public const int MaxRumors = 20;

		[JsonProperty("counters")]
		public Dictionary<string, int> Counters { get; set; } = new Dictionary<string, int>(StringComparer.Ordinal);

		[JsonProperty("biomes")]
		public Dictionary<string, double> Biomes { get; set; } = new Dictionary<string, double>(StringComparer.OrdinalIgnoreCase);

		[JsonProperty("visited")]
		public HashSet<string> Visited { get; set; } = new HashSet<string>(StringComparer.Ordinal);

		[JsonProperty("chronicle")]
		public List<ChronicleEntry> Chronicle { get; set; } = new List<ChronicleEntry>();

		[JsonProperty("flags")]
		public Dictionary<string, string> Flags { get; set; } = new Dictionary<string, string>(StringComparer.Ordinal);

		[JsonProperty("places")]
		public List<RememberedPlace> Places { get; set; } = new List<RememberedPlace>();

		[JsonProperty("echoed")]
		public Dictionary<string, double> Echoed { get; set; } = new Dictionary<string, double>(StringComparer.Ordinal);

		[JsonProperty("falls")]
		public List<FallSite> Falls { get; set; } = new List<FallSite>();

		[JsonProperty("rumors")]
		public List<Rumor> Rumors { get; set; } = new List<Rumor>();

		[JsonProperty("nextRumorAt")]
		public double NextRumorAt { get; set; }

		public int Get(string key)
		{
			if (key == null || !Counters.TryGetValue(key, out var value))
			{
				return 0;
			}
			return value;
		}

		public int Add(string key, int amount)
		{
			int num = Get(key) + Math.Max(0, amount);
			Counters[key] = num;
			return num;
		}

		public void Remember(ChronicleKind kind, string target, int count, double at)
		{
			Chronicle.Add(new ChronicleEntry
			{
				At = at,
				Kind = kind,
				Target = target,
				Count = count
			});
			if (Chronicle.Count > 200)
			{
				Chronicle.RemoveRange(0, Chronicle.Count - 200);
			}
		}
	}
	public enum ChronicleKind
	{
		Biome,
		Boss,
		Cleared,
		MainDone,
		KillMilestone,
		ExploreMilestone,
		EchoPlace,
		EchoFall,
		Rumor,
		RumorFound
	}
	public sealed class RememberedPlace
	{
		[JsonProperty("site")]
		public string SiteId { get; set; }

		[JsonProperty("opportunity")]
		public string OpportunityId { get; set; }

		[JsonProperty("x")]
		public float X { get; set; }

		[JsonProperty("z")]
		public float Z { get; set; }

		[JsonProperty("at")]
		public double ClearedAt { get; set; }
	}
	public sealed class FallSite
	{
		[JsonProperty("id")]
		public string Id { get; set; }

		[JsonProperty("biome")]
		public string Biome { get; set; }

		[JsonProperty("x")]
		public float X { get; set; }

		[JsonProperty("z")]
		public float Z { get; set; }

		[JsonProperty("at")]
		public double At { get; set; }

		[JsonProperty("done")]
		public bool Done { get; set; }

		[JsonProperty("cause")]
		public string Cause { get; set; }

		[JsonProperty("killer")]
		public string Killer { get; set; }

		[JsonProperty("killerToken")]
		public string KillerToken { get; set; }

		[JsonProperty("killerHealth")]
		public float KillerHealth { get; set; }

		[JsonProperty("killerZdo")]
		public string KillerZdo { get; set; }
	}
	public sealed class Rumor
	{
		[JsonProperty("site")]
		public string SiteId { get; set; }

		[JsonProperty("opportunity")]
		public string OpportunityId { get; set; }

		[JsonProperty("x")]
		public float X { get; set; }

		[JsonProperty("z")]
		public float Z { get; set; }

		[JsonProperty("at")]
		public double At { get; set; }

		[JsonProperty("found")]
		public bool Found { get; set; }
	}
	public sealed class ChronicleEntry
	{
		[JsonProperty("at")]
		public double At { get; set; }

		[JsonProperty("kind")]
		public ChronicleKind Kind { get; set; }

		[JsonProperty("target")]
		public string Target { get; set; }

		[JsonProperty("count")]
		public int Count { get; set; }
	}
	public static class MemoryKeys
	{
		public const string Kill = "kill";

		public const string Build = "build";

		public const string Craft = "craft";

		public const string Death = "death";

		public const string Fall = "fall";

		public const string Visit = "visit";

		public const string Clear = "clear";

		public const string Biome = "biome";

		public const string Boss = "boss";

		public const string Quest = "quest";

		public const string Any = "any";

		public static readonly string[] Namespaces = new string[9] { "kill", "build", "craft", "death", "visit", "clear", "biome", "boss", "quest" };

		public static readonly int[] KillMilestones = new int[6] { 10, 50, 100, 250, 500, 1000 };

		public static readonly int[] ExploreMilestones = new int[5] { 5, 10, 25, 50, 100 };

		public static string Of(string ns, string target)
		{
			return ns + ":" + target;
		}

		public static int MilestoneReached(int[] steps, int before, int after)
		{
			return steps.Where((int s) => before < s && after >= s).DefaultIfEmpty(0).Max();
		}
	}
	public interface IQuestEngineSink
	{
		void PlayerChanged(long playerId);

		void Notice(long playerId, string text, bool center, bool progress = false);

		void RewardIssued(LedgerEntry entry);
	}
	public sealed class EngineSettings
	{
		public Func<bool> Enabled { get; set; } = () => true;

		public Func<QuestCategory, bool> CategoryEnabled { get; set; } = (QuestCategory _) => true;

		public Func<QuestCategory, int> MaxActive { get; set; } = (QuestCategory _) => 1;

		public Func<double> OfferIntervalSeconds { get; set; } = () => 300.0;

		public Func<double> MainOfferDelaySeconds { get; set; } = () => 0.0;

		public Func<bool> MainOfferAnywhere { get; set; } = () => false;

		public Func<double> OfferTtlSeconds { get; set; } = () => 1800.0;

		public Func<double> IgnoreCooldownSeconds { get; set; } = () => 3600.0;

		public Func<double> AbandonCooldownSeconds { get; set; } = () => 1800.0;

		public Func<double> SecondsPerDay { get; set; } = () => 1800.0;

		public Func<float> ActivityInfluence { get; set; } = () => 0.5f;

		public Func<double> ActivityHalfLifeSeconds { get; set; } = () => 3600.0;

		public Func<bool> SiteOpportunitiesEnabled { get; set; } = () => true;

		public Func<double> SiteDeclineCooldownSeconds { get; set; } = () => 5400.0;

		public Func<double> SiteMinGapSeconds { get; set; } = () => 120.0;

		public Func<double> SiteRepeatSeconds { get; set; } = () => 9000.0;

		public Func<float> SiteRepopulatedShare { get; set; } = () => 0.5f;

		public Func<string, string> BiomeRequiredKey { get; set; } = (string _) => (string)null;

		public Func<bool> PerCharacterProgression { get; set; } = () => false;

		public Func<string, float, float, Func<SiteSighting, bool>, SiteSighting> FindSite { get; set; }

		public Func<float> ContractMaxDistance { get; set; } = () => 3000f;

		public Func<bool> EchoPlacesEnabled { get; set; } = () => false;

		public Func<double> EchoPlaceCooldownSeconds { get; set; } = () => 5400.0;

		public Func<bool> EchoFallsEnabled { get; set; } = () => false;

		public Func<double> EchoFallDelaySeconds { get; set; } = () => 600.0;

		public Func<bool> RumorsEnabled { get; set; } = () => false;

		public Func<double> RumorIntervalSeconds { get; set; } = () => 3600.0;

		public Func<double> RumorTtlSeconds { get; set; } = () => 9000.0;

		public Func<float> RumorMaxDistance { get; set; } = () => 2500f;

		public Func<string, bool> CreatureExists { get; set; }

		public Func<string, bool> IsBossToken { get; set; } = (string _) => false;

		public Func<float> ItemRewardMultiplier { get; set; } = () => 1f;

		public Func<int> MaxRewardAmount { get; set; } = () => 200;

		public Func<bool> SkillRewardsEnabled { get; set; } = () => true;

		public Func<float> SkillRewardMultiplier { get; set; } = () => 1f;

		public Func<float> MaxSkillLevelsPerReward { get; set; } = () => 2f;

		public Func<bool> AdaptiveSkillRewards { get; set; } = () => true;

		public Func<bool> BossCreditByParticipation { get; set; } = () => true;

		public Func<bool> CountPreviousBossDefeats { get; set; } = () => true;

		public Func<bool> BossKillRewardsEnabled { get; set; } = () => false;

		public Func<int, float> BossFirstKillLevels { get; set; } = (int order) => 1f;

		public Func<float> BossSecondKillFraction { get; set; } = () => 0.25f;

		public Func<float> BossLaterKillFraction { get; set; } = () => 0.1f;

		public Func<float> BossSecondSkillShare { get; set; } = () => 0.5f;

		public Func<float> BossKillMaxLevels { get; set; } = () => 10f;

		public Func<string> BossKillFallbackSkill { get; set; } = () => "Clubs";
	}
	public sealed class QuestEngine
	{
		private const int MaxClosedHistory = 30;

		private const int MaxRecentClaims = 256;

		private const int MaxClaimAmount = 999;

		private const double NoCandidateRetrySeconds = 60.0;

		private const double ActivitySampleSeconds = 10.0;

		private readonly Dictionary<string, double> lastActivitySample = new Dictionary<string, double>();

		private readonly ContentRegistry content;

		private readonly IGameCatalog catalog;

		private readonly EngineSettings settings;

		private readonly IQuestEngineSink sink;

		public const string SitePresenceOutside = "Outside";

		private const double SurviveMinimumWatchShare = 0.1;

		private const int MaxTalliesPerReport = 64;

		private const int MaxTallyAmount = 500;

		private const int ViewChronicleLines = 40;

		public const string CensusSummary = "*";

		public const string ChestCensus = "#chests";

		public const string EchoPlacePrefix = "place:";

		public const string EchoFallPrefix = "fall:";

		private const float PlaceEchoRadius = 40f;

		private const float FallEchoRadius = 15f;

		private const float EchoServerSlack = 80f;

		private const string ZdoTargetPrefix = "zdo:";

		public const int MaxOpenEchoes = 3;

		public const string EchoCauseCreature = "Creature";

		public static readonly string[] EchoCauses = new string[9] { "Creature", "Fall", "Drowning", "Burning", "Freezing", "Poisoned", "Crushed", "Player", "Other" };

		private static readonly string[] Directions = new string[8] { "n", "ne", "e", "se", "s", "sw", "w", "nw" };

		public QuestWorldSave Save { get; private set; }

		public bool Dirty { get; set; }

		public Action<string> Logger { get; set; }

		public QuestEngine(ContentRegistry content, IGameCatalog catalog, EngineSettings settings, IQuestEngineSink sink)
		{
			this.content = content;
			this.catalog = catalog;
			this.settings = settings;
			this.sink = sink;
		}

		public void Load(QuestWorldSave save)
		{
			Save = save ?? new QuestWorldSave();
			Save.GeneratorVersion = 2;
		}

		public PlayerQuestData GetOrCreatePlayer(long playerId, string name)
		{
			string key = playerId.ToString(CultureInfo.InvariantCulture);
			if (!Save.Players.TryGetValue(key, out var value))
			{
				value = new PlayerQuestData
				{
					PlayerId = playerId,
					Name = name
				};
				Save.Players[key] = value;
				Dirty = true;
			}
			else if (!string.IsNullOrEmpty(name) && value.Name != name)
			{
				value.Name = name;
				Dirty = true;
			}
			return value;
		}

		public PlayerQuestData FindPlayer(long playerId)
		{
			if (!Save.Players.TryGetValue(playerId.ToString(CultureInfo.InvariantCulture), out var value))
			{
				return null;
			}
			return value;
		}

		public bool TryOffer(PlayerContext player, WorldContextSnapshot world, double now, bool force, string forcedTemplateId, out string message)
		{
			message = null;
			if (!settings.Enabled())
			{
				message = "mod disabled by config";
				return false;
			}
			if (player == null || player.PlayerId == 0L)
			{
				message = "player id unknown";
				return false;
			}
			PlayerQuestData orCreatePlayer = GetOrCreatePlayer(player.PlayerId, player.Name);
			if (orCreatePlayer.Quests.Any((QuestInstance q) => q.Status == QuestStatus.Offered && !q.Deferred))
			{
				message = "an offer is already waiting for an answer";
				return false;
			}
			if (string.IsNullOrEmpty(player.Biome) || player.Biome == "None")
			{
				message = "player biome not known yet";
				return false;
			}
			if (player.InInterior)
			{
				message = "player is inside a dungeon";
				return false;
			}
			string text = BiomeLock(player.Biome, world, orCreatePlayer);
			if (text != null)
			{
				message = "biome " + player.Biome + " locked until '" + text + "'";
				return false;
			}
			bool flag = false;
			if (!force && now - orCreatePlayer.LastOfferAt < settings.OfferIntervalSeconds())
			{
				double num = settings.MainOfferDelaySeconds();
				if (num <= 0.0 || now - orCreatePlayer.LastOfferAt < num)
				{
					message = "offer interval not elapsed";
					return false;
				}
				flag = true;
			}
			if (!force && !flag && now < orCreatePlayer.NextAttemptAt)
			{
				message = "nothing eligible recently; retrying soon";
				return false;
			}
			GenerationContext generationContext = BuildContext(player, world, now, orCreatePlayer);
			List<string> list = new List<string>();
			IEnumerable<QuestTemplate> enumerable = content.AvailableTemplates;
			if (flag)
			{
				List<CandidateResult> list2 = OfferGenerator.Candidates(enumerable.Where((QuestTemplate t) => t.Category == QuestCategory.Main), orCreatePlayer, generationContext);
				if (list2.Count == 0)
				{
					message = "offer interval not elapsed";
					return false;
				}
				enumerable = list2.Select((CandidateResult c) => c.Template);
			}
			if (!string.IsNullOrEmpty(forcedTemplateId))
			{
				if (!content.TryGet(forcedTemplateId, out var _))
				{
					message = "unknown template '" + forcedTemplateId + "'";
					return false;
				}
				if (!content.IsAvailable(forcedTemplateId))
				{
					message = "template '" + forcedTemplateId + "' is disabled";
					return false;
				}
				enumerable = enumerable.Where((QuestTemplate t) => t.Id == forcedTemplateId);
			}
			QuestTemplate questTemplate = OfferGenerator.Pick(OfferGenerator.Candidates(enumerable, orCreatePlayer, generationContext, list), world?.WorldUid ?? 0, player.PlayerId, generationContext.TimeWindow);
			if (questTemplate == null)
			{
				orCreatePlayer.NextAttemptAt = now + Math.Min(Math.Max(1.0, settings.OfferIntervalSeconds()), 60.0);
				Dirty = true;
				message = ((list.Count == 0) ? "no available templates" : ("no eligible template: " + string.Join("; ", list)));
				return false;
			}
			orCreatePlayer.LastOfferAt = now;
			orCreatePlayer.NextAttemptAt = double.MinValue;
			Dirty = true;
			QuestInstance questInstance = CreateOffer(orCreatePlayer, questTemplate, player.Biome, now);
			message = "offered " + questTemplate.Id + " as " + questInstance.InstanceId;
			sink.Notice(player.PlayerId, questTemplate.Generation.Narrative ? "$wow_msg_new_story" : "$wow_msg_new_offer", questTemplate.Generation.Narrative);
			return true;
		}

		private int ActiveInCategory(PlayerQuestData data, QuestCategory category)
		{
			QuestTemplate template;
			return data.Quests.Count((QuestInstance q) => q.Status == QuestStatus.Active && q.Category == category && q.SiteKey == null && (!content.TryGet(q.TemplateId, out template) || !template.EchoOnly));
		}

		private void StartQuest(PlayerQuestData data, QuestInstance quest, QuestTemplate template, WorldContextSnapshot world, PlayerContext playerCtx, double now)
		{
			quest.Status = QuestStatus.Active;
			quest.AcceptedAt = now;
			quest.Deferred = false;
			quest.ExpiresAt = ((quest.Category == QuestCategory.Dynamic && template.Generation.ExpiresAfterDays.HasValue) ? new double?(now + (double)template.Generation.ExpiresAfterDays.Value * settings.SecondsPerDay()) : ((double?)null));
			Dictionary<string, int> dictionary = (from o in template.Stages.SelectMany((QuestStageDefinition s) => s.Objectives)
				where o.Target == "Killer"
				where quest.RequiredOverride.ContainsKey(o.Id)
				select o).ToDictionary((ObjectiveDefinition o) => o.Id, (ObjectiveDefinition o) => quest.RequiredOverride[o.Id]);
			quest.StageIndex = 0;
			quest.Progress.Clear();
			quest.Watch.Clear();
			quest.RequiredOverride.Clear();
			foreach (KeyValuePair<string, int> item in dictionary)
			{
				quest.RequiredOverride[item.Key] = item.Value;
			}
			quest.SiteTargets.Clear();
			Touch(data);
			EvaluateStageEntry(data, quest, template, world, playerCtx, now);
		}

		private QuestInstance CreateOffer(PlayerQuestData data, QuestTemplate template, string biome, double now)
		{
			QuestInstance questInstance = new QuestInstance
			{
				InstanceId = "q" + Save.NextInstance++.ToString(CultureInfo.InvariantCulture),
				TemplateId = template.Id,
				TemplateRevision = template.Revision,
				PackId = template.PackId,
				Category = template.Category,
				Status = QuestStatus.Offered,
				OfferedAt = now,
				ExpiresAt = now + settings.OfferTtlSeconds(),
				OriginBiome = biome,
				Rewards = (from r in template.Rewards.Select(FreezeReward)
					where r != null
					select r).ToList(),
				TextArgs = ResolveTextArgs(data, template)
			};
			data.Quests.Add(questInstance);
			Touch(data);
			return questInstance;
		}

		private GenerationContext BuildContext(PlayerContext player, WorldContextSnapshot world, double now, PlayerQuestData data)
		{
			double num = Math.Max(1.0, settings.OfferIntervalSeconds());
			QuestTemplate template;
			return new GenerationContext
			{
				MainAnywhere = settings.MainOfferAnywhere(),
				IsBiomeOpen = (string b) => BiomeLock(b, world, data) == null,
				ResolveMemoryKey = ResolveMemoryKey,
				World = world,
				Player = player,
				Now = now,
				IsCategoryEnabled = settings.CategoryEnabled,
				MaxActive = settings.MaxActive,
				TimeWindow = (long)(now / num),
				ActivityInfluence = settings.ActivityInfluence(),
				ActivityHalfLifeSeconds = settings.ActivityHalfLifeSeconds(),
				TemplateLookup = (string id) => (!content.TryGet(id, out template)) ? null : template
			};
		}

		public string DescribeOffers(PlayerContext player, WorldContextSnapshot world, double now)
		{
			if (player == null || player.PlayerId == 0L)
			{
				return "player id unknown";
			}
			PlayerQuestData orCreatePlayer = GetOrCreatePlayer(player.PlayerId, player.Name);
			GenerationContext generationContext = BuildContext(player, world, now, orCreatePlayer);
			List<string> list = new List<string> { $"Generator v{2}, biome {player.Biome}, tier {world?.ProgressionTier ?? 0}, " + $"activity influence {generationContext.ActivityInfluence:0.##}" };
			Dictionary<ObjectiveType, double> dictionary = ActivityProfile.Shares(orCreatePlayer, now, generationContext.ActivityHalfLifeSeconds);
			list.Add((dictionary.Count == 0) ? "Recent activity: too little to judge yet" : ("Recent activity: " + string.Join(", ", from s in dictionary
				orderby s.Value descending
				select $"{s.Key} {s.Value:P0}")));
			List<KeyValuePair<QuestTemplate, float>> list2 = new List<KeyValuePair<QuestTemplate, float>>();
			foreach (QuestTemplate item in content.AvailableTemplates.OrderBy((QuestTemplate t) => t.Category).ThenBy<QuestTemplate, string>((QuestTemplate t) => t.Id, StringComparer.Ordinal))
			{
				string text = OfferGenerator.Reject(item, orCreatePlayer, generationContext);
				if (text != null)
				{
					list.Add("  - " + item.Id + ": " + text);
				}
				else
				{
					list2.Add(new KeyValuePair<QuestTemplate, float>(item, OfferGenerator.Score(item, orCreatePlayer, generationContext)));
				}
			}
			bool mainFirst = list2.Any((KeyValuePair<QuestTemplate, float> e) => e.Key.Category == QuestCategory.Main);
			float num = list2.Where((KeyValuePair<QuestTemplate, float> e) => !mainFirst || e.Key.Category == QuestCategory.Main).Sum((KeyValuePair<QuestTemplate, float> e) => e.Value);
			foreach (KeyValuePair<QuestTemplate, float> item2 in list2.OrderByDescending((KeyValuePair<QuestTemplate, float> e) => e.Value))
			{
				string text2 = (((!mainFirst || item2.Key.Category == QuestCategory.Main) && num > 0f) ? $"{item2.Value / num:P0}" : "0% (Main first)");
				list.Add("  + " + item2.Key.Id + ": " + text2 + " — " + OfferGenerator.Explain(item2.Key, orCreatePlayer, generationContext));
			}
			return string.Join("\n", list);
		}

		public FrozenReward FreezeReward(RewardDefinition r)
		{
			switch (r.Type)
			{
			case RewardType.Item:
			{
				int val = (int)Math.Round((float)r.Amount * settings.ItemRewardMultiplier(), MidpointRounding.AwayFromZero);
				return new FrozenReward
				{
					Id = r.Id,
					Type = RewardType.Item,
					Prefab = r.Prefab,
					Amount = Math.Max(1, Math.Min(val, settings.MaxRewardAmount())),
					Quality = r.Quality
				};
			}
			case RewardType.Skill:
			{
				if (!settings.SkillRewardsEnabled())
				{
					return null;
				}
				float num = Math.Min(r.Levels * settings.SkillRewardMultiplier(), settings.MaxSkillLevelsPerReward());
				if (num <= 0f)
				{
					return null;
				}
				bool flag = ContentValidator.IsAdaptiveSkill(r.Skill);
				return new FrozenReward
				{
					Id = r.Id,
					Type = RewardType.Skill,
					Skill = ((flag && !settings.AdaptiveSkillRewards()) ? r.FallbackSkill : r.Skill),
					FallbackSkill = r.FallbackSkill,
					Levels = (float)Math.Round(num, 3)
				};
			}
			default:
				return null;
			}
		}

		public string ApplyIntent(long playerId, IntentMessage intent, WorldContextSnapshot world, PlayerContext playerCtx, double now)
		{
			PlayerQuestData playerQuestData = FindPlayer(playerId);
			if (playerQuestData == null || intent == null)
			{
				return "unknown player";
			}
			QuestInstance questInstance = playerQuestData.Quests.FirstOrDefault((QuestInstance q) => q.InstanceId == intent.InstanceId);
			if (questInstance == null)
			{
				return "unknown quest instance";
			}
			content.TryGet(questInstance.TemplateId, out var template);
			switch (intent.Action)
			{
			case IntentAction.Accept:
				if (questInstance.Status != QuestStatus.Offered)
				{
					return "not an open offer";
				}
				if (template == null || !content.IsAvailable(template.Id))
				{
					return "template no longer available";
				}
				if (!template.EchoOnly && ActiveInCategory(playerQuestData, questInstance.Category) >= settings.MaxActive(questInstance.Category))
				{
					sink.Notice(playerId, "$wow_msg_limit_reached", center: false);
					return "active limit reached";
				}
				StartQuest(playerQuestData, questInstance, template, world, playerCtx, now);
				sink.Notice(playerId, "$wow_msg_accepted " + template.TitleKey, center: false);
				return null;
			case IntentAction.Defer:
				if (questInstance.Status != QuestStatus.Offered)
				{
					return "not an open offer";
				}
				questInstance.Deferred = true;
				Touch(playerQuestData);
				return null;
			case IntentAction.Ignore:
				if (questInstance.Status != QuestStatus.Offered)
				{
					return "not an open offer";
				}
				Close(playerQuestData, questInstance, QuestStatus.Ignored, now, settings.IgnoreCooldownSeconds());
				return null;
			case IntentAction.Abandon:
				if (questInstance.Status != QuestStatus.Active)
				{
					return "quest is not active";
				}
				if (template != null && !template.IsAbandonable)
				{
					return "quest cannot be abandoned";
				}
				Close(playerQuestData, questInstance, QuestStatus.Abandoned, now, settings.AbandonCooldownSeconds());
				sink.Notice(playerId, "$wow_msg_abandoned " + (template?.TitleKey ?? questInstance.TemplateId), center: false);
				return null;
			default:
				return "unknown action";
			}
		}

		public string ApplyClaim(long playerId, ClaimMessage claim, WorldContextSnapshot world, PlayerContext playerCtx, double now)
		{
			PlayerQuestData playerQuestData = FindPlayer(playerId);
			if (playerQuestData == null || claim == null)
			{
				return "unknown player";
			}
			if (claim.Cheated)
			{
				return "cheated item/event";
			}
			if (string.IsNullOrEmpty(claim.EventKey) || string.IsNullOrEmpty(claim.Target))
			{
				return "malformed claim";
			}
			if (playerQuestData.RecentClaims.Contains(claim.EventKey))
			{
				return "duplicate event";
			}
			playerQuestData.RecentClaims.Add(claim.EventKey);
			if (playerQuestData.RecentClaims.Count > 256)
			{
				playerQuestData.RecentClaims.RemoveRange(0, playerQuestData.RecentClaims.Count - 256);
			}
			if (claim.Kind == ClaimKind.Death)
			{
				if (!BreakSurviveWatches(playerQuestData))
				{
					return "no survive objective watching";
				}
				return null;
			}
			if (claim.Kind == ClaimKind.Echo)
			{
				return ApplyEcho(playerQuestData, claim, playerCtx, now);
			}
			if (claim.Kind == ClaimKind.SitePresence)
			{
				bool flag = false;
				foreach (QuestInstance item in playerQuestData.Quests.Where((QuestInstance q) => q.Status == QuestStatus.Active && q.SiteId != null).ToList())
				{
					if (content.TryGet(item.TemplateId, out var template))
					{
						flag |= ApplySitePresence(playerQuestData, item, template, claim, world, playerCtx, now);
					}
				}
				Dirty = true;
				if (!flag)
				{
					return "no place quest affected";
				}
				return null;
			}
			if (claim.Kind == ClaimKind.SiteCensus)
			{
				bool flag2 = false;
				foreach (QuestInstance item2 in playerQuestData.Quests.Where((QuestInstance q) => q.Status == QuestStatus.Active && q.SiteId != null).ToList())
				{
					if (content.TryGet(item2.TemplateId, out var template2) && ApplySiteCensus(playerQuestData, item2, template2, claim))
					{
						flag2 = true;
						CheckStage(playerQuestData, item2, template2, world, playerCtx, now);
					}
				}
				if (!flag2)
				{
					return "census changed nothing";
				}
				return null;
			}
			ObjectiveType? objectiveType = ActivityProfile.TypeOfClaim(claim.Kind);
			if (objectiveType.HasValue)
			{
				string key = playerQuestData.PlayerId.ToString(CultureInfo.InvariantCulture) + ":" + objectiveType.Value;
				if (!lastActivitySample.TryGetValue(key, out var value) || now - value >= 10.0 || now < value)
				{
					lastActivitySample[key] = now;
					ActivityProfile.Record(playerQuestData, objectiveType.Value, now, settings.ActivityHalfLifeSeconds());
				}
			}
			int amount = ((claim.Kind != ClaimKind.Gather && claim.Kind != ClaimKind.Craft) ? 1 : Math.Max(1, Math.Min(claim.Amount, 999)));
			bool flag3 = false;
			foreach (QuestInstance item3 in playerQuestData.Quests.Where((QuestInstance q) => q.Status == QuestStatus.Active).ToList())
			{
				if (!content.TryGet(item3.TemplateId, out var template3))
				{
					continue;
				}
				QuestStageDefinition questStageDefinition = CurrentStage(item3, template3);
				if (questStageDefinition == null)
				{
					continue;
				}
				bool flag4 = claim.Kind == ClaimKind.ChestOpened || claim.Kind == ClaimKind.SiteDeath;
				if (flag4 && item3.Seen.Contains(claim.EventKey))
				{
					continue;
				}
				bool flag5 = false;
				foreach (ObjectiveDefinition objective in questStageDefinition.Objectives)
				{
					if (Matches(objective, claim, item3) && ((!objective.AtSite && objective.Type != ObjectiveType.Loot && objective.Type != ObjectiveType.OpenChests) || (item3.SiteId != null && string.Equals(item3.SiteId, claim.Site, StringComparison.Ordinal))) && (IsClearSite(objective) ? AdvanceClearSite(playerQuestData, item3, template3, objective, claim.Target) : Advance(playerQuestData, item3, template3, objective, amount)))
					{
						flag5 = true;
					}
				}
				if (flag5)
				{
					if (flag4)
					{
						item3.Seen.Add(claim.EventKey);
					}
					flag3 = true;
					CheckStage(playerQuestData, item3, template3, world, playerCtx, now);
				}
			}
			Dirty = true;
			if (!flag3)
			{
				return "no matching active objective";
			}
			return null;
		}

		private string RepeatBlocker(SiteRecord record, SiteSighting s, double now)
		{
			double num = settings.SiteRepeatSeconds();
			if (num <= 0.0)
			{
				return "already completed";
			}
			double num2 = record.CompletedAt + num - now;
			if (num2 > 0.0)
			{
				double num3 = num2 / Math.Max(1.0, settings.SecondsPerDay());
				return string.Format(CultureInfo.InvariantCulture, "completed recently (can return in {0:0.#} day(s))", num3);
			}
			if (!s.CensusCreatures.HasValue && !s.CensusChests.HasValue)
			{
				return "completed; the place was not measured yet";
			}
			int num4 = s.CensusCreatures.GetValueOrDefault() + s.CensusChests.GetValueOrDefault();
			int num5 = record.BaselineCreatures + record.BaselineChests;
			int num6 = Math.Max(1, (int)Math.Ceiling((float)num5 * Math.Max(0f, settings.SiteRepopulatedShare())));
			if (num4 < num6)
			{
				return $"completed; not refilled yet ({num4}/{num6} creatures+chests)";
			}
			return null;
		}

		public string BiomeLock(string biome, WorldContextSnapshot world, PlayerQuestData data)
		{
			string text = (string.IsNullOrEmpty(biome) ? null : settings.BiomeRequiredKey(biome));
			if (text == null)
			{
				return null;
			}
			if (settings.PerCharacterProgression())
			{
				if (data == null || !EarnedProgress(data).Contains(text))
				{
					return text;
				}
				return null;
			}
			if (world != null && world.HasGlobalKey(text))
			{
				return null;
			}
			return text;
		}

		public HashSet<string> EarnedProgress(PlayerQuestData data)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			foreach (string key in data.Completed.Keys)
			{
				if (content.TryGet(key, out var template) && !string.IsNullOrEmpty(template.GrantsProgress))
				{
					hashSet.Add(template.GrantsProgress);
				}
			}
			return hashSet;
		}

		public static string SiteKey(SiteKind kind, string prefab, float x, float z)
		{
			return string.Format(CultureInfo.InvariantCulture, "{0}:{1}:{2:0}:{3:0}", kind, prefab, Math.Round(x), Math.Round(z));
		}

		public string CheckSite(long playerId, SiteSighting s, double now, out OpportunityDefinition definition, WorldContextSnapshot world = null)
		{
			definition = null;
			if (!settings.Enabled() || !settings.SiteOpportunitiesEnabled())
			{
				return "place opportunities disabled";
			}
			if (s == null || string.IsNullOrEmpty(s.Prefab))
			{
				return "unknown place";
			}
			definition = content.MatchOpportunity(s.Kind, s.Prefab);
			if (definition == null)
			{
				return $"no opportunity defined for {s.Kind} '{s.Prefab}'";
			}
			string text = BiomeLock(s.Biome, world, FindPlayer(playerId));
			if (text != null)
			{
				return "biome " + s.Biome + " locked until '" + text + "'";
			}
			foreach (string item in definition.RequiredGlobalKeys ?? new List<string>())
			{
				if (world == null || !world.HasGlobalKey(item))
				{
					return "needs world progress '" + item + "'";
				}
			}
			PlayerQuestData playerQuestData = FindPlayer(playerId);
			if (playerQuestData == null)
			{
				return "player not registered";
			}
			string thisSite = SiteId(s.Prefab, s.X, s.Z);
			if (playerQuestData.Quests.Any((QuestInstance q) => q.Status == QuestStatus.Active && q.SiteKey == null && q.SiteId == thisSite))
			{
				return "a contract already leads here";
			}
			if (playerQuestData.Sites.TryGetValue(s.Key, out var value))
			{
				bool flag = value.Status == SiteStatus.Accepted && value.QuestInstanceId == null && definition.Quest != null;
				if (value.Status == SiteStatus.Accepted && !flag)
				{
					return "already accepted";
				}
				if (value.Status == SiteStatus.Completed)
				{
					string text2 = RepeatBlocker(value, s, now);
					if (text2 != null)
					{
						return text2;
					}
				}
				if (value.Status != SiteStatus.Offered && value.CooldownUntil > now)
				{
					return value.Status.ToString().ToLowerInvariant() + " recently (cooldown)";
				}
			}
			if (now < playerQuestData.NextSiteOfferAt)
			{
				return "another place was offered moments ago";
			}
			return null;
		}

		public SiteRecord OfferSite(long playerId, SiteSighting s, double now, out string reason, WorldContextSnapshot world = null)
		{
			reason = CheckSite(playerId, s, now, out var definition, world);
			if (reason != null)
			{
				return null;
			}
			PlayerQuestData playerQuestData = FindPlayer(playerId);
			if (!playerQuestData.Sites.TryGetValue(s.Key, out var value))
			{
				value = new SiteRecord
				{
					Key = s.Key,
					Kind = s.Kind,
					Prefab = s.Prefab,
					X = s.X,
					Z = s.Z
				};
				playerQuestData.Sites[s.Key] = value;
			}
			value.OpportunityId = definition.Id;
			value.Biome = s.Biome;
			value.Status = SiteStatus.Offered;
			value.OfferedAt = now;
			value.AnsweredAt = null;
			value.TimesOffered++;
			playerQuestData.NextSiteOfferAt = now + settings.SiteMinGapSeconds();
			Touch(playerQuestData);
			return value;
		}

		public string AnswerSite(long playerId, string key, bool accept, double now)
		{
			PlayerQuestData playerQuestData = FindPlayer(playerId);
			if (playerQuestData == null || key == null || !playerQuestData.Sites.TryGetValue(key, out var value))
			{
				return "unknown place";
			}
			if (value.Status != SiteStatus.Offered)
			{
				return $"place is {value.Status}, not waiting for an answer";
			}
			content.TryGetOpportunity(value.OpportunityId, out var definition);
			value.AnsweredAt = now;
			if (accept)
			{
				value.Status = SiteStatus.Accepted;
				if (definition != null && definition.Quest != null && content.TryGet(definition.Quest, out var template) && content.IsAvailable(template.Id))
				{
					QuestInstance questInstance = StartSiteQuest(playerQuestData, value, template, now);
					sink.Notice(playerId, "$wow_msg_accepted " + template.TitleKey, center: true);
					Log("place quest " + template.Id + " started as " + questInstance.InstanceId + " at " + value.Key);
				}
				else
				{
					sink.Notice(playerId, "$wow_site_accepted " + (definition?.TitleKey ?? value.Prefab), center: true);
				}
			}
			else
			{
				value.Status = SiteStatus.Declined;
				value.CooldownUntil = now + SiteCooldown(definition);
			}
			Touch(playerQuestData);
			return null;
		}

		public string WithdrawSite(long playerId, string key, double now)
		{
			PlayerQuestData playerQuestData = FindPlayer(playerId);
			if (playerQuestData == null || key == null || !playerQuestData.Sites.TryGetValue(key, out var value))
			{
				return "unknown place";
			}
			if (value.Status != SiteStatus.Offered)
			{
				return $"place is {value.Status}, nothing to withdraw";
			}
			content.TryGetOpportunity(value.OpportunityId ?? string.Empty, out var definition);
			value.Status = SiteStatus.Withdrawn;
			value.AnsweredAt = now;
			value.CooldownUntil = now + SiteCooldown(definition);
			Touch(playerQuestData);
			return null;
		}

		private double SiteCooldown(OpportunityDefinition definition)
		{
			if (definition == null || !definition.CooldownDays.HasValue)
			{
				return settings.SiteDeclineCooldownSeconds();
			}
			return (double)definition.CooldownDays.Value * settings.SecondsPerDay();
		}

		public static string SiteId(string prefab, float x, float z)
		{
			return string.Format(CultureInfo.InvariantCulture, "{0}:{1:0}:{2:0}", prefab, Math.Round(x), Math.Round(z));
		}

		private QuestInstance StartSiteQuest(PlayerQuestData data, SiteRecord record, QuestTemplate template, double now)
		{
			QuestInstance questInstance = new QuestInstance
			{
				InstanceId = "q" + Save.NextInstance++.ToString(CultureInfo.InvariantCulture),
				TemplateId = template.Id,
				TemplateRevision = template.Revision,
				PackId = template.PackId,
				Category = template.Category,
				Status = QuestStatus.Active,
				OfferedAt = now,
				AcceptedAt = now,
				OriginBiome = record.Biome,
				SiteKey = record.Key,
				SiteId = SiteId(record.Prefab, record.X, record.Z),
				Rewards = RollRewards(template, record.Key, record.TimesCompleted)
			};
			data.Quests.Add(questInstance);
			record.QuestInstanceId = questInstance.InstanceId;
			return questInstance;
		}

		private bool ApplySitePresence(PlayerQuestData data, QuestInstance quest, QuestTemplate template, ClaimMessage claim, WorldContextSnapshot world, PlayerContext playerCtx, double now)
		{
			if (quest.SiteId == null || !string.Equals(quest.SiteId, claim.Site, StringComparison.Ordinal))
			{
				return false;
			}
			QuestStageDefinition questStageDefinition = CurrentStage(quest, template);
			if (questStageDefinition == null)
			{
				return false;
			}
			bool result = false;
			for (int i = 0; i < 3; i++)
			{
				if (quest.Status != QuestStatus.Active)
				{
					break;
				}
				questStageDefinition = CurrentStage(quest, template);
				if (questStageDefinition == null)
				{
					break;
				}
				bool flag = false;
				foreach (ObjectiveDefinition item in questStageDefinition.Objectives.Where((ObjectiveDefinition o) => o.Type == ObjectiveType.EnterSite || o.Type == ObjectiveType.LeaveSite || o.Type == ObjectiveType.ReachSite))
				{
					if (PresenceSatisfies(item, claim.Target))
					{
						flag |= Advance(data, quest, template, item, item.Required);
					}
				}
				if (!flag)
				{
					break;
				}
				result = true;
				int stageIndex = quest.StageIndex;
				CheckStage(data, quest, template, world, playerCtx, now);
				if (quest.StageIndex == stageIndex)
				{
					break;
				}
			}
			if (quest.Status == QuestStatus.Active && claim.Target == "Outside" && quest.SiteKey != null)
			{
				FailSiteQuest(data, quest, template, now);
				return true;
			}
			return result;
		}

		private static bool PresenceSatisfies(ObjectiveDefinition o, string presence)
		{
			bool flag = presence == "Interior";
			bool flag2 = presence == "Area";
			if (o.Type == ObjectiveType.EnterSite)
			{
				if (!(o.Target == "Interior"))
				{
					return flag || flag2;
				}
				return flag;
			}
			if (o.Type == ObjectiveType.LeaveSite)
			{
				if (!(o.Target == "Interior"))
				{
					return presence == "Outside";
				}
				return !flag;
			}
			if (o.Type == ObjectiveType.ReachSite)
			{
				return flag || flag2;
			}
			return false;
		}

		private void FailSiteQuest(PlayerQuestData data, QuestInstance quest, QuestTemplate template, double now)
		{
			Close(data, quest, QuestStatus.Failed, now, 0.0);
			sink.Notice(data.PlayerId, "$wow_msg_site_failed " + template.TitleKey, center: true);
			if (quest.SiteKey != null && data.Sites.TryGetValue(quest.SiteKey, out var value))
			{
				content.TryGetOpportunity(value.OpportunityId ?? string.Empty, out var definition);
				value.Status = SiteStatus.Failed;
				value.CooldownUntil = now + SiteCooldown(definition);
			}
			Log("place quest " + quest.TemplateId + " (" + quest.InstanceId + ") failed: left " + quest.SiteId + " before finishing");
		}

		private void OnSiteQuestClosed(PlayerQuestData data, QuestInstance quest, QuestStatus status, double now)
		{
			if (quest.SiteKey == null && status == QuestStatus.Completed && quest.RevealedOpportunity != null && content.TryGet(quest.TemplateId, out var template) && template.Stages.SelectMany((QuestStageDefinition s) => s.Objectives).Any((ObjectiveDefinition o) => o.AtSite || o.Type == ObjectiveType.OpenChests))
			{
				RememberCleared(data, quest.RevealedOpportunity, now);
				List<RememberedPlace> places = MemoryOf(data).Places;
				if (quest.SiteId != null && quest.PinX.HasValue && quest.PinZ.HasValue && places.All((RememberedPlace p) => p.SiteId != quest.SiteId))
				{
					places.Add(new RememberedPlace
					{
						SiteId = quest.SiteId,
						OpportunityId = quest.RevealedOpportunity,
						X = quest.PinX.Value,
						Z = quest.PinZ.Value,
						ClearedAt = now
					});
				}
			}
			if (quest.SiteKey != null && data.Sites.TryGetValue(quest.SiteKey, out var value))
			{
				switch (status)
				{
				case QuestStatus.Completed:
					value.Status = SiteStatus.Completed;
					value.TimesCompleted++;
					value.CompletedAt = now;
					value.BaselineCreatures = quest.MeasuredCreatures;
					value.BaselineChests = quest.MeasuredChests;
					RememberCleared(data, value.OpportunityId, now);
					break;
				case QuestStatus.Abandoned:
				{
					content.TryGetOpportunity(value.OpportunityId ?? string.Empty, out var definition);
					value.Status = SiteStatus.Declined;
					value.CooldownUntil = now + SiteCooldown(definition);
					break;
				}
				}
			}
		}

		private void Log(string message)
		{
			Logger?.Invoke(message);
		}

		public void TickSurvive(PlayerContext player, WorldContextSnapshot world, bool isNight, double now)
		{
			PlayerQuestData playerQuestData = ((player != null) ? FindPlayer(player.PlayerId) : null);
			if (playerQuestData == null)
			{
				return;
			}
			RetryReveals(playerQuestData, player, world, now);
			TickRumors(playerQuestData, player, world, now);
			ReleaseLostTargets(playerQuestData, now);
			double num = Math.Max(60.0, settings.SecondsPerDay());
			foreach (QuestInstance item in playerQuestData.Quests.Where((QuestInstance q) => q.Status == QuestStatus.Active).ToList())
			{
				if (!content.TryGet(item.TemplateId, out var template))
				{
					continue;
				}
				QuestStageDefinition questStageDefinition = CurrentStage(item, template);
				if (questStageDefinition == null)
				{
					continue;
				}
				bool flag = false;
				foreach (ObjectiveDefinition item2 in questStageDefinition.Objectives.Where((ObjectiveDefinition o) => o.Type == ObjectiveType.Survive))
				{
					item.Progress.TryGetValue(item2.Id, out var value);
					if (value >= item2.Required)
					{
						continue;
					}
					bool flag2 = player.IsDead != true && SurviveTargetMatches(item2.Target, player.Biome);
					double value2;
					bool flag3 = item.Watch.TryGetValue(item2.Id, out value2);
					if (isNight)
					{
						if (flag3 && value2 >= 0.0 && now - value2 > num)
						{
							item.Watch.Remove(item2.Id);
							flag3 = false;
							Touch(playerQuestData);
						}
						if (!flag3 && flag2)
						{
							item.Watch[item2.Id] = now;
							Touch(playerQuestData);
							sink.Notice(playerQuestData.PlayerId, "$wow_msg_watch_start " + template.TitleKey, center: false, progress: true);
						}
					}
					else if (flag3)
					{
						item.Watch.Remove(item2.Id);
						Touch(playerQuestData);
						if (value2 >= 0.0 && now - value2 <= num && now - value2 >= num * 0.1 && flag2)
						{
							flag |= Advance(playerQuestData, item, template, item2, 1);
							ActivityProfile.Record(playerQuestData, ObjectiveType.Survive, now, settings.ActivityHalfLifeSeconds());
						}
						else if (value2 >= 0.0)
						{
							sink.Notice(playerQuestData.PlayerId, "$wow_msg_watch_failed " + template.TitleKey, center: false, progress: true);
						}
					}
				}
				if (flag)
				{
					CheckStage(playerQuestData, item, template, world, player, now);
				}
			}
		}

		public static bool SurviveTargetMatches(string target, string biome)
		{
			if (!string.Equals(target, "Any", StringComparison.OrdinalIgnoreCase))
			{
				if (!string.IsNullOrEmpty(biome))
				{
					return string.Equals(target, biome, StringComparison.OrdinalIgnoreCase);
				}
				return false;
			}
			return true;
		}

		private bool BreakSurviveWatches(PlayerQuestData data)
		{
			bool flag = false;
			foreach (QuestInstance item in data.Quests.Where((QuestInstance q) => q.Status == QuestStatus.Active))
			{
				if (!content.TryGet(item.TemplateId, out var template))
				{
					continue;
				}
				QuestStageDefinition questStageDefinition = CurrentStage(item, template);
				if (questStageDefinition == null)
				{
					continue;
				}
				foreach (ObjectiveDefinition item2 in questStageDefinition.Objectives.Where((ObjectiveDefinition o) => o.Type == ObjectiveType.Survive))
				{
					double value;
					bool num = item.Watch.TryGetValue(item2.Id, out value) && value >= 0.0;
					item.Watch[item2.Id] = -1.0;
					if (num)
					{
						flag = true;
						sink.Notice(data.PlayerId, "$wow_msg_watch_broken " + template.TitleKey, center: true);
					}
				}
			}
			if (flag)
			{
				Touch(data);
			}
			return flag;
		}

		public string OnBossDefeated(string globalKey, string bossToken, int bossOrder, ICollection<long> participants, ICollection<long> online, WorldContextSnapshot world, double now, long killerPlayerId = 0L, string killerSkill = null)
		{
			bool flag = settings.BossCreditByParticipation();
			int num = 0;
			List<string> list = new List<string>();
			if (settings.BossKillRewardsEnabled())
			{
				foreach (long participant in participants)
				{
					PlayerQuestData playerQuestData = FindPlayer(participant);
					if (playerQuestData != null)
					{
						list.Add(PayBossKill(playerQuestData, globalKey, bossToken, bossOrder, now, (participant == killerPlayerId) ? killerSkill : null));
					}
				}
			}
			foreach (PlayerQuestData value in Save.Players.Values)
			{
				bool flag2 = participants.Contains(value.PlayerId);
				bool flag3 = !flag || flag2;
				bool flag4 = false;
				foreach (QuestInstance item in value.Quests.Where((QuestInstance q) => q.Status == QuestStatus.Active).ToList())
				{
					if (!content.TryGet(item.TemplateId, out var template))
					{
						continue;
					}
					QuestStageDefinition questStageDefinition = CurrentStage(item, template);
					if (questStageDefinition == null)
					{
						continue;
					}
					List<ObjectiveDefinition> list2 = questStageDefinition.Objectives.Where((ObjectiveDefinition o) => o.Type == ObjectiveType.BossMilestone && string.Equals(o.Target, globalKey, StringComparison.OrdinalIgnoreCase)).ToList();
					if (list2.Count == 0)
					{
						continue;
					}
					flag4 = true;
					if (!flag3)
					{
						continue;
					}
					bool flag5 = false;
					foreach (ObjectiveDefinition item2 in list2)
					{
						flag5 |= Advance(value, item, template, item2, item2.Required);
					}
					if (flag5)
					{
						num++;
						CheckStage(value, item, template, world, world?.FindPlayer(value.PlayerId), now);
					}
				}
				if (!flag2 && online.Contains(value.PlayerId))
				{
					sink.Notice(value.PlayerId, bossToken + ((flag4 && flag) ? " $wow_msg_boss_elsewhere" : " $wow_msg_boss_fallen"), flag4 && flag);
				}
			}
			return $"{bossToken} ({globalKey}) fell; {participants.Count} player(s) in the zone, {num} quest(s) credited, " + "mode " + (flag ? "participation" : "world") + "." + ((list.Count > 0) ? (" Kill rewards: " + string.Join("; ", list)) : string.Empty);
		}

		private string PayBossKill(PlayerQuestData player, string globalKey, string bossToken, int bossOrder, double now, string killingBlowSkill)
		{
			player.BossKills.TryGetValue(globalKey, out var value);
			int num = value + 1;
			player.BossKills[globalKey] = num;
			Touch(player);
			float num2 = Math.Min(settings.BossFirstKillLevels(bossOrder) * num switch
			{
				2 => settings.BossSecondKillFraction(), 
				1 => 1f, 
				_ => settings.BossLaterKillFraction(), 
			}, settings.BossKillMaxLevels());
			float num3 = Math.Min(num2 * settings.BossSecondSkillShare(), settings.BossKillMaxLevels());
			if (num == 1)
			{
				sink.Notice(player.PlayerId, bossToken + " $wow_msg_boss_first_kill", center: true);
			}
			bool flag = settings.AdaptiveSkillRewards();
			string text = settings.BossKillFallbackSkill();
			string text2 = ((!flag) ? text : (killingBlowSkill ?? "KillingWeapon"));
			IssueSkill(player, $"boss:{globalKey}:{num}:primary", text2, text, num2, now, null);
			if (flag)
			{
				IssueSkill(player, $"boss:{globalKey}:{num}:second", "SecondBestCombat", text, num3, now, killingBlowSkill);
			}
			return $"{player.Name} kill #{num} -> {num2:0.##} lv {text2} (+{(flag ? num3 : 0f):0.##} second)";
		}

		private void IssueSkill(PlayerQuestData player, string id, string skill, string fallback, float levels, double now, string excludeSkill)
		{
			if (!(levels < 0.01f))
			{
				string key = $"{Save.WorldUid}:{player.PlayerId}:{id}";
				if (!Save.Ledger.ContainsKey(key))
				{
					LedgerEntry ledgerEntry = new LedgerEntry
					{
						Key = key,
						PlayerId = player.PlayerId,
						InstanceId = id,
						Type = RewardType.Skill,
						Skill = skill,
						FallbackSkill = fallback,
						ExcludeSkill = excludeSkill,
						Levels = (float)Math.Round(levels, 3),
						Status = LedgerStatus.Pending,
						CreatedAt = now
					};
					Save.Ledger[key] = ledgerEntry;
					Dirty = true;
					sink.RewardIssued(ledgerEntry);
				}
			}
		}

		public void OnWorldKeys(WorldContextSnapshot world, double now)
		{
			if (settings.BossCreditByParticipation())
			{
				return;
			}
			foreach (PlayerQuestData value in Save.Players.Values)
			{
				foreach (QuestInstance item in value.Quests.Where((QuestInstance q) => q.Status == QuestStatus.Active).ToList())
				{
					if (!content.TryGet(item.TemplateId, out var template))
					{
						continue;
					}
					QuestStageDefinition questStageDefinition = CurrentStage(item, template);
					if (questStageDefinition == null)
					{
						continue;
					}
					bool flag = false;
					foreach (ObjectiveDefinition item2 in questStageDefinition.Objectives.Where((ObjectiveDefinition o) => o.Type == ObjectiveType.BossMilestone))
					{
						if (world.HasGlobalKey(item2.Target) && Advance(value, item, template, item2, item2.Required))
						{
							flag = true;
						}
					}
					if (flag)
					{
						CheckStage(value, item, template, world, world.FindPlayer(value.PlayerId), now);
					}
				}
			}
		}

		public void TickExpiry(double now)
		{
			CloseOrphans(now);
			foreach (PlayerQuestData value in Save.Players.Values)
			{
				foreach (QuestInstance item in value.Quests.Where((QuestInstance q) => q.IsOpen && q.ExpiresAt.HasValue && q.ExpiresAt.Value <= now).ToList())
				{
					bool num = item.Status == QuestStatus.Active;
					Close(value, item, QuestStatus.Expired, now, 0.0);
					if (num && content.TryGet(item.TemplateId, out var template))
					{
						sink.Notice(value.PlayerId, "$wow_msg_expired " + template.TitleKey, center: false);
					}
				}
			}
		}

		private void CloseOrphans(double now)
		{
			if (content.Templates.Count == 0)
			{
				return;
			}
			foreach (PlayerQuestData value in Save.Players.Values)
			{
				QuestTemplate template;
				foreach (QuestInstance item in value.Quests.Where((QuestInstance q) => q.IsOpen && !content.TryGet(q.TemplateId, out template)).ToList())
				{
					Close(value, item, QuestStatus.Expired, now, 0.0);
					Log("closed " + item.InstanceId + " (" + item.TemplateId + ") for " + value.Name + ": its template no longer exists");
				}
			}
		}

		public bool ForgetTemplate(long playerId, string templateId)
		{
			PlayerQuestData playerQuestData = FindPlayer(playerId);
			if (playerQuestData == null)
			{
				return false;
			}
			bool num = playerQuestData.Completed.Remove(templateId) | playerQuestData.Cooldowns.Remove(templateId);
			if (num)
			{
				Touch(playerQuestData);
			}
			return num;
		}

		public IEnumerable<LedgerEntry> PendingRewards(long playerId)
		{
			return Save.Ledger.Values.Where((LedgerEntry l) => l.PlayerId == playerId && l.Status == LedgerStatus.Pending);
		}

		public void MarkDelivered(long playerId, string ledgerKey)
		{
			if (ledgerKey != null && Save.Ledger.TryGetValue(ledgerKey, out var value) && value.PlayerId == playerId && value.Status == LedgerStatus.Pending)
			{
				value.Status = LedgerStatus.Delivered;
				Dirty = true;
			}
		}

		private static PlayerMemory MemoryOf(PlayerQuestData data)
		{
			return data.Memory ?? (data.Memory = new PlayerMemory());
		}

		public int ApplyMemory(long playerId, MemoryReportMessage report, double now)
		{
			PlayerQuestData playerQuestData = FindPlayer(playerId);
			if (playerQuestData == null || report?.Tallies == null)
			{
				return 0;
			}
			PlayerMemory playerMemory = MemoryOf(playerQuestData);
			int num = 0;
			foreach (MemoryTally item in report.Tallies.Take(64))
			{
				if (item == null || string.IsNullOrEmpty(item.Kind) || string.IsNullOrEmpty(item.Target) || item.Target.Length > 200)
				{
					continue;
				}
				int num2 = Math.Max(1, Math.Min(item.Amount, 500));
				string kind = item.Kind;
				if (kind == null)
				{
					continue;
				}
				int length = kind.Length;
				if (length != 4)
				{
					if (length != 5)
					{
						continue;
					}
					switch (kind[3])
					{
					case 'l':
						if (!(kind == "build"))
						{
							continue;
						}
						goto IL_01b0;
					case 'f':
						if (!(kind == "craft"))
						{
							continue;
						}
						goto IL_01b0;
					case 't':
						if (!(kind == "death"))
						{
							continue;
						}
						goto IL_01b0;
					case 'm':
						if (!(kind == "biome"))
						{
							continue;
						}
						RememberBiome(playerMemory, item.Target, now);
						break;
					case 'i':
						if (!(kind == "visit"))
						{
							continue;
						}
						RememberVisit(playerMemory, item.Target, now);
						break;
					default:
						continue;
						IL_01b0:
						playerMemory.Add(MemoryKeys.Of(item.Kind, item.Target), num2);
						playerMemory.Add(MemoryKeys.Of(item.Kind, "any"), num2);
						break;
					}
				}
				else
				{
					char c = kind[0];
					if (c != 'f')
					{
						if (c != 'k' || !(kind == "kill"))
						{
							continue;
						}
						RememberKill(playerMemory, item.Target, num2, now);
					}
					else
					{
						if (!(kind == "fall"))
						{
							continue;
						}
						RememberFall(playerMemory, item.Target, now);
					}
				}
				num++;
			}
			if (num > 0)
			{
				Touch(playerQuestData);
			}
			return num;
		}

		private void RememberKill(PlayerMemory m, string token, int n, double now)
		{
			int before = m.Get(MemoryKeys.Of("kill", token));
			int after = m.Add(MemoryKeys.Of("kill", token), n);
			m.Add(MemoryKeys.Of("kill", "any"), n);
			if (settings.IsBossToken(token))
			{
				m.Add(MemoryKeys.Of("boss", "any"), n);
				m.Remember(ChronicleKind.Boss, token, m.Add(MemoryKeys.Of("boss", token), n), now);
				return;
			}
			int num = MemoryKeys.MilestoneReached(MemoryKeys.KillMilestones, before, after);
			if (num > 0)
			{
				m.Remember(ChronicleKind.KillMilestone, token, num, now);
			}
		}

		private static void RememberBiome(PlayerMemory m, string biome, double now)
		{
			if (!(biome == "None") && !m.Biomes.ContainsKey(biome))
			{
				m.Biomes[biome] = now;
				m.Counters[MemoryKeys.Of("biome", biome)] = 1;
				m.Remember(ChronicleKind.Biome, biome, m.Biomes.Count, now);
			}
		}

		private void RememberVisit(PlayerMemory m, string key, double now)
		{
			string[] array = key.Split(':');
			if (array.Length != 4 || !Enum.TryParse<SiteKind>(array[0], out var result))
			{
				return;
			}
			float result2;
			float result3;
			string siteId = SiteId(array[1], float.TryParse(array[2], NumberStyles.Float, CultureInfo.InvariantCulture, out result2) ? result2 : 0f, float.TryParse(array[3], NumberStyles.Float, CultureInfo.InvariantCulture, out result3) ? result3 : 0f);
			foreach (Rumor item in m.Rumors.Where((Rumor r) => !r.Found && r.SiteId == siteId))
			{
				item.Found = true;
				m.Remember(ChronicleKind.RumorFound, item.OpportunityId, 1, now);
			}
			if (m.Visited.Add(key))
			{
				int before = m.Get(MemoryKeys.Of("visit", "any"));
				int after = m.Add(MemoryKeys.Of("visit", "any"), 1);
				OpportunityDefinition opportunityDefinition = content.MatchOpportunity(result, array[1]);
				if (opportunityDefinition != null)
				{
					m.Add(MemoryKeys.Of("visit", opportunityDefinition.Id), 1);
				}
				int num = MemoryKeys.MilestoneReached(MemoryKeys.ExploreMilestones, before, after);
				if (num > 0)
				{
					m.Remember(ChronicleKind.ExploreMilestone, "any", num, now);
				}
			}
		}

		private void RememberQuest(PlayerQuestData data, QuestTemplate template, double now)
		{
			PlayerMemory playerMemory = MemoryOf(data);
			playerMemory.Add(MemoryKeys.Of("quest", template.Category.ToString().ToLowerInvariant()), 1);
			playerMemory.Add(MemoryKeys.Of("quest", "any"), 1);
			if (template.Category == QuestCategory.Main && !template.SiteOnly)
			{
				playerMemory.Remember(ChronicleKind.MainDone, template.TitleKey, 1, now);
			}
		}

		private void RememberCleared(PlayerQuestData data, string opportunityId, double now)
		{
			if (!string.IsNullOrEmpty(opportunityId))
			{
				PlayerMemory playerMemory = MemoryOf(data);
				playerMemory.Add(MemoryKeys.Of("clear", "any"), 1);
				playerMemory.Remember(ChronicleKind.Cleared, opportunityId, playerMemory.Add(MemoryKeys.Of("clear", opportunityId), 1), now);
			}
		}

		public string ResolveMemoryKey(string key)
		{
			int num = key?.IndexOf(':') ?? (-1);
			if (num <= 0)
			{
				return key;
			}
			string text = key.Substring(0, num);
			string text2 = key.Substring(num + 1);
			if (text2 == "any" || text2.StartsWith("$", StringComparison.Ordinal))
			{
				return key;
			}
			string text3 = null;
			switch (text)
			{
			case "kill":
			case "boss":
				text3 = catalog?.GetCreatureToken(text2);
				break;
			case "build":
				text3 = catalog?.GetPieceToken(text2);
				break;
			case "craft":
				text3 = catalog?.GetItemToken(text2);
				break;
			}
			if (text3 == null)
			{
				return key;
			}
			return MemoryKeys.Of(text, text3);
		}

		public Dictionary<string, string> ResolveTextArgs(PlayerQuestData data, QuestTemplate template)
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal);
			if (template.TextArgs == null || template.TextArgs.Count == 0)
			{
				return dictionary;
			}
			PlayerMemory playerMemory = MemoryOf(data);
			foreach (KeyValuePair<string, string> textArg in template.TextArgs)
			{
				string text = textArg.Value ?? string.Empty;
				string text2;
				switch (text)
				{
				case "@name":
					text2 = data.Name;
					break;
				case "@mostHunted":
					text2 = (from c in (from c in playerMemory.Counters
							where c.Key.StartsWith("kill:$", StringComparison.Ordinal) && !settings.IsBossToken(c.Key.Substring("kill".Length + 1))
							orderby c.Value descending
							select c).ThenBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> c) => c.Key, StringComparer.Ordinal)
						select c.Key.Substring("kill".Length + 1)).FirstOrDefault();
					break;
				case "@lastBoss":
					text2 = playerMemory.Chronicle.LastOrDefault((ChronicleEntry c) => c.Kind == ChronicleKind.Boss)?.Target;
					break;
				case "@lastBiome":
					text2 = (from b in playerMemory.Biomes
						orderby b.Value
						select "$biome_" + b.Key.ToLowerInvariant()).LastOrDefault();
					break;
				case "@lastCleared":
				{
					string text3 = playerMemory.Chronicle.LastOrDefault((ChronicleEntry c) => c.Kind == ChronicleKind.Cleared)?.Target;
					text2 = ((text3 != null && content.TryGetOpportunity(text3, out var definition) && definition != null) ? definition.TitleKey : null);
					break;
				}
				case "@deadliestBiome":
					text2 = (from c in playerMemory.Counters
						where c.Key.StartsWith("death:", StringComparison.Ordinal) && c.Key != MemoryKeys.Of("death", "any")
						orderby c.Value descending
						select "$biome_" + c.Key.Substring("death".Length + 1).ToLowerInvariant()).FirstOrDefault();
					break;
				default:
					text2 = playerMemory.Get(ResolveMemoryKey(text)).ToString(CultureInfo.InvariantCulture);
					break;
				}
				dictionary[textArg.Key] = text2 ?? "?";
			}
			return dictionary;
		}

		public string DescribeMemory(long playerId, double now, double secondsPerDay)
		{
			PlayerQuestData playerQuestData = FindPlayer(playerId);
			if (playerQuestData == null)
			{
				return "player not registered";
			}
			PlayerMemory playerMemory = MemoryOf(playerQuestData);
			List<string> list = new List<string>();
			list.Add($"Memory of {playerQuestData.Name}: {playerMemory.Counters.Count} counter(s), {playerMemory.Visited.Count} place(s) seen, {playerMemory.Chronicle.Count} chronicle line(s)");
			List<string> list2 = list;
			foreach (IGrouping<string, KeyValuePair<string, int>> group in from c in playerMemory.Counters.OrderBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> c) => c.Key, StringComparer.Ordinal)
				group c by c.Key.Substring(0, Math.Max(0, c.Key.IndexOf(':'))))
			{
				list2.Add("  " + group.Key + ": " + string.Join(", ", group.Select((KeyValuePair<string, int> c) => $"{c.Key.Substring(group.Key.Length + 1)}={c.Value}")));
			}
			list2.Add("  biomes: " + string.Join(", ", from b in playerMemory.Biomes
				orderby b.Value
				select b.Key + " (" + Day(b.Value) + ")"));
			list2.Add("  chronicle (newest first):");
			foreach (ChronicleEntry item in playerMemory.Chronicle.AsEnumerable().Reverse().Take(15))
			{
				list2.Add($"    {Day(item.At)}: {item.Kind} {item.Target} x{item.Count}");
			}
			return string.Join("\n", list2);
			string Day(double at)
			{
				if (!(secondsPerDay > 0.0))
				{
					return at.ToString("0", CultureInfo.InvariantCulture);
				}
				return "day " + ((int)(at / secondsPerDay) + 1).ToString(CultureInfo.InvariantCulture);
			}
		}

		private static MemoryView BuildMemoryView(PlayerQuestData data)
		{
			PlayerMemory playerMemory = MemoryOf(data);
			return new MemoryView
			{
				Kills = playerMemory.Get(MemoryKeys.Of("kill", "any")),
				Bosses = playerMemory.Get(MemoryKeys.Of("boss", "any")),
				Explored = playerMemory.Get(MemoryKeys.Of("visit", "any")),
				Cleared = playerMemory.Get(MemoryKeys.Of("clear", "any")),
				Built = playerMemory.Get(MemoryKeys.Of("build", "any")),
				Crafted = playerMemory.Get(MemoryKeys.Of("craft", "any")),
				Deaths = playerMemory.Get(MemoryKeys.Of("death", "any")),
				Quests = playerMemory.Get(MemoryKeys.Of("quest", "any")),
				Biomes = (from b in playerMemory.Biomes
					orderby b.Value
					select b.Key).ToList(),
				TopKills = (from c in (from c in playerMemory.Counters
						where c.Key.StartsWith("kill:$", StringComparison.Ordinal)
						orderby c.Value descending
						select c).ThenBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> c) => c.Key, StringComparer.Ordinal).Take(5)
					select new KeyValuePair<string, int>(c.Key.Substring("kill".Length + 1), c.Value)).ToList(),
				Chronicle = playerMemory.Chronicle.AsEnumerable().Reverse().Take(40)
					.ToList()
			};
		}

		public PlayerQuestView BuildView(long playerId, double now)
		{
			PlayerQuestView playerQuestView = new PlayerQuestView();
			PlayerQuestData playerQuestData = FindPlayer(playerId);
			if (playerQuestData == null)
			{
				return playerQuestView;
			}
			playerQuestView.Revision = playerQuestData.Revision;
			playerQuestView.PerCharacter = settings.PerCharacterProgression();
			playerQuestView.Progress = (from k in EarnedProgress(playerQuestData)
				orderby k
				select k).ToList();
			playerQuestView.Memory = BuildMemoryView(playerQuestData);
			playerQuestView.Echoes = EchoPoints(playerQuestData, now);
			playerQuestView.Marked = MarkedCreatures(playerQuestData);
			playerQuestView.Rumors = OpenRumors(playerQuestData, now);
			foreach (QuestInstance item in playerQuestData.Quests.Where((QuestInstance q) => q.IsOpen).Concat((from q in playerQuestData.Quests
				where !q.IsOpen && q.Status != QuestStatus.Ignored
				orderby q.FinishedAt.GetValueOrDefault() descending
				select q).Take(10)))
			{
				content.TryGet(item.TemplateId, out var template);
				QuestView questView = new QuestView
				{
					InstanceId = item.InstanceId,
					TemplateId = item.TemplateId,
					Category = item.Category,
					Status = item.Status,
					TitleKey = (template?.TitleKey ?? item.TemplateId),
					DescriptionKey = template?.DescriptionKey,
					Abandonable = (template?.IsAbandonable ?? true),
					Deferred = item.Deferred,
					Stage = item.StageIndex,
					StageCount = (template?.Stages.Count ?? 0),
					SecondsLeft = ((item.IsOpen && item.ExpiresAt.HasValue) ? new double?(Math.Max(0.0, item.ExpiresAt.Value - now)) : ((double?)null)),
					Rewards = item.Rewards,
					SiteId = (item.IsOpen ? item.SiteId : null),
					Narrative = (template?.Generation.Narrative ?? false),
					Contract = (template?.Stages.Any((QuestStageDefinition s) => s.Objectives.Any((ObjectiveDefinition o) => o.Type == ObjectiveType.ReachSite)) ?? false),
					Echo = (template?.EchoOnly ?? false),
					PinX = (item.IsOpen ? item.PinX : ((float?)null)),
					PinZ = (item.IsOpen ? item.PinZ : ((float?)null)),
					TextArgs = ((item.TextArgs != null && item.TextArgs.Count > 0) ? item.TextArgs : null)
				};
				QuestStageDefinition questStageDefinition = ((template != null && item.IsOpen) ? CurrentStage(item, template) : null);
				if (questStageDefinition != null)
				{
					foreach (ObjectiveDefinition objective in questStageDefinition.Objectives)
					{
						if (IsClearSite(objective))
						{
							AddClearSiteViews(questView, item, objective);
							continue;
						}
						item.Progress.TryGetValue(objective.Id, out var value);
						questView.Objectives.Add(new ObjectiveView
						{
							Id = objective.Id,
							Type = objective.Type,
							Target = objective.Target,
							TargetToken = ((objective.Type != ObjectiveType.ReachSite) ? ((item.TargetOverride != null && item.TargetOverride.TryGetValue(objective.Id, out var value2)) ? ((value2.StartsWith("zdo:", StringComparison.Ordinal) && item.TextArgs.TryGetValue("killer", out var value3)) ? value3 : value2) : TokenFor(objective)) : ((content.TryGetOpportunity(objective.Target ?? string.Empty, out var definition) && definition != null) ? definition.TitleKey : objective.Target)),
							DescriptionKey = objective.DescriptionKey,
							Current = Math.Min(value, Req(item, objective)),
							Required = Req(item, objective),
							Watching = (objective.Type == ObjectiveType.Survive && item.Watch.TryGetValue(objective.Id, out var value4) && value4 >= 0.0),
							AtSite = (objective.AtSite || objective.Type == ObjectiveType.Loot || objective.Type == ObjectiveType.OpenChests),
							ScaleToSite = objective.ScaleToSite,
							Measured = (!objective.ScaleToSite || item.RequiredOverride.ContainsKey(objective.Id))
						});
					}
				}
				playerQuestView.Quests.Add(questView);
			}
			foreach (SiteRecord item2 in (from s in playerQuestData.Sites.Values
				where s.Status == SiteStatus.Accepted && s.QuestInstanceId == null
				orderby s.AnsweredAt.GetValueOrDefault() descending
				select s).Take(20))
			{
				if (content.TryGetOpportunity(item2.OpportunityId ?? string.Empty, out var definition2))
				{
					playerQuestView.Sites.Add(new SiteView
					{
						Key = item2.Key,
						OpportunityId = item2.OpportunityId,
						TitleKey = (definition2?.TitleKey ?? item2.Prefab),
						Kind = item2.Kind,
						Prefab = item2.Prefab,
						Biome = item2.Biome,
						Status = item2.Status,
						QuestAvailable = (definition2?.Quest != null)
					});
				}
			}
			return playerQuestView;
		}

		private static QuestStageDefinition CurrentStage(QuestInstance q, QuestTemplate t)
		{
			if (q.StageIndex < 0 || q.StageIndex >= t.Stages.Count)
			{
				return null;
			}
			return t.Stages[q.StageIndex];
		}

		private string TokenFor(ObjectiveDefinition o)
		{
			switch (o.Type)
			{
			case ObjectiveType.Kill:
				return catalog.GetCreatureToken(o.Target);
			case ObjectiveType.Gather:
			case ObjectiveType.Craft:
				return catalog.GetItemToken(o.Target);
			case ObjectiveType.Loot:
				if (!string.Equals(o.Target, "Any", StringComparison.OrdinalIgnoreCase))
				{
					return catalog.GetItemToken(o.Target);
				}
				return null;
			case ObjectiveType.Build:
				return catalog.GetPieceToken(o.Target);
			default:
				return null;
			}
		}

		private bool Matches(ObjectiveDefini