/// <summary> /// Initializes a new instance of the <see cref="Resources"/> class. /// </summary> internal static void Initialize() { Resources.Logger = LogManager.GetCurrentClassLogger(typeof(Resources)); Factory.Initialize(); CSV.Initialize(); LevelFile.Initialize(); Fingerprint.Initialize(); Globals.Initialize(); if (Constants.Database == DBMS.Mongo) { Mongo.Initialize(); } Resources.Redis = new Redis(); Resources.Regex = new Regex("[ ]{2,}", RegexOptions.Compiled); Resources.Players = new Players(); Resources.Clans = new Clans(); Resources.Chats = new Chats(); Resources.Battles = new Battles(); Resources.Random = new XorShift(); Resources.TCPGateway = new TCPServer(); Resources.UDPGateway = new UDPServer(); Resources.Started = true; Parser.Initialize(); EventsHandler.Initialize(); }
public LevelFile LoadFromFile() { LevelFile saveFile = null; if (gc.isAndroid) { int index = StringToInt(level_dict, levelName); saveFile = levelFiles[index]; return(saveFile); } string targetName = SaveLocation(); targetName += levelName; if (!File.Exists(targetName)) { Debug.Log(levelName + "Not found"); } else { IFormatter formatter = new BinaryFormatter(); FileStream stream = new FileStream(targetName, FileMode.Open); LevelFile save = (LevelFile)formatter.Deserialize(stream); saveFile = save; stream.Close(); } return(saveFile); }
private void SelectLevel(int index) { if (index == -1) { selectedLevel = null; } else { if (mode == Mode.Custom) { selectedLevel = custom[index]; } else if (mode == Mode.Official) { selectedLevel = official[index]; } } if (selectedLevel != null) { levelTitleText.text = selectedLevel.name; launchButton.gameObject.SetActive(true); } else { levelTitleText.text = string.Empty; launchButton.gameObject.SetActive(false); } }
private void SelectAndLoadFile(object p_sender, System.Action <byte[][]> p_onLoadedCallback, bool p_isReload) { if (p_isReload) { if (!string.IsNullOrEmpty(m_reloadLevelName)) { LoadFile(p_sender, m_reloadLevelName, p_onLoadedCallback); } else { Debug.LogError("FileSelectionExtensionLoader: SelectAndLoadFile: no level was loaded yet, but 'p_isReload' was 'true'!"); } return; } // load file with the level file names ((MonoBehaviour)p_sender).StartCoroutine(LevelDB.GetLevelListAsync((LevelFile[] p_levelFiles) => { if (uMyGUI_PopupManager.Instance != null) { // show file selection UI string[] levelNames = LevelFile.GetLevelNames(p_levelFiles); string[] levelIconPaths = LevelFile.GetLevelIconPaths(p_levelFiles); ((LE_PopupFileSelection)uMyGUI_PopupManager.Instance.ShowPopup(LE_FileSelectionHelpers.POPUP_NAME)) .SetFiles(levelNames, levelIconPaths, (int p_selectedLevelIndex) => { LoadFile(p_sender, p_levelFiles[p_selectedLevelIndex].PathData, p_onLoadedCallback); }, null) .SetText("Load Level", "Which level do you want to load?") .ShowButton("close"); } })); }
private IEnumerator LaunchGame(LevelFile level) { currentLevel = level; splash.SetActive(true); var async = SceneManager.LoadSceneAsync("Game", LoadSceneMode.Single); while (!async.isDone) { loadingBar.Progress = async.progress * 0.7f; yield return(null); } Destroy(FindObjectOfType <LevelEditorManager>()); GameManager gameManager = FindObjectOfType <GameManager>(); gameManager.LoadGame(level, towerFactory, unitFactory, delegate(float progress) { loadingBar.Progress = 0.7f + progress * 0.3f; }); while (loadingBar.Progress < 0.95f) { yield return(null); } loadingBar.Progress = 1.0f; splash.SetActive(false); }
public LevelTerrain(string name, LevelFile levelRes, AtlasMaterial material) : base() { Name = name; this.levelRes = levelRes; TintColor = new Vector4(1, 1, 1, 0); this.material = material; if (!material.Ready) { return; } if (setupGeometry()) { Log.WriteLine("HiOctane Terrain '" + name + "' loaded " + positionVboData.Length + " vertices, " + normalVboData.Length + " normals, " + uvVboData.Length + " UVs, " + indicesVboData.Length + " indices"); createVBOs(); createVAOs(); ready = true; } else { Log.WriteLine(Log.LOG_ERROR, "failed setting up game model '" + Name + "'"); } }
private void OnSaveLevel(LevelFile level) { level = level.Clone(); byte[] bytes = ByteSerializer.Serialize(level); string path = level.isOfficial ? officialLevelsDir_FullPath : customLevelsDir; path = Path.Combine(path, level.fileName) + (level.isOfficial ? ".txt" : ".lvl"); File.WriteAllBytes(path, bytes); if (level.isOfficial) { RegisterLevel(officialLevels, level); } else { RegisterLevel(customLevels, level); } EventManager.Raise(new LevelSavedEvent(level)); #if UNITY_EDITOR UnityEditor.AssetDatabase.Refresh(); #endif }
private IEnumerator LaunchEditor(LevelFile level) { currentLevel = level; splash.SetActive(true); var async = SceneManager.LoadSceneAsync("Game", LoadSceneMode.Single); while (!async.isDone) { loadingBar.Progress = async.progress * 0.7f; yield return(null); } Destroy(FindObjectOfType <GameManager>()); LevelEditorManager levelEditorManager = FindObjectOfType <LevelEditorManager>(); levelEditorManager.SetEditorFunctions(OnSaveLevel, OnDeleteLevel); #if UNITY_EDITOR levelEditorManager.LoadEditor(level, officialLevels, customLevels, delegate(float progress) { loadingBar.Progress = 0.7f + progress * 0.3f; }); #else levelEditorManager.LoadEditor(level, new List <LevelFile>(), customLevels, delegate(float progress) { loadingBar.Progress = 0.7f + progress * 0.3f; }); #endif while (loadingBar.Progress < 0.95f) { yield return(null); } loadingBar.Progress = 1.0f; splash.SetActive(false); }
public Column(ColumnDefinition def, Vector3 pos, LevelFile levelRes, AtlasMaterial material) : base() { Name = "Column at " + pos.X + "/" + pos.Z; this.levelRes = levelRes; Definition = def; Position = pos; TintColor = new Vector4(1.0f, 0.0f, 0.0f, 0.0f); // alpha is intensity this.material = material; if (!material.Ready) { return; } if (setupGeometry()) { Log.WriteLine("HiOctane '" + Name + "' loaded " + positionVboData.Length + " vertices, " + normalVboData.Length + " normals, " + uvVboData.Length + " UVs, " + indicesVboData.Length + " indices"); createVBOs(); createVAOs(); ready = true; } else { Log.WriteLine(Log.LOG_ERROR, "failed setting up game model '" + Name + "'"); } }
///////////////////////// API ///////////////////////// public void Initialise(LevelFile _file = null) { if (_file != null) { DimensionX = (uint)_file.DimensionX; DimensionY = (uint)_file.DimensionY; } else { // Random dimensions within range DimensionX = 7; DimensionY = DimensionX; } ClearGrid(); IsSolved = false; if (_file != null) { LoadInputs(_file.Inputs); LoadOutputs(_file.Outputs, _file.NumStartingOutputs); } else { GenerateInputs(); GenerateOutputs(); } }
public void Inject(LevelFile level) { this.level = level; levelNameField.text = level.name; currencyField.text = level.startingCurrency.ToString(); healthField.text = level.startingHealth.ToString(); }
public void LoadEditor(LevelFile level, List <LevelFile> official, List <LevelFile> custom, Action <float> onProgress) { this.level = level; officialLevels = official; customLevels = custom; loadProgress = onProgress; SetState(State.LoadEditor); }
public void LoadGame(LevelFile level, TowerFactory towerFactory, UnitFactory unitFactory, Action <float> onProgress) { this.level = level; this.towerFactory = towerFactory; this.unitFactory = unitFactory; loadProgress = onProgress; SetState(State.Loading); }
private void MenuItemFileOpen_Click(object sender, EventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Title = "Open File"; open.Filter = "Map File (*.map)|*.map|Level file (*.lvl)|*.lvl"; if (!String.IsNullOrEmpty(mainController.CurrentWorkingDirectory)) { open.InitialDirectory = mainController.CurrentWorkingDirectory; } if (open.ShowDialog() == DialogResult.OK) { if (open.InitialDirectory != mainController.CurrentWorkingDirectory) { mainController.CurrentWorkingDirectory = Directory.GetCurrentDirectory(); } var level = new LevelFile(); Stream input; if ((input = open.OpenFile()) != null) { level.Deserialize(input); FileName = open.SafeFileName; input.Close(); //Strip duplicated blobs for (int i = 0; i < level.Floors.Count; i++) { var floor = level.Floors[i]; if (floor.FileName != null && floor.FileName.EndsWith(".lvb.blo") == true) { floor.FileName = null; level.Floors[i] = floor; } } for (int i = 0; i < level.Objects.Count; i++) { var obj = level.Objects[i]; if (obj.FileName != null && obj.FileName.EndsWith(".lvb.blo") == true) { obj.FileName = null; level.Objects[i] = obj; } } } mainController.LoadLevel(level); } open.Dispose(); }
LevelFile IsDuplicate(LevelFile s) { for (int i = 0; i < levelFiles.Count; i++) { if (string.Equals(levelFiles[i].levelName, s.levelName)) { return(levelFiles[i]); } } return(null); }
private void RegisterLevel(List <LevelFile> levels, LevelFile level) { int idx = levels.FindIndex(obj => obj.Equals(level)); if (idx == -1) { levels.Add(level); } else { levels[idx] = level; } }
/// <summary> /// Use to be able to pull all level data from a level and store that data in a /// JSON format. /// </summary> /// <param name="levelInformation"></param> public void CreateLevelFile(LevelInformation levelInformation) { GameObject singular = GameObject.CreatePrimitive(PrimitiveType.Cube); singular.transform.position = new Vector3(100000, 100000, 100000); singular.name = "SceneLooker"; GameObject[] objects = singular.scene.GetRootGameObjects(); foreach (GameObject o in objects) { if (o.name == "Level") { GameObject levelData = o.transform.Find("LevelData").gameObject; CreateLevelData(levelData); } if (o.CompareTag("Enemy")) { CreateEnemyData(o); } if (o.CompareTag("InteractableObject")) { CreateInteractableObjects(o); } if (o.CompareTag("MissionTrigger")) { CreateMissionTriggers(o); } if (o.CompareTag("Player")) { playerPosition = new ObjectPosition(o.transform.position); } } ObjectData objectData = new ObjectData(_walls.ToArray(), _enemies.ToArray(), _interactableObjects.ToArray(), _missionTriggers.ToArray(), playerPosition); var oj = JsonConvert.SerializeObject(objectData); SceneData sceneData = new SceneData(objectData); LevelFile levelFileStruct = new LevelFile(levelInformation, sceneData); var json = JsonConvert.SerializeObject(levelFileStruct); WriteLevelDataToFile(json, levelInformation.title.ToLower()); DestroyImmediate(singular); }
void SaveToFile() { LevelFile save = new LevelFile(); save.levelName = levelName; save.levelTexture = gc.GetTextureInstance().EncodeToPNG(); save.spawnPosition = new SaveVector(); save.spawnPosition.x = spawnPoint.transform.position.x; save.spawnPosition.y = spawnPoint.transform.position.y; save.exitPosition = new SaveVector(); save.exitPosition.x = exitPoint.transform.position.x; save.exitPosition.y = exitPoint.transform.position.y; /*save.enemySpawnPosition = new SaveVector(); * save.enemySpawnPosition.x = enemySpawnPoint.transform.position.x; * save.enemySpawnPosition.y = enemySpawnPoint.transform.position.y;*/ if (gc.isAndroid) { int targetIndex = levelFiles.Count; LevelFile d = IsDuplicate(save); if (d != null) { targetIndex = StringToInt(level_dict, save.levelName); levelFiles[targetIndex] = save; } else { levelFiles.Add(save); level_dict.Add(save.levelName, targetIndex); } return; } string saveLocation = SaveLocation(); saveLocation += levelName; IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(saveLocation, FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(stream, save); stream.Close(); }
private IEnumerator LoadCustomLevels() { customLevels = new List <LevelFile>(); DirectoryInfo dir = new DirectoryInfo(customLevelsDir); FileInfo[] files = dir.GetFiles("*.lvl"); foreach (var file in files) { LevelFile level = ByteSerializer.Deserialize <LevelFile>(File.ReadAllBytes(file.FullName)); level.fileName = Path.GetFileNameWithoutExtension(file.FullName); level.isOfficial = false; customLevels.Add(level); } yield return(null); }
private IEnumerator LoadOfficialLevels() { officialLevels = new List <LevelFile>(); // TODO: Heavy, think of something else. var levelAssets = Resources.LoadAll <TextAsset>(officialLevelsDir); foreach (var levelAsset in levelAssets) { LevelFile level = ByteSerializer.Deserialize <LevelFile>(levelAsset.bytes); level.fileName = levelAsset.name; level.isOfficial = true; officialLevels.Add(level); } yield return(null); }
private void SelectAndSaveFile(object p_sender, byte[] p_levelData, byte[] p_levelMeta, int p_removedDuplicatesCount) { // load file with the level file names ((MonoBehaviour)p_sender).StartCoroutine(LevelDB.GetLevelListAsync((LevelFile[] p_levelFiles) => { if (uMyGUI_PopupManager.Instance != null) { // show file selection UI with an enter file name field string[] levelNames = LevelFile.GetLevelNames(p_levelFiles); string[] levelIconPaths = LevelFile.GetLevelIconPaths(p_levelFiles); LE_PopupFileSelection filePopup = ((LE_PopupFileSelection)uMyGUI_PopupManager.Instance.ShowPopup(LE_FileSelectionHelpers.POPUP_NAME)); filePopup.SetFiles(levelNames, levelIconPaths, // on level selected -> enter level name in the input field (int p_selectedLevelIndex) => { filePopup.SaveInput.text = levelNames[p_selectedLevelIndex]; }, // on delete button -> delete file, then refresh level list (int p_deletedLevelIndex) => { filePopup.Hide(); ((MonoBehaviour)p_sender).StartCoroutine(LevelDB.Delete(p_levelFiles[p_deletedLevelIndex], (bool p_isDeleted) => SelectAndSaveFile(p_sender, p_levelData, p_levelMeta, p_removedDuplicatesCount))); }, false) .SetText("Save Level", "Enter level name or select an existing level.") .ShowButton("close") .ShowButton("save", () => { if (!string.IsNullOrEmpty(filePopup.SaveInput.text)) { LevelDB.SaveFile(filePopup.SaveInput.text, p_levelData, p_levelMeta, p_removedDuplicatesCount, p_levelFiles, // update reload level name on success (string p_savedFilePath) => m_reloadLevelName = p_savedFilePath, // show file selection popup on failure () => SelectAndSaveFile(p_sender, p_levelData, p_levelMeta, p_removedDuplicatesCount)); } else { ((uMyGUI_PopupText)uMyGUI_PopupManager.Instance.ShowPopup(LE_FileSelectionHelpers.POPUP_TEXT)).SetText("Save Level", "The level name cannot be empty!").ShowButton("ok", () => { SelectAndSaveFile(p_sender, p_levelData, p_levelMeta, p_removedDuplicatesCount); }); } }); } })); }
void DefaultLevel() { LevelFile defaultLvl = new LevelFile(); defaultLvl.levelName = "default"; defaultLvl.levelTexture = defaultLevel.EncodeToPNG(); defaultLvl.spawnPosition = new SaveVector(); defaultLvl.spawnPosition.x = 1; defaultLvl.spawnPosition.y = 1; defaultLvl.exitPosition = new SaveVector(); defaultLvl.exitPosition.x = 9.465f; defaultLvl.exitPosition.y = 0.571f; levelFiles.Add(defaultLvl); /*defaultLvl.enemySpawnPosition = new SaveVector(); * defaultLvl.enemySpawnPosition.x = 4.35f; * defaultLvl.enemySpawnPosition.y = 1.23f;*/ }
internal static void Initialize() { Resources.Logger = LogManager.GetCurrentClassLogger(typeof(Resources)); Factory.Initialize(); CSV.Initialize(); LevelFile.Initialize(); GameEvents.Initialize(); Globals.Initialize(); Settings.Initialize(); Fingerprint.Initialize(); if (Constants.Database == DBMS.Mongo) { Mongo.Initialize(); } Resources.Regex = new Regex("[ ]{2,}", RegexOptions.Compiled); Resources.Name = new Regex("^[a-zA-Z0-9- ]*$"); Resources.Processor = new Processor(); Resources.Devices = new Devices(); Resources.Accounts = new Accounts(); Resources.Battles = new Battles(); Resources.Clans = new Clans(); Resources.Chats = new Chats(); Resources.Duels = new Duels(); Resources.Random2 = new System.Random(DateTime.UtcNow.ToString().GetHashCode()); Resources.Random = new XorShift(); Resources.Gateway = new Gateway(); Resources.StartTime = DateTime.UtcNow; Resources.Timers = new Timers(); Resources.Started = true; Parser.Initialize(); EventsHandler.Initialize(); Console.WriteLine("We loaded " + Factory.Messages.Count + " messages, " + Factory.Commands.Count + " commands, and " + Factory.Debugs.Count + " debug commands.\n"); #if Debug Resources.Test = new Test(); #endif }
public IEnumerator LoadLevel(LevelFile level, bool addWaypoints = false) { towerSpotParent = new GameObject("TowerSpots").transform; for (int i = 0; i < level.towerSpots.Count; ++i) { Vector2 position = level.towerSpots[i].position; Vector2 scale = level.towerSpots[i].scale; scale *= towerSpotPrefab.CellSize; Transform towerSpot = Instantiate(towerSpotPrefab, towerSpotParent).transform; Vector3 localPosition = towerSpot.localPosition; Vector3 localScale = towerSpot.localScale; localPosition = new Vector3(position.x, localPosition.y, position.y); localScale = new Vector3(scale.x, localScale.y, scale.y); towerSpot.localPosition = localPosition; towerSpot.localScale = localScale; yield return(null); } pathsParent = new GameObject("Paths").transform; for (int i = 0; i < level.paths.Count; ++i) { LineRenderer pathRenderer = Instantiate(pathRendererPrefab, pathsParent); PathIndicator pathIndicator = Instantiate(pathIndicatorPrefab, pathRenderer.transform); pathRenderer.name = i.ToString(); Vector3[] waypoints = level.paths[i].Waypoints3D; if (addWaypoints) { yield return(StartCoroutine(AddWaypoints(pathRenderer.transform, waypoints))); } pathRenderer.positionCount = waypoints.Length; pathRenderer.SetPositions(waypoints); pathIndicator.SetWaypoints(waypoints); yield return(null); } }
private void OnDeleteLevel(LevelFile level) { string path = level.isOfficial ? officialLevelsDir_FullPath : customLevelsDir; path = Path.Combine(path, level.fileName) + (level.isOfficial ? ".txt" : ".lvl"); File.Delete(path); #if UNITY_EDITOR File.Delete(path + ".meta"); #endif officialLevels.Remove(level); customLevels.Remove(level); EventManager.Raise(new LevelDeletedEvent(level)); #if UNITY_EDITOR UnityEditor.AssetDatabase.Refresh(); #endif }
public static Level ConvertFromFileFormat(LevelFile levelData) { var level = new Level(levelData.Width, levelData.Height); level.Enemies.AddRange(levelData.Enemies.Select(enemy => new Enemy { X = enemy.X, Y = enemy.Y, Type = enemy.Type, Direction = enemy.Direction })); for (int y = 0; y < levelData.CollisionMap.Height; y++) { for (int x = 0; x < levelData.CollisionMap.Width; x++) { level.CollisionMap[x, y] = levelData.CollisionMap.Data[y][x]; } } return(level); }
public void Inject(LevelFile level) { this.level = level; CloneWaves(); if (waveEntries == null) { waveEntries = new List <WaveContainer>(level.waves.Count); wavePrefab.gameObject.SetActive(false); } // TODO: Duplicate code with WavesPanel. Think of a way to populate UI with generic data. for (int i = 0; i < waves.Count; ++i) { NewWave(i); } for (int i = waves.Count; i < waveEntries.Count; ++i) { waveEntries[i].gameObject.SetActive(false); } }
//Loads the level from file and sets spawn + exit positions public void LoadLevel() { LevelFile save = LevelEditor.singleton.LoadFromFile(); levelTexture = new Texture2D(0, 0); levelTexture.LoadImage(save.levelTexture); SaveVector spawn = save.spawnPosition; if (spawn != null) { Vector3 posit = Vector3.zero; posit.x = spawn.x; posit.y = spawn.y; levelEditor.spawnPoint.transform.position = posit; } SaveVector exit = save.exitPosition; if (exit != null) { Vector3 posexit = Vector3.zero; posexit.x = exit.x; posexit.y = exit.y; levelEditor.exitPoint.transform.position = posexit; } /*SaveVector eSpawn = save.enemySpawnPosition; * * if(eSpawn != null) * { * Vector3 posESpawn = Vector3.zero; * posESpawn.x = eSpawn.x; * posESpawn.y = eSpawn.y; * levelEditor.enemySpawnPoint.transform.position = posESpawn; * }*/ }
/// <summary> /// Load in a level from JSON /// </summary> /// <param name="name">JSON file, negate extension</param> /// <param name="isReload">Use if reloading.</param> public void LoadLevel(string name = "Test_Level", bool isReload = false) { if (isReload) { UnloadLevel(); } var levelFile = LoadLevelDataFromFile(name); // load json first _level = JsonConvert.DeserializeObject <LevelFile>(levelFile); // then load actual data GameObject Level = new GameObject("Level"); // Generate level object for walls n stuff // floor GameObject levelFloor = floor; levelFloor.transform.localScale = new Vector3(_level.LevelInformation.sizeX, 1, _level.LevelInformation.sizeY); Instantiate(levelFloor); // player var playerT = _level.sceneData.objectData.playerPosition; var playerR = (new Quaternion(playerT.rotation.x, playerT.rotation.y, playerT.rotation.z, playerT.rotation.w)); var p = Instantiate(player, playerT.position, playerR); p.transform.Rotate(0, 90, 0); // for some reason the player sometimes comes out this way // create all non-enemy objects CreateWalls(_level.sceneData.objectData.walls, Level); CreateInteractableObjects(_level.sceneData.objectData.interactableObjects); CreateMissionTriggers(_level.sceneData.objectData.missionTriggers); // Create navmesh before loading in enemies so they don't crash the game LocalNavMeshBuilder localNavMeshBuilder = gameObject.AddComponent <LocalNavMeshBuilder>(); localNavMeshBuilder.UpdateNavMesh(); // then create enemies CreateEnemies(_level.sceneData.objectData.enemies); }
public LoadLevelEvent(LevelFile level) { this.level = level; }