/* * Scratch Project Editor and Player * Copyright (C) 2014 Massachusetts Institute of Technology * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package { import flash.display.BitmapData; import flash.display3D.*; import flash.display3D.textures.Texture; import flash.geom.Rectangle; import flash.geom.Matrix; import flash.geom.Point; import org.villekoskela.utils.RectanglePacker; public class ScratchTextureBitmap extends BitmapData { private static var indexOfIDs:Array; private var rectPacker:RectanglePacker; private var texture:Texture; private var rectangles:Object; private var dirty:Boolean; public function ScratchTextureBitmap(width:int, height:int, transparent:Boolean=true, fillColor:uint=4.294967295E9) { super(width, height, transparent, fillColor); rectPacker = new RectanglePacker(width, height); rectangles = {}; dirty = false; } public function getTexture(context:Context3D):Texture { if(!texture) { texture = context.createTexture(width, height, Context3DTextureFormat.BGRA, true); dirty = true; } if(dirty) texture.uploadFromBitmapData(this); dirty = false; return texture; } public function disposeTexture():void { if(texture) { texture.dispose(); texture = null; } } // Returns an array of bitmap ids packed and rendered private var tmpPt:Point = new Point(); public function packBitmaps(bitmapsByID:Object):Array { fillRect(this.rect, 0x00000000); // Removing this speeds up texture repacking but creates edge rendering artifacts rectPacker.reset(width, height); indexOfIDs = []; var i:uint=0; for (var k:Object in bitmapsByID) { var bmd:BitmapData = bitmapsByID[k]; // Add a small margin around the bitmaps rectPacker.insertRectangle(bmd.width+1, bmd.height+1, i); indexOfIDs.push(k); ++i; } rectPacker.packRectangles(); // Render the packed bitmaps var rect:Rectangle; var m:Matrix = new Matrix(); rectangles = {}; var packedIDs:Array = []; for (i=0; i