using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using I2.Loc;
using Kasizuki;
using MaidStatus;
using Schedule;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.VR;
using Yotogis;

public class GameMain : MonoSingleton<GameMain>
{
	public bool IsDebugCharaLoad
	{
		get
		{
			return this.m_boDebugCharaLoad;
		}
	}

	public static GameMain Instance
	{
		get
		{
			return GameMain.m_objInstance;
		}
	}

	public static int tick_count
	{
		get
		{
			return GameMain.m_TickCount;
		}
	}

	public CameraMain MainCamera
	{
		get
		{
			return this.m_camMainCamera;
		}
	}

	public Camera ThumCamera
	{
		get
		{
			return this.m_camThumCamera;
		}
	}

	public LightMain MainLight
	{
		get
		{
			return this.m_camMainLight;
		}
	}

	public CMSystem CMSystem
	{
		get
		{
			return this.m_System;
		}
	}

	public ScriptManager ScriptMgr
	{
		get
		{
			return this.script_mgr_;
		}
	}

	public ScriptManagerFast ScriptMgrFast
	{
		get
		{
			return this.script_mgr_fast_;
		}
	}

	public AnmParse AnmParse
	{
		get
		{
			return this.anm_parse_;
		}
	}

	public EnumData EnumDataMPN { get; private set; }

	public EnumData EnumDataPartsColor { get; private set; }

	public MenuDataBase MenuDataBase { get; private set; }

	public SoundMgr SoundMgr
	{
		get
		{
			return this.m_SoundMgr;
		}
	}

	public CharacterMgr CharacterMgr
	{
		get
		{
			return this.m_CharacterMgr;
		}
	}

	public BgMgr BgMgr
	{
		get
		{
			return this.m_BgMgr;
		}
	}

	public FacilityManager FacilityMgr
	{
		get
		{
			return this.m_FacilityMgr;
		}
	}

	public KasizukiManager KasizukiMgr
	{
		get
		{
			return this.m_KasizukiMgr;
		}
	}

	public ScenarioSelectMgr ScenarioSelectMgr
	{
		get
		{
			return this.m_ScenarioSelectMgr;
		}
	}

	public SystemDialog SysDlg
	{
		get
		{
			return this.m_SysDlg;
		}
	}

	public LoadIcon LoadIcon
	{
		get
		{
			return this.m_LoadIcon;
		}
	}

	public SystemShortcut SysShortcut
	{
		get
		{
			return this.m_SysShortcut;
		}
	}

	public FpsCounter FpsCounter
	{
		get
		{
			return this.m_FpsCounter;
		}
	}

	public MessageWindowMgr MsgWnd
	{
		get
		{
			return this.m_MsgWnd;
		}
	}

	public TutorialPanel TutorialPanel
	{
		get
		{
			return this.m_TutorialPanel;
		}
	}

	public bool isQuitting
	{
		get
		{
			return this.m_bQuitting;
		}
	}

	public bool IsForceSkip()
	{
		return Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl);
	}

	public bool VRMode
	{
		get
		{
			return this.m_bVRMode;
		}
	}

	public bool VRDummyMode
	{
		get
		{
			return this.m_bVRDummyMode;
		}
		set
		{
			if (value || this.m_bVRDummyMode)
			{
				this.m_bVRMode = value;
				this.m_bVRDummyMode = value;
			}
			else
			{
				this.m_bVRDummyMode = value;
			}
		}
	}

	public bool IsVRDeviceReady
	{
		get
		{
			return this.m_bIsVRDeviceReady;
		}
	}

	public GameMain.VRFamilyType VRFamily
	{
		get
		{
			return this.m_eVRFamily;
		}
	}

	public GameMain.VRDeviceType VRDeviceTypeID
	{
		get
		{
			if (this.m_eVRDeviceType == GameMain.VRDeviceType.FOVE && SceneVRCommunication.Instance != null)
			{
				return GameMain.VRDeviceType.RIFT;
			}
			return this.m_eVRDeviceType;
		}
		set
		{
			this.m_eVRDeviceType = value;
		}
	}

	public OvrMgr OvrMgr
	{
		get
		{
			return this.m_OvrMgr;
		}
	}

	public OVRLipSync LipSyncMgr
	{
		get
		{
			return this.m_LipSyncMgr;
		}
	}

	public OvrIK OvrIK
	{
		get
		{
			return OvrIK.Instance;
		}
	}

	public Webs Webs
	{
		get
		{
			return this.m_Webs;
		}
	}

	public override void OnInitialize()
	{
		string[] commandLineArgs = Environment.GetCommandLineArgs();
		GameMain.m_objInstance = this;
		bool flag = false;
		if (!string.IsNullOrEmpty(Array.Find<string>(commandLineArgs, (string s) => s.ToLower().Contains("/reboot"))))
		{
			flag = true;
		}
		if (!flag)
		{
			Process currentProcess = Process.GetCurrentProcess();
			string processName = currentProcess.ProcessName;
			Process[] processesByName = Process.GetProcessesByName(processName);
			foreach (Process process in processesByName)
			{
				if (process.Id != currentProcess.Id)
				{
					NUty.WinMessageBox(NUty.GetWindowHandle(), "ゲームは既に起動しています。", "警告", 48);
					Application.Quit();
					return;
				}
			}
		}
		UnityEngine.Debug.Log("TestSingleton#OnInitialize");
		LocalizationManager.CurrentLanguage = "English";
		Thread.CurrentThread.CurrentCulture = new CultureInfo("ja-JP");
		UnityEngine.Debug.Log(SystemInfo.operatingSystem);
		UnityEngine.Debug.Log(string.Concat(new object[]
		{
			SystemInfo.processorType,
			" : ",
			SystemInfo.processorCount,
			"Core"
		}));
		UnityEngine.Debug.Log(SystemInfo.systemMemorySize + " MB System Memory ");
		UnityEngine.Debug.Log(string.Concat(new object[]
		{
			SystemInfo.graphicsDeviceName,
			" : ",
			SystemInfo.graphicsMemorySize,
			"MB : ",
			SystemInfo.graphicsDeviceType
		}));
		string text = SystemInfo.graphicsDeviceName.ToLower();
		if (text.Contains("radeon") && text.Contains("hd") && NUty.WinMessageBox(NUty.GetWindowHandle(), "ご利用中のグラフィックボード・ビデオカード（" + SystemInfo.graphicsDeviceName + "）は非対応の機種です。\nゲーム中にクラッシュする場合があります。\n公式ページより対応GPUをご確認下さい。\nこのままゲームを続行しますか？", "ご注意", 52) == 7)
		{
			Application.Quit();
		}
		if (!string.IsNullOrEmpty(Array.Find<string>(commandLineArgs, (string s) => s.ToLower().Contains("/vr"))))
		{
			this.m_bVRMode = true;
		}
		else
		{
			this.m_bVRMode = false;
		}
		VRSettings.enabled = this.m_bVRMode;
		if (!this.m_bVRMode)
		{
			VRSettings.LoadDeviceByName("None");
		}
		string fullPath = Path.GetFullPath(".\\");
		if (!UTY.IsLowercaseAlphanumeric(fullPath))
		{
		}
		this.m_boDebugCharaLoad = false;
		NDebug.Assert(this.m_camMainCamera != null, "GameMainにメインカメラが設定されていません。");
		NDebug.Assert(this.m_camThumCamera != null, "GameMainにサムネイル用カメラが設定されていません。");
		NDebug.Assert(this.m_camMainLight != null, "GameMainにメインライトが設定されていません。");
		UTY.InitDll();
		base.transform.position = Vector3.zero;
		Transform transform = base.transform.Find("BG");
		NDebug.Assert(transform != null, "__GameMain__の子にBGが居ません。");
		transform.position = Vector3.zero;
		Transform transform2 = base.transform.Find("Camera");
		NDebug.Assert(transform2 != null, "__GameMain__の子にCameraが居ません。");
		transform2.position = Vector3.zero;
		GameUty.DeviceInitialize();
		this.m_System = new CMSystem();
		GameUty.Init();
		this.m_SoundMgr = base.gameObject.AddComponent<SoundMgr>().GetComponent<SoundMgr>();
		this.m_SoundMgr.Init(base.gameObject);
		GameObject childObject = UTY.GetChildObject(base.gameObject, "SystemUI Root/FpsCounter", false);
		this.m_FpsCounter = childObject.GetComponent<FpsCounter>();
		this.m_System.LoadIni();
		if ((!this.VRMode || this.VRDummyMode) && Application.targetFrameRate != 60)
		{
			NUty.WinMessageBox(NUty.GetWindowHandle(), "TargetFPS が 60 以外の設定になっています。\n60 以外では描画が乱れる場合があり、サポート対象外の設定となります。", "targetFrameRate Warning", 0);
		}
		Skill.CreateData();
		this.m_BgMgr = base.gameObject.AddComponent<BgMgr>().GetComponent<BgMgr>();
		GameObject childObject2 = UTY.GetChildObject(base.gameObject, "SystemUI Root/SystemDialog", false);
		this.m_SysDlg = childObject2.GetComponent<SystemDialog>();
		this.m_SysDlg.Init();
		this.m_LoadIcon = UTY.GetChildObject(base.gameObject, "LoadIcon", false).GetComponent<LoadIcon>();
		GameObject childObject3 = UTY.GetChildObject(base.gameObject, "SystemUI Root/SystemShortcut", false);
		this.m_SysShortcut = childObject3.GetComponent<SystemShortcut>();
		this.m_CharacterMgr = base.gameObject.AddComponent<CharacterMgr>().GetComponent<CharacterMgr>();
		this.m_CharacterMgr.Init(this);
		this.m_FacilityMgr = base.gameObject.AddComponent<FacilityManager>();
		this.m_FacilityMgr.Init(this);
		this.m_KasizukiMgr = base.gameObject.AddComponent<KasizukiManager>();
		this.m_KasizukiMgr.Init();
		if (this.CMSystem.NetUse)
		{
			this.m_Webs = base.gameObject.AddComponent<Webs>();
			this.m_Webs.Init();
		}
		this.m_ScenarioSelectMgr.InitScenarioData();
		CasinoDataMgr.Instance.InitShopData();
		VsDanceDataMgr.CreateInstance();
		this.m_LipSyncMgr = base.gameObject.AddComponent<OVRLipSync>();
		this.m_LipSyncMgr.Init();
		GameObject gameObject = GameObject.Find("SystemUI Root/Manager_SystemUI/MessageWindowMgr");
		NDebug.Assert(gameObject != null, "MessageWindowMgrが見つかりません");
		this.m_MsgWnd = gameObject.GetComponent<MessageWindowMgr>();
		NDebug.Assert(this.m_MsgWnd != null, "コンポーネント:MessageWindowMgrが見つかりません");
		this.m_TutorialPanel = GameObject.Find("SystemUI Root/TutorialPanel").GetComponent<TutorialPanel>();
		this.anm_parse_ = new AnmParse();
		this.EnumDataMPN = new EnumData();
		IEnumerator enumerator = Enum.GetValues(typeof(MPN)).GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				object obj = enumerator.Current;
				string text2 = obj.ToString();
				MPN id = MPN.null_mpn;
				try
				{
					id = (MPN)Enum.Parse(typeof(MPN), text2);
				}
				catch (Exception e)
				{
					NDebug.AssertParseError("MPN", e);
				}
				this.EnumDataMPN.AddMember((int)id, text2);
			}
		}
		finally
		{
			IDisposable disposable;
			if ((disposable = (enumerator as IDisposable)) != null)
			{
				disposable.Dispose();
			}
		}
		this.EnumDataPartsColor = new EnumData();
		IEnumerator enumerator2 = Enum.GetValues(typeof(MaidParts.PARTS_COLOR)).GetEnumerator();
		try
		{
			while (enumerator2.MoveNext())
			{
				object obj2 = enumerator2.Current;
				string text3 = obj2.ToString();
				MaidParts.PARTS_COLOR id2 = MaidParts.PARTS_COLOR.EYE_L;
				try
				{
					id2 = (MaidParts.PARTS_COLOR)Enum.Parse(typeof(MaidParts.PARTS_COLOR), text3);
				}
				catch (Exception e2)
				{
					NDebug.AssertParseError("MaidParts.PARTS_COLOR", e2);
				}
				this.EnumDataPartsColor.AddMember((int)id2, text3);
			}
		}
		finally
		{
			IDisposable disposable2;
			if ((disposable2 = (enumerator2 as IDisposable)) != null)
			{
				disposable2.Dispose();
			}
		}
		this.MenuDataBase = new MenuDataBase(GameUty.FileSystem.NativePointerToInterfaceFileSystemWide, this.EnumDataMPN, this.EnumDataPartsColor);
		this.MenuDataBase.StartAnalysis();
		this.script_mgr_ = new ScriptManager();
		this.script_mgr_.Initialize();
		this.script_mgr_fast_ = new ScriptManagerFast(this.script_mgr_);
		this.script_mgr_fast_.Initialize();
		this.UpdateSaveDataDay();
		GameMain.Instance.SysShortcut.gameObject.SetActive(true);
		DeskManager.CreateCsvData();
		DeskManager.Deserialize();
		if (this.m_bVRMode)
		{
			string loadedDeviceName = VRSettings.loadedDeviceName;
			string model = VRDevice.model;
			UnityEngine.Debug.Log("VR Device " + loadedDeviceName + " / " + model);
			if (loadedDeviceName.ToLower().Contains("oculus"))
			{
				this.m_eVRFamily = GameMain.VRFamilyType.Oculus;
				this.m_eVRDeviceType = GameMain.VRDeviceType.RIFT_TOUCH;
				UnityEngine.Debug.Log("VR Family is Oculus! " + this.m_eVRDeviceType.ToString());
				this.OvrInit();
				base.StartCoroutine(this.CoOvrStart());
			}
			else if (loadedDeviceName.ToLower().Contains("openvr"))
			{
				this.m_eVRFamily = GameMain.VRFamilyType.HTC;
				this.m_eVRDeviceType = GameMain.VRDeviceType.VIVE;
				UnityEngine.Debug.Log("VR Family is HTC!");
				this.OvrInit();
				this.m_bIsVRDeviceReady = true;
			}
			else
			{
				VRSettings.enabled = false;
				this.m_bVRMode = false;
			}
		}
	}

	private IEnumerator CoOvrStart()
	{
		yield return null;
		VRSettings.enabled = true;
		this.m_bIsVRDeviceReady = true;
		yield break;
	}

	public void OvrInit()
	{
		this.m_OvrMgr = base.gameObject.AddComponent<OvrMgr>();
		this.m_OvrMgr.Init();
		this.m_camBackupMainCamera = this.m_camMainCamera;
		this.m_camMainCamera = this.m_OvrMgr.OvrCamera;
		if (this.VRFamily != GameMain.VRFamilyType.NON)
		{
			this.m_System.LoadIni();
		}
		GameMain.Instance.MainCamera.SetPos(new Vector3(0f, -100f, 0f));
	}

	public void OvrUninit()
	{
		if (this.VRFamily != GameMain.VRFamilyType.NON)
		{
			this.m_System.SaveIni();
		}
		this.m_camMainCamera = this.m_camBackupMainCamera;
		this.m_bVRMode = false;
		this.m_bVRDummyMode = false;
		this.m_eVRFamily = GameMain.VRFamilyType.NON;
		this.m_eVRDeviceType = GameMain.VRDeviceType.NON;
		this.m_bIsVRDeviceReady = false;
		if (this.m_OvrMgr != null)
		{
			this.m_OvrMgr.Uninit();
			UnityEngine.Object.DestroyImmediate(this.m_OvrMgr);
			this.m_OvrMgr = null;
		}
		Cursor.visible = true;
		Cursor.lockState = CursorLockMode.None;
	}

	public void OnStartDay()
	{
		this.FacilityMgr.UpdateNextDay();
		ScheduleAPI.DayStartManage();
		bool flag = false;
		for (int i = 0; i < GameMain.Instance.CharacterMgr.GetStockMaidCount(); i++)
		{
			Maid stockMaid = GameMain.Instance.CharacterMgr.GetStockMaid(i);
			if (stockMaid != null && stockMaid.status.leader)
			{
				flag = true;
				break;
			}
		}
		if (!flag)
		{
			bool flag2 = false;
			for (int j = 0; j < GameMain.Instance.CharacterMgr.GetMaidCount(); j++)
			{
				Maid maid = GameMain.Instance.CharacterMgr.GetMaid(j);
				if (maid != null)
				{
					maid.status.leader = true;
					flag2 = true;
					break;
				}
			}
			if (!flag2)
			{
				for (int k = 0; k < GameMain.Instance.CharacterMgr.GetStockMaidCount(); k++)
				{
					Maid stockMaid2 = GameMain.Instance.CharacterMgr.GetStockMaid(k);
					if (stockMaid2 != null)
					{
						stockMaid2.status.leader = true;
						break;
					}
				}
			}
		}
		this.m_CharacterMgr.status.days++;
		if (GameMain.Instance.CharacterMgr.status.isAvailableRanking)
		{
			int flag3 = GameMain.Instance.CharacterMgr.status.GetFlag("__ランキング日数");
			GameMain.Instance.CharacterMgr.status.SetFlag("__ランキング日数", flag3 + 1);
		}
		Dictionary<int, List<Maid>> dictionary = new Dictionary<int, List<Maid>>();
		for (int l = 0; l < this.CharacterMgr.GetStockMaidCount(); l++)
		{
			Maid stockMaid3 = this.CharacterMgr.GetStockMaid(l);
			if (stockMaid3 != null && stockMaid3.status.heroineType == HeroineType.Sub)
			{
				int id = stockMaid3.status.subCharaData.id;
				if (stockMaid3.ActiveSlotNo != -1)
				{
					this.CharacterMgr.DeactivateMaid(stockMaid3);
				}
				if (!dictionary.ContainsKey(id))
				{
					dictionary.Add(id, new List<Maid>());
				}
				else
				{
					dictionary[id].Add(stockMaid3);
				}
			}
		}
		foreach (KeyValuePair<int, List<Maid>> keyValuePair in dictionary)
		{
			List<Maid> value = keyValuePair.Value;
			foreach (Maid maid2 in value)
			{
				UnityEngine.Debug.Log("■増殖確認がとれたサブメイド[" + maid2.status.subCharaData.uniqueName + "]を削除します");
				this.CharacterMgr.BanishmentMaid(maid2);
			}
		}
		ScheduleAPI.DayStartManage();
	}

	public void OnEndDay()
	{
		for (int i = 0; i < this.m_CharacterMgr.GetStockMaidCount(); i++)
		{
			Maid stockMaid = this.m_CharacterMgr.GetStockMaid(i);
			stockMaid.status.RemoveFeature(Feature.GetData("疲労"));
			if (stockMaid.status.currentHp <= 0 && stockMaid.status.currentMind <= 0)
			{
				stockMaid.status.AddFeature(Feature.GetData("疲労"));
			}
			stockMaid.status.currentHp = stockMaid.status.maxHp;
			stockMaid.status.currentMind = stockMaid.status.maxMind;
		}
	}

	public bool Serialize(int f_nSaveNo, string f_strComment)
	{
		MemoryStream memoryStream = new MemoryStream();
		BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
		string strSaveTime = DateTime.Now.ToString("yyyyMMddHHmmss");
		GameMain.SerializeHeader serializeHeader = new GameMain.SerializeHeader();
		serializeHeader.strSaveTime = strSaveTime;
		serializeHeader.nGameDay = this.m_CharacterMgr.status.days;
		serializeHeader.strPlayerName = this.m_CharacterMgr.status.playerName;
		serializeHeader.nMaidNum = this.m_CharacterMgr.GetStockMaidCount();
		serializeHeader.strComment = f_strComment;
		binaryWriter.Write("COM3D2_SAVE");
		binaryWriter.Write(1170);
		this.SerializeWriteHeader(binaryWriter, serializeHeader);
		binaryWriter.Write("bookmark_kk_01");
		GameMain.BinaryBookmark binaryBookmark = new GameMain.BinaryBookmark(binaryWriter);
		binaryWriter.Write("bookmark_kk_02");
		GameMain.BinaryBookmark binaryBookmark2 = new GameMain.BinaryBookmark(binaryWriter);
		bool value = false;
		foreach (Maid maid in this.m_CharacterMgr.GetStockMaidList())
		{
			if (maid.status.isCompatiblePersonality)
			{
				value = true;
				break;
			}
		}
		binaryWriter.Write(value);
		binaryWriter.Write(GameUty.ExistCsvPathList.Count);
		foreach (string value2 in GameUty.ExistCsvPathList)
		{
			binaryWriter.Write(value2);
		}
		binaryWriter.Write(GameUty.ExistCsvPathListOld.Count);
		foreach (string value3 in GameUty.ExistCsvPathListOld)
		{
			binaryWriter.Write(value3);
		}
		this.m_CharacterMgr.Serialize(binaryWriter);
		this.script_mgr_.Serialize(binaryWriter);
		DeskManager.SerializeSingleSaveData(binaryWriter);
		this.m_ScenarioSelectMgr.Serialize(binaryWriter);
		this.m_FacilityMgr.Serialize(binaryWriter);
		binaryBookmark.WriteBinaryLength(binaryWriter);
		this.m_KasizukiMgr.Serialize(binaryWriter);
		binaryBookmark2.WriteBinaryLength(binaryWriter);
		CasinoDataMgr.Instance.Serialize(binaryWriter);
		VsDanceDataMgr.Instance.Serialize(binaryWriter);
		string path = this.MakeSavePathFileName(f_nSaveNo);
		File.WriteAllBytes(path, memoryStream.ToArray());
		memoryStream.Close();
		memoryStream.Dispose();
		memoryStream = null;
		this.UpdateSaveDataDay();
		return true;
	}

	private bool SerializeWriteHeader(BinaryWriter bwWrite, GameMain.SerializeHeader f_head)
	{
		bwWrite.Write(f_head.strSaveTime);
		bwWrite.Write(f_head.nGameDay);
		bwWrite.Write(f_head.strPlayerName);
		bwWrite.Write(f_head.nMaidNum);
		bwWrite.Write(f_head.strComment);
		return true;
	}

	public string MakeSavePathFileName(int f_nSaveNo)
	{
		string fullPath = Path.GetFullPath(".\\");
		string text = fullPath + "SaveData";
		if (!Directory.Exists(text))
		{
			Directory.CreateDirectory(text);
		}
		return text + "/" + string.Format("SaveData{0:D3}", f_nSaveNo) + ".save";
	}

	public int GetSaveFileNameToSaveNo(string f_strFileName)
	{
		string text = Path.GetFileName(f_strFileName);
		if (Path.GetExtension(text) != Path.GetExtension(".save"))
		{
			return -1;
		}
		text = Path.GetFileNameWithoutExtension(text);
		if (text.Length != 11)
		{
			return -1;
		}
		int num = text.IndexOf("SaveData");
		if (num != 0)
		{
			return -1;
		}
		string s = text.Substring(8);
		int result = -1;
		if (!int.TryParse(s, out result))
		{
			return -1;
		}
		return result;
	}

	public bool SaveDataCommentSave(int f_nSaveNo, string f_strComment)
	{
		GameMain.SerializeHeader saveDataHeader = this.GetSaveDataHeader(f_nSaveNo);
		if (saveDataHeader == null)
		{
			UnityEngine.Debug.LogWarning("このスロットにはセーブデータはありません。" + f_nSaveNo);
			return false;
		}
		saveDataHeader.strComment = f_strComment;
		string path = this.MakeSavePathFileName(f_nSaveNo);
		FileStream fileStream = new FileStream(path, FileMode.Open);
		if (fileStream == null)
		{
			return false;
		}
		byte[] array = new byte[fileStream.Length];
		fileStream.Read(array, 0, (int)fileStream.Length);
		fileStream.Close();
		fileStream.Dispose();
		MemoryStream memoryStream = new MemoryStream();
		BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
		binaryWriter.Write("COM3D2_SAVE");
		binaryWriter.Write(1170);
		this.SerializeWriteHeader(binaryWriter, saveDataHeader);
		binaryWriter.Write(array, (int)saveDataHeader.lHeaderSize, (int)((long)array.Length - saveDataHeader.lHeaderSize));
		File.WriteAllBytes(path, memoryStream.ToArray());
		memoryStream.Close();
		memoryStream.Dispose();
		return true;
	}

	public void DeleteSerializeData(int f_nSaveNo)
	{
		string text = this.MakeSavePathFileName(f_nSaveNo);
		try
		{
			if (File.Exists(text))
			{
				File.Delete(text);
			}
			else
			{
				UnityEngine.Debug.LogWarning("SaveDataDelete削除失敗 ファイルが有りません。" + text);
			}
		}
		catch (Exception ex)
		{
			UnityEngine.Debug.LogWarning("SaveDataDelete削除失敗 " + ex.Message);
		}
	}

	public bool SerializeKasizukiOnly(int f_nSaveNo)
	{
		using (MemoryStream memoryStream = new MemoryStream())
		{
			using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream))
			{
				if (this.GetSaveDataHeader(f_nSaveNo) == null)
				{
					UnityEngine.Debug.LogWarning("このスロットにはセーブデータはありません。" + f_nSaveNo);
					return false;
				}
				string path = this.MakeSavePathFileName(f_nSaveNo);
				FileStream fileStream = new FileStream(path, FileMode.Open);
				if (fileStream == null)
				{
					return false;
				}
				byte[] buffer = new byte[fileStream.Length];
				BinaryReader binaryReader = new BinaryReader(new MemoryStream(buffer));
				fileStream.Read(buffer, 0, (int)fileStream.Length);
				fileStream.Close();
				fileStream.Dispose();
				binaryWriter.Write(binaryReader.ReadString());
				binaryWriter.Write(binaryReader.ReadInt32());
				this.SerializeWriteHeader(binaryWriter, this.DeserializeReadHeader(binaryReader));
				if (!this.TryBinaryReadString(binaryReader.BaseStream, (string str) => str == "bookmark_kk_01"))
				{
					NDebug.MessageBox("傅きセーブ", "元セーブデータのしおり取得に失敗しました。古いセーブデータかもしれません。");
					UnityEngine.Debug.LogWarning("[GameMain.SerializeKasizukiOnly]\u3000元セーブデータのしおり取得に失敗しました。古いセーブデータかもしれません。");
					binaryReader.Close();
					return false;
				}
				GameMain.BinaryBookmark binaryBookmark = new GameMain.BinaryBookmark(binaryReader);
				if (!this.TryBinaryReadString(binaryReader.BaseStream, (string str) => str == "bookmark_kk_02"))
				{
					NDebug.MessageBox("傅きセーブ", "元セーブデータのしおり取得に失敗しました。古いセーブデータかもしれません。");
					UnityEngine.Debug.LogWarning("[GameMain.SerializeKasizukiOnly]\u3000元セーブデータのしおり取得に失敗しました。古いセーブデータかもしれません。");
					binaryReader.Close();
					return false;
				}
				GameMain.BinaryBookmark binaryBookmark2 = new GameMain.BinaryBookmark(binaryReader);
				binaryWriter.Write("bookmark_kk_01");
				GameMain.BinaryBookmark binaryBookmark3 = new GameMain.BinaryBookmark(binaryWriter);
				binaryWriter.Write("bookmark_kk_02");
				GameMain.BinaryBookmark binaryBookmark4 = new GameMain.BinaryBookmark(binaryWriter);
				binaryReader.BaseStream.Seek(binaryBookmark.bookmark_write_position, SeekOrigin.Begin);
				binaryWriter.BaseStream.Seek(binaryBookmark.bookmark_write_position, SeekOrigin.Begin);
				binaryWriter.Write(binaryReader.ReadBytes((int)binaryBookmark.bookmark_value + 8));
				binaryBookmark3.WriteBinaryLength(binaryWriter);
				this.KasizukiMgr.Serialize(binaryWriter);
				binaryBookmark4.WriteBinaryLength(binaryWriter);
				long num = binaryBookmark2.bookmark_value + binaryBookmark2.bookmark_write_position + 8L;
				binaryReader.BaseStream.Seek(num, SeekOrigin.Begin);
				binaryWriter.Write(binaryReader.ReadBytes((int)binaryReader.BaseStream.Length - (int)num));
				binaryReader.Close();
				File.WriteAllBytes(path, memoryStream.ToArray());
			}
		}
		return true;
	}

	private bool TryBinaryReadString(Stream stream, Func<string, bool> func)
	{
		BinaryReader binaryReader = new BinaryReader(stream);
		long position = binaryReader.BaseStream.Position;
		string arg = binaryReader.ReadString();
		bool flag = func(arg);
		if (!flag)
		{
			binaryReader.BaseStream.Seek(position, SeekOrigin.Begin);
		}
		return flag;
	}

	public bool Deserialize(int f_nSaveNo, bool scriptExec = true)
	{
		this.CMSystem.m_GenericTmpFlag.Clear();
		this.m_TutorialPanel.Reset();
		GameObject gameObject = GameObject.Find("SystemUI Root/TrophyAchieveEffect");
		if (gameObject != null)
		{
			TrophyAchieveEffect component = gameObject.GetComponent<TrophyAchieveEffect>();
			if (component != null)
			{
				component.EffectStackClear();
			}
		}
		string text = this.MakeSavePathFileName(f_nSaveNo);
		NDebug.Assert(File.Exists(text), "ファイルを開けません。" + text);
		FileStream fileStream = new FileStream(text, FileMode.Open);
		if (fileStream == null)
		{
			return false;
		}
		byte[] buffer = new byte[fileStream.Length];
		fileStream.Read(buffer, 0, (int)fileStream.Length);
		fileStream.Close();
		fileStream.Dispose();
		BinaryReader binaryReader = new BinaryReader(new MemoryStream(buffer));
		string text2 = binaryReader.ReadString();
		if (!(text2 == "COM3D2_SAVE"))
		{
			NDebug.MessageBox("エラー", "セーブデータファイルのヘッダーが不正です\n" + text2);
			binaryReader.Close();
			return false;
		}
		int num = binaryReader.ReadInt32();
		GameMain.SerializeHeader serializeHeader = this.DeserializeReadHeader(binaryReader);
		if (this.TryBinaryReadString(binaryReader.BaseStream, (string str) => str == "bookmark_kk_01"))
		{
			GameMain.BinaryBookmark binaryBookmark = new GameMain.BinaryBookmark(binaryReader);
		}
		else
		{
			UnityEngine.Debug.Log("[GameMain.Deserialize()]\u3000しおりの取得に失敗しました。\u3000古いセーブデータかもしれないです。");
		}
		if (this.TryBinaryReadString(binaryReader.BaseStream, (string str) => str == "bookmark_kk_02"))
		{
			GameMain.BinaryBookmark binaryBookmark2 = new GameMain.BinaryBookmark(binaryReader);
		}
		else
		{
			UnityEngine.Debug.Log("[GameMain.Deserialize()]\u3000しおりの取得に失敗しました。\u3000古いセーブデータかもしれないです。");
		}
		bool flag = false;
		if (215 < num)
		{
			flag = binaryReader.ReadBoolean();
			if (flag)
			{
				bool flag2 = false;
				if (!GameUty.IsEnabledCompatibilityMode)
				{
					UnityEngine.Debug.LogError("カスタムメイド3D2のメイドがいますが、カスタムメイド3D2の互換設定が正しくありません");
					NDebug.MessageBox("エラー", "カスタムメイド3D2のメイドがいますが、カスタムメイド3D2の互換設定が正しくありません");
					flag2 = true;
				}
				if (!flag2 && !PluginData.IsEnabled("Legacy"))
				{
					UnityEngine.Debug.LogError("カスタムメイド3D2のメイドがいますが、互換アップデートパッチがインストールされていません");
					NDebug.MessageBox("エラー", "カスタムメイド3D2のメイドがいますが、互換アップデートパッチがインストールされていません");
					flag2 = true;
				}
				if (flag2)
				{
					binaryReader.Close();
					return false;
				}
			}
			List<string> list = new List<string>();
			int num2 = binaryReader.ReadInt32();
			for (int i = 0; i < num2; i++)
			{
				list.Add(binaryReader.ReadString());
			}
			List<string> list2 = new List<string>();
			foreach (string item in list)
			{
				if (!GameUty.ExistCsvPathList.Contains(item))
				{
					list2.Add(item);
				}
			}
			if (list2.Count > 0)
			{
				string str4 = "カスタムオーダーメイド3D2";
				string text3 = str4 + "に以下のプラグインが存在しません。\n不具合が出る可能性があります。\n";
				num2 = 1;
				foreach (string str2 in list2)
				{
					text3 += str2;
					if (num2 % 5 == 0)
					{
						text3 += "\n";
					}
					else
					{
						text3 += ",";
					}
					num2++;
				}
				UnityEngine.Debug.LogError(text3);
				NDebug.MessageBox("エラー", text3);
			}
			List<string> list3 = new List<string>();
			num2 = binaryReader.ReadInt32();
			for (int j = 0; j < num2; j++)
			{
				list3.Add(binaryReader.ReadString());
			}
			if (flag)
			{
				list2 = new List<string>();
				foreach (string item2 in list3)
				{
					if (!GameUty.ExistCsvPathListOld.Contains(item2))
					{
						list2.Add(item2);
					}
				}
				if (list2.Count > 0)
				{
					string text4 = "カスタムメイド3D2に以下のプラグインが存在しません。\n不具合が出る可能性があります。\n";
					num2 = 1;
					foreach (string str3 in list2)
					{
						text4 += str3;
						if (num2 % 5 == 0)
						{
							text4 += "\n";
						}
						else
						{
							text4 += ",";
						}
						num2++;
					}
					UnityEngine.Debug.LogError(text4);
					NDebug.MessageBox("エラー", text4);
				}
			}
		}
		try
		{
			this.m_CharacterMgr.Deserialize(binaryReader);
			this.script_mgr_.Deserialize(binaryReader);
			DeskManager.DeserializeSingleSaveData(binaryReader, num);
			if (num >= 206)
			{
				this.m_ScenarioSelectMgr.Deserialize(binaryReader);
			}
			this.m_FacilityMgr.Deserialize(binaryReader);
			this.m_KasizukiMgr.Deserialize(f_nSaveNo, binaryReader);
			CasinoDataMgr.Instance.Deserialize(binaryReader, num);
			VsDanceDataMgr.Instance.Deserialize(binaryReader, num);
			binaryReader.Close();
			binaryReader = null;
		}
		catch (Exception ex)
		{
			UnityEngine.Debug.LogError(ex.Message + "\n\n" + ex.StackTrace);
			NDebug.MessageBox("エラー", ex.Message + "\n\n" + ex.StackTrace);
			binaryReader.Close();
			return false;
		}
		if (scriptExec)
		{
			this.ScriptMgr.adv_kag.Exec();
		}
		return true;
	}

	private GameMain.SerializeHeader DeserializeReadHeader(BinaryReader brRead)
	{
		return new GameMain.SerializeHeader
		{
			strSaveTime = brRead.ReadString(),
			nGameDay = brRead.ReadInt32(),
			strPlayerName = brRead.ReadString(),
			nMaidNum = brRead.ReadInt32(),
			strComment = brRead.ReadString()
		};
	}

	public GameMain.SerializeHeader GetSaveDataHeader(int f_nSaveNo)
	{
		string path = this.MakeSavePathFileName(f_nSaveNo);
		if (File.Exists(path))
		{
			GameMain.SerializeHeader serializeHeader;
			using (FileStream fileStream = new FileStream(path, FileMode.Open))
			{
				if (fileStream == null)
				{
					return null;
				}
				BinaryReader binaryReader = new BinaryReader(fileStream);
				string a = binaryReader.ReadString();
				if (a == "COM3D2_CBL_SAVE")
				{
					return null;
				}
				NDebug.Assert(a == "COM3D2_SAVE", "セーブデータファイルのヘッダーが不正です。_SAVE 2");
				int nVer = binaryReader.ReadInt32();
				serializeHeader = this.DeserializeReadHeader(binaryReader);
				serializeHeader.nVer = nVer;
				serializeHeader.lHeaderSize = binaryReader.BaseStream.Position;
			}
			return serializeHeader;
		}
		return null;
	}

	public bool IsSaveDataNew(int f_nSaveNo)
	{
		return (long)f_nSaveNo == this.m_lNewSaveDataNo;
	}

	public long NewSaveDataNo()
	{
		return this.m_lNewSaveDataNo;
	}

	public void UpdateSaveDataDay()
	{
		string fullPath = Path.GetFullPath(".\\");
		string path = fullPath + "SaveData";
		int num = -1;
		if (Directory.Exists(path))
		{
			string[] files = Directory.GetFiles(path, "*.save");
			long num2 = -1L;
			foreach (string f_strFileName in files)
			{
				int saveFileNameToSaveNo = this.GetSaveFileNameToSaveNo(f_strFileName);
				if (saveFileNameToSaveNo != -1)
				{
					GameMain.SerializeHeader saveDataHeader = this.GetSaveDataHeader(saveFileNameToSaveNo);
					if (saveDataHeader != null)
					{
						long num3 = 0L;
						if (long.TryParse(saveDataHeader.strSaveTime, out num3))
						{
							if (num2 < num3)
							{
								num2 = num3;
								num = saveFileNameToSaveNo;
							}
						}
					}
				}
			}
		}
		this.m_lNewSaveDataNo = (long)num;
	}

	public override void OnFinalize()
	{
		UnityEngine.Debug.Log("GameMain::OnFinalize Start");
		base.BroadcastMessage("OnPreFinalize", SendMessageOptions.DontRequireReceiver);
		UnityEngine.Object.DestroyImmediate(this.CharacterMgr);
		UnityEngine.Object.DestroyImmediate(this.SoundMgr);
		this.anm_parse_.Dispose();
		this.script_mgr_fast_.SelfDispose();
		this.script_mgr_.Dispose();
		if (this.MenuDataBase != null)
		{
			this.MenuDataBase.Dispose();
			this.MenuDataBase = null;
		}
		this.EnumDataMPN.Dispose();
		this.EnumDataPartsColor.Dispose();
		GameUty.Finish();
		UTY.FreeDll();
		UnityEngine.Debug.Log("GameMain::OnFinalize Finish");
	}

	public string GetNowSceneName()
	{
		return this.m_strBeforeSceneName;
	}

	public List<string> GetAddSceneName()
	{
		return this.m_listStackScene;
	}

	public void LoadScene(string f_strSceneName)
	{
		this.m_listStackScene.Clear();
		SceneManager.LoadScene(f_strSceneName, LoadSceneMode.Single);
		this.m_strBeforeSceneName = f_strSceneName;
		UnityEngine.Debug.Log("GameMain::LoadScene " + f_strSceneName);
	}

	public void AddScene(string f_strSceneName)
	{
		if (this.m_listStackScene.Contains(f_strSceneName))
		{
			NDebug.Assert("AddScene 既に同名のシーンがロードされています。" + f_strSceneName, false);
			return;
		}
		SceneManager.LoadScene(f_strSceneName, LoadSceneMode.Additive);
		this.m_listStackScene.Add(f_strSceneName);
		base.StartCoroutine(this.CoAddScene(SceneManager.GetSceneByName(f_strSceneName)));
	}

	private IEnumerator CoAddScene(Scene f_scene)
	{
		while (!f_scene.isLoaded)
		{
			yield return null;
		}
		base.BroadcastMessage("OnLevelWasLoaded", f_scene.buildIndex, SendMessageOptions.DontRequireReceiver);
		yield break;
	}

	public void SceneActivate(string f_strSceneName)
	{
		Scene sceneByName = SceneManager.GetSceneByName(f_strSceneName);
		NDebug.Assert(true, f_strSceneName + " シーンはありません。");
		NDebug.Assert(sceneByName.isLoaded, "未だ " + f_strSceneName + " はロードされていません。Start()以降で利用可能です。");
		bool flag = SceneManager.SetActiveScene(sceneByName);
		NDebug.Assert(flag, "シーンをアクティブ化できませんでした。");
	}

	public void UnloadScene(string f_strSceneName)
	{
		if (!this.m_listStackScene.Contains(f_strSceneName))
		{
			UnityEngine.Debug.LogWarning("追加シーンではないシーンを破棄しようとしました。" + f_strSceneName);
		}
		SceneManager.UnloadScene(f_strSceneName);
		this.m_listStackScene.Remove(f_strSceneName);
		string name;
		if (this.m_listStackScene.Count<string>() == 0)
		{
			name = this.m_strBeforeSceneName;
		}
		else
		{
			name = this.m_listStackScene.Last<string>();
		}
		base.BroadcastMessage("OnLevelWasLoaded", SceneManager.GetSceneByName(name).buildIndex, SendMessageOptions.DontRequireReceiver);
		UnityEngine.Debug.Log("シーンを破棄しました。" + f_strSceneName);
	}

	public void UnloadPopScene()
	{
		if (this.m_listStackScene.Count<string>() == 0)
		{
			return;
		}
		string f_strSceneName = this.m_listStackScene.Last<string>();
		this.UnloadScene(f_strSceneName);
	}

	public void OnLevelWasLoaded(int level)
	{
		UnityEngine.Debug.Log("シーン切り替え完了 Level=" + level);
		if (GameMain.Instance != null)
		{
			GameMain.Instance.SysShortcut.gameObject.SetActive(true);
		}
	}

	private void Update()
	{
		if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.F6))
		{
			string[] array = LocalizationManager.GetAllLanguages(true).ToArray();
			int num = 0;
			foreach (string a in array)
			{
				if (a == LocalizationManager.CurrentLanguage)
				{
					num++;
					if (array.Length <= num)
					{
						num = 0;
					}
					LocalizationManager.CurrentLanguage = array[num];
					break;
				}
				num++;
			}
		}
		if (GameMain.Instance.VRMode)
		{
			NInput.SelfUpdateVR();
		}
		if (GameMain.Instance.VRMode && !GameMain.Instance.VRDummyMode)
		{
			if (Input.GetKeyUp(KeyCode.Escape))
			{
				Cursor.visible = true;
				Cursor.lockState = CursorLockMode.None;
			}
			if (NInput.GetMouseButtonUp(0) && 0f <= Input.mousePosition.x && Input.mousePosition.x < (float)Screen.width && 0f <= Input.mousePosition.y && Input.mousePosition.y < (float)Screen.height)
			{
				Cursor.visible = false;
				Cursor.lockState = CursorLockMode.Locked;
			}
		}
		GameMain.m_TickCount = (int)(Time.realtimeSinceStartup * 1000f);
		this.script_mgr_.Update();
	}

	public void ToApplicationQuit(bool f_bForceQuit = false)
	{
		if (f_bForceQuit)
		{
			Application.Quit();
		}
		else
		{
			GameMain.Instance.SysDlg.ShowFromLanguageTerm("Dialog/終了しますか？", SystemDialog.TYPE.OK_CANCEL, new SystemDialog.OnClick(this.OnToEnd), new SystemDialog.OnClick(this.OnCancel));
		}
	}

	public void OnToEnd()
	{
		GameMain.Instance.SysDlg.Close();
		Application.Quit();
	}

	public void OnCancel()
	{
		GameMain.Instance.SysDlg.Close();
	}

	protected override void OnApplicationQuit()
	{
		if (GameMain.Instance.VRMode)
		{
			this.BgMgr.OnSaveDD();
		}
		this.CMSystem.SaveSystem();
		this.CMSystem.SaveIni();
		this.m_bQuitting = true;
		base.OnApplicationQuit();
		UnityEngine.Debug.Log("GameMain::OnApplicationQuit");
	}

	private static GameMain m_objInstance;

	[SerializeField]
	private bool m_boDebugCharaLoad = true;

	private CMSystem m_System;

	private ScriptManager script_mgr_;

	private ScriptManagerFast script_mgr_fast_;

	private static int m_TickCount;

	[SerializeField]
	private CameraMain m_camMainCamera;

	private CameraMain m_camBackupMainCamera;

	[SerializeField]
	private Camera m_camThumCamera;

	[SerializeField]
	private LightMain m_camMainLight;

	private AnmParse anm_parse_;

	private SoundMgr m_SoundMgr;

	private CharacterMgr m_CharacterMgr;

	private BgMgr m_BgMgr;

	private FacilityManager m_FacilityMgr;

	private KasizukiManager m_KasizukiMgr;

	private ScenarioSelectMgr m_ScenarioSelectMgr = new ScenarioSelectMgr();

	private SystemDialog m_SysDlg;

	private LoadIcon m_LoadIcon;

	private SystemShortcut m_SysShortcut;

	private FpsCounter m_FpsCounter;

	private List<KeyValuePair<Material, string>> m_listMozaMat = new List<KeyValuePair<Material, string>>();

	private MessageWindowMgr m_MsgWnd;

	private TutorialPanel m_TutorialPanel;

	private bool m_bQuitting;

	private long m_lNewSaveDataNo = -1L;

	[SerializeField]
	[Header("VRモード")]
	private bool m_bVRMode;

	private bool m_bVRDummyMode;

	private bool m_bIsVRDeviceReady;

	private GameMain.VRFamilyType m_eVRFamily;

	private GameMain.VRDeviceType m_eVRDeviceType;

	private OvrMgr m_OvrMgr;

	private OVRLipSync m_LipSyncMgr;

	private Webs m_Webs;

	private AsyncOperation m_aoLoadScene;

	private string m_strBeforeSceneName;

	private List<string> m_listStackScene = new List<string>();

	public enum VRFamilyType
	{
		NON,
		Oculus,
		HTC,
		FOVE
	}

	public enum VRDeviceType
	{
		NON,
		VIVE,
		RIFT,
		RIFT_TOUCH,
		FOVE
	}

	public class SerializeHeader
	{
		public string strSaveTime;

		public int nGameDay;

		public string strPlayerName;

		public int nMaidNum;

		public string strComment;

		public int nVer;

		public long lHeaderSize;
	}

	private struct BinaryBookmark
	{
		public BinaryBookmark(BinaryWriter bwWrite)
		{
			this.bookmark_write_position = bwWrite.BaseStream.Position;
			bwWrite.Write(-1L);
			this.bookmark_value = -1L;
		}

		public BinaryBookmark(BinaryReader brRead)
		{
			this.bookmark_write_position = brRead.BaseStream.Position;
			this.bookmark_value = brRead.ReadInt64();
		}

		public void WriteBinaryLength(BinaryWriter bwWrite)
		{
			long position = bwWrite.BaseStream.Position;
			long value = position - this.bookmark_write_position - 8L;
			bwWrite.Seek((int)this.bookmark_write_position, SeekOrigin.Begin);
			bwWrite.Write(value);
			bwWrite.Seek((int)position, SeekOrigin.Begin);
			this.bookmark_value = value;
		}

		public readonly long bookmark_write_position;

		public long bookmark_value;
	}
}
