1 module PixelPerfectEngine.map.mapdata; 2 /* 3 * Copyright (C) 2015-2017, by Laszlo Szeremi under the Boost license. 4 * 5 * Pixel Perfect Engine, map module 6 */ 7 import std.stdio; 8 import std.file; 9 import std.conv; 10 import std.base64; 11 import PixelPerfectEngine.graphics.bitmap; 12 import PixelPerfectEngine.graphics.layers; 13 import PixelPerfectEngine.system.exc; 14 import PixelPerfectEngine.system.etc; 15 import core.stdc.stdlib; 16 import core.stdc.stdio; 17 import std..string; 18 19 version(Windows){ 20 import core.sys.windows.windows; 21 import std.windows.syserror; 22 }else{ 23 import core.stdc.errno; 24 } 25 26 public import PixelPerfectEngine.system.exc; 27 /** 28 * Contains the very basic data for the map binary file (*.mbf). 29 */ 30 public struct MapDataHeader{ 31 public uint flags; ///Currently unused 32 //public uint fileLength; /// fileLength = sizeX * sizeY + MapDataHeader.sizeof; 33 public int sizeX; ///width of the map 34 public int sizeY; ///Height of the map 35 this(int sizeX, int sizeY){ 36 //this.fileLength = cast(uint)(sizeX * sizeY + MapDataHeader.sizeof); 37 this.sizeX = sizeX; 38 this.sizeY = sizeY; 39 } 40 } 41 42 /** 43 * Saves a map to an external file. 44 */ 45 public void saveMapFile(MapDataHeader* header, ref MappingElement[] map, string name){ 46 FILE* outputStream = fopen(toStringz(name), "wb"); 47 if(outputStream is null){ 48 import std.conv; 49 version(Windows){ 50 DWORD errorCode = GetLastError(); 51 }else version(Posix){ 52 int errorCode = errno; 53 } 54 throw new FileAccessException("File access error! Error number: " ~ to!string(errorCode)); 55 } 56 57 fwrite(cast(void*)header, MapDataHeader.sizeof, 1, outputStream); 58 fwrite(cast(void*)map.ptr, MappingElement.sizeof, map.length, outputStream); 59 60 fclose(outputStream); 61 } 62 ///Ditto, but safer. 63 public void saveMapFile(F = File)(MapDataHeader header, MappingElement[] map, F file) @trusted { 64 ubyte[] writeBuf = toStream(header); 65 file.rawWrite(writeBuf); 66 file.rawWrite(map); 67 } 68 /** 69 * Loads a map from an external file. 70 */ 71 public MappingElement[] loadMapFile(F = File)(F file, ref MapDataHeader header){ 72 ubyte[] readbuffer; 73 MappingElement[] result; 74 readbuffer.length = MapDataHeader.sizeof; 75 readbuffer = file.rawRead(readbuffer); 76 header = reinterpretGet!MapDataHeader(readbuffer); 77 result.length = header.sizeX * header.sizeY; 78 result = file.rawRead(result); 79 return result; 80 } 81 82 /** 83 * Loads a map from a BASE64 string. 84 */ 85 public MappingElement[] loadMapFromBase64(in char[] input, int length){ 86 MappingElement[] result; 87 result.length = length; 88 Base64.decode(input, cast(ubyte[])cast(void[])result); 89 return result; 90 } 91 92 /** 93 * Saves a map to a BASE64 string. 94 */ 95 public char[] saveMapToBase64(in MappingElement[] input){ 96 char[] result; 97 Base64.encode(cast(ubyte[])cast(void[])input, result); 98 return result; 99 }