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 core.stdc.stdlib; 15 import core.stdc.stdio; 16 import std..string; 17 18 version(Windows){ 19 import core.sys.windows.windows; 20 import std.windows.syserror; 21 }else{ 22 import core.stdc.errno; 23 } 24 25 public import PixelPerfectEngine.system.exc; 26 /** 27 * Contains the very basic data for the map binary file (*.mbf). 28 */ 29 public struct MapDataHeader{ 30 public uint flags; 31 public uint fileLength; /// fileLength = sizeX * sizeY + MapDataHeader.sizeof; 32 public int sizeX; 33 public int sizeY; 34 this(int sizeX, int sizeY){ 35 this.fileLength = sizeX * sizeY + MapDataHeader.sizeof; 36 this.sizeX = sizeX; 37 this.sizeY = sizeY; 38 } 39 } 40 41 /** 42 * Saves a map to an external file. 43 */ 44 public void saveMapFile(MapDataHeader* header, ref MappingElement[] map, string name){ 45 FILE* outputStream = fopen(toStringz(name), "wb"); 46 if(outputStream is null){ 47 import std.conv; 48 version(Windows){ 49 DWORD errorCode = GetLastError(); 50 }else version(Posix){ 51 int errorCode = errno; 52 } 53 throw new FileAccessException("File access error! Error number: " ~ to!string(errorCode)); 54 } 55 56 fwrite(cast(void*)header, MapDataHeader.sizeof, 1, outputStream); 57 fwrite(cast(void*)map.ptr, MappingElement.sizeof, map.length, outputStream); 58 59 fclose(outputStream); 60 } 61 62 /** 63 * Loads a map from an external file. Header must be preallocated. 64 */ 65 public MappingElement[] loadMapFile(MapDataHeader* header, string name){ 66 FILE* inputStream = fopen(toStringz(name), "rb"); 67 MappingElement[] result; 68 if(inputStream is null){ 69 import std.conv; 70 version(Windows){ 71 DWORD errorCode = GetLastError(); 72 }else version(Posix){ 73 int errorCode = errno; 74 } 75 throw new FileAccessException("File access error! Error number: " ~ to!string(errorCode)); 76 } 77 78 fread(cast(void*)header, MapDataHeader.sizeof, 1, inputStream); 79 result.length = header.sizeX * header.sizeY; 80 fread(cast(void*)result, MappingElement.sizeof, result.length, inputStream); 81 82 fclose(inputStream); 83 return result; 84 } 85 86 /** 87 * Loads a map from a BASE64 string. 88 */ 89 public MappingElement[] loadMapFromBase64(in char[] input, int length){ 90 MappingElement[] result; 91 result.length = length; 92 Base64.decode(input, cast(ubyte[])cast(void[])result); 93 return result; 94 } 95 96 /** 97 * Saves a map to a BASE64 string. 98 */ 99 public char[] saveMapToBase64(in MappingElement[] input){ 100 char[] result; 101 Base64.encode(cast(ubyte[])cast(void[])input, result); 102 return result; 103 }