summary refs log tree commit diff stats
path: root/tools/sprite_dumper/main.cpp
blob: 79e3df0ae28490ead4b25f31524f643b36b81652 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// Inspired a lot by https://github.com/jeffman/MOTHER-3-Funland

#include <fstream>
#include <string_view>
#include <stdexcept>
#include <string>
#include <vector>
#include <iostream>
#include <Magick++.h>

class Rom {
public:

  explicit Rom(std::string_view filename) {
    std::ifstream romfile(filename.data(), std::ios::binary);
    if (!romfile.is_open()) {
      throw std::invalid_argument("Could not find ROM file: " + std::string(filename));
    }

    romfile.seekg(0, romfile.end);
    int length = romfile.tellg();
    romfile.seekg(0, romfile.beg);

    if (length != 0x2000000) {
      throw std::invalid_argument("Incorrect ROM length");
    }

    data_ = std::vector<char>(length, 0);
    romfile.read(data_.data(), length);

    const char header[] = {'M','O','T','H','E','R','3',0,0,0,0,0,'A','3','U','J'};
    std::string headerTest;
    for (int i = 0xA0; i < 0xB0; i++) {
      if (data_.at(i) != header[i-0xA0]) {
        std::cout << i << std::endl;

        throw std::invalid_argument("Invalid ROM header");
      }
    }
  }

  const std::vector<char>& data() const { return data_; }

  int ReadNextByte() {
    int o2r = offset_;
    offset_++;
    return ReadByte(o2r);
  }

  int ReadByte(int addr) const {
    return static_cast<unsigned char>(data_[addr]);
  }

  int ReadNextTwoBytes() {
    int o2r = offset_;
    offset_+=2;
    return ReadTwoBytes(o2r);
  }

  int ReadTwoBytes(int addr) const {
    return static_cast<unsigned char>(data_[addr]) | (data_[addr + 1] << 8);
  }

  int ReadNextFourBytes() {
    int o2r = offset_;
    offset_+=4;
    return ReadFourBytes(o2r);
  }

  int ReadFourBytes(int addr) const {
    return static_cast<unsigned char>(data_[addr]) | (data_[addr + 1] << 8) | (data_[addr + 2] << 16) | (data_[addr + 3] << 24);
  }

  void Seek(int offset) {
    offset_ = offset;
  }

  void SeekAdd(int delta) {
    offset_ += delta;
  }

private:

  std::vector<char> data_;
  int offset_ = 0;
};

class Palette {
public:

  Palette() = default;

  Palette(Rom& m3, const int addr) {
    for (int i=0; i<16; i++) {
      unsigned short ch = m3.ReadTwoBytes(addr + (i << 1));
      int r = (ch & 0x1F);
      int g = ((ch >> 5) & 0x1F);
      int b = ((ch >> 10) & 0x1F);
      colors_.push_back(Magick::ColorRGB((r << 3)/256.0, (g << 3)/256.0, (b << 3)/256.0));
    }
  }

  const std::vector<Magick::Color>& Colors() const { return colors_; }

private:
  std::vector<Magick::Color> colors_;
};

class PaletteSet {
public:
  PaletteSet(Rom& m3) : m3_(m3) {
    for (int i=0; i<16; i++) {
      defaultPals_.emplace_back(m3, GetPointer(0) + (i << 5));
    }
  }

  const Palette& GetPalette(int spriteindex, int palnum = -1) {
    int a = GetPointer(spriteindex);

    if ((spriteindex > 0xFF) && (spriteindex < 0x26C)) {
      specialPals_[spriteindex] = Palette(m3_, a);
      return specialPals_[spriteindex];
    } else {
      if (palnum == -1) {
        palnum = static_cast<unsigned char>(m3_.ReadByte(0x1433D7C + 1 + ((spriteindex + 1) * 12))) & 0xF;
      }

      return defaultPals_.at(palnum);
    }
  }

private:

  int GetPointer(int spriteindex) {
    const int ADDR = 0x1A41548;

    int index = 0;

    if ((spriteindex > 0xFF) && (spriteindex < 0x26C)) {
      // These sprites use the (spriteindex - 0xFF)th entry
      index = spriteindex - 0xff;
    }

    int a = m3_.ReadFourBytes(ADDR + 4 + (index << 2));
    if (a == -1) return -1;
    return ADDR + a;
  }

  Rom& m3_;
  std::vector<Palette> defaultPals_;
  std::map<int, Palette> specialPals_;
};

struct Subsprite {
  int x;
  int y;
  int tile;
  bool flipH;
  bool flipV;
  int objSize;
  int objShape;

  int Width() const { return WIDTHS[objShape][objSize]; }

  int Height() const { return HEIGHTS[objShape][objSize]; }

private:

  static constexpr int WIDTHS[3][4] = { { 8, 16, 32, 64 }, { 16, 32, 32, 64 }, { 8, 8, 16, 32 } };
  static constexpr int HEIGHTS[3][4] = { { 8, 16, 32, 64 }, { 8, 8, 16, 32 }, { 16, 32, 32, 64 } };
};

struct FrameOutput {
  Magick::Image image;
  int width;
  int height;
  int centerX;
  int centerY;
};

struct Sprite {
  std::vector<Subsprite> subsprites;

  FrameOutput render(Rom& m3, const Palette& palette, const int gfxPtr) const {
    FrameOutput output;

    if (subsprites.empty()) return output;

    int minX = subsprites[0].x;
    int minY = subsprites[0].y;
    int maxX = minX + subsprites[0].Width();
    int maxY = minY + subsprites[0].Height();

    for (int j=1; j<subsprites.size(); j++) {
      const Subsprite& o = subsprites[j];

      if (o.x < minX) minX = o.x;
      if (o.y < minY) minY = o.y;
      if ((o.x + o.Width()) > maxX) maxX = o.x + o.Width();
      if ((o.y + o.Height()) > maxY) maxY = o.y + o.Height();
    }

    int width = maxX - minX;
    int height = maxY - minY;
    int centerX = -minX;
    int centerY = -minY;

    output.width = width;
    output.height = height;
    output.centerX = centerX;
    output.centerY = centerY;
    output.image = Magick::Image(Magick::Geometry(width, height), "transparent");
    output.image.modifyImage();

    Magick::Pixels view(output.image);

    for (const Subsprite& o : subsprites) {
      int tilePointer = o.tile << 5;
      for (int y=0; y<o.Height(); y += 8) {
        int actualY = o.flipV ? (o.Height() - y - 8) : y;

        for (int x=0; x<o.Width(); x += 8) {
          int tileData[8][8];

          int tileSrcOffset = gfxPtr + tilePointer;
          for (int ty=0; ty<8; ty++) {
            for (int tx=0; tx<4; tx++) {
              unsigned char ch = m3.ReadByte(tileSrcOffset++);
              tileData[tx*2][ty] = static_cast<unsigned char>(ch & 0xF);
              tileData[tx*2+1][ty] = static_cast<unsigned char>((ch >> 4) & 0xF);
            }
          }

          tilePointer += 0x20;

          int actualX = o.flipH ? (o.Width() - x - 8) : x;

          int destX = o.x + centerX + actualX;
          int destY = o.y + centerY + actualY;

          Magick::PixelPacket* pixels = view.get(destX,destY,8,8);

          for (int ty=0; ty<8; ty++) {
            int actualTy = o.flipV ? (7-ty) : ty;

            for (int tx=0; tx<8; tx++) {
              int actualTx = o.flipH ? (7-tx) : tx;

              if (tileData[actualTx][actualTy] != 0) {
                //auto& c = palette.Colors().at(tileData[actualTx][actualTy]);
                //std::cout << c.redQuantum() << "," << c.greenQuantum() << "," << c.blueQuantum() << std::endl;
                *pixels = palette.Colors().at(tileData[actualTx][actualTy]);
                //std::cout << tileData[actualTx][actualTy] << std::endl;
              }
              pixels++;
            }
          }

          view.sync();
        }
      }
    }

    return output;
  }
};

struct SpriteSheet {
  int spriteindex = 0;
  int gfxPtr;
  std::vector<Sprite> sprites;

  Magick::Image render(Rom& m3, PaletteSet& palettes) const {
    int maxWidth = 0;
    int maxHeight = 0;
    std::vector<FrameOutput> frames;

    const Palette& palette = palettes.GetPalette(spriteindex);
    for (int i=0; i<sprites.size(); i++) {
      FrameOutput f = sprites[i].render(m3, palette, gfxPtr);

      if (f.width > maxWidth) maxWidth = f.width;
      if (f.height > maxHeight) maxHeight = f.height;
      frames.push_back(std::move(f));
    }

    const int FRAMES_PER_ROW = 10;
    int sheetWidth;
    int sheetHeight;

    std::ofstream datafile("out.txt");
    datafile << maxWidth << "," << maxHeight << " cell size" << std::endl;
    datafile << FRAMES_PER_ROW << " frames per row" << std::endl;
    datafile << frames.size() << " frames" << std::endl;
    datafile << std::endl;

    if (frames.size() < FRAMES_PER_ROW) {
      sheetWidth = frames.size() * maxWidth;
      sheetHeight = maxHeight;
    } else {
      sheetWidth = FRAMES_PER_ROW * maxWidth;
      sheetHeight = (frames.size() / FRAMES_PER_ROW + 1) * maxHeight;
    }

    Magick::Image sheet(Magick::Geometry(sheetWidth, sheetHeight), "transparent");
    for (int i=0; i<frames.size(); i++) {
      const FrameOutput& f = frames.at(i);
      sheet.composite(f.image, (i%FRAMES_PER_ROW)*maxWidth, (i/FRAMES_PER_ROW)*maxHeight, Magick::OverCompositeOp);
      datafile << f.width << "," << f.height << "," << f.centerX << "," << f.centerY << std::endl;
    }

    return sheet;
  }
};

class Bank {
public:

  Bank(Rom& m3, const int baseAddr, const int gfxAddr) : baseAddr_(baseAddr), gfxAddr_(gfxAddr) {
    int numEntries = m3.ReadFourBytes(baseAddr);
    std::cout << numEntries << std::endl;

    for (int i = 0; i < numEntries; i++) {
      int sheetAddr = GetPointerToSheet(m3, i);
      if (sheetAddr == -1) continue;

      SpriteSheet ss;
      ss.spriteindex = i;
      ss.gfxPtr = GetGfxPointer(m3, i);

      m3.Seek(sheetAddr);
      m3.SeekAdd(8);

      unsigned short spriteCount = m3.ReadNextTwoBytes();
      for (int j=0; j<spriteCount; j++) {
        Sprite sprite;

        unsigned short subspriteCount = m3.ReadNextTwoBytes();
        for (int k=0; k<subspriteCount; k++) {
          Subsprite subsprite;
          subsprite.y = static_cast<char>(m3.ReadNextByte());
          subsprite.x = static_cast<char>(m3.ReadNextByte());

          unsigned short ch = m3.ReadNextTwoBytes();
          subsprite.tile = static_cast<unsigned short>(ch & 0x3FF);
          subsprite.flipH = (ch & 0x400) != 0;
          subsprite.flipV = (ch & 0x800) != 0;
          subsprite.objSize = static_cast<unsigned char>((ch >> 12) & 3);
          subsprite.objShape = static_cast<unsigned char>((ch >> 14) & 3);

          std::cout << subsprite.y << std::endl;
          std::cout << subsprite.x << std::endl;
          std::cout << subsprite.flipH << "," << subsprite.flipV << std::endl;

          sprite.subsprites.push_back(std::move(subsprite));
        }

        m3.SeekAdd(2);

        ss.sprites.push_back(std::move(sprite));
      }

      spritesheets_[i] = std::move(ss);
      if (i == 2) return;
    }
  }

  const std::map<int, SpriteSheet>& SpriteSheets() const { return spritesheets_; }

private:

  int GetPointerToSheet(Rom& m3, int index) {
    int a = m3.ReadFourBytes(baseAddr_ + 4 + (index << 2));
    if (a == 0) return -1;
    return a + baseAddr_;
  }

  int GetGfxPointer(Rom& m3, int index) {
    return m3.ReadFourBytes(gfxAddr_ + 4 + (index << 2)) + gfxAddr_;
  }

  int baseAddr_;
  int gfxAddr_;
  std::map<int, SpriteSheet> spritesheets_;
};

int main(int argc, char** argv) {
  if (argc != 2) {
    std::cout << "Usage" << std::endl;
    return -1;
  }

  Magick::InitializeMagick(nullptr);

  Rom m3(argv[1]);
  PaletteSet palettes(m3);
  //const int banks[] = {0x1A442A4, 0x1AE0638, 0x1AEE4C4, 0x1AF1ED0};
  Bank b1(m3, 0x1A442A4, 0x14383E4);
  Magick::Image im = b1.SpriteSheets().at(1).render(m3, palettes);
  im.magick("png");
  im.write("out.png");

  return 0;
}