/// <summary> /// Loads this map from a given object or file path. /// </summary> /// <param name="url">Url of file to open map from. </param> /// <param name="password">If a password is required to open this map, this will be used.</param> /// <param name="baseNode">The base node that all loading should be started from, this allows you to ignore this node and any nodes higher in the graph like the Root Camera.</param> /// <param name="keepPersistent">If set to true persistent ob jects will be kept.</param> /// <param name="keepCameras">If set to true all cameras will not be destroyed.</param> public void Load(object url, string password, SceneNode baseNode, bool keepPersistent, bool keepCameras) { // Keep track of the url. if (url is string) { _url = url as string; } // Try and open a stream to the file. Stream stream = StreamFactory.RequestStream(url, StreamMode.Open); if (stream == null) { return; } BinaryReader reader = new BinaryReader(stream); // Check the header of this file to make sure it really is a Fusion map file. if (reader.ReadChar() != 'F' || reader.ReadChar() != 'M' || reader.ReadChar() != 'P') { throw new Exception("Fusion map file has invalid header, file may be corrupt."); } // Read in the bit mask explaining the header. int headerBitMask = reader.ReadByte(); if ((headerBitMask & 4) != 0) { _mapProperties.Name = reader.ReadString(); } if ((headerBitMask & 8) != 0) { _mapProperties.Author = reader.ReadString(); } if ((headerBitMask & 16) != 0) { _mapProperties.Description = reader.ReadString(); } if ((headerBitMask & 32) != 0) { _mapProperties.Version = reader.ReadSingle(); } // Read in the rest of the file into memory so we can decompress / decrypt it. byte[] fileData = reader.ReadBytes((int)(stream.Length - stream.Position)); // Decrypt the data if required. if ((headerBitMask & 2) != 0) { fileData = DataMethods.Decrypt(fileData, password); } // Decompress the data if required. if ((headerBitMask & 1) != 0) { fileData = DataMethods.Inflate(fileData); } // Create a memory stream and a binary reader so we can minipulate the data better. MemoryStream memStream = new MemoryStream(fileData, 0, fileData.Length); BinaryReader memStreamReader = new BinaryReader(memStream); // Read in the encryption header to make sure everything went correctly. if ((headerBitMask & 2) != 0 || (headerBitMask & 1) != 0) { if (memStreamReader.ReadChar() != 'C' || memStreamReader.ReadChar() != 'H' || memStreamReader.ReadChar() != 'K') { throw new Exception("Unable to open Fusion map file, password is invalid or fils is corrupted."); } } // Read in the tileset pool used to render tilemap segments. int tilesetCount = memStreamReader.ReadByte(); Tileset.TilesetPool.Clear(); for (int i = 0; i < tilesetCount; i++) { if (memStreamReader.ReadBoolean() == true) { string newTilesetUrl = memStreamReader.ReadString(); if (newTilesetUrl.ToString().ToLower().StartsWith("pak@")) { newTilesetUrl = newTilesetUrl.ToString().Substring(4); // Legacy support. } if (Runtime.Resources.ResourceManager.ResourceIsCached(newTilesetUrl)) { Tileset.AddToTilesetPool(Runtime.Resources.ResourceManager.RetrieveResource(newTilesetUrl) as Tileset); } else { Runtime.Debug.DebugLogger.WriteLog("Loading tileset from " + newTilesetUrl); Tileset newTileset = new Tileset(); newTileset.Load(newTilesetUrl); Tileset.AddToTilesetPool(newTileset); Runtime.Resources.ResourceManager.CacheResource(newTilesetUrl, newTileset); } } } // Tell the scene graph to load itself from this memory stream. _sceneGraph.Load(memStreamReader, keepPersistent, keepCameras, baseNode); // Free up the memory stream and reader. memStream.Close(); memStream = null; // Free up the reader and stream. stream.Close(); stream = null; // Reclaim memory used during loading. GC.Collect(); }
/// <summary> /// Called by the base engine class when its safe to begin initialization. /// </summary> protected override bool Begin() { // We alwasy want to run with the editor state! ScriptExecutionProcess.DefaultToEditorState = true; // Bind all function sets to the global virtual machine. NativeFunctionSet.RegisterCommandSetsToVirtualMachine(VirtualMachine.GlobalInstance); // Set the output file. DebugLogger.OutputFile = _logPath + "\\Editor " + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + " " + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + ".log"; // Ahhhh, no game given!! if (_gameName == "") { MessageBox.Show("No game was specified. Please pass a command line of -game:<ident> when running this application.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); return(true); } // Make sure this game has not already been compiled. if (_gameConfigFile["resources:usepakfiles", "0"] == "1") { DebugLogger.WriteLog("Unable to edit game, game's media has already been compiled into pak files.", LogAlertLevel.FatalError); } _fpsLimit = int.Parse(_engineConfigFile["graphics:fpslimit", _fpsLimit.ToString()]); // Disable all resource caching. //ResourceManager.ResourceCacheEnabled = false; // Create the editor's window. _window = new EditorWindow(); _window.FormClosing += new FormClosingEventHandler(OnClosing); _window.Show(); AudioManager.Driver.AttachToControl(_window); InputManager.Driver.AttachToControl(_window); // Load in the default tileset if it exists and add it to the tileset list. if (ResourceManager.ResourceExists(_tilesetPath + "\\default.xml") == true) { DebugLogger.WriteLog("Found default tileset, loading..."); Tileset.AddToTilesetPool(new Tileset(_tilesetPath + "\\default.xml")); } // Load in the default font if it exists. if (ResourceManager.ResourceExists(_fontPath + "\\default.xml") == true) { DebugLogger.WriteLog("Found default bitmap font, loading..."); GraphicsManager.DefaultBitmapFont = new BitmapFont(_fontPath + "\\default.xml"); } // Load in the required language pack. string languageFile = _languagePath + "\\" + _language + ".xml"; if (ResourceManager.ResourceExists(languageFile) == true) { DebugLogger.WriteLog("Loading language pack for language " + _language + "."); LanguageManager.LoadLanguagePack(_languagePath + "\\" + _language + ".xml", _language); } else { DebugLogger.WriteLog("Unable to find language pack for language " + _language + ".", LogAlertLevel.FatalError); } // Setup a camera that we can view the scene from. _camera = new CameraNode("Root Camera"); _map.SceneGraph.AttachCamera(_camera); _camera.BackgroundImage = new Image(ReflectionMethods.GetEmbeddedResourceStream("grid.png"), 0); _camera.ClearColor = unchecked ((int)0xFFACACAC); // Show the tip-of-the-day window. if (_engineConfigFile["editor:showtipsonstartup", "1"] == "1") { (new TipOfTheDayWindow()).ShowDialog(); } // Disable collision processing. CollisionManager.Enabled = false; return(false); }
/// <summary> /// Called by the base engine class when its safe to begin initialization. /// </summary> protected override bool Begin() { Runtime.Debug.DebugLogger.WriteLog("Entered begin function", LogAlertLevel.Warning); // Create the fusion fuction set. new FusionFunctionSet(); new NetworkFunctionSet(); // Bind all function sets to the global virtual machine. NativeFunctionSet.RegisterCommandSetsToVirtualMachine(VirtualMachine.GlobalInstance); // Grab some config out of the games config file. ASCIIEncoding encoding = new ASCIIEncoding(); _currentPassword = _engineConfigFile["account:password", ""]; _currentUsername = _engineConfigFile["account:username", ""]; // Make sure we have a game we can run. if (_gameName != "") { // Create the loading window thread. _loading = true; new Thread(LoadingWindowThread).Start(); NetworkManager.IsServer = _isServer; if (_isServer == false) { // Setup graphics window. SetupGameWindow(); } else { // Setup graphics window. We are only actually doing this so the graphics and audio drivers have something to bind to. // Notice that we are hiding it as soon as its made. SetupGameWindow(); _window.Hide(); // Setup server window. _serverWindow = new ServerWindow(); _serverWindow.FormClosing += new FormClosingEventHandler(OnClosing); _serverWindow.Show(); // Setup server. if (NetworkManager.Start() == false) { throw new Exception("An error occured while attempting to setup network."); } } // Create some hooks into network events. NetworkManager.ClientConnected += new ClientConnectedEventHandler(ClientConnected); NetworkManager.ClientDisconnected += new ClientDisconnectedEventHandler(ClientDisconnected); NetworkManager.Disconnected += new DisconnectedEventHandler(Disconnected); NetworkManager.PacketRecieved += new PacketRecievedEventHandler(PacketRecieved); // If pak files are being used then load all of them in and register // them with the resource manager if (_usePakFiles == true) { ResourceManager.UsePakFiles = true; DebugLogger.WriteLog("Looking for resources in pak files..."); foreach (string file in Directory.GetFiles(Environment.CurrentDirectory)) { if (file.ToLower().EndsWith(".pk") == true) { DebugLogger.WriteLog("Looking for resources in \"" + Path.GetFileName(file) + "\"..."); PakFile pakFile = new PakFile(file); ResourceManager.RegisterPakFile(pakFile); } } } // Load in the default tileset if it exists and add it to the tileset list. if (ResourceManager.ResourceExists(_tilesetPath + "\\default.xml") == true) { DebugLogger.WriteLog("Found default tileset, loading..."); Tileset.AddToTilesetPool(new Tileset(_tilesetPath + "\\default.xml")); } // Load in the default font if it exists. if (ResourceManager.ResourceExists(_fontPath + "\\default.xml") == true) { DebugLogger.WriteLog("Found default bitmap font, loading..."); GraphicsManager.DefaultBitmapFont = new BitmapFont(_fontPath + "\\default.xml"); } // Load in the required language pack. string languageFile = _languagePath + "\\" + _language + ".xml"; if (ResourceManager.ResourceExists(languageFile) == true) { DebugLogger.WriteLog("Loading language pack for language " + _language + "."); LanguageManager.LoadLanguagePack(_languagePath + "\\" + _language + ".xml", _language); } else { DebugLogger.WriteLog("Unable to find language pack for language " + _language + ".", LogAlertLevel.Error); } // Register the console commands, incase we turn the console on later. new StatisticalConsoleCommands(); new FusionConsoleCommands(); new MapConsoleCommands(); new SystemConsoleCommands(); // Register all the command sets with the console. ConsoleCommandSet.RegisterCommandSets(); // Shall we setup the graphical console? if (_showConsole == true && _isServer == false) { // Enable the graphical console. GraphicalConsole.Enabled = true; } // Check if the start script exists. if (ResourceManager.ResourceExists(_startScript) == true) { // It does, w00t, lets create an execution process for it then. _gameScriptProcess = new ScriptExecutionProcess(_startScript); if (_gameScriptProcess.Process != null) { _gameScriptProcess.Priority = 1000000; // Always runs first, otherwise all hell breaks loose with the OnCreate events. _gameScriptProcess.IsPersistent = true; _gameScriptProcess.Process.OnStateChange += this.OnStateChange; ProcessManager.AttachProcess(_gameScriptProcess); OnStateChange(_gameScriptProcess.Process, _gameScriptProcess.Process.State); } } // Pump out a GameBegin event. EventManager.FireEvent(new Event("game_begin", this, null)); // Close the loading window. _loading = false; // Show the game window. if (_isServer == false) { _window.Show(); _window.BringToFront(); _window.Activate(); } else { _serverWindow.Show(); _serverWindow.BringToFront(); _serverWindow.Activate(); } } // Nope? Ok show the games explorer. else { _explorerWindow = new GamesExplorerWindow(); _explorerWindow.FormClosing += new FormClosingEventHandler(OnClosing); _explorerWindow.Show(); } return(false); }