// ------------------------------------------------------------------------------------------------------------------- private void CheckGameStart() { if (m_playersConfirmedImReady == null) { logger.Error("ERROR!!! Unexpected null reference during game start. IsInit? " + m_initialized); return; } //check if all expected players confirmed our gamestart message if (m_playersConfirmedImReady.Count == m_numberOfPlayers - 1) { //check if all expected players sent their gamestart message if (m_readyPlayers.Count == m_numberOfPlayers - 1) { //we are ready to start logger.Debug("All players are ready to start. Starting Game."); //we no longer need these lists m_playersConfirmedImReady = null; m_readyPlayers = null; GameStart(); } } }
//读取模组定义文件 private void ReadLevelDef(string defText) { LevelDefText = defText; try { levelDefXmlDoc = new XmlDocument(); levelDefXmlDoc.LoadXml(defText); XmlNode nodeMod = levelDefXmlDoc.SelectSingleNode("Level"); foreach (XmlNode node in nodeMod.ChildNodes) { switch (node.Name) { case "BaseInfo": ReadLevelDefBaseInfo(node); break; case "Compatibility": ReadLevelDefCompatibility(node); break; } } } catch (Exception e) { GameLogger.Error(TAG, (object)("Failed to solve LevelDef.xml : " + e.Message)); GameLogger.Exception(e); } }
private void ReadLevelDefFull() { try { XmlNode nodeMod = levelDefXmlDoc.SelectSingleNode("Level"); foreach (XmlNode node in nodeMod.ChildNodes) { switch (node.Name) { case "Game": ReadLevelDefGame(node); break; case "Groups": ReadLevelDefGroup(node); break; case "Data": break; default: if (ModManager.LevelDefCustomPropertySolver.ContainsKey(node.Name)) { ModManager.LevelDefCustomPropertySolver[node.Name](node, this); } break; } } } catch (Exception e) { GameLogger.Error(TAG, (object)("Failed to solve LevelDef.xml : " + e.Message)); GameLogger.Exception(e); } }
private LuaTable CreateFillTable() { LuaTable result = null; if (m_createTableFunc != null) { result = m_createTableFunc.callReturnTable(); if (result == null) { throw new LuaException("must a function return table"); } } else if (m_luaTable != null) { return(m_luaTable); } else { if (GameLogger.IsEnable) { GameLogger.Error("c# m_createTableFunc is null"); } } return(result); }
/// <summary> /// 初始化管理器 /// </summary> /// <param name="manager">目标管理器</param> public void InitManager(BaseManager manager) { if (!manager.Initialized) { try { if (!manager.InitManager()) { GameLogger.Error("GameManager", "InitManager 失败,管理器 {0}:{1} 初始化失败", manager.GetName(), manager.GetSubName()); GameErrorManager.LastError = GameError.InitializationFailed; } else { manager.initialized = true; manager.loadIndex = ++loadIndex; GameLogger.Log("GameManager", "{0}:{1} Inited ", manager.GetName(), manager.GetSubName()); CallManagerRedayCallback(manager, manager.GetNameWithSub()); if (GameManager.GameMediator != null) { GameManager.GameMediator.DispatchGlobalEvent(GameEventNames.EVENT_BASE_MANAGER_INIT_FINISHED, "*", manager.GetName(), manager.GetSubName()); } } } catch (Exception e) { GameLogger.Error("GameManager", (object)("管理器 " + manager.GetName() + ":" + manager.GetSubName() + " 初始化失败: " + e.Message + "\n" + e)); } } }
private void Handle_Completed(AssetOperationHandle obj) { TextAsset temp = _handle.AssetObject as TextAsset; if (temp != null) { try { SecurityParser sp = new SecurityParser(); sp.LoadXml(temp.text); _xml = sp.ToXml(); // 解析数据 if (_xml != null) { ParseData(); } } catch (Exception ex) { GameLogger.Error($"Failed to parse xml {Location}. Exception : {ex.ToString()}"); } } // 注意:为了节省内存这里立即释放了资源 if (_assetRef != null) { _assetRef.Release(); _assetRef = null; } _userCallback?.Invoke(); }
private void Handle_Completed(AssetOperationHandle obj) { if (_handle.AssetObject == null) { return; } Go = _handle.InstantiateObject; // 设置父类 GameObject uiDesktop = UIManager.Instance.UIDesktop; Go.transform.SetParent(uiDesktop.transform, false); // 获取组件 _manifest = Go.GetComponent <UIManifest>(); if (_manifest == null) { GameLogger.Error($"Not found {nameof(UIManifest)} in window {WindowType}"); return; } // 获取组件 _canvas = Go.GetComponent <Canvas>(); if (_canvas == null) { GameLogger.Error($"Not found {nameof(Canvas)} in window {WindowType}"); return; } _canvas.overrideSorting = true; // 获取组件 _raycaster = Go.GetComponent <GraphicRaycaster>(); if (_raycaster == null) { GameLogger.Error($"Not found {nameof(GraphicRaycaster)} in window {WindowType}"); return; } // 获取组件 _childCanvas = Go.GetComponentsInChildren <Canvas>(true); _childRaycaster = Go.GetComponentsInChildren <GraphicRaycaster>(true); // 虚函数 if (IsPrepare == false) { IsPrepare = true; OnCreate(); } // 最后设置是否激活 Go.SetActive(IsOpen); // 通知UI管理器 _userCallback?.Invoke(this); }
private bool OnCommandInitializeMod(string keyword, string fullCmd, string[] args) { GameMod mod = FindGameModByAssetStr(args[0]); if (mod == null) { GameLogger.Error(TAG, "未找到模组 {0} ", args[0]); return(false); } return(InitializeLoadGameMod(mod)); }
public void AddCommand(Command command, int playerID, int lockStepTurn, int commandsLockStepTurn) { logger.Debug("Player " + playerID + " added pending command for turn " + commandsLockStepTurn); int index = commandsLockStepTurn - lockStepTurn + 2; if ((index <= 0) || (index > (m_nofTurns - 1))) { logger.Error("WARNING!!!! Unexpected lockstepID " + commandsLockStepTurn + " received"); //TODO: Error Handling return; } // if command is for next turn, add for processing 3 turns away if (m_commands[index][playerID - 1] != null) { logger.Error("WARNING!!!! Recieved multiple commands from player " + playerID + " for turn " + commandsLockStepTurn); //TODO: Error Handling } m_commands[index][playerID - 1] = command; m_commandCounts[index]++; return; }
public void AddData(int firstPK, int secondPK, ConfigData data) { long longID = firstPK; if (secondPK >= 0) { longID = ((long)firstPK << 32) + (long)secondPK; } if (DataMap.ContainsKey(longID)) { GameLogger.Error(LOG_CHANNEL.ERROR, "Table:" + TableName + ",Has two Keys:" + firstPK + "/" + secondPK); } DataMap.Add(longID, data); }
public void Create(System.Action callback) { if (_spawnGo != null) { GameLogger.Error($"Avatar is create yet : {_avatarTable.Id}"); return; } _callback = callback; // 对象池 _spawnGo = GameObjectPoolManager.Instance.Spawn(GetModelName()); _spawnGo.Completed += SpawnGo_Completed; }
private void DoInitUICore(LuaTable bind) { m_bindTable = bind; if (m_bindTable == null) { if (GameLogger.IsEnable) { GameLogger.Error("m_bindTable is nil"); } return; } Init(m_bindTable); m_bindTable.Set("_grid", m_grid); m_bindTable.Set("_core", this); }
//加载基础信息 private bool LoadBaseInfo() { bool hasDefFile = false; //在zip中加载LevelDef ZipInputStream zip = ZipUtils.OpenZipFile(FilePath); ZipEntry theEntry; while ((theEntry = zip.GetNextEntry()) != null) { if (theEntry.Name == "/LevelDef.xml" || theEntry.Name == "LevelDef.xml") { hasDefFile = true; LoadLevelDefInZip(zip, theEntry); } else if (theEntry.Name == "/" + Logo || theEntry.Name == Logo) { LoadLogoInZip(zip, theEntry); } } zip.Close(); zip.Dispose(); if (!hasDefFile) { GameLogger.Error(TAG, "加载模组包失败,未找到 LevelDef.xml"); GameErrorManager.LastError = GameError.InitializationFailed; LoadStatus = GameModStatus.InitializeFailed; LoadError = "未找到 ModDef.xml"; return(false); } //检查兼容性 if (LevelCompatibilityInfo.MinVersion > GameConst.GameBulidVersion) { GameLogger.Error(TAG, "加载模组包失败,关卡与游戏版本不兼容"); GameErrorManager.LastError = GameError.BadMod; LoadStatus = GameModStatus.BadMod; LoadError = "关卡与游戏版本不兼"; return(false); } return(true); }
/// <summary> /// 生成 垂直自动布局 /// </summary> /// <param name="name">布局名称</param> /// <param name="template">UI模板</param> /// <param name="handlers">接收器模板</param> /// <returns></returns> public UILayout BuildLayoutByTemplate(string name, string templateXml, Dictionary <string, GameHandler> handlers, string[] initialProps) { if (string.IsNullOrEmpty(templateXml)) { GameLogger.Error(TAG, "BuildLayoutByTemplate {0} failed, templateXml is Empty", name); GameErrorManager.LastError = GameError.ParamNotProvide; return(null); } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(templateXml); return(BuildLayoutByTemplateInternal(name, xmlDocument.DocumentElement, handlers, null, null, initialProps)); }
/// <summary> /// 加载模组包 /// </summary> /// <param name="packagePath">模组包路径</param> /// <param name="initialize">是否立即初始化模组包</param> /// <returns>返回模组包UID</returns> public GameMod LoadGameMod(string packagePath, bool initialize = true) { GameMod mod = FindGameModByPath(packagePath); if (mod != null) { GameLogger.Warning(TAG, "Mod \"{0}\" already registered, skip", packagePath); return(mod); } //路径处理 if (StringUtils.IsUrl(packagePath)) { GameLogger.Error(TAG, "不支持从 URL 加载模组包 \"{0}\" ,请将其先下载至 streamingAssetsPath 后再加载。", packagePath); return(null); } //处理路径至mod文件夹路径 if (!File.Exists(packagePath) && !GamePathManager.IsAbsolutePath(packagePath)) { packagePath = GamePathManager.GetResRealPath("mod", packagePath); } if (!File.Exists(packagePath)) { GameLogger.Error(TAG, "Mod file \"{0}\" not exists", packagePath); return(null); } mod = new GameMod(packagePath, this); if (!mod.Init()) { return(null); } if (!gameMods.Contains(mod)) { gameMods.Add(mod); } GameManager.GameMediator.DispatchGlobalEvent(GameEventNames.EVENT_MOD_REGISTERED, "*", mod.PackageName, mod); GameLogger.Log(TAG, "Register mod \"{0}\"", packagePath); if (initialize) { mod.Load(this); } return(mod); }
public bool DoPreInit() { if (preIinitialized) { return(true); } preIinitialized = true; InitPre(); if (IsLuaModul && luaObjectHost == null) { GameLogger.Error(GetFullName(), "LuaModul can oly use when GameLuaObjectHost is bind ! "); return(false); } return(DoInitStore()); }
private void LoadLogoInZip(ZipInputStream zip, ZipEntry theEntry) { try { Texture2D texture2D = new Texture2D(128, 128); MemoryStream ms = ZipUtils.ReadZipFileToMemory(zip); texture2D.LoadImage(ms.ToArray()); ms.Close(); ms.Dispose(); LevelLogo = Sprite.Create(texture2D, new Rect(Vector2.zero, new Vector2(texture2D.width, texture2D.height)), new Vector2(0.5f, 0.5f)); } catch (Exception e) { LevelLogo = null; GameLogger.Error(TAG, "在加载关卡的 Logo {0} 失败\n错误信息:{1}", Logo, e.ToString()); } }
public void CreateScrollView(int dataCount, LuaFunction createTableFunc, LuaTable data) { try { if (!m_initiated) { InitPosAndScroll(); } Clear(); SlotData(dataCount); m_createTableFunc = createTableFunc; dataTable = data; ResetToBegin(); } catch (Exception e) { if (GameLogger.IsEnable) { GameLogger.Error(e.ToString()); } } }
/// <summary> /// Get data from a store and casts the type for you. /// This assumes you know what the type is. /// </summary> /// <typeparam name="T">The type to cast the data to.</typeparam> /// <param name="type">The game data type.</param> /// <param name="dataName">Name of the data to load.</param> /// <returns>The game data, or null if not found.</returns> public static T Get <T>(GameDataType type, string dataName) where T : class { object data = Get(type, dataName); T dataCasted = data as T; if (dataCasted != null) { return(dataCasted); } else if (data != null) { GameLogger.Error("Found game data '{0}' in {1} but could not load as type '{2}'", dataName, type.ToString(), typeof(T).Name); } else { GameLogger.Error("Failed to load game data from store. Store = '{0}'. Data = '{1}'.", type.ToString(), dataName); } return(default(T)); }
public void Create(GameWorld world, int avatarID, Vector3 pos, Vector3 rot) { if (Root != null) { GameLogger.Error("EntityObject is create yet."); return; } World = world; // 创建Avatar Avatar = new EntityAvatar(this, avatarID); Avatar.Create(OnAvatarLoad); // 创建游戏对象 Root = new GameObject($"Entity{EntityID}"); Root.transform.position = pos; Root.transform.rotation = Quaternion.Euler(rot); OnCreate(); }
private void InitCommands() { commands = new List <CmdItem>(); //注册基础内置命令 RegisterCommand("quit", (keyword, fullCmd, args) => { GameManager.QuitGame(); return(true); }, 0, "退出游戏"); RegisterCommand("echo", (keyword, fullCmd, args) => { GameLogger.Log(TAG, "[echo] " + fullCmd.Substring(3)); return(true); }, 1, "[any] 测试"); RegisterCommand("lua", (keyword, fullCmd, args) => { LuaSvr.mainState.doString(fullCmd.Substring(3)); return(true); }, 1, "[any] 运行 LUA 命令"); RegisterCommand("fps", (keyword, fullCmd, args) => { int fpsVal = 0; if (args.Length >= 1) { if (int.TryParse(args[0], out fpsVal) && fpsVal > 0 && fpsVal < 120) { fPSManager.ForceSetFps(fpsVal); } else { GameLogger.Error(TAG, "错误的参数:{0}", args[0]); } } GameLogger.Error(TAG, "Application.targetFrameRate = {0}", Application.targetFrameRate); return(true); }, 0, "[targetFps:int] 获取或设置 targetFrameRate"); RegisterCommand("help", OnCommandHelp, 1, "显示命令帮助"); }
//初始化 internal bool Init() { if (IsEditorPack) { inited = true; } if (inited) { return(true); } if (FileUtils.TestFileIsZip(FilePath)) { inited = true; return(LoadBaseInfo()); } //文件格式不支持 GameErrorManager.LastError = GameError.BadFileType; GameLogger.Error(TAG, "Level package not support {0}", FilePath); return(false); }
public void Execute() { System.Object objectToCommand; // Some commands does not operate on an object... if (objectNameToCommand == "") { objectToCommand = null; } else { objectToCommand = CommandableDictionary.instance.get(objectNameToCommand); if (objectToCommand == null) { logger.Error("Could not find commandable object " + objectNameToCommand); return; } } Perform(objectToCommand); }
private bool OnCommandShowModAssets(string keyword, string fullCmd, string[] args) { GameMod mod = FindGameModByAssetStr(args[0]); if (mod == null) { GameLogger.Error(TAG, "未找到模组 {0} ", args[0]); return(false); } if (mod.LoadStatus == GameModStatus.InitializeSuccess && mod.AssetBundle != null) { StringBuilder sb = new StringBuilder(); string[] paths = mod.AssetBundle.GetAllAssetNames(); string[] scensePaths = mod.AssetBundle.GetAllScenePaths(); sb.Append("\n<size=16>Asset Names: </size>(" + paths.Length + ")\n"); foreach (string s in paths) { sb.Append(s); sb.Append("\n"); } sb.Append("<size=16>Scene Paths: </size>(" + scensePaths.Length + ")\n"); foreach (string s in scensePaths) { sb.Append(s); sb.Append("\n"); } GameLogger.Log(TAG, sb.ToString()); } else { GameLogger.Error(TAG, "指定模组未初始化或初始化失败"); } return(true); }
/// <summary> /// 创建预制的天空盒 /// </summary> /// <param name="s">天空盒名字,(必须是 A~K ,对应原版游戏11个天空)</param> /// <returns>返回创建好的天空盒材质</returns> public static Material MakeSkyBox(string s) { if (ModManager == null) { ModManager = (IModManager)GameManager.GetManager("ModManager"); } if (skyAssetPack == null) { skyAssetPack = ModManager.FindGameMod("core.assets.skys"); } if (skyAssetPack == null) { GameLogger.Error(TAG, "MakeSkyBox failed because skybase pack core.assets.skys not load !"); return(null); } Texture SkyLeft = skyAssetPack.GetAsset <Texture>("Sky_" + s + "_Left.BMP"); Texture SkyRight = skyAssetPack.GetAsset <Texture>("Sky_" + s + "_Right.BMP"); Texture SkyFront = skyAssetPack.GetAsset <Texture>("Sky_" + s + "_Front.BMP"); Texture SkyBack = skyAssetPack.GetAsset <Texture>("Sky_" + s + "_Back.BMP"); Texture SkyDown = skyAssetPack.GetAsset <Texture>("Sky_" + s + "_Down.BMP"); return(MakeCustomSkyBox(SkyLeft, SkyRight, SkyFront, SkyBack, SkyDown, null)); }
// Init and get // =========================== private bool LuaInit() { if (GameMod == null) { if (string.IsNullOrEmpty(LuaModName)) { GameLogger.Error(TAG + ":" + Name, "LuaObject {0} load error : LuaModName not provide ", Name); GameErrorManager.LastError = GameError.ParamNotProvide; return(false); } GameMod = ModManager.FindGameMod(LuaModName); if (GameMod == null) { GameLogger.Error(TAG + ":" + Name, "LuaObject {0} load error : LuaModName not found : {1}", Name, LuaModName); GameErrorManager.LastError = GameError.NotRegister; return(false); } GameMod.AddeLuaObject(this); _PackageName = GameMod.PackageName; if (CreateStore) { Store = GameManager.GameMediator.RegisterGlobalDataStore(PackageName + ":" + Name); } if (CreateActionStore) { ActionStore = GameManager.GameMediator.RegisterActionStore(PackageName + ":" + Name); } LuaState = GameMod.ModLuaState; if (LuaState == null) { GameLogger.Error(TAG + ":" + Name, "LuaObject {0} load error : Mod can not run : {1}", Name, LuaModName); GameErrorManager.LastError = GameError.ModCanNotRun; return(false); } } LuaFunction classInit = GameMod.RequireLuaClass(LuaClassName); if (classInit == null) { GameLogger.Error(TAG + ":" + Name, "LuaObject {0} load error : class not found : {1}", Name, LuaClassName); GameErrorManager.LastError = GameError.ClassNotFound; return(false); } object o = classInit.call(); if (o != null && o is LuaTable) { self = o as LuaTable; } else { GameLogger.Error(TAG + ":" + Name, "LuaObject {0} load error : table not return ", Name); GameErrorManager.LastError = GameError.NotReturn; return(false); } InitLuaInternalVars(); InitLuaVars(); //初始化引入参数 //调用其他LUA初始化脚本 SendMessage("OnInitLua", gameObject, SendMessageOptions.DontRequireReceiver); InitLuaEvents(); return(true); }
private UILayout BuildLayoutByTemplateInternal(string name, XmlNode templateXml, Dictionary <string, GameHandler> handlers, UILayout parent, UILayout root, string[] initialProps) { //实例化UI预制体 string prefabName = templateXml.Name; GameObject prefab = UIManager.FindRegisterElementPrefab(prefabName); if (prefab == null) { GameLogger.Log(TAG, "BuildLayoutByTemplate failed, not found prefab {0}", prefabName); GameErrorManager.LastError = GameError.PrefabNotFound; return(null); } //获取预制体上的脚本 UILayout ilayout = prefab.GetComponent <UILayout>(); if (ilayout == null) //该方法必须实例化UI容器 { GameLogger.Error(TAG, "BuildLayoutByTemplate with prefab {0} failed, root must be a container", prefabName); GameErrorManager.LastError = GameError.MustBeContainer; return(null); } GameObject newCon = GameCloneUtils.CloneNewObjectWithParent(prefab, parent == null ? UIManager.UIRoot.transform : parent.RectTransform); ilayout = newCon.GetComponent <UILayout>(); ilayout.DoCallStart(); ilayout.LayoutLock(); ilayout.RectTransform = newCon.GetComponent <RectTransform>(); UIAnchorPosUtils.SetUIPivot(ilayout.RectTransform, UIPivot.TopCenter); ilayout.RectTransform.anchoredPosition = Vector2.zero; if (root == null) { root = ilayout; root.IsRootLayout = true; } GameObject newEle = null; UIElement uIElement = null; //子元素 for (int i = 0, c = templateXml.ChildNodes.Count; i < c; i++) { string eleName = ""; //xml 属性读取 XmlNode eleNode = templateXml.ChildNodes[i]; foreach (XmlAttribute a in eleNode.Attributes) { if (a.Name.ToLower() == "name") { eleName = a.Value; } } //预制体 prefab = UIManager.FindRegisterElementPrefab(eleNode.Name); if (prefab == null) { GameLogger.Error(TAG, "BuildLayoutByTemplate failed, not found prefab {0}", prefabName); continue; } if (prefab.GetComponent <UILayout>() != null) //这是UI容器 { UILayout newLayout = BuildLayoutByTemplateInternal(eleName, eleNode, handlers, ilayout, root, initialProps); //递归构建 uIElement = newLayout; uIElement.rootContainer = root; uIElement.Name = eleName; } else { //构建子元素 newEle = GameCloneUtils.CloneNewObjectWithParent(prefab, ilayout.RectTransform, eleName); uIElement = newEle.GetComponent <UIElement>(); uIElement.RectTransform = newEle.GetComponent <RectTransform>(); uIElement.DoCallStart(); uIElement.Init(eleNode); uIElement.rootContainer = root; uIElement.Name = eleName; } //初始化 InitiazeChildElement(uIElement, handlers, initialProps); //添加元素 ilayout.AddElement(uIElement, false); } ilayout.Init(templateXml); //容器的XML读取 InitiazeChildElement(ilayout, handlers, initialProps); ilayout.LayoutUnLock(); ilayout.PostDoLayout(); if (root == ilayout) { ilayout.DoLayout(); } return(ilayout); }
public static void SetLastErrorAndLog(GameError code, string tag, string message) { LastError = code; GameLogger.Error(tag, message); }
/// <summary> /// 设置错误码并打印日志 /// </summary> /// <param name="code">错误码</param> /// <param name="tag">TAG</param> /// <param name="message">错误信息</param> /// <param name="param">日志信息</param> public static void SetLastErrorAndLog(GameError code, string tag, string message, params object[] param) { LastError = code; GameLogger.Error(tag, message, param); }