| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
package uk.me.parabola.imgfmt.mdxfmt; |
| 15 |
|
| 16 |
import java.io.FileOutputStream; |
| 17 |
import java.io.IOException; |
| 18 |
import java.io.UnsupportedEncodingException; |
| 19 |
import java.nio.ByteBuffer; |
| 20 |
import java.nio.ByteOrder; |
| 21 |
import java.nio.channels.FileChannel; |
| 22 |
import java.nio.channels.WritableByteChannel; |
| 23 |
import java.nio.charset.StandardCharsets; |
| 24 |
import java.util.ArrayList; |
| 25 |
import java.util.List; |
| 26 |
|
| 27 |
import uk.me.parabola.log.Logger; |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
public class MdxFile { |
| 38 |
private final char familyId; |
| 39 |
private final char productId; |
| 40 |
|
| 41 |
private final List<MapInfo> maps = new ArrayList<>(); |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
public MdxFile(int familyId, int productId) { |
| 51 |
this.familyId = (char) familyId; |
| 52 |
this.productId = (char) productId; |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
public void addMap(int name, int hexname, String filename) { |
| 64 |
MapInfo info = new MapInfo(); |
| 65 |
info.setHexMapname(hexname); |
| 66 |
info.setMapname(name); |
| 67 |
info.setFamilyId(familyId); |
| 68 |
info.setProductId(productId); |
| 69 |
info.setFilename(filename); |
| 70 |
|
| 71 |
maps.add(info); |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
public void write(String filename) throws IOException { |
| 78 |
try (FileOutputStream stream = new FileOutputStream(filename); FileChannel chan = stream.getChannel();) { |
| 79 |
ByteBuffer buf = ByteBuffer.allocate(1024); |
| 80 |
buf.order(ByteOrder.LITTLE_ENDIAN); |
| 81 |
|
| 82 |
writeHeader(chan, buf); |
| 83 |
writeBody(chan, buf); |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
private void writeHeader(WritableByteChannel chan, ByteBuffer buf) throws IOException { |
| 88 |
buf.put("Midx".getBytes(StandardCharsets.US_ASCII)); |
| 89 |
buf.putChar((char) 100); |
| 90 |
buf.putInt(12); |
| 91 |
buf.putInt(maps.size()); |
| 92 |
|
| 93 |
buf.flip(); |
| 94 |
chan.write(buf); |
| 95 |
} |
| 96 |
|
| 97 |
private void writeBody(WritableByteChannel chan, ByteBuffer buf) throws IOException { |
| 98 |
|
| 99 |
maps.sort((o1, o2) -> Integer.compare(o1.getHexMapname(), o2.getHexMapname())); |
| 100 |
|
| 101 |
for (MapInfo info : maps) { |
| 102 |
|
| 103 |
|
| 104 |
if (info.getHexMapname() == 0 || info.getMapname() == 0) |
| 105 |
Logger.defaultLogger.error("Invalid mapname for " + info.getFilename() + ", perhaps it is not a .img file"); |
| 106 |
|
| 107 |
buf.compact(); |
| 108 |
info.write(buf); |
| 109 |
|
| 110 |
buf.flip(); |
| 111 |
chan.write(buf); |
| 112 |
} |
| 113 |
} |
| 114 |
} |