| 12 | }; |
| 13 | |
| 14 | var stitch = function(outFile, pathPrefix, matrix, tileWidth, tileHeight, cb) { |
| 15 | var tileColumns = matrix[0].length, tileRows = matrix.length; |
| 16 | var matrixSize = tileColumns * tileRows; |
| 17 | var stitched = new PNG({width: tileWidth * tileColumns, height: tileHeight * tileRows}); |
| 18 | var tileX = 0, tileY = 0; |
| 19 | var completed = 0; |
| 20 | |
| 21 | var name2Coord = {}; |
| 22 | |
| 23 | coverArea(tileRows, tileColumns, function(tileX, tileY) { |
| 24 | var name = matrix[tileY][tileX]; |
| 25 | |
| 26 | if (!name) { |
| 27 | completed += 1; // TODO: write empty instead |
| 28 | return; |
| 29 | } |
| 30 | |
| 31 | var pathFS = pathPrefix + name + '.png'; |
| 32 | |
| 33 | var png = new PNG(); |
| 34 | try { |
| 35 | png.parse(fs.readFileSync(pathFS)); |
| 36 | } catch (e) { |
| 37 | console.log('skipping '+pathFS); |
| 38 | completed += 1; |
| 39 | return; |
| 40 | } |
| 41 | |
| 42 | if (!name2Coord[name]) // don't overwrite |
| 43 | name2Coord[name] = [tileX, tileY]; |
| 44 | |
| 45 | png.on('parsed', function() { |
| 46 | if (this.width !== tileWidth || this.height !== tileHeight) |
| 47 | // TODO: handle multi-framed textures (animated water_flow, etc.) |
| 48 | console.log('WARNING: unexpected dimensions on '+pathFS+': '+this.width+'x'+this.height+' !== '+tileWidth+'x'+tileHeight); |
| 49 | |
| 50 | this.bitblt(stitched, 0, 0, tileWidth, tileHeight, tileX * tileWidth, tileY * tileHeight); |
| 51 | |
| 52 | completed += 1; |
| 53 | if (completed == matrixSize) { |
| 54 | console.log('Writing',outFile); |
| 55 | var w = fs.createWriteStream(outFile); |
| 56 | stitched.pack().pipe(w); |
| 57 | w.on('finish', function() { |
| 58 | cb(name2Coord); |
| 59 | }); |
| 60 | } |
| 61 | }); |
| 62 | }); |
| 63 | }; |
| 64 | |
| 65 | module.exports = stitch; |
| 66 | |