summaryrefslogtreecommitdiff
path: root/jeu-test/Lemmini/0.84/src/Extract/ExtractSPR.java
blob: 45f5f3defcf6c5004d5588aa151bbf1bda7c57ba (plain)
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package Extract;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

/*
 * Copyright 2009 Volker Oth
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Extract graphics from "Lemming for Win95" SPR data files.
 * @author Volker Oth
 */
public class ExtractSPR {
	/** palette index of transparent color */
	private final static int transparentIndex = 0;

	private final static long serialVersionUID = 0x01;

	/** array of GIF images to store to disk */
	private GIFImage images[];
	/** color palette */
	private Palette palette = null;
	/** buffer used to compress the palette (remove double entries) to work around issues on MacOS */
	private int lookupBuffer[];

	/**
	 * Load palette.
	 * @param fname Name of palette file
	 * @return ColorModel representation of Palette
	 * @throws ExtractException
	 */
	Palette loadPalette(final String fname) throws ExtractException {
		byte buffer[];

		// read file into buffer
		int paletteSize = 0;
		try {
			File f = new File(fname);
			FileInputStream fi = new FileInputStream(fname);
			buffer = new byte[(int)f.length()];
			fi.read(buffer);
			fi.close();
		} catch(FileNotFoundException e) {
			throw new ExtractException("File "+fname+" not found");
		}
		catch(IOException e) {
			throw new ExtractException("I/O error while reading "+fname);
		}
		// check header
		if (buffer[0] != 0x20 || buffer[1] != 0x4c || buffer[2] != 0x41 || buffer[3] != 0x50 )
			throw new ExtractException("File "+fname+" ist not a lemmings palette file");

		paletteSize = unsigned(buffer[4]) + unsigned(buffer[5])*256;   // number of palette entries

		byte[] r = new byte[paletteSize];
		byte[] g = new byte[paletteSize];
		byte[] b = new byte[paletteSize];

		int ofs = 6; // skip two bytes which contain number of palettes (?)
		for (int idx = 0; idx < paletteSize; idx++) {
			r[idx] = buffer[ofs++];
			g[idx] = buffer[ofs++];
			b[idx] = buffer[ofs++];
			ofs++;
		}

		// search for double entries, create
		// new palette without double entries
		// and lookup table to fix the pixel values
		byte compressedR[] = new byte[paletteSize];
		byte compressedG[] = new byte[paletteSize];
		byte compressedB[] = new byte[paletteSize];
		lookupBuffer = new int[paletteSize];

		Arrays.fill(lookupBuffer,-1); // mark all entries invalid
		Arrays.fill(compressedR, (byte)0);
		Arrays.fill(compressedG, (byte)0);
		Arrays.fill(compressedB, (byte)0);

		int compressedIndex = 0;
		for (int i=0; i<paletteSize; i++) {

			if (lookupBuffer[i] == -1) {             // if -1, this value is no doublette of a lower index
				compressedR[compressedIndex] = r[i]; // copy value to compressed buffer
				compressedG[compressedIndex] = g[i];
				compressedB[compressedIndex] = b[i];
				if ( i != transparentIndex ) {       // don't search doublettes of transparent color
					// search for doublettes at higher indeces
					for (int j=i+1; j<paletteSize; j++) {
						if ( j == transparentIndex ) // transparent color can't be a doublette of another color
							continue;
						if ( (r[i] == r[j]) && (g[i] == g[j]) && (b[i] == b[j]) )
							lookupBuffer[j] = compressedIndex; // mark double entry in lookupBuffer
					}
				}
				lookupBuffer[i] = compressedIndex++;
			}
		}

		if (paletteSize != compressedIndex) {
			paletteSize = compressedIndex;
			r = compressedR;
			g = compressedG;
			b = compressedB;
		}

		palette = new Palette(r, g, b);
		return palette;
	}

	/**
	 * Convert byte in unsigned int
	 * @param b Byte to convert
	 * @return Unsigned value of byte
	 */
	private static int unsigned(final byte b) {
		return b & 0xFF;
	}

	/**
	 * Load SPR file. Load palette first!
	 * @param fname Name of SPR file
	 * @return Array of Images representing all images stored in the SPR file
	 * @throws ExtractException
	 */
	GIFImage[] loadSPR(final String fname) throws ExtractException {
		byte buffer[];

		if (palette == null)
			throw new ExtractException("Load Palette first!");

		// read file into buffer
		try {
			File f = new File(fname);
			FileInputStream fi = new FileInputStream(fname);
			buffer = new byte[(int)f.length()];
			fi.read(buffer);
			fi.close();
		} catch(FileNotFoundException e) {
			throw new ExtractException("File "+fname+" not found");
		}
		catch(IOException e) {
			throw new ExtractException("I/O error while reading "+fname);
		}
		// check header
		if (buffer[0] != 0x53 || buffer[1] != 0x52 || buffer[2] != 0x4c || buffer[3] != 0x45 )
			throw new ExtractException("File "+fname+" ist not a lemmings sprite file");
		// get number of frames
		int frames = unsigned(buffer[4]) + unsigned(buffer[5])*256;
		int ofs = unsigned(buffer[6]) + unsigned(buffer[7])*256;

		images = new GIFImage[frames];
		byte b;
		int lineOfs;

		for (int frame=0; frame < frames; frame++) {
			// get header info
			int xOfs = unsigned(buffer[ofs++]) + unsigned(buffer[ofs++])*256;   // x offset of data in output image
			int yOfs = unsigned(buffer[ofs++]) + unsigned(buffer[ofs++])*256;   // y offset of data in output image
			int maxLen = unsigned(buffer[ofs++]) + unsigned(buffer[ofs++])*256; // maximum length of a data line
			int lines = unsigned(buffer[ofs++]) + unsigned(buffer[ofs++])*256;  // number of data lines
			int width = unsigned(buffer[ofs++]) + unsigned(buffer[ofs++])*256;  // width of output image
			int height = unsigned(buffer[ofs++]) + unsigned(buffer[ofs++])*256; // height of output image

			byte pixels[] = new byte[width*height];

			for (int i=0; i<pixels.length; i++)
				pixels[i] = transparentIndex;

			int y = yOfs*width;

			int pxOffset = 0; // additional offset for lines broken in several packets

			for (int line = 0; line < lines; ) {
				// read line
				b = buffer[ofs++]; // start character including length (>= 0x80) or line offset (<0x80)
				lineOfs = 0;
				while (b == 0x7f) {   // special line offset for large sprites
					lineOfs += 0x7f;
					b = buffer[ofs++];
				}
				if (!( (b & 0x80) == 0x80)) {
					// additional line offset
					lineOfs += (b & 0x7f);
					b = buffer[ofs++]; // start character
				}
				// get line length
				int len = (b & 0xff) - 0x80;
				if (len < 0 || len > 0x7f || len > maxLen)
					throw new ExtractException(
							"Maximum data line length exceeded in line "+line+" of frame "+frame+" of "+fname+" (ofs:"+ofs+")");
				if (len > 0) {
					try {
						for (int pixel = 0; pixel < len; pixel++) {
							// none of the extracted images uses more than 128 colors (indeed much less)
							// but some use higher indeces. Instead of mirroring the palette, just and every
							// entry with 0x7f.
							// The lookup table is needed to get new index in compresse palette
							byte pixelVal = (byte)(lookupBuffer[buffer[ofs++] & 0x7f] & 0xff);
							pixels[y+xOfs+lineOfs+pixel+pxOffset] = pixelVal;
						}
					} catch (ArrayIndexOutOfBoundsException ex) {
						throw new ExtractException(
								"Index out of bounds in line "+line+" of frame "+frame+" of "+fname+" (ofs:"+ofs+")");
					}
					b = buffer[ofs++]; // end character must be 0x80
					if ( (b & 0xff) != 0x80) {
						// if this is not the end character, the line is continued after an offset
						pxOffset += (lineOfs + len);
						ofs--;
						continue;
					}
				}
				pxOffset = 0;
				line++;
				y += width;
			}
			// convert byte array into BufferedImage
			images[frame] = new GIFImage(width, height, pixels, palette);
		}

		return images;
	}

	/**
	 * Save all images of currently loaded SPR file
	 * @param fname Filename of GIF files to export. "_N.gif" will be appended with N being the image number.
	 * @param keepAnims If true, consequently stored imaged with same size will be stored inside one GIF (one beneath the other)
	 * @return Array of all the filenames stored
	 * @throws ExtractException
	 */
	String[] saveAll(final String fname, final boolean keepAnims) throws ExtractException {
		int width = images[0].getWidth();
		int height = images[0].getHeight();
		int startIdx = 0;
		int animNum = 0;
		ArrayList<String> files = new ArrayList<String>();

		for (int idx=1; idx <= images.length; idx++) {
			// search for first image with different size
			if (keepAnims)
				if (idx < images.length)
					if (images[idx].getWidth() == width && images[idx].getHeight() == height)
						continue;
			// now save all the images in one: one above the other
			int num;
			if (keepAnims)
				num = idx - startIdx;
			else num = 1;
			byte pixels[] = new byte[width*num*height];
			GIFImage anim = new GIFImage(width, num*height, pixels, palette);
			for (int n = 0; n<num; n++)
				System.arraycopy(images[startIdx+n].getPixels(), 0, pixels, n*height*width, images[startIdx+n].getPixels().length);

			startIdx = idx;
			// construct filename
			String fn = fname+"_"+Integer.toString(animNum++)+".gif";
			// save gif
			saveGif(anim, fn);
			files.add(fn.toLowerCase());
			// remember new size
			if (idx < images.length) {
				width = images[idx].getWidth();
				height = images[idx].getHeight();
			}
		}
		String[] fileArray = new String[files.size()];
		return files.toArray(fileArray);
	}

	/**
	 * Save a number of images of currently loaded SPR file into one GIF (one image beneath the other)
	 * @param fname Name of GIF file to create (".gif" will NOT be appended)
	 * @param startIdx Index of first image to store
	 * @param frames Number of frames to store
	 * @throws ExtractException
	 */
	void saveAnim(final String fname, final int startIdx, final int frames) throws ExtractException {
		int width = images[startIdx].getWidth();
		int height = images[startIdx].getHeight();

		byte pixels[] = new byte[width*frames*height];
		GIFImage anim = new GIFImage(width, frames*height, pixels, palette);
		for (int n = 0; n<frames; n++)
			System.arraycopy(images[startIdx+n].getPixels(), 0, pixels, n*height*width, images[startIdx+n].getPixels().length);
		// save gif
		saveGif(anim, fname);
	}

	/**
	 * Save one image as GIF
	 * @param img Image object to save
	 * @param fname Name of GIF file to create (".gif" will NOT be appended)
	 * @throws ExtractException
	 */
	public static void saveGif(final GIFImage img, final String fname) throws ExtractException {
		GifEncoder gifEnc = new GifEncoder(img.getWidth(), img.getHeight(), img.getPixels(),
				img.palette.getRed(), img.palette.getGreen(), img.getPalette().getBlue());
		try {
			FileOutputStream f = new FileOutputStream(fname);
			gifEnc.setTransparentPixel(transparentIndex);
			gifEnc.write(f);
			f.close();
		} catch(FileNotFoundException ex) {
			throw new ExtractException("Can't open file "+fname+" for writing." );
		}
		catch(IOException ex) {
			throw new ExtractException("I/O error while writing file "+fname);
		}
	}


	/**
	 * Storage class for palettes.
	 * @author Volker Oth
	 */
	class Palette {
		/** byte array of red components */
		private byte[] red;
		/** byte array of green components */
		private byte[] green;
		/** byte array of blue components */
		private byte[] blue;

		/**
		 * Create palette from array of color components
		 * @param r byte array of red components
		 * @param g byte array of green components
		 * @param b byte array of blue components
		 */
		Palette(final byte[] r, final byte[] g, final byte[] b) {
			red = r;
			green = g;
			blue = b;
		}

		/**
		 * Get blue components.
		 * @return byte array of blue components
		 */
		public byte[] getBlue() {
			return blue;
		}

		/**
		 * Get green components.
		 * @return byte array of green components
		 */
		public byte[] getGreen() {
			return green;
		}

		/**
		 * Get red components.
		 * @return byte array of red components
		 */
		public byte[] getRed() {
			return red;
		}
	}

	/**
	 * Stores GIF Image in RAM.
	 */
	class GIFImage {
		/** width in pixels */
		private int width;
		/** height in pixels */
		private int height;
		/** pixel data */
		private byte[] pixels;
		/** color palette */
		private Palette palette;

		/**
		 * Constructor.
		 * @param w width in pixels.
		 * @param h height in pixels.
		 * @param buf pixel data
		 * @param p color palette
		 */
		GIFImage(final int w, final int h, final byte[] buf, final Palette p) {
			width = w;
			height = h;
			pixels = buf;
			palette = p;
		}

		/**
		 * Get pixel data.
		 * @return pixel data as array of bytes
		 */
		public byte[] getPixels() {
			return pixels;
		}

		/**
		 * Get width in pixels.
		 * @return width in pixels
		 */
		public int getWidth() {
			return width;
		}

		/**
		 * Get height in pixels.
		 * @return height in pixels
		 */
		public int getHeight() {
			return height;
		}

		/**
		 * Get color palette.
		 * @return color palette
		 */
		public Palette getPalette() {
			return palette;
		}
	}
}